Merge lane-go: titles, verdicts, human stage, line result format, stale-client guard

Integrates nine commits of reviewed work from the lane-go branch after the
automated resolver failed on this merge five times (each attempt dying on the
malformed-result defect whose fix is contained in this same merge).

Integration decisions:
- Search: kept main's shipped design (Store.Search + SearchResponse.Results) and
  dropped lane-go's parallel, older attempt (an unused Message.Matches field, an
  absent runs.search, and two partial TUI plumbing blocks). lane-go itself did not
  compile: protocol.SearchMatch was undefined and model.go referenced searchNav,
  requestSearch and applyRunNav, which exist nowhere. Those partial TUI blocks are
  removed; the queued TUI omni-search item will implement the surface properly on
  main's design.
- Both sides' additions are kept where they are independent: run titles and
  provenance, the human decision stage and its CLI/TUI surface, the derived stage
  verdict, the stale-client guard, the line-oriented result format, and main's
  search command.
- The search key's help label is now "/ omni search"; the two tests asserting the
  old label are updated rather than the label reverted.
- docs/cli.md and the packaged operations reference carry both sides' text.

Verified: go build ./... , go vet ./... and the full go test ./... suite pass.
This commit is contained in:
2026-10-16 22:21:43 +01:00
669 changed files with 7205 additions and 276 deletions
+113 -12
View File
@@ -33,15 +33,16 @@ type App struct {
In io.Reader
}
type options struct {
harness string
url, name, prompt, template, workspace, paths, key, opencode, model string
output string
conflict string
kind string
all bool
json, source, noOpen, yes, allow, createOnly, force, wait bool
version, expected, limit int
timeout, waitTimeout time.Duration
harness string
url, name, prompt, title, template, workspace, paths, key, opencode, model string
option, feedback string
output string
conflict string
kind string
all bool
json, source, noOpen, yes, allow, createOnly, force, wait bool
version, expected, limit int
timeout, waitTimeout time.Duration
}
func (a App) flags(command string) (*flag.FlagSet, *options) {
@@ -90,6 +91,7 @@ func (a App) flags(command string) (*flag.FlagSet, *options) {
case "run":
f.StringVar(&o.name, "pipeline", "", "Exact registered pipeline name or ID")
f.StringVar(&o.prompt, "prompt", "", "Task prompt; omitted opens a multiline composer")
f.StringVar(&o.title, "title", "", "Explicit run title; default is derived from the prompt")
f.StringVar(&o.workspace, "workspace", "", "Run directory (default: current directory)")
f.BoolVar(&o.yes, "yes", false, "Confirm execution without an interactive prompt")
f.BoolVar(&o.allow, "allow-tools", false, "Compatibility flag; stage-declared tools are enabled automatically")
@@ -110,6 +112,9 @@ func (a App) flags(command string) (*flag.FlagSet, *options) {
f.DurationVar(&o.waitTimeout, "wait-timeout", 0, "Client limit for --wait (0 waits until the run ends); independent of --timeout")
case "cancel", "draft-delete":
f.BoolVar(&o.yes, "yes", false, "Confirm this action without an interactive prompt")
case "decide":
f.StringVar(&o.option, "option", "", "Option key to choose among the waiting stage's edges (required)")
f.StringVar(&o.feedback, "feedback", "", "Optional free-text feedback recorded with the decision")
case "debug":
f.StringVar(&o.harness, "harness", "", "Debugging harness: configured opencode/pi, or nvim")
f.BoolVar(&o.yes, "yes", false, "Approve opening a debugging session without prompting")
@@ -145,6 +150,18 @@ func envOr(key, value string) string {
return value
}
// recordedFeedback returns the feedback the server actually stored for the
// decided step that carries the chosen option, so a repeated (idempotent)
// decision reports the recorded evidence rather than the ignored request text.
func recordedFeedback(detail *protocol.RunDetail, option string) string {
for i := len(detail.Steps) - 1; i >= 0; i-- {
if chosen, feedback := protocol.DecisionEvidence(detail.Steps[i].Output); chosen == option {
return strings.TrimSpace(feedback)
}
}
return ""
}
// parse allows flags before or after positional arguments without reinterpreting values.
func parse(f *flag.FlagSet, args []string) error {
var flags, positionals []string
@@ -391,6 +408,13 @@ func (a App) Run(ctx context.Context, args []string) error {
return err
}
defer c.Close()
// Report at most one build/protocol warning per invocation on stderr, so
// stdout stays parseable JSON; an unsafe newer server fails the command.
c.Report(func(relationship buildinfo.Relationship) {
if relationship.Message != "" {
a.notice("warning: " + relationship.Message)
}
})
call := func(request protocol.Message) (protocol.Message, error) {
requestCtx, cancel := context.WithTimeout(ctx, o.timeout)
defer cancel()
@@ -662,7 +686,7 @@ func (a App) Run(ctx context.Context, args []string) error {
}
case "runs":
for _, run := range r.Runs {
fmt.Fprintf(a.Out, "%d\t%s\tv%d\t%s\n", run.ID, run.Name, run.Version, run.Status)
fmt.Fprintf(a.Out, "%d\t%s\t%s\tv%d\t%s\n", run.ID, run.Label(), run.Name, run.Version, run.Status)
}
case "ping":
fmt.Fprintln(a.Out, "Connected ·", r.Time)
@@ -671,11 +695,19 @@ func (a App) Run(ctx context.Context, args []string) error {
} else {
fmt.Fprintln(a.Out, "Server build: unavailable (older server)")
}
build := buildinfo.Current()
fmt.Fprintf(a.Out, "Client: %s (commit %s)\n", build.Version, build.Commit)
if note := identityNote(r); note != "" {
fmt.Fprintln(a.Out, "Note:", note)
}
case "connection":
fmt.Fprintln(a.Out, "Server:", o.url)
for _, n := range r.NotificationEndpoints {
fmt.Fprintf(a.Out, "ntfy: %s · topic %s\n", n.ServerURL, n.Topic)
}
if note := identityNote(r); note != "" {
fmt.Fprintln(a.Out, "Note:", note)
}
}
return nil
case "export":
@@ -806,6 +838,58 @@ func (a App) Run(ctx context.Context, args []string) error {
return a.finishRun(ctx, r, o, call)
}
return a.output(r.RunDetail)
case "decide":
if len(pos) < 1 || len(pos) > 2 {
return fmt.Errorf("decide requires a run ID and an optional stage key")
}
id, err := strconv.ParseInt(pos[0], 10, 64)
if err != nil || id <= 0 {
return fmt.Errorf("run ID must be positive")
}
option := strings.TrimSpace(o.option)
if option == "" {
return fmt.Errorf("decide requires --option KEY")
}
stageKey := ""
if len(pos) == 2 {
stageKey = pos[1]
}
r, err := call(protocol.Message{Type: protocol.DecideRun, RunID: id, Stage: stageKey, Option: option, Feedback: o.feedback})
if err != nil {
return err
}
if r.RunDetail == nil {
return fmt.Errorf("server did not return run detail")
}
if o.json {
return a.output(r.RunDetail)
}
line := fmt.Sprintf("Decided run #%d: %s · %s", r.RunDetail.ID, option, r.RunDetail.Status)
if feedback := recordedFeedback(r.RunDetail, option); feedback != "" {
line += " · feedback: " + feedback
}
_, err = fmt.Fprintln(a.Out, line)
return err
case "title":
if len(pos) != 2 {
return fmt.Errorf("title requires a run ID and a title")
}
id, err := strconv.ParseInt(pos[0], 10, 64)
if err != nil || id <= 0 {
return fmt.Errorf("run ID must be positive")
}
r, err := call(protocol.Message{Type: protocol.SetRunTitle, RunID: id, Title: pos[1]})
if err != nil {
return err
}
if r.RunDetail == nil {
return fmt.Errorf("server did not return run detail")
}
if o.json {
return a.output(r.RunDetail)
}
_, err = fmt.Fprintf(a.Out, "Renamed run #%d to %s\n", r.RunDetail.ID, r.RunDetail.Label())
return err
case "rpc":
path, err := one()
if err != nil {
@@ -868,6 +952,23 @@ func searchLabel(hit protocol.SearchResult) string {
return ""
}
// notice writes one non-fatal line to stderr so machine-readable stdout stays
// intact. It never falls back to stdout, where it could corrupt --json output
// for an embedder that does not configure Err.
func (a App) notice(line string) {
w := a.Err
if w == nil {
w = os.Stderr
}
fmt.Fprintln(w, line)
}
// identityNote describes how this client build relates to a server response for
// human output; it is empty when both peers match.
func identityNote(response protocol.Message) string {
return buildinfo.Compare(buildinfo.Current(), protocol.MaxSupportedProtocol, response.Protocol, response.Build).Message
}
type callFunc func(protocol.Message) (protocol.Message, error)
type resolveFunc func(string) (protocol.PipelineSummary, error)
@@ -1044,7 +1145,7 @@ func (a App) run(ctx context.Context, pos []string, o *options, call callFunc, r
if o.wait || o.key != "" || o.version > 0 {
return fmt.Errorf("--wait, --request-key and --version require --json")
}
_, err := tea.NewProgram(tui.NewRun(ctx, o.url, tui.RunOptions{Pipeline: o.name, Prompt: o.prompt, Workspace: workspace, Yes: o.yes, AllowTools: o.allow, WritePaths: paths}), tea.WithContext(ctx), tea.WithAltScreen()).Run()
_, err := tea.NewProgram(tui.NewRun(ctx, o.url, tui.RunOptions{Pipeline: o.name, Prompt: o.prompt, Title: o.title, Workspace: workspace, Yes: o.yes, AllowTools: o.allow, WritePaths: paths}), tea.WithContext(ctx), tea.WithAltScreen()).Run()
return err
}
if o.name == "" || strings.TrimSpace(o.prompt) == "" {
@@ -1065,7 +1166,7 @@ func (a App) run(ctx context.Context, pos []string, o *options, call callFunc, r
if key == "" {
key = fmt.Sprintf("cli-%d-%d", os.Getpid(), time.Now().UnixNano())
}
r, err := call(protocol.Message{Type: protocol.RunPipeline, PipelineID: p.ID, Version: version, RequestKey: key, Workspace: workspace, Input: map[string]any{"prompt": o.prompt}, AllowTools: o.allow, WritePaths: paths})
r, err := call(protocol.Message{Type: protocol.RunPipeline, PipelineID: p.ID, Version: version, RequestKey: key, Workspace: workspace, Title: o.title, Input: map[string]any{"prompt": o.prompt}, AllowTools: o.allow, WritePaths: paths})
if err != nil {
return err
}
+19 -13
View File
@@ -17,11 +17,13 @@ var usage = map[string]string{
"import": "import [FILE.zip] [--all] [--on-conflict ask|keep|both|import] [--yes] [--json]",
"templates": "templates [--json]",
"template": "template <key> [--source | --json]",
"run": "run [name|id] [prompt] [--json [--wait [--wait-timeout DURATION]]]",
"run": "run [name|id] [prompt] [--title TITLE] [--json [--wait [--wait-timeout DURATION]]]",
"runs": "runs [--pipeline NAME] [--json]",
"inspect": "inspect <run-id> [--json]",
"cancel": "cancel <run-id> [--json]",
"decide": "decide <run-id> [stage] --option KEY [--feedback TEXT] [--json]",
"retry": "retry <run-id> [--json [--wait [--wait-timeout DURATION]]]",
"title": "title <run-id> \"<title>\" [--json]",
"debug": "debug <run-id> [--json | --no-open]",
"connection": "connection [--json]",
"ping": "ping [--json]",
@@ -33,18 +35,22 @@ var usage = map[string]string{
}
var notes = map[string]string{
"version": "Identify the local CLI binary without connecting to a server. --version is an alias. Use ping --json to identify the running server separately.",
"ping": "Pong includes the running server's compiled build.version, build.commit and build.dirty (null when unknown). This identifies the server, not the client or runtime workspace. Older servers omit build.",
"export": "Without a name, select pipelines with Space and save a ZIP in the current directory. --output writes a portable definition bundle; --all skips selection. One name without --output prints Markdown as before. No runs, credentials or old versions are exported.",
"import": "Select definitions from a ZIP. Identical existing definitions are skipped. For differing names, choose keep existing, keep both under a new name, or use imported as a new version (history retained). --on-conflict supplies an explicit automation policy; --yes only approves final publication. Schedules may activate; no run history is imported.",
"new": "Create an optional template copy or a one-stage starter. Opens the configured default harness; --harness opencode|pi|nvim overrides it. No submission is performed.",
"edit": "Omit the name to open fuzzy selection. Original immutable source is copied to a private draft. The configured harness edits that draft, never the live definition.",
"validate": "Uses the same server parser as submission. Does not persist or activate schedules. Structural validity does not prove runtime/tool availability.",
"submit": "Confirm publication at the prompt, or use --yes for explicit automation; schedules activate on acceptance. Managed drafts provide the name and base-version guard. --force never bypasses validation.",
"run": "Runs in your current directory after action confirmation (--yes skips it). Select a pipeline and compose a multiline task with Ctrl+S. Stage tools are enabled automatically; no file list or typed RUN confirmation. Cancellation does not undo edits. In JSON mode --wait polls until terminal; --wait-timeout bounds only the client wait after admission and is independent of per-request --timeout. A reached wait limit leaves the run active: inspect read-only with `inspect <run-id> --json`, or reattach with --wait reusing the original --request-key (never an automatic replay or cancel).",
"retry": "Start a new attempt of a failed run with the same initial input, directory, pipeline version, and edit scope. Original history is retained. Already-completed side effects are not undone. --wait/--wait-timeout behave as for run: a reached wait limit leaves the new run active; inspect read-only with `inspect <run-id> --json`, or reattach with --wait and the original --request-key instead of starting a duplicate retry.",
"debug": "Open a fresh configured harness conversation to investigate a run using inspect/show/runs CLI queries. --harness opencode|pi|nvim chooses another configured harness or read-only nvim packet. Does not resume implementation or retry. --json returns the prompt without launching anything.",
"rpc": "Accepts a JSON protocol envelope; '-' reads stdin. Every TUI server operation is available here too. Mutating commands are not dry runs.",
"version": "Identify the local CLI binary without connecting to a server. --version is an alias. Use ping --json to identify the running server separately.",
"ping": "Pong includes the running server's compiled build.version, build.commit and build.dirty (null when unknown). This identifies the server, not the client or runtime workspace. Older servers omit build. The client compares its own build/protocol against the server: a same-protocol build mismatch prints one warning to stderr, a server speaking a newer protocol fails the command, and a response carrying a field this client does not model prints a one-time unrecognized-field notice instead of dropping it silently.",
"connection": "Prints the server endpoint and phone notification endpoints. Like ping, it reports the client/server build relationship and warns or fails rather than silently proceeding against a mismatched server.",
"status": "Reports server, host and ntfy publishing health. The client compares its build/protocol against the server and warns once (or fails on a newer protocol) rather than proceeding silently.",
"export": "Without a name, select pipelines with Space and save a ZIP in the current directory. --output writes a portable definition bundle; --all skips selection. One name without --output prints Markdown as before. No runs, credentials or old versions are exported.",
"import": "Select definitions from a ZIP. Identical existing definitions are skipped. For differing names, choose keep existing, keep both under a new name, or use imported as a new version (history retained). --on-conflict supplies an explicit automation policy; --yes only approves final publication. Schedules may activate; no run history is imported.",
"new": "Create an optional template copy or a one-stage starter. Opens the configured default harness; --harness opencode|pi|nvim overrides it. No submission is performed.",
"edit": "Omit the name to open fuzzy selection. Original immutable source is copied to a private draft. The configured harness edits that draft, never the live definition.",
"validate": "Uses the same server parser as submission. Does not persist or activate schedules. Structural validity does not prove runtime/tool availability.",
"submit": "Confirm publication at the prompt, or use --yes for explicit automation; schedules activate on acceptance. Managed drafts provide the name and base-version guard. --force never bypasses validation.",
"run": "Runs in your current directory after action confirmation (--yes skips it). Select a pipeline and compose a multiline task with Ctrl+S. Stage tools are enabled automatically; no file list or typed RUN confirmation. Cancellation does not undo edits. --title sets an explicit run title; without it the title is derived from the prompt. In JSON mode --wait polls until terminal; --wait-timeout bounds only the client wait after admission and is independent of per-request --timeout. A reached wait limit leaves the run active: inspect read-only with `inspect <run-id> --json`, or reattach with --wait reusing the original --request-key (never an automatic replay or cancel).",
"retry": "Start a new attempt of a failed run with the same initial input, directory, pipeline version, and edit scope. Original history is retained. Already-completed side effects are not undone. --wait/--wait-timeout behave as for run: a reached wait limit leaves the new run active; inspect read-only with `inspect <run-id> --json`, or reattach with --wait and the original --request-key instead of starting a duplicate retry.",
"title": "Rename a run's operator-facing title after the fact without touching its input, steps or execution. The title is collapsed to a single bounded line and recorded as explicitly set. `pipelines runs` and `pipelines inspect` then show it.",
"decide": "Choose an option for a run waiting on a human stage. The run must be `waiting`; the option must be one of that stage's non-error edges. The stage is inferred from the run's current stage unless named. The choice and optional --feedback are recorded as the step's evidence (visible in inspect and the TUI) and the run resumes along the chosen edge. An unknown option is refused with the valid list; a repeated decision for an already-decided visit does not double-apply. Works across a server restart because the wait is persisted.",
"debug": "Open a fresh configured harness conversation to investigate a run using inspect/show/runs CLI queries. --harness opencode|pi|nvim chooses another configured harness or read-only nvim packet. Does not resume implementation or retry. --json returns the prompt without launching anything.",
"rpc": "Accepts a JSON protocol envelope; '-' reads stdin. Every TUI server operation is available here too. Mutating commands are not dry runs. The omni-search command is `search` (fields query, optional kind and limit) and answers with ranked `search_results`.",
"search": "One read-only query over pipelines, versions, runs, steps, field text and artifacts. QUERY is free text, a bare status word (queued, running, succeeded, failed, canceled, interrupted) selecting those runs, or a lone date expression (today, yesterday, this week [Monday 00:00 local], or YYYY-MM-DD) selecting the runs created in that window. --type is the only narrowing mechanism and takes one kind: pipeline, version, run, step, field or artifact; an unknown kind is an error. Ranking: an exact name match (3) beats a name substring (2) beats a body-text match (1); equal tiers break by recency, then a stable kind/target tie-break, and every hit reports score, matched_field and recency so a client can re-rank. Bounds: the result cap defaults to 50 and clamps to 200 (0 = default); every kind scans at most 2000 rows and field-text scanning is additionally capped at 2000 steps / 1 MiB; Truncated plus scanned_steps, scanned_bytes and scan_bound_bytes report when a bound applied. Targets are stable: pipeline:<id>, pipeline:<id>:v<version>, run:<id>, run:<id>:<sequence>, run:<id>:<sequence>:<field>, or an artifact URL.",
}
+99
View File
@@ -0,0 +1,99 @@
package cli_test
import (
"context"
"encoding/json"
"strconv"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
const cliHumanSource = "# stage gate\n\n```output\nDecision evidence.\n```\n\n```prompt\nApprove the release.\n```\n\n```edges\ngo -> #success\nhalt -> #failure\nerror -> #failure\n```\n\n```configs\ntype=human\n```\n\n"
func TestCLIDecideWaitingHumanRun(t *testing.T) {
run, store, _ := setup(t)
ctx := context.Background()
if _, err := store.Submit(ctx, "human-ws", cliHumanSource); err != nil {
t.Fatal(err)
}
output, err := run("run", "human-ws", "ship it", "--json", "--yes")
if err != nil {
t.Fatal(err)
}
var started protocol.Message
if err := json.Unmarshal([]byte(output), &started); err != nil || started.RunDetail == nil {
t.Fatalf("run did not return detail: %v %s", err, output)
}
runID := started.RunDetail.ID
waitFor := func(status string) protocol.RunDetail {
t.Helper()
for i := 0; i < 100; i++ {
text, err := run("inspect", strconv.FormatInt(runID, 10), "--json")
if err != nil {
t.Fatal(err)
}
var detail protocol.RunDetail
if err := json.Unmarshal([]byte(text), &detail); err != nil {
t.Fatal(err)
}
if detail.Status == status {
return detail
}
}
t.Fatalf("run never reached %s", status)
return protocol.RunDetail{}
}
waiting := waitFor(protocol.RunStatusWaiting)
if len(waiting.Steps) != 1 || waiting.Steps[0].Status != protocol.StepStatusWaiting {
t.Fatalf("waiting step not visible: %+v", waiting.Steps)
}
if prompt := protocol.WaitingPrompt(waiting.Steps[0].Output); !strings.Contains(prompt, "Approve the release") {
t.Fatalf("waiting prompt not visible: %+v", waiting.Steps[0].Output)
}
if _, err := run("decide", strconv.FormatInt(runID, 10)); err == nil || !strings.Contains(err.Error(), "--option") {
t.Fatalf("missing --option was accepted: %v", err)
}
if _, err := run("decide", strconv.FormatInt(runID, 10), "--option", "launch"); err == nil || !strings.Contains(err.Error(), "valid options") {
t.Fatalf("unknown option was accepted: %v", err)
}
output, err = run("decide", strconv.FormatInt(runID, 10), "gate", "--option", "go", "--feedback", "approved", "--json")
if err != nil {
t.Fatal(err)
}
var decided protocol.RunDetail
if err := json.Unmarshal([]byte(output), &decided); err != nil {
t.Fatal(err)
}
final := waitFor("succeeded")
gate := final.Steps[0]
if gate.Outcome != "go" || gate.Target != protocol.SuccessEnd || gate.Output["feedback"] != "approved" || gate.Diagnostic != "" {
t.Fatalf("decision evidence not recorded: %+v", gate)
}
if gate.Verdict == nil || gate.Verdict.Option != "go → success" || gate.Verdict.Reason != "approved" {
t.Fatalf("derived verdict missing the decision: %+v", gate.Verdict)
}
// A repeated decision must not double-apply and must report the recorded
// evidence, not the ignored request text.
repeat, err := run("decide", strconv.FormatInt(runID, 10), "gate", "--option", "go", "--feedback", "again")
if err != nil {
t.Fatal(err)
}
if strings.Contains(repeat, "again") || !strings.Contains(repeat, "approved") {
t.Fatalf("repeated decision reported the request, not the recorded evidence: %q", repeat)
}
after := waitFor("succeeded")
if len(after.Steps) != 1 || after.Steps[0].Output["feedback"] != "approved" {
t.Fatalf("repeated decision changed the recorded evidence: %+v", after.Steps)
}
if _, err := run("help", "decide"); err != nil {
t.Fatal(err)
}
}
+10
View File
@@ -27,7 +27,9 @@ EXECUTE
runs List audited runs; --pipeline filters results
inspect <run-id> Inspect stages, outputs, errors and status
cancel <run-id> Cancel a run; changes are NOT rolled back
decide <run-id> [stage] Choose an option for a run waiting on a person
retry <run-id> Restart a failed run with its original input and directory
title <run-id> "<title>" Rename a run after the fact; input/steps unchanged
debug <run-id> Investigate a run with a configured harness or nvim
draft-delete <draft.md> Delete a selected retained draft and its metadata
connection Server and public phone connection (no secrets)
@@ -66,4 +68,12 @@ when a checkout is linked) edits a private draft; nvim remains a client editor.
Nothing is published automatically.
Every submission is validated server-side. Submission activates any schedules.
JSON mode never launches an editor or picker; supply explicit arguments.
Search: the TUI '/' popup and the protocol 'search' command (via 'pipelines rpc')
find pipelines, versions, runs, stages/visits, artifact names and the text of stage
inputs, outputs and evidence. A bare status word (queued, running, succeeded,
failed, canceled, interrupted) or a date (today, yesterday, this week, or
YYYY-MM-DD interpreted in UTC) selects runs. A leading prefix pipeline:, version:,
run:, step:, field:, artifact: or match: (a field alias) narrows the result kind;
unrecognised words stay text.
`
+104
View File
@@ -0,0 +1,104 @@
package cli
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/buildinfo"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/wstest"
)
func TestCLIWarnsOnceOnDifferingBuildAndKeepsJSONParseable(t *testing.T) {
server := buildinfo.Info{Version: "v0-stale-server", Commit: "deadbeef"}
endpoint := wstest.Server(t, func(protocol.Message) protocol.Message {
return protocol.Message{Type: protocol.Pong, Build: &server, Protocol: protocol.ProtocolVersion}
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var out, errOut bytes.Buffer
app := App{Out: &out, Err: &errOut, In: strings.NewReader("")}
if err := app.Run(ctx, []string{"--url", endpoint, "ping", "--json"}); err != nil {
t.Fatal(err)
}
// stdout must stay valid JSON.
var decoded protocol.Message
if err := json.Unmarshal(out.Bytes(), &decoded); err != nil {
t.Fatalf("stdout is not parseable JSON: %v\n%s", err, out.String())
}
if decoded.Build == nil || decoded.Build.Version != server.Version {
t.Fatalf("stdout lost the server build: %+v", decoded.Build)
}
warnings := 0
for _, line := range strings.Split(strings.TrimSpace(errOut.String()), "\n") {
if strings.HasPrefix(line, "warning:") {
warnings++
client := buildinfo.Current()
for _, needle := range []string{client.Version, server.Version} {
if !strings.Contains(line, needle) {
t.Fatalf("warning %q does not name %q", line, needle)
}
}
}
}
if warnings != 1 {
t.Fatalf("differing build produced %d stderr warnings, want exactly one:\n%s", warnings, errOut.String())
}
t.Logf("stdout:\n%s", out.String())
t.Logf("stderr:\n%s", strings.TrimSpace(errOut.String()))
// Human ping prints the relationship too, without hiding the server build.
var humanOut, humanErr bytes.Buffer
human := App{Out: &humanOut, Err: &humanErr, In: strings.NewReader("")}
if err := human.Run(ctx, []string{"--url", endpoint, "ping"}); err != nil {
t.Fatal(err)
}
if !strings.Contains(humanOut.String(), "Note:") || !strings.Contains(humanOut.String(), server.Version) {
t.Fatalf("human ping omitted the client/server relationship:\n%s", humanOut.String())
}
}
func TestCLINoticesUnmodeledFieldInsteadOfDroppingIt(t *testing.T) {
payload := map[string]any{"type": protocol.Pong, "future_field": true}
payload["build"] = buildinfo.Current()
payload["protocol"] = protocol.ProtocolVersion
endpoint := wstest.Raw(t, func(protocol.Message) map[string]any { return payload })
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var out, errOut bytes.Buffer
app := App{Out: &out, Err: &errOut, In: strings.NewReader("")}
if err := app.Run(ctx, []string{"--url", endpoint, "ping"}); err != nil {
t.Fatal(err)
}
if !strings.Contains(errOut.String(), "future_field") || !strings.Contains(errOut.String(), "unrecognized") {
t.Fatalf("unmodeled field was silent: stderr=%q stdout=%q", errOut.String(), out.String())
}
t.Logf("stderr:\n%s", strings.TrimSpace(errOut.String()))
}
func TestCLIRefusesNewerServerProtocol(t *testing.T) {
server := buildinfo.Info{Version: "v9-future-server", Commit: "deadbeef"}
endpoint := wstest.Server(t, func(protocol.Message) protocol.Message {
return protocol.Message{Type: protocol.Pong, Build: &server, Protocol: protocol.ProtocolVersion + 7}
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var out, errOut bytes.Buffer
app := App{Out: &out, Err: &errOut, In: strings.NewReader("")}
err := app.Run(ctx, []string{"--url", endpoint, "ping", "--json"})
if err == nil {
t.Fatal("a newer server protocol did not fail the command")
}
client := buildinfo.Current()
for _, needle := range []string{client.Version, server.Version, fmt.Sprint(protocol.ProtocolVersion + 7), fmt.Sprint(protocol.ProtocolVersion)} {
if !strings.Contains(err.Error(), needle) {
t.Fatalf("refusal %q does not name %q", err.Error(), needle)
}
}
t.Logf("exit error: %v", err)
}