CLI for agents: non-TTY safe run/confirmations, compact inspect, wait hints and exit codes

- Without a terminal, run behaves as --json, tui refuses and confirmations
  fail fast naming --yes instead of prompting.
- inspect prints a compact summary by default; --step N, --transcripts and
  --json give detail.
- wait names a failed run's stage and first diagnostic line, prints how to
  answer a run waiting on a person, and exits 2 when any run failed,
  was canceled or interrupted (1 stays for client errors).
- help describes the current # outcome / # handoff format.
- Task starter's Land stage drops edit to match format.md; skill docs
  document run --json --yes, retry --yes --json and the new behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 00:27:14 +00:00
parent accb9970b6
commit 2bde6b6344
16 changed files with 658 additions and 56 deletions
+4
View File
@@ -96,6 +96,10 @@ func main() {
} else {
fmt.Fprintln(os.Stderr, "pipelines:", err)
}
var status *cli.StatusError
if errors.As(err, &status) && status.Code > 0 {
os.Exit(status.Code)
}
os.Exit(1)
}
}
+1 -1
View File
@@ -80,7 +80,7 @@ func stageByKey(t *testing.T, graph protocol.Graph, key string) protocol.Stage {
// make the requested change may edit; nothing has web tools.
var exampleTools = map[string]map[string][]string{
"research": {"research": {"read", "glob", "grep", "shell", "websearch", "webfetch"}, "report": {"read", "glob", "grep", "edit", "shell"}},
"task": {"Code": {"read", "glob", "grep", "edit", "shell"}, "Review": {"read", "glob", "grep", "shell"}, "UIReview": {"read", "glob", "grep", "shell"}, "Land": {"read", "glob", "grep", "edit", "shell"}},
"task": {"Code": {"read", "glob", "grep", "edit", "shell"}, "Review": {"read", "glob", "grep", "shell"}, "UIReview": {"read", "glob", "grep", "shell"}, "Land": {"read", "glob", "grep", "shell"}},
}
func TestExampleRoleToolRestrictions(t *testing.T) {
+1 -2
View File
@@ -110,14 +110,13 @@ error -> UIReview
# stage Land
```prompt
Commit this run's reviewed change locally and leave a clean candidate. Never push, tag, rebase or amend, and do not merge into the base branch yourself. Inspect status and the diff, stage the run's changes, check for unrelated work and secrets, and create no empty commit. Report the commit hash and any files left out. Do not run suites or analyzers here; the delivery checks run them. If there is nothing to stage, report success clearly.
Commit this run's reviewed change locally and leave a clean candidate. Do not edit files; only stage and commit what earlier stages changed. Never push, tag, rebase or amend, and do not merge into the base branch yourself. Inspect status and the diff, stage the run's changes, check for unrelated work and secrets, and create no empty commit. Report the commit hash and any files left out. Do not run suites or analyzers here; the delivery checks run them. If there is nothing to stage, report success clearly.
```
```tools
read
glob
grep
edit
shell
```
+22 -9
View File
@@ -12,25 +12,38 @@ task with the least ceremony, and keep work small enough to verify.
## Using it
`pipelines list` shows the registered workflows; `pipelines runs` shows history.
Start a run with `pipelines run <name> "<task>"`, and inspect it with
`pipelines inspect <id>`.
From an agent's shell always pass `--yes` and `--json`; without a terminal the
CLI never opens a full-screen view or prompts, and a missing `--yes` fails at once.
Start a run with `pipelines run <name> "<task>" --json --yes` (prints the run id),
and inspect it with `pipelines inspect <id>`: a compact summary (one line per
step with status, outcome, duration and first diagnostic line, plus the final
handoff). `--step N` shows one step in full, `--transcripts` adds transcripts,
and `--json` is the full record.
After starting a run, always follow it with `pipelines wait <id>` until it
finishes; never start a run and move on without waiting. Run the wait as a
background command (one per run, or one loop over several ids) so the session is
notified the moment the run ends, then read its result with
`pipelines inspect <id> --json` and act on it: land, retry, or fix and report.
`pipelines inspect <id>` and act on it: land, retry, or fix and report.
`wait` prints one line per run, naming a failed run's stage and first diagnostic
line, and exits 0 when every run succeeded, 2 when any failed, was canceled or
interrupted, and 1 for a client error (unknown id, connection, `--timeout`).
Do not poll with repeated `pipelines runs` calls, and do not tell the user a run
is done, or will be reported, without a wait covering it. `wait` keeps blocking
while a run is `waiting` on a human stage (`pipelines decide`, user's choice only).
while a run is `waiting` on a human stage and prints how to answer it
(`pipelines decide <id> --option KEY`, the user's choice only).
A run started from a repository's main checkout runs in its own worktree
(`<repo>-runs/...`, branch `pipelines/run-...`); a failed run keeps that tree and
its commits. Read `pipelines inspect <id> --json` before deciding: resume the
failed stage (`pipelines retry <id>`; `--stage`/`--visit`, `--input-file`,
`--mode=restart` from entry), fix directly, or continue from the preserved
branch. Only `failed` runs can be retried; `interrupted` (server stopped
mid-run) and `canceled` runs need a new run or direct work on their branch.
its commits. Read `pipelines inspect <id>` before deciding: resume the
failed stage (`pipelines retry <id> --yes --json`; `--stage`/`--visit`,
`--input-file`, `--mode=restart` from entry), fix directly, or continue from the
preserved branch. `failed` and `interrupted` (server stopped mid-run) runs can be
retried: resume reruns the failed or interrupted stage, or starts the next stage
after the last completed one. `canceled` runs need a new run or direct work on
their branch. A retried stage's `input.md` carries a `# Previous attempt` section
(why the last attempt failed) and, with `--input-file`, a `# Operator correction`
section holding only the overridden keys.
## Use an existing pipeline
+10 -7
View File
@@ -1,6 +1,6 @@
# Recover a failed run
1. Read `pipelines inspect ID --json`, the failed stage's actual input/result,
1. Read `pipelines inspect ID` (then `--step N` or `--json`), the failed stage's actual input/result,
retained tool evidence, artifacts and Git diff. A timeout is not proof of lost work.
2. Separate code failure, environment/setup failure and result-format failure.
Missing evidence is not a passing check; a failed result does not erase edits.
@@ -10,12 +10,15 @@
4. Verify the repair with a focused regression; run broader checks once relevant
inputs settle. Do not raise retry/time budgets to hide a reproducible defect.
`pipelines retry ID` resumes the failed stage; `--stage KEY [--visit N]` picks a
recorded stage, `--input-file FILE|-` merges a bounded JSON correction,
`--version N` a published version of the same pipeline, `--mode=restart` starts
at entry (say so). Only `failed` runs retry; an `interrupted` run (server stopped
mid-stage) or a `canceled` one needs a new run or direct work on its preserved
branch. Verify the retry's actual stage input, not merely its admission.
`pipelines retry ID --yes --json` resumes the failed stage; `--stage KEY [--visit N]` picks a
recorded stage, `--input-file FILE|-` merges a bounded JSON correction (shown to
the stage as `# Operator correction`), `--version N` a published version of the
same pipeline, `--mode=restart` starts at entry (say so). `failed` and
`interrupted` runs retry (an interrupted run resumes its unfinished stage or the
stage after the last completed one); a `canceled` one needs a new run or direct
work on its preserved branch. The retried stage sees a `# Previous attempt`
section with the failing stage and diagnostic. Verify the retry's actual stage
input, not merely its admission.
A clean preparation stage succeeds without an empty commit. A `land` stage with a
delivery gate succeeds with a clean checked candidate; the server lands afterward.
+21 -2
View File
@@ -91,6 +91,12 @@ Use the authoritative `CLI_PREFIX` from the prompt:
distinguishable; `CLI_PREFIX title RUN_ID "..."` renames a run after the fact
without changing its input or steps. The stored prompt is unchanged, and
listing/renaming never calls a model.
- `CLI_PREFIX inspect RUN_ID`: compact summary — a header (status, outcome,
duration, diagnostic), one line per step (stage, status, outcome, duration,
first diagnostic line), how to answer a `waiting` run and the final `# handoff`
(bounded). `--step N` prints one step in full without its transcript (add
`--transcripts` for it), `--transcripts` alone appends every transcript, and
`--json` (with `--step N`, just that step) is the complete record below.
- `CLI_PREFIX inspect RUN_ID --json`: selected run, visits and retained evidence.
Each model step carries the usage its harness reported (`usage.tokens_total`,
`tokens_in`/`tokens_out` only when `split_known`, `cost_usd` only when
@@ -105,6 +111,17 @@ Use the authoritative `CLI_PREFIX` from the prompt:
complete tool history.
- `CLI_PREFIX decide RUN_ID [STAGE] --option KEY [--feedback TEXT] [--json]`: answer
a run `waiting` on a `type=human` stage (`references/format.md`).
- Without a terminal on stdin/stdout (an agent's shell, a pipe, CI) `run` behaves
as `--json` and never opens the full-screen view, `tui` refuses, and every
confirmation fails at once naming `--yes` instead of prompting: pass
`run NAME "TASK" --json --yes` and `retry RUN_ID --yes --json`.
- `CLI_PREFIX wait RUN_ID ...`: one line per run as it finishes (a failed run's
stage and first diagnostic line); while a run waits on a human it prints
`waiting at STAGE — answer with: pipelines decide ID --option KEY` once (stderr
under `--json`). Exit status: 0 every run succeeded, 2 a run failed, was
canceled or interrupted, 1 a client error (unknown id, connection, `--timeout`
reached; the run is untouched). `run --wait` and `retry --wait` also exit 2
for an unsuccessful run.
- `CLI_PREFIX run ... --json --wait --wait-timeout DURATION`: `--wait` polls until
terminal and `--wait-timeout` bounds only the client wait after admission,
independent of per-request `--timeout`. A reached wait limit leaves the admitted run
@@ -267,8 +284,10 @@ assistant message with the same bounded readback as the final result, so a small
final result is visible behind large prior tool content. Inspect the retained
session itself when a preview is bounded or omitted; never assume a complete tool
history from a preview.
Retry is allowed only for a `failed` run after cleanup stops (`interrupted` and
`canceled` runs need a new run). It creates a new linked run with the original
Retry is allowed for a `failed` or `interrupted` run after cleanup stops
(`canceled` runs need a new run); an interrupted run resumes its unfinished
stage, or the stage after its last completed one, and refuses resume (pointing
to `--mode=restart`) when neither is safe. It creates a new linked run with the original
input, directory, pinned version, edit scope and overrides. The default `resume`
mode restarts the failed stage (or `--stage`/`--visit`) with the completed
prefix's handoff and `public/` files; `--mode=restart` starts at entry;
@@ -39,7 +39,7 @@ and costs as agreed.
## Recovery and landing
Inspect `pipelines inspect ID --json` and actual files after failure. Preserve
Read `pipelines inspect ID` (`--step N`/`--json` for detail) and actual files after failure. Preserve
partial changes. Prefer resuming the original stage with corrected input or fixing
and merging directly; do not repeat completed work or add a merger pipeline.
For delivery=true, return a clean checked candidate and let the server land it.
+144
View File
@@ -0,0 +1,144 @@
package cli
import (
"bytes"
"context"
"os"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func notInteractive() bool { return false }
// Without a terminal a confirmation must fail at once, naming --yes, rather
// than block on stdin that an agent's Bash tool never answers.
func TestConfirmationFailsFastWithoutTerminal(t *testing.T) {
var out, stderr bytes.Buffer
a := App{Out: &out, Err: &stderr, In: strings.NewReader("y\n"), Interactive: notInteractive}
err := a.confirmAction("Retry failed run #4?", false)
if err == nil || !strings.Contains(err.Error(), "--yes") || !strings.Contains(err.Error(), "not a terminal") {
t.Fatalf("non-interactive confirmation = %v", err)
}
if stderr.Len() != 0 {
t.Fatalf("prompted without a terminal: %q", stderr.String())
}
if err := a.confirmAction("Retry failed run #4?", true); err != nil {
t.Fatalf("--yes refused: %v", err)
}
}
// A real non-terminal file (a pipe, /dev/null) is detected without an override.
func TestTerminalDetectionTreatsFilesAsNonInteractive(t *testing.T) {
devnull, err := os.Open(os.DevNull)
if err != nil {
t.Fatal(err)
}
defer devnull.Close()
a := App{In: devnull, Out: devnull}
if a.stdinInteractive() || a.terminalUI() {
t.Fatal("/dev/null treated as a terminal")
}
if (App{}).stdinInteractive() {
t.Fatal("nil stdin treated as interactive")
}
}
// `run NAME TASK` without a terminal takes the JSON path (no full-screen view)
// and so fails fast on the missing confirmation instead of hanging.
func TestRunWithoutTerminalUsesJSONPathAndNeedsYes(t *testing.T) {
var out, stderr bytes.Buffer
a := App{Out: &out, Err: &stderr, In: strings.NewReader(""), Interactive: notInteractive}
o := &options{name: "demo", prompt: "do it", notifyMode: "auto", workspace: t.TempDir()}
resolve := func(string) (protocol.PipelineSummary, error) {
return protocol.PipelineSummary{ID: 1, Name: "demo", Version: 3}, nil
}
called := false
call := func(protocol.Message) (protocol.Message, error) { called = true; return protocol.Message{}, nil }
err := a.run(context.Background(), nil, o, call, resolve)
if err == nil || !strings.Contains(err.Error(), "--yes") {
t.Fatalf("run without terminal and --yes = %v", err)
}
if !o.json || called {
t.Fatalf("run without terminal: json=%v called=%v", o.json, called)
}
}
func sampleRun() *protocol.RunDetail {
d := &protocol.RunDetail{}
d.ID, d.Name, d.Version, d.Status, d.Outcome = 7, "task", 2, "failed", "error"
d.CreatedAt, d.FinishedAt = "2026-01-01T00:00:00Z", "2026-01-01T00:02:00Z"
d.Steps = []protocol.RunStep{
{Sequence: 1, Stage: "plan", Status: "succeeded", Outcome: "done", StartedAt: "2026-01-01T00:00:00Z", FinishedAt: "2026-01-01T00:00:30Z",
Output: map[string]any{"markdown": "# handoff\nPlan: edit a.go\n\n# outcome\ndone"}, Transcript: strings.Repeat("plan transcript ", 2000)},
{Sequence: 2, Stage: "implement", Status: "failed", Diagnostic: "go test failed\nlong detail line", Transcript: "IMPLEMENT-TRANSCRIPT",
StartedAt: "2026-01-01T00:00:30Z", FinishedAt: "2026-01-01T00:02:00Z"},
}
return d
}
func TestInspectDefaultsToCompactSummary(t *testing.T) {
var out bytes.Buffer
if err := (App{Out: &out}).inspect(sampleRun(), &options{}); err != nil {
t.Fatal(err)
}
text := out.String()
for _, want := range []string{"run 7 · task v2 · failed (error) · 2m0s", "#1 plan · succeeded (done) · 30s", "#2 implement · failed · 1m30s · go test failed", "Plan: edit a.go", "--step N"} {
if !strings.Contains(text, want) {
t.Fatalf("summary missing %q:\n%s", want, text)
}
}
if strings.Contains(text, "plan transcript") || strings.Contains(text, "long detail line") || len(text) > 2000 {
t.Fatalf("summary is not compact (%d bytes):\n%s", len(text), text)
}
}
func TestInspectStepAndTranscriptsAndJSON(t *testing.T) {
var out bytes.Buffer
if err := (App{Out: &out}).inspect(sampleRun(), &options{step: 2}); err != nil {
t.Fatal(err)
}
if text := out.String(); !strings.Contains(text, "long detail line") || strings.Contains(text, "IMPLEMENT-TRANSCRIPT") {
t.Fatalf("--step 2:\n%s", text)
}
out.Reset()
if err := (App{Out: &out}).inspect(sampleRun(), &options{step: 2, transcripts: true}); err != nil || !strings.Contains(out.String(), "IMPLEMENT-TRANSCRIPT") {
t.Fatalf("--step 2 --transcripts: %v\n%s", err, out.String())
}
out.Reset()
if err := (App{Out: &out}).inspect(sampleRun(), &options{transcripts: true}); err != nil || !strings.Contains(out.String(), "IMPLEMENT-TRANSCRIPT") {
t.Fatalf("--transcripts: %v", err)
}
out.Reset()
if err := (App{Out: &out}).inspect(sampleRun(), &options{json: true}); err != nil || !strings.Contains(out.String(), `"transcript": "IMPLEMENT-TRANSCRIPT"`) {
t.Fatalf("--json must keep full detail: %v", err)
}
if err := (App{Out: &out}).inspect(sampleRun(), &options{step: 9}); err == nil {
t.Fatal("unknown step accepted")
}
}
func TestWaitLineNamesFailingStageAndDiagnostic(t *testing.T) {
line := waitLine(sampleRun())
if !strings.Contains(line, "failed at implement · go test failed") || strings.Contains(line, "long detail line") {
t.Fatalf("wait line = %q", line)
}
}
func TestWaitingHintTellsHowToDecide(t *testing.T) {
d := &protocol.RunDetail{}
d.ID, d.Status, d.CurrentStage = 12, protocol.RunStatusWaiting, "decide"
d.Steps = []protocol.RunStep{{Sequence: 3, Stage: "decide", Status: protocol.RunStatusWaiting,
Output: map[string]any{protocol.WaitingOptionsKey: []any{"approve", "revise"}, protocol.WaitingPromptKey: "Ship it?"}}}
hint := waitingHint(d)
for _, want := range []string{"waiting at decide", "pipelines decide 12 --option approve|revise", "Ship it?"} {
if !strings.Contains(hint, want) {
t.Fatalf("hint missing %q: %q", want, hint)
}
}
d.ExportPendingSequence = 3
if waitingHint(d) != "" {
t.Fatal("an export handoff is not a human decision")
}
}
+83 -7
View File
@@ -36,6 +36,9 @@ type App struct {
// Install is the native installation manifest this CLI belongs to, or nil
// (Docker installation, or a development/Go-installed CLI).
Install *installation.Config
// Interactive overrides terminal detection (tests and embedders). Nil
// detects it: stdin (and stdout for full-screen views) must be terminals.
Interactive func() bool
}
type options struct {
outputFormat string
@@ -53,6 +56,8 @@ type options struct {
debugFiles bool
json, source, noOpen, yes, allow, createOnly, force, wait bool
archived bool
transcripts bool
step int
version, expected, limit, retryVisit int
timeout, waitTimeout time.Duration
stageModels stageModelFlags
@@ -185,6 +190,9 @@ func (a App) flags(command string) (*flag.FlagSet, *options) {
f.IntVar(&o.version, "version", 0, "Explicit published version of the same pipeline (default: source version)")
f.StringVar(&o.retryInputFile, "input-file", "", "JSON object merged into the selected stage input; '-' reads stdin")
f.StringVar(&o.notifyMode, "notify", "auto", "Notifications for this retry: auto, on, or off")
case "inspect":
f.IntVar(&o.step, "step", 0, "Show one step (its sequence number) in full, without its transcript")
f.BoolVar(&o.transcripts, "transcripts", false, "Include stage transcripts (long)")
case "cancel", "draft-delete":
f.BoolVar(&o.yes, "yes", false, "Confirm this action without an interactive prompt")
case "retention":
@@ -474,6 +482,9 @@ func (a App) Run(ctx context.Context, args []string) error {
if len(pos) > 0 {
return fmt.Errorf("tui takes no arguments")
}
if !a.terminalUI() {
return fmt.Errorf("the dashboard needs a terminal; use pipelines runs, inspect or wait instead")
}
_, err := tea.NewProgram(tui.New(ctx, o.url), tea.WithContext(ctx), tea.WithAltScreen()).Run()
return err
}
@@ -973,7 +984,7 @@ func (a App) Run(ctx context.Context, args []string) error {
}
key := ""
if command == "retry" {
if err := a.confirmAction(fmt.Sprintf("Retry failed run #%d as a fresh run? Reuses original input/directory; side effects may repeat.", id), o.yes); err != nil {
if err := a.confirmAction(fmt.Sprintf("Retry run #%d (failed or interrupted) as a fresh run? Reuses original input/directory; side effects may repeat.", id), o.yes); err != nil {
return err
}
typeName = protocol.RetryRun
@@ -1041,6 +1052,7 @@ func (a App) Run(ctx context.Context, args []string) error {
for _, warning := range r.RunDetail.Warnings {
a.notice("warning: " + warning)
}
return a.inspect(r.RunDetail, o)
}
return a.output(r.RunDetail)
case "decide":
@@ -1361,6 +1373,11 @@ func (a App) run(ctx context.Context, pos []string, o *options, call callFunc, r
if o.yes && (o.name == "" || strings.TrimSpace(o.prompt) == "") {
return fmt.Errorf("--yes requires a pipeline and nonempty prompt")
}
// Without a terminal (an agent's Bash tool, a pipe, CI) the full-screen run
// view would hang; behave as --json, which never prompts without --yes.
if !o.json && !a.terminalUI() {
o.json = true
}
if !o.json {
if o.name != "" {
p, err := resolve(o.name)
@@ -1455,7 +1472,14 @@ func (a App) finishRun(ctx context.Context, r protocol.Message, o *options, call
return err
}
if o.wait && r.RunDetail.Status != "succeeded" {
return fmt.Errorf("run ended %s", r.RunDetail.Status)
message := fmt.Sprintf("run %d ended %s", r.RunDetail.ID, r.RunDetail.Status)
if note := failureNote(r.RunDetail); note != "" {
message += " (" + note + ")"
}
if hint := waitingHint(r.RunDetail); hint != "" {
message += "; " + hint
}
return &StatusError{Code: WaitRunsUnsuccessful, Message: message}
}
return nil
}
@@ -1496,6 +1520,21 @@ func (a App) wait(ctx context.Context, pos []string, o *options, call callFunc)
deadline = timer.C
}
terminal := make([]protocol.Message, 0, len(initial))
// A run parked on a human decision keeps the wait blocking; say once per
// waiting visit how to answer it, so an agent is not left guessing.
announced := map[int64]string{}
onActive := func(r protocol.Message) {
hint := waitingHint(r.RunDetail)
if hint == "" || announced[r.RunDetail.ID] == hint {
return
}
announced[r.RunDetail.ID] = hint
if o.json {
a.notice(hint)
return
}
fmt.Fprintln(a.Out, hint)
}
err := a.awaitRuns(ctx, initial, deadline, call, runUnfinished, func(r protocol.Message) error {
terminal = append(terminal, r)
if o.json {
@@ -1503,7 +1542,7 @@ func (a App) wait(ctx context.Context, pos []string, o *options, call callFunc)
}
_, writeErr := fmt.Fprintln(a.Out, waitLine(r.RunDetail))
return writeErr
})
}, onActive)
if err != nil {
var limit *waitLimitError
if errors.As(err, &limit) {
@@ -1512,12 +1551,32 @@ func (a App) wait(ctx context.Context, pos []string, o *options, call callFunc)
return err
}
if o.json {
var outputErr error
if len(terminal) == 1 {
return a.output(terminal[0])
outputErr = a.output(terminal[0])
} else {
outputErr = a.output(terminal)
}
if outputErr != nil {
return outputErr
}
return a.output(terminal)
}
return nil
return unsuccessfulRuns(terminal)
}
// unsuccessfulRuns is the wait's exit status: nil when every run succeeded,
// otherwise a StatusError (exit 2) naming the runs that did not.
func unsuccessfulRuns(runs []protocol.Message) error {
var failed []string
for _, r := range runs {
if r.RunDetail.Status != "succeeded" {
failed = append(failed, fmt.Sprintf("run %d %s", r.RunDetail.ID, r.RunDetail.Status))
}
}
if len(failed) == 0 {
return nil
}
return &StatusError{Code: WaitRunsUnsuccessful, Message: strings.Join(failed, ", ") + "; read pipelines inspect ID, then retry with pipelines retry ID --yes --json or fix directly"}
}
// awaitRuns polls unfinished runs using GetRun reattachment. Export waits remain
@@ -1526,10 +1585,16 @@ func (a App) wait(ctx context.Context, pos []string, o *options, call callFunc)
// entry, in the order supplied). A deadline that passes first returns a
// *waitLimitError naming the runs still active; ctx ending first returns
// ctx.Err(). It never cancels, retries or otherwise changes a run.
func (a App) awaitRuns(ctx context.Context, runs []protocol.Message, deadline <-chan time.Time, call callFunc, active func(string) bool, onTerminal func(protocol.Message) error) error {
func (a App) awaitRuns(ctx context.Context, runs []protocol.Message, deadline <-chan time.Time, call callFunc, active func(string) bool, onTerminal func(protocol.Message) error, onActive ...func(protocol.Message)) error {
progress := func(r protocol.Message) {
for _, f := range onActive {
f(r)
}
}
remaining := make([]protocol.Message, 0, len(runs))
for _, r := range runs {
if active(r.RunDetail.Status) || (r.RunDetail.Status == protocol.RunStatusWaiting && r.RunDetail.ExportPendingSequence > 0) {
progress(r)
remaining = append(remaining, r)
continue
}
@@ -1555,6 +1620,7 @@ func (a App) awaitRuns(ctx context.Context, runs []protocol.Message, deadline <-
return fmt.Errorf("server did not return run detail for %d", r.RunDetail.ID)
}
if active(refreshed.RunDetail.Status) || (refreshed.RunDetail.Status == protocol.RunStatusWaiting && refreshed.RunDetail.ExportPendingSequence > 0) {
progress(refreshed)
next = append(next, refreshed)
continue
}
@@ -1620,6 +1686,16 @@ func waitLine(d *protocol.RunDetail) string {
if elapsed := runElapsed(d.CreatedAt, d.FinishedAt); elapsed != "" {
line += " · " + elapsed
}
// An unsuccessful run also names the stage it stopped at (when that is not
// the stage already shown) and the first line of its diagnostic.
if failing, diagnostic := failureDetail(d); failing != "" || diagnostic != "" {
if failing != "" && failing != strings.TrimSpace(d.CurrentStage) {
line += " · failed at " + failing
}
if diagnostic != "" {
line += " · " + diagnostic
}
}
return line
}
+6 -5
View File
@@ -21,13 +21,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] [--title TITLE] [--model PROVIDER/MODEL] [--stage-model STAGE=PROVIDER/MODEL ...] [--json [--wait [--wait-timeout DURATION]]]",
"run": "run [name|id] [prompt] [--yes] [--title TITLE] [--model PROVIDER/MODEL] [--stage-model STAGE=PROVIDER/MODEL ...] [--json [--wait [--wait-timeout DURATION]]]",
"runs": "runs [--pipeline NAME] [--json] | runs rm <run-id> [run-id ...] [--yes] [--json]",
"inspect": "inspect <run-id> [--json]",
"inspect": "inspect <run-id> [--step N] [--transcripts] [--json]",
"wait": "wait <run-id> [run-id ...] [--timeout DURATION] [--json]",
"cancel": "cancel <run-id> [--json]",
"decide": "decide <run-id> [stage] --option KEY [--feedback TEXT] [--json]",
"retry": "retry <run-id> [--mode resume|restart] [--stage KEY [--visit N]] [--version N] [--input-file FILE|-] [--json [--wait [--wait-timeout DURATION]]]",
"retry": "retry <run-id> [--yes] [--mode resume|restart] [--stage KEY [--visit N]] [--version N] [--input-file FILE|-] [--json [--wait [--wait-timeout DURATION]]]",
"title": "title <run-id> \"<title>\" [--json]",
"debug": "debug <run-id> [--json | --no-open]",
"chat-adopt": "chat-adopt <session-id> [--harness opencode|claude|codex] [--title TEXT] [--json]",
@@ -55,13 +55,14 @@ var notes = map[string]string{
"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. --model PROVIDER/MODEL overrides the model for every stage of that run; --stage-model STAGE=PROVIDER/MODEL overrides one stage and is repeatable, with a repeated key last-wins. Precedence is per-stage > whole-run > the model pinned in the pipeline version; overrides apply to that run only and never change the pinned definition. An unknown stage key or a malformed provider/model is refused before the run starts, naming the valid stage keys. 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": "Resume a failed stage by default, restoring the completed prefix handoff; use --mode=restart to start at entry. --stage selects a recorded stage (use --visit for repeated stages). --input-file accepts a bounded JSON object, merged with replacement at the selected stage; '-' reads stdin. Original history and pinned identity are retained; --version selects an explicit published version of the same pipeline only. --wait-timeout leaves an active retry for later read-only inspection or reattachment with the original --request-key, rather than starting a duplicate retry.",
"retry": "Resume a failed or interrupted run's stage by default (an interrupted run resumes its unfinished stage, or the one after its last completed stage), restoring the completed prefix handoff; use --mode=restart to start at entry. --stage selects a recorded stage (use --visit for repeated stages). --input-file accepts a bounded JSON object, merged with replacement at the selected stage and shown to it as an Operator correction; the retried stage also sees why the previous attempt failed; '-' reads stdin. Original history and pinned identity are retained; --version selects an explicit published version of the same pipeline only. --wait-timeout leaves an active retry for later read-only inspection or reattachment with the original --request-key, rather than starting a duplicate retry.",
"list": "Lists active pipelines. Archived pipelines are hidden; --archived lists only them and --all lists both, marking archived ones with their archive time.",
"archive": "Retire a pipeline from lists after confirmation (--yes for scripts). Nothing is deleted: versions, runs, artifacts and search history stay and keep its name. An archived pipeline cannot start runs and its name stays reserved (new/submit say so). Archiving is refused while an enabled schedule points at it, naming the schedule; pause or repoint it first. The latest version is sent as a guard, so a publication in between is refused.",
"unarchive": "Return an archived pipeline to lists; it can run and take new versions again. Schedules stay paused until you enable them.",
"runs": "Lists runs newest first; --json includes each run's size_bytes (bytes on disk: artifacts, session exports, server-created Pi session directories and an estimate of its database rows; 0 until first measured) and, when any model stage recorded usage, its usage total (tokens_total, split and cache components, cost). `runs rm <id...>` permanently deletes finished runs (succeeded, failed, canceled, interrupted) with every database row and server-owned file for them, after confirmation (--yes for scripts). Active runs, runs an unfinished retry depends on and unknown ids are refused individually with a reason, and the command then exits 1. User workspaces are never touched. Database pages are reused by SQLite; `retention apply` additionally VACUUMs to shrink the file.",
"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.",
"wait": "Block until each named run reaches a terminal status - succeeded, failed, canceled or interrupted, and also through a run waiting on a person - then print one line per run with its id, status and outcome, its stage and how long it took, and exit 0 even for a run that finished unsuccessfully. Several ids wait together in one command. The exit is non-zero only for a client-side failure: an unknown run id, a connection that could not be established, or --timeout expiring while a run is still active; a timeout says so plainly, never cancels, retries or otherwise touches a run, and is never reported as its outcome. Read-only: it needs no workspace, is not refused by the workspace guard and writes nothing. --json prints the final run envelope instead of the line (one envelope for one id, an array for several).",
"inspect": "Print a compact summary of a run: status, outcome and duration, one line per step (stage, status, outcome, duration, first diagnostic line), how to answer a run waiting on a person and the bounded final handoff. --step N prints that step in full (output, diagnostic, file changes, artifacts) without its transcript; --transcripts adds transcripts (to every step, or to --step N); --json prints the complete run record (or just --step N), including transcripts.",
"wait": "Block until each named run reaches a terminal status - succeeded, failed, canceled or interrupted, and also through a run waiting on a person - then print one line per run with its id, status and outcome, its stage, how long it took and, for an unsuccessful run, the failing stage and the first line of its diagnostic. While a run waits on a person it prints once how to answer: waiting at STAGE — answer with: pipelines decide ID --option KEY (on stderr under --json). Several ids wait together in one command. Exit status: 0 when every run succeeded; 2 when any run failed, was canceled or interrupted (every run is still reported); 1 for a client-side failure: an unknown run id, a connection that could not be established, or --timeout expiring while a run is still active. A timeout says so plainly, never cancels, retries or otherwise touches a run, and is never reported as its outcome. Read-only: it needs no workspace, is not refused by the workspace guard and writes nothing. --json prints the final run envelope instead of the line (one envelope for one id, an array for several).",
"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`.",
+41
View File
@@ -3,13 +3,23 @@ package cli
import (
"bufio"
"fmt"
"io"
"os"
"strings"
"golang.org/x/term"
)
func (a App) confirmAction(question string, yes bool) error {
if yes {
return nil
}
// An agent's Bash tool has no terminal: a prompt would block on a pipe that
// never answers. Fail at once with the flag that makes the command
// non-interactive instead.
if !a.stdinInteractive() {
return fmt.Errorf("%s\nconfirmation required but stdin is not a terminal; rerun with --yes to confirm non-interactively", question)
}
fmt.Fprint(a.Err, question+" [y/N]: ")
line, _ := bufio.NewReader(a.In).ReadString('\n')
if answer := strings.ToLower(strings.TrimSpace(line)); answer != "y" && answer != "yes" {
@@ -17,3 +27,34 @@ func (a App) confirmAction(question string, yes bool) error {
}
return nil
}
// stdinInteractive reports whether a person can answer a prompt. A real file
// must be a terminal; a nil reader cannot answer. Any other reader is an
// embedder- or test-supplied answer stream and counts as interactive.
func (a App) stdinInteractive() bool {
if a.Interactive != nil {
return a.Interactive()
}
return isTerminal(a.In)
}
// terminalUI reports whether a full-screen terminal UI can run: both stdin and
// stdout must be terminals. Without one the CLI uses its JSON paths instead.
func (a App) terminalUI() bool {
if a.Interactive != nil {
return a.Interactive()
}
return isTerminal(a.In) && isTerminal(a.Out)
}
func isTerminal(stream any) bool {
switch s := stream.(type) {
case nil:
return false
case *os.File:
return s != nil && term.IsTerminal(int(s.Fd()))
case io.Reader, io.Writer:
return true
}
return false
}
+15
View File
@@ -10,3 +10,18 @@ type ExitError struct{ Code int }
func (e *ExitError) Error() string { return fmt.Sprintf("subprocess exited with status %d", e.Code) }
func (e *ExitError) ExitCode() int { return e.Code }
// StatusError is a failure whose message is printed like any other error but
// whose process exit status is Code rather than the generic 1, so a caller can
// tell, for example, a run that ended unsuccessfully from a client failure.
type StatusError struct {
Code int
Message string
}
func (e *StatusError) Error() string { return e.Message }
// WaitRunsUnsuccessful is the `pipelines wait` / `run --wait` exit status when
// every wait completed but at least one run ended failed, canceled or
// interrupted. Client failures (unknown run, connection, wait limit) exit 1.
const WaitRunsUnsuccessful = 2
+19 -7
View File
@@ -8,7 +8,7 @@ EXECUTE
provider-check Validate a provider/model with a tool-free response
run [name] [prompt] Fuzzy selection, multiline prompt, live inspector
runs List audited runs; --pipeline filters results
inspect <run-id> Inspect stages, outputs, errors and status
inspect <run-id> Compact run summary; --step N, --transcripts, --json for detail
wait <run-id> ... Block until runs finish, then report each (read-only)
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
@@ -74,14 +74,26 @@ Options: --url ws://127.0.0.1:8080/connect --json --help
Use pipelines help <command> for its flags. Names with spaces must be quoted.
Stage result format:
Model and agent stages accept a line-oriented result. The first non-empty line
is the declared outcome, followed by "# " sections. "# output" is required and
short (a JSON object carrying the next stage's data); additional sections are
free-form markdown evidence. The legacy {"outcome":...,"output":...} JSON
envelope remains accepted for compatibility.
A model stage writes markdown to output.md. Only "# outcome" is parsed: its
first non-blank line is exactly one of the stage's declared outcome words
(case-insensitive). "# handoff" is the short note the next stage receives;
everything else is free markdown evidence. Larger results go in public/.
# handoff
Changed a.go; tests pass. Review the retry path.
# outcome
done
Agents and scripts (no terminal): pass --yes and --json. Without a terminal the
CLI never opens a full-screen view or prompts; a missing --yes fails at once.
pipelines run "bug fix" "Fix the layout" --json --yes
pipelines wait <run-id> exit 0 succeeded, 2 a run failed/canceled/interrupted, 1 client error
pipelines inspect <run-id> compact summary (--step N, --transcripts, --json)
pipelines retry <run-id> --yes --json
Examples:
pipelines run "bug fix" "Fix the layout" --json
pipelines run "bug fix" "Fix the layout" --json --yes
pipelines run "bug fix" "Fix the layout" --model openai/gpt-5 --stage-model review=openai/o4 --json
Authoring examples — use only when the operator explicitly requested a definition change:
+269
View File
@@ -0,0 +1,269 @@
package cli
import (
"encoding/json"
"fmt"
"strings"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/turn"
)
// inspectHandoffCap bounds the final handoff the compact summary prints; the
// full text stays available with --step N or --json.
const inspectHandoffCap = 1500
// inspectSummary is the default, compact `pipelines inspect` view: a header,
// one line per step and the run's final handoff. It deliberately omits inputs,
// transcripts and full outputs, which --step N, --transcripts and --json show.
func inspectSummary(d *protocol.RunDetail) string {
var b strings.Builder
fmt.Fprintf(&b, "run %d · %s v%d · %s", d.ID, d.Name, d.Version, d.Status)
if outcome := strings.TrimSpace(d.Outcome); outcome != "" {
fmt.Fprintf(&b, " (%s)", outcome)
}
if elapsed := runElapsed(d.CreatedAt, d.FinishedAt); elapsed != "" {
b.WriteString(" · " + elapsed)
}
b.WriteString("\n")
if title := strings.TrimSpace(d.Title); title != "" && title != d.Name {
b.WriteString("title: " + title + "\n")
}
if d.Workspace != "" {
b.WriteString("workspace: " + d.Workspace + "\n")
}
if d.RetryOf > 0 {
fmt.Fprintf(&b, "retry of run %d (%s)\n", d.RetryOf, d.RetryMode)
}
if line := firstLine(d.Diagnostic); line != "" {
b.WriteString("diagnostic: " + line + "\n")
}
if len(d.Steps) > 0 {
b.WriteString("\nsteps:\n")
}
for _, step := range d.Steps {
b.WriteString(" " + stepLine(step) + "\n")
}
if next := waitingHint(d); next != "" {
b.WriteString("\n" + next + "\n")
}
if handoff := finalHandoff(d); handoff != "" {
b.WriteString("\nhandoff:\n" + indent(handoff) + "\n")
} else if preview := strings.TrimSpace(d.ResultPreview); preview != "" {
b.WriteString("\nresult: " + preview + "\n")
}
b.WriteString(fmt.Sprintf("\nMore: pipelines inspect %d --step N | --transcripts | --json\n", d.ID))
return b.String()
}
// stepLine is one step of the compact summary: sequence, stage, status,
// outcome, duration and the first diagnostic line.
func stepLine(step protocol.RunStep) string {
line := fmt.Sprintf("#%d %s · %s", step.Sequence, step.Stage, step.Status)
if outcome := strings.TrimSpace(step.Outcome); outcome != "" {
line += " (" + outcome + ")"
}
if step.StartedAt != "" {
if elapsed := runElapsed(step.StartedAt, step.FinishedAt); elapsed != "" {
line += " · " + elapsed
}
}
if diagnostic := firstLine(step.Diagnostic); diagnostic != "" {
line += " · " + diagnostic
}
return line
}
// inspectStep renders one step in full except for its transcript, which only
// --transcripts adds.
func inspectStep(d *protocol.RunDetail, sequence int, transcripts bool) (string, error) {
step, ok := findStep(d, sequence)
if !ok {
return "", fmt.Errorf("run %d has no step %d; pipelines inspect %d lists them", d.ID, sequence, d.ID)
}
var b strings.Builder
b.WriteString(stepLine(step) + "\n")
if step.Target != "" {
b.WriteString("next: " + step.Target + "\n")
}
if step.Model != "" {
b.WriteString("model: " + step.Provider + "/" + step.Model + "\n")
}
if step.SessionID != "" {
b.WriteString("session: " + step.SessionID + "\n")
}
if diagnostic := strings.TrimSpace(step.Diagnostic); diagnostic != "" {
b.WriteString("\ndiagnostic:\n" + indent(diagnostic) + "\n")
}
if markdown, ok := step.Output["markdown"].(string); ok && strings.TrimSpace(markdown) != "" {
b.WriteString("\noutput:\n" + indent(strings.TrimSpace(markdown)) + "\n")
} else if len(step.Output) > 0 {
data, _ := json.MarshalIndent(step.Output, "", " ")
b.WriteString("\noutput:\n" + indent(string(data)) + "\n")
}
if step.FileChanges != nil {
data, _ := json.Marshal(step.FileChanges)
b.WriteString("\nfile changes: " + string(data) + "\n")
}
for _, artifact := range step.Artifacts {
fmt.Fprintf(&b, "artifact: %s (%d bytes)\n", artifact.Name, artifact.SizeBytes)
}
if transcripts && strings.TrimSpace(step.Transcript) != "" {
b.WriteString("\ntranscript:\n" + indent(strings.TrimSpace(step.Transcript)) + "\n")
}
return b.String(), nil
}
// inspectTranscripts appends each step's transcript to the compact summary.
func inspectTranscripts(d *protocol.RunDetail) string {
var b strings.Builder
b.WriteString(inspectSummary(d))
for _, step := range d.Steps {
if transcript := strings.TrimSpace(step.Transcript); transcript != "" {
fmt.Fprintf(&b, "\ntranscript #%d %s:\n%s\n", step.Sequence, step.Stage, indent(transcript))
}
}
return b.String()
}
func findStep(d *protocol.RunDetail, sequence int) (protocol.RunStep, bool) {
for _, step := range d.Steps {
if step.Sequence == sequence {
return step, true
}
}
return protocol.RunStep{}, false
}
// finalHandoff is the bounded `# handoff` of the last step that wrote one.
func finalHandoff(d *protocol.RunDetail) string {
for i := len(d.Steps) - 1; i >= 0; i-- {
markdown, _ := d.Steps[i].Output["markdown"].(string)
if section, ok := turn.HandoffSection(markdown); ok {
return bounded(section, inspectHandoffCap)
}
}
return ""
}
// waitingHint tells an agent how to answer a run parked on a human stage.
func waitingHint(d *protocol.RunDetail) string {
if d.Status != protocol.RunStatusWaiting || d.ExportPendingSequence > 0 {
return ""
}
stage := strings.TrimSpace(d.CurrentStage)
var options []string
var prompt string
for i := len(d.Steps) - 1; i >= 0; i-- {
if d.Steps[i].Status == protocol.RunStatusWaiting || (stage != "" && d.Steps[i].Stage == stage) {
options = protocol.WaitingOptions(d.Steps[i].Output)
prompt = protocol.WaitingPrompt(d.Steps[i].Output)
if stage == "" {
stage = d.Steps[i].Stage
}
break
}
}
option := "KEY"
if len(options) > 0 {
option = strings.Join(options, "|")
}
line := fmt.Sprintf("run %d waiting at %s — answer with: pipelines decide %d --option %s [--feedback TEXT]", d.ID, stage, d.ID, option)
if prompt = firstLine(prompt); prompt != "" {
line += "\n question: " + prompt
}
return line
}
// failureDetail is the stage an unsuccessful run stopped at and the first line
// of its diagnostic; both are empty for a run that has not failed.
func failureDetail(d *protocol.RunDetail) (stage, diagnostic string) {
if d.Status != "failed" && d.Status != protocol.RunStatusCanceled && d.Status != "interrupted" {
return "", ""
}
for i := len(d.Steps) - 1; i >= 0; i-- {
if d.Steps[i].Status == "failed" || strings.TrimSpace(d.Steps[i].Diagnostic) != "" {
stage, diagnostic = d.Steps[i].Stage, firstLine(d.Steps[i].Diagnostic)
break
}
}
if stage == "" {
stage = strings.TrimSpace(d.CurrentStage)
}
if line := firstLine(d.Diagnostic); line != "" {
diagnostic = line
}
return stage, diagnostic
}
// failureNote names the failing stage and its first diagnostic line.
func failureNote(d *protocol.RunDetail) string {
stage, diagnostic := failureDetail(d)
switch {
case stage != "" && diagnostic != "":
return "failed at " + stage + ": " + diagnostic
case stage != "":
return "failed at " + stage
}
return diagnostic
}
func firstLine(text string) string {
for _, line := range strings.Split(text, "\n") {
if line = strings.TrimSpace(line); line != "" {
return bounded(line, 240)
}
}
return ""
}
func bounded(text string, limit int) string {
if len(text) <= limit {
return text
}
cut := limit
for cut > 0 && !utf8.RuneStart(text[cut]) {
cut--
}
return text[:cut] + "…"
}
func indent(text string) string {
return " " + strings.ReplaceAll(text, "\n", "\n ")
}
// inspect prints a run: the compact summary by default, one step with --step,
// transcripts with --transcripts and the full RunDetail with --json.
func (a App) inspect(d *protocol.RunDetail, o *options) error {
if o.step < 0 {
return fmt.Errorf("--step must be a positive step sequence")
}
if o.json {
if o.step > 0 {
step, ok := findStep(d, o.step)
if !ok {
return fmt.Errorf("run %d has no step %d", d.ID, o.step)
}
if !o.transcripts {
step.Transcript = ""
}
return a.output(step)
}
return a.output(d)
}
text := ""
switch {
case o.step > 0:
var err error
if text, err = inspectStep(d, o.step, o.transcripts); err != nil {
return err
}
case o.transcripts:
text = inspectTranscripts(d)
default:
text = inspectSummary(d)
}
_, err := fmt.Fprint(a.Out, text)
return err
}
+15 -10
View File
@@ -3,12 +3,14 @@ package cli_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"path/filepath"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/cli"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
@@ -49,8 +51,8 @@ func seedRunIn(t *testing.T, store *pipeline.Store, key, workspace string) int64
return id
}
// A run that finished unsuccessfully is still a finished run: one line is
// printed for it and the command exits 0.
// A run that finished unsuccessfully is still reported with one line naming
// its failure, and the wait exits with the distinct unsuccessful-run status 2.
func TestCLIWaitReportsTerminalRunWithoutFailing(t *testing.T) {
run, store, _ := setup(t)
ctx := context.Background()
@@ -59,13 +61,14 @@ func TestCLIWaitReportsTerminalRunWithoutFailing(t *testing.T) {
t.Fatal(err)
}
output, err := run("wait", fmt.Sprint(id), "--timeout", "5s")
if err != nil {
t.Fatalf("a failed run must not fail the wait: %v", err)
var status *cli.StatusError
if !errors.As(err, &status) || status.Code != cli.WaitRunsUnsuccessful {
t.Fatalf("a failed run must exit %d: %v", cli.WaitRunsUnsuccessful, err)
}
t.Logf("pipelines wait %d:\n%s", id, strings.TrimSpace(output))
line := fmt.Sprintf("run %d · failed (error)", id)
if !strings.Contains(output, line) {
t.Fatalf("wait output missing %q:\n%s", line, output)
if !strings.Contains(output, line) || !strings.Contains(output, "boom") {
t.Fatalf("wait output missing %q and its diagnostic:\n%s", line, output)
}
}
@@ -105,8 +108,9 @@ func TestCLIWaitReportsEveryRunInABatch(t *testing.T) {
t.Fatal(err)
}
output, err := run("wait", fmt.Sprint(first), fmt.Sprint(second), "--timeout", "5s")
if err != nil {
t.Fatal(err)
var status *cli.StatusError
if !errors.As(err, &status) || status.Code != cli.WaitRunsUnsuccessful || !strings.Contains(err.Error(), fmt.Sprintf("run %d canceled", second)) {
t.Fatalf("a canceled run in the batch must exit %d: %v", cli.WaitRunsUnsuccessful, err)
}
for _, want := range []string{
fmt.Sprintf("run %d · succeeded (success)", first),
@@ -177,8 +181,9 @@ func TestCLIWaitJSONPrintsRunEnvelope(t *testing.T) {
t.Fatal(err)
}
output, err := run("wait", fmt.Sprint(id), "--json", "--timeout", "5s")
if err != nil {
t.Fatal(err)
var status *cli.StatusError
if !errors.As(err, &status) || status.Code != cli.WaitRunsUnsuccessful {
t.Fatalf("a failed run must exit %d: %v", cli.WaitRunsUnsuccessful, err)
}
var envelope protocol.Message
if err := json.Unmarshal([]byte(output), &envelope); err != nil {
+6 -5
View File
@@ -44,7 +44,7 @@ func TestWaitLineReportsStatusOutcomeStageAndDuration(t *testing.T) {
}
// Every named run is reported, and a run that finished unsuccessfully is still
// a finished run: the wait exits 0 and says what happened.
// reported, but the wait exits with status 2 so a caller notices it.
func TestWaitReportsEachRunAndDoesNotFailOnUnsuccessfulRuns(t *testing.T) {
var out bytes.Buffer
app := App{Out: &out, Err: &out}
@@ -53,8 +53,9 @@ func TestWaitReportsEachRunAndDoesNotFailOnUnsuccessfulRuns(t *testing.T) {
3: runMessage(3, "failed", "error", "worker", "2026-10-09T00:00:00Z", "2026-10-09T00:00:09Z"),
}
call := func(request protocol.Message) (protocol.Message, error) { return done[request.RunID], nil }
if err := app.wait(context.Background(), []string{"2", "3"}, &options{}, call); err != nil {
t.Fatalf("a finished failed run must not fail the wait: %v", err)
var status *StatusError
if err := app.wait(context.Background(), []string{"2", "3"}, &options{}, call); !errors.As(err, &status) || status.Code != WaitRunsUnsuccessful || !strings.Contains(err.Error(), "run 3 failed") {
t.Fatalf("a finished failed run must exit %d: %v", WaitRunsUnsuccessful, err)
}
text := out.String()
for _, want := range []string{
@@ -160,8 +161,8 @@ func TestWaitJSONPrintsFinalRunEnvelope(t *testing.T) {
}
var many bytes.Buffer
if err := (App{Out: &many, Err: &many}).wait(context.Background(), []string{"2", "3"}, &options{json: true}, call); err != nil {
t.Fatal(err)
if err := (App{Out: &many, Err: &many}).wait(context.Background(), []string{"2", "3"}, &options{json: true}, call); !errors.As(err, new(*StatusError)) {
t.Fatalf("a failed run in --json mode must still exit non-zero: %v", err)
}
var envelopes []protocol.Message
if err := json.Unmarshal(many.Bytes(), &envelopes); err != nil {