Report a stale client and refuse an unreadable newer server

Exchange a build/protocol identity so an older CLI can no longer talk to a
newer native server silently:

- protocol carries ProtocolVersion and every server frame (including the
  unsolicited welcome) is stamped with the server build and protocol, so a
  client that never pings still learns the server identity.
- buildinfo.Compare classifies the relationship as InSync/Warn/Refuse and
  names both builds; the client Watch reports one warning per connection and
  returns a hard error when the server speaks a newer, uninterpretable
  protocol so the caller never acts on the frame.
- client.ReceiveNotice decodes the raw frame so an unmodeled top-level field
  produces a one-time "unrecognized field(s)" notice instead of being dropped
  silently (the case that hid the artifacts field).
- CLI routes warnings to stderr, keeps machine JSON stdout clean and fails
  non-zero on a refused mismatch; ping/connection print the client/server
  relationship. The TUI surfaces the same notices through the shared log.
- scripts/setup-native.py now warns when an older `pipelines` earlier on PATH
  shadows prefix/bin/pipelines, naming both paths and versions, without
  installing or modifying anything else.
- Docs, the packaged debugging skill reference and README no longer imply the
  installed CLI always matches the server.

Tests cover the comparison table, unknown-field detection and caching, the
server identity stamping on pong and welcome, the CLI/TUI reporting paths and
the installer PATH shadowing warning.
This commit is contained in:
2026-10-16 18:37:01 +01:00
parent 98bbc2deac
commit 8c1eea53a9
25 changed files with 1239 additions and 81 deletions
+32
View File
@@ -404,6 +404,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()
@@ -684,11 +691,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":
@@ -888,6 +903,23 @@ func (a App) output(value any) error {
return encoder.Encode(value)
}
// 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)
+16 -14
View File
@@ -34,20 +34,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. --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.",
"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`.",
}
var serviceHelp = map[string]string{
+8
View File
@@ -67,4 +67,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)
}