diff --git a/cmd/pipelines/main.go b/cmd/pipelines/main.go index bd505a47..baf0ffbd 100644 --- a/cmd/pipelines/main.go +++ b/cmd/pipelines/main.go @@ -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) } } diff --git a/examples/catalog_test.go b/examples/catalog_test.go index 01eeaf8d..fb5c515f 100644 --- a/examples/catalog_test.go +++ b/examples/catalog_test.go @@ -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) { diff --git a/examples/task.md b/examples/task.md index b0c7aae6..f7391fd6 100644 --- a/examples/task.md +++ b/examples/task.md @@ -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 ``` diff --git a/internal/author/skill/SKILL.md b/internal/author/skill/SKILL.md index 841e52d2..373158b2 100644 --- a/internal/author/skill/SKILL.md +++ b/internal/author/skill/SKILL.md @@ -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 ""`, and inspect it with -`pipelines inspect `. +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 "" --json --yes` (prints the run id), +and inspect it with `pipelines inspect `: 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 ` 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 --json` and act on it: land, retry, or fix and report. +`pipelines inspect ` 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 --option KEY`, the user's choice only). A run started from a repository's main checkout runs in its own worktree (`-runs/...`, branch `pipelines/run-...`); a failed run keeps that tree and -its commits. Read `pipelines inspect --json` before deciding: resume the -failed stage (`pipelines retry `; `--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 ` before deciding: resume the +failed stage (`pipelines retry --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 @@ -77,9 +90,11 @@ only when asked). Stage use: `references/format.md`. ## In a Pipelines chat A chat's agent has a `pipelines` MCP server: `show_file`, `show_image`, -`show_html` (follows the light/dark theme when it styles for dark), `show_diff` (show the +`show_html` (follows the light/dark theme when it styles for dark; its result warns about blocked scripts or remote resources), `show_diff` (show the operator changes, e.g. before a pull request; `head`, `paths`), `show_run` (a -live run card), `schedule_followup` (come back to this chat later) and `notify` +live run card), `schedule_followup` (come back to this chat at a time, or when a +run finishes or needs the operator: `run_id` with `on`; returns an id for +`cancel_followup`) and `notify` (every Pipelines app the operator is signed in to plus their phone; cleared everywhere once they read it or open the chat). Pipelines already notifies when a reply ends or the agent asks something, so `notify` is only for news mid-turn diff --git a/internal/author/skill/references/chat.md b/internal/author/skill/references/chat.md index bb05eeb4..030393da 100644 --- a/internal/author/skill/references/chat.md +++ b/internal/author/skill/references/chat.md @@ -21,10 +21,11 @@ regenerate, or a file you rewrote. | --- | --- | --- | | `show_file` | `path`, `title?`, `replace?` | Any file the operator should see: images inline, other files as a preview card. Use instead of naming a path. A file up to 5 MiB is copied when shown, so the card keeps that version; a larger one stays linked and its card says "changed since shown" or "no longer exists". | | `show_image` | `url_or_path`, `title?`, `alt?`, `replace?` | A home `image/*` file, or an `https://` URL that Pipelines downloads and keeps (public hosts only, PNG/JPEG/GIF/WebP/AVIF/BMP, at most 10 MiB, no credentials, no redirect to plain http). A failed download is an error and nothing is shown. | -| `show_html` | `html`, `title?`, `height_hint?` (120-600), `replace?` | Self-contained HTML/SVG: diagrams, charts, tables. Sandboxed: no JavaScript, no network; inline CSS/SVG, `
`, `:hover`. Follows the operator's light/dark theme only when it declares dark support: `@media (prefers-color-scheme: dark)`, `color-scheme` or `light-dark()`; anything else is always shown light, on white. Refused above 512 KiB. | +| `show_html` | `html`, `title?`, `height_hint?` (120-600), `replace?` | Self-contained HTML/SVG: diagrams, charts, tables. Sandboxed: no JavaScript, no network; inline CSS/SVG, `
`, `:hover`. Follows the operator's light/dark theme only when it declares dark support: `@media (prefers-color-scheme: dark)`, `color-scheme` or `light-dark()`; anything else is always shown light, on white. The result warns when the document has scripts or loads remote resources (both blocked) or lacks dark support; fix and `replace`. Refused above 512 KiB. | | `show_diff` | `path?`, `base?`, `head?`, `paths?`, `committed_only?`, `title?`, `replace?` | A Git diff card when the operator asks to see the changes, or before submitting a pull request. No `base`: uncommitted work (staged, unstaged, untracked) against HEAD. `base` (e.g. `main`): everything since the merge base, which is what a PR contains, plus uncommitted work unless `committed_only`. `head` (e.g. `pipelines/run-123`): that revision instead of the work tree, against `base` or HEAD. `paths`: repository-relative files, directories or globs (`*.go`), at most 50. Pipelines runs Git; do not paste the diff. | | `show_run` | `run_id`, `title?`, `replace?` | A live card for a run: pipeline, title, status, current stage, duration; it updates as the run progresses and opens the run when tapped. | -| `schedule_followup` | `message`, `at?` or `after_minutes?` | Queue a prompt to yourself in this chat, 1 minute to 7 days ahead (`at` is RFC 3339). It is a scheduled message from "Agent follow-up" the operator can remove; it does not hold the operator's own messages back, and is delivered when the chat is free at that time. At most 3 pending per chat. Do not wait for it in the current turn. | +| `schedule_followup` | `message`, and `at?` or `after_minutes?`, or `run_id?` with `on?` | Queue a prompt to yourself in this chat: 1 minute to 7 days ahead (`at` is RFC 3339), or when run `run_id` reaches `on`: `finished` (default; it ended) or `attention` (it waits on a human decision, or ended), delivered after 7 days at the latest with the run's state appended. A run that already meets `on` is refused (act on it now). It is a scheduled message from "Agent follow-up" the operator can remove; it does not hold the operator's own messages back, and is delivered when the chat is free. At most 3 pending per chat. The result names the follow-up id and lists the pending ones. Do not wait for it in the current turn. | +| `cancel_followup` | `id` | Remove one of this chat's undelivered follow-ups by the id `schedule_followup` returned; the result lists those still pending. | | `notify` | `title`, `message`, `priority?` | A notification on every Pipelines app the operator is signed in to (web tabs, desktop, Android) and their phone (ntfy); a tap opens this chat. Opening the chat, or tapping or dismissing it on any device, clears it on all of them. Pipelines already notifies when the reply ends and for questions and approvals, so use it only for news mid-turn or after background work the turn does not wait for; a turn that notified sends no separate "replied" notification. 5 per minute per chat; the result says where it went, and undelivered sends report why. | `show_diff` lists at most 300 files; a file patch over 256 KiB or a total over @@ -43,10 +44,13 @@ authoritative record before acting. ## Questions and approvals -Claude Code questions appear as a form. The operator may pick an option, answer -in their own words, or dismiss it; a dismissal arrives as a denial saying they -will reply in the chat, so wait for that message. Question text, descriptions -and option descriptions render Markdown. +A question the agent asks appears as a form on every harness: Claude Code's +AskUserQuestion, OpenCode's question tool, and Codex's request for user input +(and MCP elicitations). The operator may pick an option, answer in their own +words, or dismiss it. On Claude Code a dismissal arrives as a denial saying +they will reply in the chat; on OpenCode, and for Codex elicitations, it cancels the question. +Either way, wait for their message. Question text, descriptions and option +descriptions render Markdown. ## Chat protocol (via `pipelines rpc -`) diff --git a/internal/author/skill/references/debugging.md b/internal/author/skill/references/debugging.md index eadff6ad..f682c1d0 100644 --- a/internal/author/skill/references/debugging.md +++ b/internal/author/skill/references/debugging.md @@ -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. diff --git a/internal/author/skill/references/operations.md b/internal/author/skill/references/operations.md index f9330feb..64d5e981 100644 --- a/internal/author/skill/references/operations.md +++ b/internal/author/skill/references/operations.md @@ -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; diff --git a/internal/author/skill/references/orchestration.md b/internal/author/skill/references/orchestration.md index d96e386e..edb0cc80 100644 --- a/internal/author/skill/references/orchestration.md +++ b/internal/author/skill/references/orchestration.md @@ -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. diff --git a/internal/chattools/mcp_test.go b/internal/chattools/mcp_test.go index 3f05c749..8451ec06 100644 --- a/internal/chattools/mcp_test.go +++ b/internal/chattools/mcp_test.go @@ -75,7 +75,7 @@ func TestHandshakeListAndCall(t *testing.T) { t.Fatalf("tool without description or schema: %v", entry) } } - if strings.Join(names, ",") != "show_file,show_image,show_html,show_diff,notify,show_run,schedule_followup" { + if strings.Join(names, ",") != "show_file,show_image,show_html,show_diff,notify,show_run,schedule_followup,cancel_followup" { t.Fatalf("tools = %v", names) } if list["id"] != "l" { diff --git a/internal/chattools/tools.go b/internal/chattools/tools.go index bab5060d..36d74ae0 100644 --- a/internal/chattools/tools.go +++ b/internal/chattools/tools.go @@ -10,6 +10,8 @@ const ( ToolNotify = "notify" // ToolScheduleFollowup queues a prompt into the calling chat for later. ToolScheduleFollowup = "schedule_followup" + // ToolCancelFollowup removes a follow-up this chat scheduled. + ToolCancelFollowup = "cancel_followup" ) // MaxHTMLBytes bounds one show_html document. A larger one is refused, never @@ -29,12 +31,16 @@ const ( MaxFollowupMinutes = 7 * 24 * 60 MaxPendingFollowups = 3 MaxFollowupTextBytes = 8 << 10 + // A run-triggered follow-up (run_id with on) is delivered when the run + // reaches the condition, or after MaxFollowupMinutes at the latest. + FollowupOnFinished = "finished" + FollowupOnAttention = "attention" ) // IsTool reports whether name is one of the Pipelines tools. func IsTool(name string) bool { switch name { - case ToolShowFile, ToolShowImage, ToolShowHTML, ToolShowDiff, ToolShowRun, ToolNotify, ToolScheduleFollowup: + case ToolShowFile, ToolShowImage, ToolShowHTML, ToolShowDiff, ToolShowRun, ToolNotify, ToolScheduleFollowup, ToolCancelFollowup: return true } return false @@ -48,7 +54,7 @@ const Instructions = "These tools act on Pipelines, the app the operator reads t "Pipelines already notifies them when your reply ends and when you ask a question or need an approval, so do not notify for those " + "(a notify replaces this turn's end-of-reply notification). It reaches every Pipelines app they are signed in to and their phone, " + "and clears everywhere once they open the chat. " + - "Use show_run to follow a pipeline run live in the chat, and schedule_followup to come back to this chat later (for example to check on a run). " + + "Use show_run to follow a pipeline run live in the chat, and schedule_followup to come back to this chat later (at a time, or when a run finishes or needs the operator; cancel_followup removes one). " + "Every show_* result names the shown item's id: pass it as replace to update that card instead of adding another. " + "Your thinking is not shown to the operator: before asking them a question (for example with AskUserQuestion), " + "write what you found and why you are asking as a normal message, because the question form shows only the question and its options." @@ -182,14 +188,29 @@ func definitions() []toolDefinition { { Name: ToolScheduleFollowup, Title: "Schedule a follow-up in this chat", - Description: "Queue a message to yourself in this chat, delivered as a new prompt at a later time (for example to check on a long run). " + - "The operator sees it in the chat as a scheduled message from the agent and can remove it. " + - "Give at (an RFC 3339 time) or after_minutes, between 1 minute and 7 days from now. At most 3 follow-ups can be pending per chat. " + - "It is delivered when the chat is free at that time, so do not wait for it in the current turn.", + Description: "Queue a message to yourself in this chat, delivered as a new prompt later: at a time (at, an RFC 3339 time, or after_minutes, " + + "between 1 minute and 7 days from now), or when a pipeline run reaches a state (run_id with on: finished when it ends, " + + "attention when it waits on the operator's decision or ends, whichever is first; delivered after 7 days at the latest). " + + "The operator sees it in the chat as a scheduled message from the agent and can remove it. At most 3 follow-ups can be pending per chat. " + + "It is delivered when the chat is free, so do not wait for it in the current turn. " + + "The result names the follow-up's id (for cancel_followup) and lists the chat's pending follow-ups.", InputSchema: objectSchema([]string{"message"}, map[string]any{ "message": stringProperty("What the follow-up prompt should say: enough for you to know what to do then."), - "at": stringProperty("When to deliver it, as an RFC 3339 time such as 2026-05-01T09:30:00Z. Give this or after_minutes."), - "after_minutes": map[string]any{"type": "integer", "description": "Minutes from now to deliver it (1-10080). Give this or at."}, + "at": stringProperty("When to deliver it, as an RFC 3339 time such as 2026-05-01T09:30:00Z. Give this, after_minutes, or run_id."), + "after_minutes": map[string]any{"type": "integer", "description": "Minutes from now to deliver it (1-10080). Give this, at, or run_id."}, + "run_id": map[string]any{"type": "integer", "description": "Deliver it when this pipeline run reaches on, instead of at a time."}, + "on": map[string]any{"type": "string", "enum": []string{FollowupOnFinished, FollowupOnAttention}, + "description": "With run_id: finished (the run ended: succeeded, failed, canceled or interrupted) or attention (it waits on a human decision, or ended). Default finished."}, + }), + Annotations: map[string]any{"readOnlyHint": false, "destructiveHint": false, "openWorldHint": false}, + }, + { + Name: ToolCancelFollowup, + Title: "Cancel a follow-up in this chat", + Description: "Remove a follow-up this chat scheduled with schedule_followup and that has not been delivered yet. " + + "The result lists the follow-ups still pending.", + InputSchema: objectSchema([]string{"id"}, map[string]any{ + "id": stringProperty("The follow-up's id, from the schedule_followup result."), }), Annotations: map[string]any{"readOnlyHint": false, "destructiveHint": false, "openWorldHint": false}, }, diff --git a/internal/chattools/validate_test.go b/internal/chattools/validate_test.go index 0cdad2d6..5974de0a 100644 --- a/internal/chattools/validate_test.go +++ b/internal/chattools/validate_test.go @@ -27,6 +27,10 @@ func TestValidateArgumentsRefusesUnknownAndMistypedFields(t *testing.T) { {ToolNotify, `{"title":"t","message":"m","priority":"urgent"}`, "priority must be one of low, default, high"}, {ToolScheduleFollowup, `{"message":"m","after_minutes":5}`, ""}, {ToolScheduleFollowup, `{"message":"m","in_minutes":5,"delay":1}`, `unknown arguments "delay", "in_minutes"`}, + {ToolScheduleFollowup, `{"message":"m","run_id":7,"on":"attention"}`, ""}, + {ToolScheduleFollowup, `{"message":"m","run_id":7,"on":"done"}`, "on must be one of finished, attention"}, + {ToolCancelFollowup, `{"id":"followup-1"}`, ""}, + {ToolCancelFollowup, `{}`, "id is required"}, } for _, c := range cases { err := ValidateArguments(c.tool, json.RawMessage(c.args)) diff --git a/internal/claude/hosted_tasks.go b/internal/claude/hosted_tasks.go index 0100b618..b4ff1ac6 100644 --- a/internal/claude/hosted_tasks.go +++ b/internal/claude/hosted_tasks.go @@ -1,8 +1,14 @@ package claude import ( + "bufio" "bytes" "encoding/json" + "io" + "os" + "path/filepath" + "strings" + "git.a-wan.net/alan/pipelines/internal/claudehost" "git.a-wan.net/alan/pipelines/internal/protocol" ) @@ -14,10 +20,14 @@ func (s *session) reconcileHostTasks(tasks *[]claudehost.Task) { if tasks == nil { return } + finished := s.finishedHostTasks(*tasks) s.mu.Lock() present := make(map[string]bool, len(*tasks)) var frames []protocol.ChatShell for _, task := range *tasks { + if finished[task.ToolUseID] { + continue + } id := task.ToolUseID if id == "" && task.TaskID != "" { id = "task:" + task.TaskID @@ -109,3 +119,129 @@ func (s *session) resolveHostedTaskLine(line []byte) []byte { } return normalized } + +// finishedHostTasks checks host-reported tasks the CLI never identified (no +// native task id) against the session's transcripts, the main one and every +// subagent's. Hosts built before launch detection was strict count a +// foreground Bash whose output merely quotes "running in background with ID" +// (a subagent reading fake-claude.py, say) as a background task, and keep a +// subagent's background command whose completion preceded its launch result; +// neither ever ends. A tool call whose result is not a launch acknowledgement, +// or whose completion notification is recorded, is finished. +func (s *session) finishedHostTasks(tasks []claudehost.Task) map[string]bool { + wanted := map[string]bool{} + for _, task := range tasks { + if task.TaskID == "" && task.ToolUseID != "" { + wanted[task.ToolUseID] = true + } + } + if len(wanted) == 0 { + return nil + } + path := findTranscriptFile(s.id) + if path == "" { + return nil + } + files := []string{path} + if agents, err := filepath.Glob(filepath.Join(strings.TrimSuffix(path, ".jsonl"), "subagents", "*.jsonl")); err == nil { + files = append(files, agents...) + } + finished := map[string]bool{} + for _, file := range files { + scanFinishedToolCalls(file, wanted, finished) + if len(finished) == len(wanted) { + break + } + } + return finished +} + +// scanFinishedToolCalls reads the newest maxTranscriptBytes of one transcript +// and marks each wanted tool call that finished there. Errors only end the scan. +func scanFinishedToolCalls(path string, wanted, finished map[string]bool) { + file, err := os.Open(path) + if err != nil { + return + } + defer file.Close() + partial := false + if info, err := file.Stat(); err == nil && info.Size() > maxTranscriptBytes { + if _, err := file.Seek(info.Size()-maxTranscriptBytes, io.SeekStart); err != nil { + return + } + partial = true + } + scanner := bufio.NewScanner(&io.LimitedReader{R: file, N: maxTranscriptBytes}) + scanner.Buffer(make([]byte, 0, 64<<10), maxLineBytes) + resultMarker := []byte(`"tool_result"`) + noticeMarker := []byte("") + for scanner.Scan() { + line := scanner.Bytes() + if partial { + partial = false // the first line read from mid-file is a fragment + continue + } + if bytes.Contains(line, resultMarker) { + var entry transcriptEntry + parsed := false + for id := range wanted { + if finished[id] || !bytes.Contains(line, []byte(id)) { + continue + } + if !parsed { + if json.Unmarshal(line, &entry) != nil { + break + } + parsed = true + } + for _, block := range decodeBlocks(entry.Message.Content) { + if block.Type != "tool_result" || block.ToolUseID != id { + continue + } + if text, _ := toolResultContent(block.Content); !launchedInBackground(text) { + finished[id] = true + } + } + } + continue + } + if bytes.Contains(line, noticeMarker) { + for id := range wanted { + if !finished[id] && bytes.Contains(line, []byte(""+id+"")) { + finished[id] = true + } + } + } + } +} + +// settleUnlistedTasks applies the CLI's background_tasks_changed event: the +// complete set of background tasks still running, subagents' included. A +// tracked task with a native id the CLI no longer lists has ended. +func (s *session) settleUnlistedTasks(line []byte) { + var event struct { + Tasks []struct { + TaskID string `json:"task_id"` + } `json:"tasks"` + } + if json.Unmarshal(line, &event) != nil { + return + } + listed := make(map[string]bool, len(event.Tasks)) + for _, task := range event.Tasks { + listed[task.TaskID] = true + } + var frames []protocol.ChatShell + s.mu.Lock() + for _, snapshot := range s.shells { + if snapshot.taskID == "" || listed[snapshot.taskID] || snapshot.shell.Status != protocol.ChatShellRunning { + continue + } + snapshot.shell.Status = protocol.ChatShellExited + frames = append(frames, snapshot.shell) + } + s.mu.Unlock() + for i := range frames { + s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: &frames[i]}) + } +} diff --git a/internal/claude/phantom_tasks_test.go b/internal/claude/phantom_tasks_test.go new file mode 100644 index 00000000..581854c4 --- /dev/null +++ b/internal/claude/phantom_tasks_test.go @@ -0,0 +1,124 @@ +package claude + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/claudehost" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// Seen live: a subagent's foreground `sed -n 1,230p fake-claude.py` printed +// the fixture's "Command running in background with ID" line, so the host +// listed it as a background task forever ("Running 1d 20h, no output yet"). +// The fake CLI streams a background subagent whose own calls (that sed, and a +// background command completed before its launch result) are sidechain lines. +func TestSubagentToolCallsAreNotOperatorBackgroundTasks(t *testing.T) { + fixture := hostedSetup(t) + first := hostedChat(t) + session := newCreatedChat(t, first) + frames := subscribe(t, first, session.ID) + if err := first.Prompt(context.Background(), session.ID, "subagent please"); err != nil { + t.Fatal(err) + } + waitStepEnded(t, frames) + onlyAgent := func(shells []protocol.ChatShell, err error) bool { + return err == nil && len(shells) == 1 && shells[0].ID == shellID("toolu_agent_fake") + } + if shells, err := first.Shells(context.Background(), session.ID); !onlyAgent(shells, err) { + t.Fatalf("the background agent alone is running: %+v %v", shells, err) + } + record := onlyRecord(t, fixture) + first.Detach() + control, status, err := claudehost.Attach(record.Socket, 0, hostAttachTimeout) + if err != nil { + t.Fatal(err) + } + _ = control.Close() + if status.Tasks == nil || len(*status.Tasks) != 1 || (*status.Tasks)[0].ToolUseID != "toolu_agent_fake" { + t.Fatalf("host lists subagent tool calls as running tasks: %+v", status.Tasks) + } + second := hostedChat(t) + if shells, err := second.Shells(context.Background(), session.ID); !onlyAgent(shells, err) { + t.Fatalf("reattached task list changed: %+v %v", shells, err) + } + frames = subscribe(t, second, session.ID) + if err := second.Prompt(context.Background(), session.ID, "agent-done"); err != nil { + t.Fatal(err) + } + waitStepEnded(t, frames) + if shells, err := second.Shells(context.Background(), session.ID); err != nil || len(shells) != 0 { + t.Fatalf("finished agent still listed: %+v %v", shells, err) + } +} + +// Hosts already running an older build keep phantom entries (no native task +// id). Reattaching settles each from the transcripts — the main one and the +// subagents' — while a genuine background command still shows until it ends. +func TestReattachSettlesLegacyPhantomTasksFromTranscripts(t *testing.T) { + config := t.TempDir() + t.Setenv("CLAUDE_CONFIG_DIR", config) + chat, s := backgroundSession(t) + t.Cleanup(chat.Close) + project := filepath.Join(config, "projects", "-repo") + write := func(path string, lines ...string) { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil { + t.Fatal(err) + } + } + write(filepath.Join(project, s.id+".jsonl"), + `{"type":"assistant","isSidechain":false,"message":{"content":[{"type":"tool_use","id":"main-bg","name":"Bash","input":{"command":"sleep 600","run_in_background":true}}]}}`, + `{"type":"user","isSidechain":false,"message":{"content":[{"type":"tool_result","tool_use_id":"main-bg","content":"Command running in background with ID: b9. Output is being written to: /tmp/b9.output"}]}}`, + `{"type":"assistant","isSidechain":false,"message":{"content":[{"type":"tool_use","id":"main-cat","name":"Bash","input":{"command":"cat translate.go"}}]}}`, + `{"type":"user","isSidechain":false,"message":{"content":[{"type":"tool_result","tool_use_id":"main-cat","content":[{"type":"text","text":"func launched() {\n\treturn \"running in background with ID\"\n}"}]}]}}`, + ) + write(filepath.Join(project, s.id, "subagents", "agent-a1.jsonl"), + `{"type":"assistant","isSidechain":true,"message":{"content":[{"type":"tool_use","id":"sub-sed","name":"Bash","input":{"command":"sed -n 1,230p internal/claude/testdata/fake-claude.py"}}]}}`, + `{"type":"user","isSidechain":true,"message":{"content":[{"type":"tool_result","tool_use_id":"sub-sed","content":"#!/usr/bin/env python3\n\"content\": \"Command running in background with ID: b1.\""}]}}`, + `{"type":"user","isSidechain":true,"message":{"content":[{"type":"tool_result","tool_use_id":"sub-xvfb","content":"Command running in background with ID: bz. Output is being written to: /tmp/bz.output"}]}}`, + `{"type":"attachment","isSidechain":true,"attachment":{"type":"queued_command","prompt":"\nbz\nsub-xvfb\ncompleted\n"}}`, + ) + legacy := []claudehost.Task{ + {ToolUseID: "main-bg", Name: "Bash", Command: "sleep 600"}, + {ToolUseID: "main-cat", Name: "Bash", Command: "cat translate.go"}, + {ToolUseID: "sub-sed", Name: "Bash", Command: "sed -n 1,230p internal/claude/testdata/fake-claude.py"}, + {ToolUseID: "sub-xvfb", Name: "Bash", Command: "Xvfb :99 &"}, + } + s.reconcileHostTasks(&legacy) + shells := running(t, chat) + if len(shells) != 1 || shells[0].ID != shellID("main-bg") { + t.Fatalf("only the genuine background command is running: %+v", shells) + } +} + +func TestBackgroundTasksChangedSettlesUnlistedTasks(t *testing.T) { + chat, s := backgroundSession(t) + t.Cleanup(chat.Close) + for _, id := range []string{"a", "b"} { + s.handleLine(nil, toolUse(t, "tool-"+id, "Bash", map[string]any{"command": "sleep 600", "run_in_background": true})) + s.handleLine(nil, []byte(`{"type":"system","subtype":"task_started","task_id":"native-`+id+`","tool_use_id":"tool-`+id+`"}`)) + s.handleLine(nil, toolResult(t, "tool-"+id, "Command running in background with ID: native-"+id)) + } + s.handleLine(nil, []byte(`{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"native-b"}]}`)) + if shells := running(t, chat); len(shells) != 1 || shells[0].ID != shellID("tool-b") { + t.Fatalf("unlisted task still running: %+v", shells) + } +} + +// A foreground subagent's report (its tool_result) may quote a launch +// acknowledgement; only the result's first line acknowledges a launch. +func TestForegroundAgentReportQuotingLaunchFinishes(t *testing.T) { + chat, s := backgroundSession(t) + t.Cleanup(chat.Close) + s.handleLine(nil, toolUse(t, "sync-agent", "Agent", map[string]any{"description": "Review"})) + s.handleLine(nil, toolResult(t, "sync-agent", "Root cause: the host matched\n\"Command running in background with ID\" anywhere in output.")) + if shells := running(t, chat); len(shells) != 0 { + t.Fatalf("finished foreground agent still running: %+v", shells) + } +} diff --git a/internal/claude/testdata/fake-claude.py b/internal/claude/testdata/fake-claude.py index 5f04cb95..2bef1bb9 100644 --- a/internal/claude/testdata/fake-claude.py +++ b/internal/claude/testdata/fake-claude.py @@ -76,6 +76,13 @@ def user_message(text): if "gate" in text: gated(message_id) return + if "subagent" in text: + subagent(message_id) + return + if "agent-done" in text: + send({"type": "system", "subtype": "task_notification", "task_id": "afake", + "tool_use_id": "toolu_agent_fake", "status": "completed", "summary": "Agent finished"}) + send({"type": "system", "subtype": "background_tasks_changed", "tasks": []}) if "background" in text: background(message_id) return @@ -191,6 +198,57 @@ def background(message_id): finish(message_id) +def subagent(message_id): + """Launches a background subagent whose own tool calls stream as a sidechain + (parent_tool_use_id), as Claude Code 2.1 sends them: a foreground Bash whose + output quotes a background acknowledgement mid-text, and a background Bash + the CLI reports complete before the tool_result acknowledging its launch. + Neither is the operator's background task; only the agent is, until a later + "agent-done" turn ends it.""" + agent = "toolu_agent_fake" + send({"type": "assistant", "message": {"id": message_id, "role": "assistant", "model": "claude-test", "content": [ + {"type": "tool_use", "id": agent, "name": "Agent", + "input": {"description": "Investigate", "prompt": "look", "run_in_background": True}}]}}) + send({"type": "system", "subtype": "task_started", "task_id": "afake", "tool_use_id": agent, + "description": "Investigate", "task_type": "local_agent", "is_backgrounded": True}) + send({"type": "user", "message": {"role": "user", "content": [ + {"type": "tool_result", "tool_use_id": agent, "content": "Async agent launched successfully.\nagentId: afake"}]}}) + send({"type": "system", "subtype": "background_tasks_changed", + "tasks": [{"task_id": "afake", "task_type": "local_agent"}]}) + sidechain = [] + sed = "toolu_sub_sed" + sidechain.append({"type": "assistant", "message": {"id": "msg_sub_1", "role": "assistant", "model": "claude-test", "content": [ + {"type": "tool_use", "id": sed, "name": "Bash", "input": {"command": "sed -n 1,230p internal/claude/testdata/fake-claude.py"}}]}}) + sidechain.append({"type": "user", "message": {"role": "user", "content": [ + {"type": "tool_result", "tool_use_id": sed, "content": + "#!/usr/bin/env python3\n block = {\"content\": \"Command running in background with ID: b1. Output is being written to: /tmp/b1.output\"}\n"}]}}) + xvfb = "toolu_sub_xvfb" + sidechain.append({"type": "assistant", "message": {"id": "msg_sub_2", "role": "assistant", "model": "claude-test", "content": [ + {"type": "tool_use", "id": xvfb, "name": "Bash", "input": {"command": "Xvfb :99 &", "run_in_background": True}}]}}) + for entry in sidechain: + send(dict(entry, parent_tool_use_id=agent)) + send({"type": "system", "subtype": "task_started", "task_id": "bz", "tool_use_id": xvfb, + "owned_by_subagent": True, "is_backgrounded": True, "task_type": "local_bash"}) + send({"type": "system", "subtype": "background_tasks_changed", + "tasks": [{"task_id": "afake", "task_type": "local_agent"}, {"task_id": "bz", "task_type": "local_bash"}]}) + send({"type": "system", "subtype": "task_notification", "task_id": "bz", "tool_use_id": xvfb, + "owned_by_subagent": True, "status": "completed", "summary": "Background command completed"}) + send({"type": "system", "subtype": "background_tasks_changed", + "tasks": [{"task_id": "afake", "task_type": "local_agent"}]}) + ack = {"type": "user", "message": {"role": "user", "content": [ + {"type": "tool_result", "tool_use_id": xvfb, "content": "Command running in background with ID: bz. Output is being written to: /tmp/bz.output"}]}} + sidechain.append(ack) + send(dict(ack, parent_tool_use_id=agent)) + send({"type": "system", "subtype": "task_progress", "task_id": "bz", "tool_use_id": xvfb}) + # The CLI keeps each subagent's transcript beside the session's. + directory = os.path.join(transcript_path()[:-len(".jsonl")], "subagents") + os.makedirs(directory, exist_ok=True) + with open(os.path.join(directory, "agent-afake.jsonl"), "a", encoding="utf-8") as file: + for entry in sidechain: + file.write(json.dumps(dict(entry, isSidechain=True, agentId="afake", timestamp=stamp())) + "\n") + finish(message_id) + + def refused(message_id): """A turn refused for a usage limit, as Claude Code 2.1 ends one: a rejected rate_limit_event, a synthetic assistant API-error message and an is_error diff --git a/internal/claude/translate.go b/internal/claude/translate.go index 0d7c3d95..6de5fd67 100644 --- a/internal/claude/translate.go +++ b/internal/claude/translate.go @@ -138,6 +138,10 @@ func (s *session) handleLine(p *process, line []byte) { s.finishNotifiedTask(line) return } + if envelope.Subtype == "background_tasks_changed" { + s.settleUnlistedTasks(line) + return + } s.handleSystem(envelope) } } @@ -832,10 +836,10 @@ func agentLabel(input json.RawMessage) string { } // launchedInBackground recognises Claude Code's immediate result for a task -// that keeps running after its tool call returns. +// that keeps running after its tool call returns (its first line only: a +// foreground result may quote the acknowledgement anywhere). func launchedInBackground(text string) bool { - return strings.Contains(text, "running in background with ID") || - strings.HasPrefix(strings.TrimSpace(text), "Async agent launched") + return claudehost.LaunchedInBackground(text) } var ( diff --git a/internal/claudehost/host.go b/internal/claudehost/host.go index 44576bb7..dfed80c9 100644 --- a/internal/claudehost/host.go +++ b/internal/claudehost/host.go @@ -87,6 +87,8 @@ type host struct { // pending maps unanswered CLI control request ids to their offsets. tasks map[string]string // running native background tools, independent of foreground busy taskOrigins map[string]Task // native identity/metadata retained independently of spool compaction + taskCalls map[string]bool // Bash/Agent/Task tool calls still awaiting their tool_result + taskEnded map[string]bool // tool and native task ids already finished; late lines never revive them pending map[string]int64 initID string init json.RawMessage diff --git a/internal/claudehost/tasks.go b/internal/claudehost/tasks.go index 5ad13281..1a98f526 100644 --- a/internal/claudehost/tasks.go +++ b/internal/claudehost/tasks.go @@ -20,7 +20,10 @@ func (h *host) trackTasksLocked(line []byte) { Description string `json:"description"` TaskType string `json:"task_type"` Timestamp string `json:"timestamp"` - Message struct { + Tasks []struct { + TaskID string `json:"task_id"` + } `json:"tasks"` + Message struct { Content json.RawMessage `json:"content"` } `json:"message"` } @@ -33,6 +36,29 @@ func (h *host) trackTasksLocked(line []byte) { if h.taskOrigins == nil { h.taskOrigins = map[string]Task{} } + if h.taskCalls == nil || len(h.taskCalls) > maxTaskMarks { + h.taskCalls = map[string]bool{} + } + if h.taskEnded == nil || len(h.taskEnded) > maxTaskMarks { + h.taskEnded = map[string]bool{} + } + // end removes a finished tool call or native task for good: a progress + // line or a launch acknowledgement that arrives after its completion + // notification (the CLI does not order them) must not revive it. + end := func(key string) { + taskID := h.tasks[key] + delete(h.tasks, key) + delete(h.taskOrigins, key) + h.taskEnded[key] = true + if strings.HasPrefix(key, "task:") { + h.taskEnded[key[len("task:"):]] = true + } + if taskID != "" { + h.taskEnded[taskID] = true + delete(h.tasks, "task:"+taskID) + delete(h.taskOrigins, "task:"+taskID) + } + } switch event.Subtype { case "task_started", "task_progress": id := event.ToolUseID @@ -47,7 +73,7 @@ func (h *host) trackTasksLocked(line []byte) { id = "task:" + event.TaskID } } - if id != "task:" { + if id != "task:" && !h.taskEnded[id] && !(event.TaskID != "" && h.taskEnded[event.TaskID]) { if event.ToolUseID != "" && event.TaskID != "" { fallback := "task:" + event.TaskID if prior, exists := h.taskOrigins[fallback]; exists { @@ -83,10 +109,30 @@ func (h *host) trackTasksLocked(line []byte) { if event.Status == "completed" || event.Status == "failed" || event.Status == "stopped" { for key, task := range h.tasks { if key == event.ToolUseID || (event.TaskID != "" && (task == event.TaskID || key == "task:"+event.TaskID)) { - delete(h.tasks, key) - delete(h.taskOrigins, key) + end(key) } } + if event.ToolUseID != "" { + h.taskEnded[event.ToolUseID] = true + } + if event.TaskID != "" { + h.taskEnded[event.TaskID] = true + } + } + case "background_tasks_changed": + // The CLI's own list of every running background task (subagents' + // included). A task it no longer lists has ended, whatever we missed. + listed := make(map[string]bool, len(event.Tasks)) + for _, task := range event.Tasks { + listed[task.TaskID] = true + } + for key, taskID := range h.tasks { + if taskID == "" && strings.HasPrefix(key, "task:") { + taskID = key[len("task:"):] + } + if taskID != "" && !listed[taskID] { + end(key) + } } } if event.Type == "result" { @@ -107,21 +153,15 @@ func (h *host) trackTasksLocked(line []byte) { finishText := func(text string) { for _, match := range completedTaskNotice.FindAllStringSubmatch(text, -1) { - key := match[1] - taskID := h.tasks[key] - delete(h.tasks, key) - delete(h.taskOrigins, key) - if taskID != "" { - delete(h.tasks, "task:"+taskID) - delete(h.taskOrigins, "task:"+taskID) - } + end(match[1]) } } for _, block := range blocks { switch block.Type { case "tool_use": if block.ID != "" && (block.Name == "Agent" || block.Name == "Task" || block.Name == "Bash") { - if block.Input.Background { + h.taskCalls[block.ID] = true + if block.Input.Background && !h.taskEnded[block.ID] { if _, exists := h.tasks[block.ID]; !exists { h.tasks[block.ID] = "" } @@ -155,23 +195,46 @@ func (h *host) trackTasksLocked(line []byte) { text += part.Text + "\n" } } - if strings.Contains(text, "running in background with ID") || strings.HasPrefix(strings.TrimSpace(text), "Async agent launched") { - if block.ToolUseID != "" { + call := h.taskCalls[block.ToolUseID] + delete(h.taskCalls, block.ToolUseID) + // Only a Bash/Agent/Task call's own acknowledgement starts a + // background task. Any other output (a foreground command that + // prints a file quoting the acknowledgement) finishes the call. + if call && LaunchedInBackground(text) { + if block.ToolUseID != "" && !h.taskEnded[block.ToolUseID] { if _, exists := h.tasks[block.ToolUseID]; !exists { h.tasks[block.ToolUseID] = "" } } + } else if _, running := h.tasks[block.ToolUseID]; running { + end(block.ToolUseID) } else { - delete(h.tasks, block.ToolUseID) delete(h.taskOrigins, block.ToolUseID) } - finishText(text) + // A tool's output is not a harness notification: only a text + // block (below) or a structured task_notification ends a task. case "text": finishText(block.Text) } } } +// maxTaskMarks bounds the bookkeeping sets; a reset only forgets marks for +// calls that never received a result or tasks finished long ago. +const maxTaskMarks = 8192 + +// LaunchedInBackground recognises Claude Code's immediate result for a tool +// call that keeps running after it returns: the acknowledgement is the +// result's first line, never text quoted somewhere inside other output. +func LaunchedInBackground(text string) bool { + first := strings.TrimSpace(text) + if i := strings.IndexByte(first, '\n'); i >= 0 { + first = first[:i] + } + return strings.Contains(first, "running in background with ID") || + strings.HasPrefix(first, "Async agent launched") +} + var completedTaskNotice = regexp.MustCompile(`(?s).*?\s*([^<\s]+)\s*.*?`) // Native stream-json message content can be an array or a plain notification. diff --git a/internal/claudehost/tasks_test.go b/internal/claudehost/tasks_test.go index f655ba51..8532dd69 100644 --- a/internal/claudehost/tasks_test.go +++ b/internal/claudehost/tasks_test.go @@ -109,3 +109,45 @@ func TestDetachedBackgroundCLIIsNotReapedAsIdle(t *testing.T) { t.Fatal("completed idle CLI was not released") } } + +// A subagent's foreground Bash that prints source quoting the background +// acknowledgement (sed of fake-claude.py, seen live) is not a background task. +func TestForegroundOutputQuotingLaunchIsNotATask(t *testing.T) { + h := &host{} + h.trackTasksLocked([]byte(`{"type":"assistant","parent_tool_use_id":"agent","message":{"content":[{"type":"tool_use","id":"sed","name":"Bash","input":{"command":"sed -n 1,230p internal/claude/testdata/fake-claude.py"}}]}}`)) + h.trackTasksLocked([]byte(`{"type":"user","parent_tool_use_id":"agent","message":{"content":[{"type":"tool_result","tool_use_id":"sed","content":"#!/usr/bin/env python3\n \"content\": \"Command running in background with ID: b1.\"\nother"}]}}`)) + // A result for no known Bash/Agent call never starts a task either. + h.trackTasksLocked([]byte(`{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"unknown","content":"Command running in background with ID: b2."}]}}`)) + if status := h.statusLocked(); len(*status.Tasks) != 0 { + t.Fatalf("foreground output registered a task: %+v", *status.Tasks) + } +} + +// The CLI may report a subagent's background command complete before the +// tool_result acknowledging its launch; the late acknowledgement and progress +// must not revive it (seen live: Xvfb launched by a subagent). +func TestCompletionBeforeLaunchAcknowledgementStaysFinished(t *testing.T) { + h := &host{} + h.trackTasksLocked([]byte(`{"type":"assistant","parent_tool_use_id":"agent","message":{"content":[{"type":"tool_use","id":"xvfb","name":"Bash","input":{"command":"Xvfb :99 &","run_in_background":true}}]}}`)) + h.trackTasksLocked([]byte(`{"type":"system","subtype":"task_started","task_id":"bz","tool_use_id":"xvfb","owned_by_subagent":true,"is_backgrounded":true}`)) + h.trackTasksLocked([]byte(`{"type":"system","subtype":"task_notification","task_id":"bz","tool_use_id":"xvfb","status":"completed"}`)) + h.trackTasksLocked([]byte(`{"type":"user","parent_tool_use_id":"agent","message":{"content":[{"type":"tool_result","tool_use_id":"xvfb","content":"Command running in background with ID: bz. Output is being written to: /tmp/bz.output"}]}}`)) + h.trackTasksLocked([]byte(`{"type":"system","subtype":"task_progress","task_id":"bz","tool_use_id":"xvfb"}`)) + if status := h.statusLocked(); len(*status.Tasks) != 0 { + t.Fatalf("finished task revived: %+v", *status.Tasks) + } +} + +// background_tasks_changed is the CLI's full running set; a task it omits ended. +func TestBackgroundTasksChangedDropsUnlistedTasks(t *testing.T) { + h := &host{} + for _, id := range []string{"a", "b"} { + h.trackTasksLocked([]byte(`{"type":"assistant","message":{"content":[{"type":"tool_use","id":"tool-` + id + `","name":"Bash","input":{"command":"sleep 600","run_in_background":true}}]}}`)) + h.trackTasksLocked([]byte(`{"type":"system","subtype":"task_started","task_id":"native-` + id + `","tool_use_id":"tool-` + id + `"}`)) + } + h.trackTasksLocked([]byte(`{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"native-b","task_type":"local_bash"}]}`)) + status := h.statusLocked() + if len(*status.Tasks) != 1 || (*status.Tasks)[0].ToolUseID != "tool-b" { + t.Fatalf("running set not reconciled: %+v", *status.Tasks) + } +} diff --git a/internal/cli/agent_mode_test.go b/internal/cli/agent_mode_test.go new file mode 100644 index 00000000..ab18edb7 --- /dev/null +++ b/internal/cli/agent_mode_test.go @@ -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") + } +} diff --git a/internal/cli/app.go b/internal/cli/app.go index 2911a65b..24678ec2 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -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,15 @@ 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 ended %s (run %d", r.RunDetail.Status, r.RunDetail.ID) + if note := failureNote(r.RunDetail); note != "" { + message += ": " + note + } + message += ")" + if hint := waitingHint(r.RunDetail); hint != "" { + message += "; " + hint + } + return &StatusError{Code: WaitRunsUnsuccessful, Message: message} } return nil } @@ -1496,6 +1521,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 +1543,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 +1552,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 +1586,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 +1621,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 +1687,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 } diff --git a/internal/cli/commands.go b/internal/cli/commands.go index e328b64c..75b8ef9f 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -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 [--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 ...] [--yes] [--json]", - "inspect": "inspect [--json]", + "inspect": "inspect [--step N] [--transcripts] [--json]", "wait": "wait [run-id ...] [--timeout DURATION] [--json]", "cancel": "cancel [--json]", "decide": "decide [stage] --option KEY [--feedback TEXT] [--json]", - "retry": "retry [--mode resume|restart] [--stage KEY [--visit N]] [--version N] [--input-file FILE|-] [--json [--wait [--wait-timeout DURATION]]]", + "retry": "retry [--yes] [--mode resume|restart] [--stage KEY [--visit N]] [--version N] [--input-file FILE|-] [--json [--wait [--wait-timeout DURATION]]]", "title": "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`.", diff --git a/internal/cli/confirmation.go b/internal/cli/confirmation.go index cd09e4e4..4f0d2098 100644 --- a/internal/cli/confirmation.go +++ b/internal/cli/confirmation.go @@ -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 +} diff --git a/internal/cli/exit.go b/internal/cli/exit.go index 1963d8da..f5b142fa 100644 --- a/internal/cli/exit.go +++ b/internal/cli/exit.go @@ -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 diff --git a/internal/cli/help.go b/internal/cli/help.go index c376ef71..0e32d4fd 100644 --- a/internal/cli/help.go +++ b/internal/cli/help.go @@ -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: diff --git a/internal/cli/inspect.go b/internal/cli/inspect.go new file mode 100644 index 00000000..fe53caff --- /dev/null +++ b/internal/cli/inspect.go @@ -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 +} diff --git a/internal/cli/wait_command_test.go b/internal/cli/wait_command_test.go index 73a5d406..a85b6b1d 100644 --- a/internal/cli/wait_command_test.go +++ b/internal/cli/wait_command_test.go @@ -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 { diff --git a/internal/cli/wait_test.go b/internal/cli/wait_test.go index 81ce0da8..4a9fb19a 100644 --- a/internal/cli/wait_test.go +++ b/internal/cli/wait_test.go @@ -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 { diff --git a/internal/server/chat_hub.go b/internal/server/chat_hub.go index 77164cda..191efd96 100644 --- a/internal/server/chat_hub.go +++ b/internal/server/chat_hub.go @@ -95,6 +95,9 @@ type chatHub struct { // shownRefresh brings listed items up to date (file states, followed // runs) before a subscribe reply carries them; nil leaves them as stored. shownRefresh func(ctx context.Context, sessionID string, items []protocol.ChatShownItem) []protocol.ChatShownItem + // queueResumed runs once the durable queues are restored after a restart + // (the chat tools re-arm run-triggered follow-ups); nil does nothing. + queueResumed func(ctx context.Context) // autoSwitch records the usage-limit refusals the server already // continued on another Claude account (chat_auto_switch.go). autoSwitch chatAutoSwitchState diff --git a/internal/server/chat_tools_followup.go b/internal/server/chat_tools_followup.go index 693aec6a..39a40f1f 100644 --- a/internal/server/chat_tools_followup.go +++ b/internal/server/chat_tools_followup.go @@ -5,7 +5,10 @@ import ( "crypto/rand" "encoding/hex" "fmt" + "log" + "strconv" "strings" + "sync" "time" "git.a-wan.net/alan/pipelines/internal/chattools" @@ -16,12 +19,33 @@ import ( // with a send_at, under the sender label chatFollowupClient. The operator sees // it as a scheduled message from the agent and can remove it like any queued // prompt; until it is due it does not hold the operator's prompts back -// (chatQueueHead). +// (chatQueueHead). cancel_followup removes one the agent no longer needs. +// +// A run-triggered follow-up (run_id with on) is queued the same way with the +// longest allowed send_at as its deadline, and its operation id names the run +// and condition (chatRunFollowupPrefix). The run event hub tells the service +// when a run changes; once the run meets the condition the prompt is requeued +// as due now, with the run's state appended. The queue row is the durable +// record: after a restart resumeRunFollowups re-arms the watches from it. // chatFollowupClient is the sender label of an agent's follow-up prompt. const chatFollowupClient = "Agent follow-up" -func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, message, at string, afterMinutes *int64) chattools.Result { +// chatRunFollowupPrefix starts a run-triggered follow-up's operation id: +// followup-run-<run id>-<on>-<random>. +const chatRunFollowupPrefix = chatFollowupPrefix + "run-" + +// runFollowupWatches maps a run to the follow-ups (operation id to session) +// waiting on it. mu also serialises every count-then-queue, cancel and trigger +// of the follow-ups, so concurrent calls cannot exceed the pending bound or +// deliver one twice. +type runFollowupWatches struct { + mu sync.Mutex + items map[int64]map[string]string + timers map[int64]*time.Timer +} + +func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, message, at string, afterMinutes, runID *int64, on string) chattools.Result { fail := func(format string, args ...any) chattools.Result { return chattools.Result{Text: "Nothing was scheduled: " + fmt.Sprintf(format, args...), IsError: true} } @@ -35,7 +59,34 @@ func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, me at = strings.TrimSpace(at) now := s.now() var sendAt time.Time + var run *protocol.RunSummary switch { + case runID != nil && (at != "" || afterMinutes != nil): + return fail("give run_id or a time (at or after_minutes), not both.") + case runID == nil && on != "": + return fail("on needs run_id.") + case runID != nil: + if on == "" { + on = chattools.FollowupOnFinished + } + if *runID <= 0 { + return fail("run_id must be a positive run number.") + } + if s.runs == nil { + return fail("this server does not record runs.") + } + summary, found, err := s.runs.RunSummaryByID(ctx, *runID) + if err != nil { + return fail("%v", err) + } + if !found { + return fail("there is no run %d.", *runID) + } + if runFollowupDue(summary, on) { + return fail("run %d is already %s; act on it now (pipelines inspect %d).", *runID, runStateText(summary), *runID) + } + run = &summary + sendAt = now.Add(time.Duration(chattools.MaxFollowupMinutes) * time.Minute) case at != "" && afterMinutes != nil: return fail("give either at or after_minutes, not both.") case afterMinutes != nil: @@ -57,37 +108,322 @@ func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, me } sendAt = parsed default: - return fail("give at (an RFC 3339 time) or after_minutes.") + return fail("give at (an RFC 3339 time), after_minutes, or run_id.") } if s.hub == nil || s.broker == nil { return fail("follow-ups are not available on this server.") } - pending := 0 - for _, prompt := range s.hub.queueFrame(sessionID).Prompts { - if strings.HasPrefix(prompt.OperationID, chatFollowupPrefix) { - pending++ - } - } - if pending >= chattools.MaxPendingFollowups { - return fail("this chat already has %d follow-ups pending (the limit is %d); the operator can remove one, or wait for one to be delivered.", pending, chattools.MaxPendingFollowups) + w := &s.followups + w.mu.Lock() + pending := s.pendingFollowups(sessionID) + if len(pending) >= chattools.MaxPendingFollowups { + w.mu.Unlock() + return fail("this chat already has %d follow-ups pending (the limit is %d); cancel one with cancel_followup, or wait for one to be delivered.%s", len(pending), chattools.MaxPendingFollowups, followupListText(pending, now)) } var token [8]byte _, _ = rand.Read(token[:]) operationID := chatFollowupPrefix + hex.EncodeToString(token[:]) text := fmt.Sprintf("[Follow-up you scheduled at %s with schedule_followup] %s", now.UTC().Format(time.RFC3339), message) + if run != nil { + operationID = fmt.Sprintf("%s%d-%s-%s", chatRunFollowupPrefix, run.ID, on, hex.EncodeToString(token[:])) + text = fmt.Sprintf("[Follow-up you scheduled at %s with schedule_followup, for when run %d %s; delivered at %s at the latest] %s", + now.UTC().Format(time.RFC3339), run.ID, runFollowupCondition(on), sendAt.UTC().Format(time.RFC3339), message) + } if err := s.hub.queueFollowup(ctx, s.broker, sessionID, operationID, text, sendAt); err != nil { + w.mu.Unlock() return fail("%v", err) } - return chattools.Result{Text: fmt.Sprintf("Scheduled: Pipelines will send this chat your follow-up at %s (in %s), when the chat is free; the operator sees it queued and can remove it. Do not wait for it now.", - sendAt.UTC().Format(time.RFC3339), sendAt.Sub(now).Round(time.Minute))} + if run != nil { + s.watchRunFollowupLocked(run.ID, sessionID, operationID) + } + pending = s.pendingFollowups(sessionID) + w.mu.Unlock() + if run != nil { + // The run may have changed between the check above and the watch: + // look again once, as an event would. + s.scheduleRunFollowupCheck(run.ID) + return chattools.Result{Text: fmt.Sprintf("Scheduled follow-up %s: Pipelines will send this chat your follow-up when run %d %s (it is %s now), or at %s at the latest, when the chat is free; the operator sees it queued and can remove it. Do not wait for it now.%s", + operationID, run.ID, runFollowupCondition(on), runStateText(*run), sendAt.UTC().Format(time.RFC3339), followupListText(pending, now))} + } + return chattools.Result{Text: fmt.Sprintf("Scheduled follow-up %s: Pipelines will send this chat your follow-up at %s (in %s), when the chat is free; the operator sees it queued and can remove it. Do not wait for it now.%s", + operationID, sendAt.UTC().Format(time.RFC3339), sendAt.Sub(now).Round(time.Minute), followupListText(pending, now))} +} + +// runCancelFollowup removes one of this chat's pending follow-ups. +func (s *chatToolService) runCancelFollowup(ctx context.Context, sessionID, id string) chattools.Result { + id = strings.TrimSpace(id) + if s.hub == nil { + return chattools.Result{Text: "Nothing was canceled: follow-ups are not available on this server.", IsError: true} + } + w := &s.followups + w.mu.Lock() + defer w.mu.Unlock() + if !strings.HasPrefix(id, chatFollowupPrefix) { + return chattools.Result{Text: fmt.Sprintf("Nothing was canceled: %q is not a follow-up id (they start with %s).%s", id, chatFollowupPrefix, followupListText(s.pendingFollowups(sessionID), s.now())), IsError: true} + } + found, err := s.hub.unqueue(ctx, sessionID, id) + if err != nil { + return chattools.Result{Text: "Nothing was canceled: " + err.Error(), IsError: true} + } + if runID, _, ok := parseRunFollowupID(id); ok { + s.unwatchRunFollowupLocked(runID, id) + } + pending := s.pendingFollowups(sessionID) + if !found { + return chattools.Result{Text: fmt.Sprintf("Nothing was canceled: this chat has no pending follow-up %s (it may have been delivered or removed already).%s", id, followupListText(pending, s.now())), IsError: true} + } + return chattools.Result{Text: fmt.Sprintf("Canceled follow-up %s.%s", id, followupListText(pending, s.now()))} +} + +// pendingFollowups are the chat's follow-ups still waiting in its queue. +func (s *chatToolService) pendingFollowups(sessionID string) []protocol.ChatQueuedPrompt { + var pending []protocol.ChatQueuedPrompt + for _, prompt := range s.hub.queueFrame(sessionID).Prompts { + if strings.HasPrefix(prompt.OperationID, chatFollowupPrefix) { + pending = append(pending, prompt) + } + } + return pending +} + +// followupListText lists pending follow-ups for a tool result, or says there +// are none. +func followupListText(pending []protocol.ChatQueuedPrompt, now time.Time) string { + if len(pending) == 0 { + return " No follow-ups are pending in this chat." + } + parts := make([]string, 0, len(pending)) + for _, prompt := range pending { + when := "when the chat is free" + if runID, on, ok := parseRunFollowupID(prompt.OperationID); ok && prompt.SendAt > now.UnixMilli() { + when = fmt.Sprintf("when run %d %s", runID, runFollowupCondition(on)) + } else if prompt.SendAt > now.UnixMilli() { + when = "at " + time.UnixMilli(prompt.SendAt).UTC().Format(time.RFC3339) + } + parts = append(parts, prompt.OperationID+" ("+when+")") + } + return fmt.Sprintf(" Pending follow-ups (%d of %d): %s.", len(pending), chattools.MaxPendingFollowups, strings.Join(parts, "; ")) +} + +// parseRunFollowupID reads the run and condition from a run-triggered +// follow-up's operation id. +func parseRunFollowupID(operationID string) (int64, string, bool) { + rest, ok := strings.CutPrefix(operationID, chatRunFollowupPrefix) + if !ok { + return 0, "", false + } + fields := strings.SplitN(rest, "-", 3) + if len(fields) != 3 { + return 0, "", false + } + runID, err := strconv.ParseInt(fields[0], 10, 64) + if err != nil || runID <= 0 || (fields[1] != chattools.FollowupOnFinished && fields[1] != chattools.FollowupOnAttention) { + return 0, "", false + } + return runID, fields[1], true +} + +func runFollowupCondition(on string) string { + if on == chattools.FollowupOnAttention { + return "needs the operator or finishes" + } + return "finishes" +} + +// runFollowupDue reports whether a run meets a follow-up's condition: it ended, +// or (for attention) it waits on a human decision. +func runFollowupDue(summary protocol.RunSummary, on string) bool { + if shownRunTerminal(summary.Status) { + return true + } + return on == chattools.FollowupOnAttention && summary.Status == protocol.RunStatusWaiting && summary.ExportPendingSequence == 0 +} + +// runStateText describes a run's state in one phrase. +func runStateText(summary protocol.RunSummary) string { + text := summary.Status + if outcome := strings.TrimSpace(summary.Outcome); outcome != "" { + text += " (" + outcome + ")" + } + if stage := strings.TrimSpace(summary.CurrentStage); stage != "" { + if summary.Status == protocol.RunStatusWaiting { + text += " waiting at stage " + stage + } else { + text += " at stage " + stage + } + } + return text +} + +func (s *chatToolService) watchRunFollowupLocked(runID int64, sessionID, operationID string) { + w := &s.followups + if w.items == nil { + w.items = map[int64]map[string]string{} + } + if w.items[runID] == nil { + w.items[runID] = map[string]string{} + } + w.items[runID][operationID] = sessionID +} + +func (s *chatToolService) unwatchRunFollowupLocked(runID int64, operationID string) { + w := &s.followups + delete(w.items[runID], operationID) + if len(w.items[runID]) == 0 { + delete(w.items, runID) + } +} + +// observeRunFollowups is the run event hub's observer for run-triggered +// follow-ups: a watched run's change is checked once its burst settles. +func (s *chatToolService) observeRunFollowups(frame protocol.RunEventFrame) { + s.followups.mu.Lock() + watched := len(s.followups.items[frame.RunID]) > 0 + s.followups.mu.Unlock() + if watched { + s.scheduleRunFollowupCheck(frame.RunID) + } +} + +// scheduleRunFollowupCheck checks runID's follow-ups after the coalescing +// delay, at most once at a time. +func (s *chatToolService) scheduleRunFollowupCheck(runID int64) { + w := &s.followups + w.mu.Lock() + defer w.mu.Unlock() + if w.timers == nil { + w.timers = map[int64]*time.Timer{} + } + if w.timers[runID] != nil { + return + } + w.timers[runID] = time.AfterFunc(shownRunRefreshDelay, func() { + w.mu.Lock() + delete(w.timers, runID) + w.mu.Unlock() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + s.checkRunFollowups(ctx, runID) + }) +} + +// checkRunFollowups delivers runID's follow-ups whose condition the run now +// meets: each is requeued as due now with the run's state appended. One that +// is no longer queued (delivered at its deadline, or removed) is forgotten. +func (s *chatToolService) checkRunFollowups(ctx context.Context, runID int64) { + if s.runs == nil || s.hub == nil { + return + } + summary, found, err := s.runs.RunSummaryByID(ctx, runID) + if err != nil { + log.Printf("chat follow-ups run=%d: %v", runID, err) + return + } + w := &s.followups + w.mu.Lock() + defer w.mu.Unlock() + for operationID, sessionID := range w.items[runID] { + _, on, ok := parseRunFollowupID(operationID) + if !ok { + s.unwatchRunFollowupLocked(runID, operationID) + continue + } + state := "" + switch { + case !found: + state = fmt.Sprintf("run %d no longer exists", runID) + case runFollowupDue(summary, on): + state = fmt.Sprintf("run %d is now %s", runID, runStateText(summary)) + default: + continue + } + s.unwatchRunFollowupLocked(runID, operationID) + var text string + for _, prompt := range s.hub.queueFrame(sessionID).Prompts { + if prompt.OperationID == operationID { + text = prompt.Text + } + } + if text == "" { + continue + } + removed, err := s.hub.unqueue(ctx, sessionID, operationID) + if err != nil || !removed { + if err != nil { + log.Printf("chat follow-ups session=%s run=%d: %v", sessionID, runID, err) + } + continue + } + text += "\n\n[Pipelines: " + state + "; read it with pipelines inspect " + strconv.FormatInt(runID, 10) + ".]" + // The chat already shows this follow-up from when it was scheduled, so + // the requeue is not announced as a second user message. + if _, err := s.hub.admitFollowup(ctx, s.broker, sessionID, operationID, text, time.Time{}); err != nil { + log.Printf("chat follow-ups session=%s run=%d: requeue: %v", sessionID, runID, err) + } + } +} + +// resumeRunFollowups re-arms the run-triggered follow-ups the restored queues +// hold, and delivers those whose run already meets the condition (it may have +// finished while the server was down). +func (s *chatToolService) resumeRunFollowups(ctx context.Context) { + if s.hub == nil { + return + } + s.hub.mu.Lock() + type waiting struct { + runID int64 + sessionID, opID string + } + var found []waiting + for sessionID, room := range s.hub.rooms { + for _, p := range room.queue { + if runID, _, ok := parseRunFollowupID(p.operationID); ok && p.sendAt.After(s.hub.clock()) { + found = append(found, waiting{runID, sessionID, p.operationID}) + } + } + } + s.hub.mu.Unlock() + runs := map[int64]bool{} + s.followups.mu.Lock() + for _, f := range found { + s.watchRunFollowupLocked(f.runID, f.sessionID, f.opID) + runs[f.runID] = true + } + s.followups.mu.Unlock() + for runID := range runs { + s.checkRunFollowups(ctx, runID) + } } // queueFollowup queues an agent's follow-up prompt for sendAt: durably, under // the follow-up sender label, shown to every attached client as scheduled. func (h *chatHub) queueFollowup(ctx context.Context, broker chatBroker, sessionID, operationID, text string, sendAt time.Time) error { + // An agent's tool call can arrive while start-up recovery still restores + // the durable queue (see awaitRecovery). admitFollowup itself is not + // gated: recovery's own run-follow-up re-check (queueResumed) calls it + // before the gate opens. if !h.awaitRecovery(ctx) { return ctx.Err() } + messageID, err := h.admitFollowup(ctx, broker, sessionID, operationID, text, sendAt) + if err != nil { + return err + } + h.broadcastUser(protocol.ChatEventFrame{ + SessionID: sessionID, + MessageID: messageID, + Kind: protocol.ChatEventUser, + Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: text}, + Client: chatFollowupClient, + OperationID: operationID, + }, "") + return nil +} + +// admitFollowup queues a follow-up prompt without announcing it and returns +// its message id. +func (h *chatHub) admitFollowup(ctx context.Context, broker chatBroker, sessionID, operationID, text string, sendAt time.Time) (string, error) { p := &chatQueuedPrompt{ text: text, operationID: operationID, @@ -100,15 +436,7 @@ func (h *chatHub) queueFollowup(ctx context.Context, broker chatBroker, sessionI admission, err := h.admitPrompt(ctx, sessionID, broker, p) if admission == chatAdmitRefused { h.forgetOp(sessionID, operationID) - return err + return "", err } - h.broadcastUser(protocol.ChatEventFrame{ - SessionID: sessionID, - MessageID: p.messageID, - Kind: protocol.ChatEventUser, - Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: text}, - Client: chatFollowupClient, - OperationID: operationID, - }, "") - return nil + return p.messageID, nil } diff --git a/internal/server/chat_tools_followup_more_test.go b/internal/server/chat_tools_followup_more_test.go new file mode 100644 index 00000000..300c3abf --- /dev/null +++ b/internal/server/chat_tools_followup_more_test.go @@ -0,0 +1,243 @@ +package server + +import ( + "context" + "strings" + "sync" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/chattools" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// lockedRuns is a run store a test can change while the service reads it. +type lockedRuns struct { + mu sync.Mutex + runs map[int64]protocol.RunSummary +} + +func (l *lockedRuns) RunSummaryByID(_ context.Context, id int64) (protocol.RunSummary, bool, error) { + l.mu.Lock() + defer l.mu.Unlock() + run, ok := l.runs[id] + return run, ok, nil +} + +func (l *lockedRuns) set(run protocol.RunSummary) { + l.mu.Lock() + defer l.mu.Unlock() + l.runs[run.ID] = run +} + +func followupID(t *testing.T, r chattools.Result) string { + t.Helper() + _, rest, ok := strings.Cut(r.Text, "Scheduled follow-up ") + if r.IsError || !ok { + t.Fatalf("the result names the follow-up id: %v", r) + } + return strings.TrimSuffix(strings.Fields(rest)[0], ":") +} + +func newFollowupFixture(t *testing.T) (*chatToolFixture, *lockedRuns) { + t.Helper() + f := newChatToolFixture(t) + runs := &lockedRuns{runs: map[int64]protocol.RunSummary{}} + f.service.runs = runs + f.service.broker = newChannelChat() + return f, runs +} + +// awaitReleased waits until sessionID's follow-up was delivered to the broker +// with want in its text, or requeued as due now with it. +func awaitReleased(t *testing.T, f *chatToolFixture, sessionID, want string) { + t.Helper() + broker := f.service.broker.(*channelChat) + deadline := time.Now().Add(5 * time.Second) + for { + for _, text := range broker.promptTexts() { + if strings.Contains(text, want) { + return + } + } + for _, p := range f.service.pendingFollowups(sessionID) { + if p.SendAt == 0 && strings.Contains(p.Text, want) { + return + } + } + if time.Now().After(deadline) { + t.Fatalf("the follow-up was not released with %q: prompts %v, queue %+v", want, broker.promptTexts(), f.service.pendingFollowups(sessionID)) + } + time.Sleep(10 * time.Millisecond) + } +} + +// The schedule result names the id and lists what is pending; cancel_followup +// removes exactly that follow-up. +func TestScheduleFollowupReturnsTheIDAndCancelRemovesIt(t *testing.T) { + f, _ := newFollowupFixture(t) + token := f.token(t, chatToolSessionScope+"ses_c") + first := f.call(token, "schedule_followup", `{"message":"one","after_minutes":30}`) + id := followupID(t, first) + if !strings.HasPrefix(id, chatFollowupPrefix) || !strings.Contains(first.Text, "Pending follow-ups (1 of 3): "+id+" (at ") { + t.Fatalf("schedule result = %v", first) + } + second := followupID(t, f.call(token, "schedule_followup", `{"message":"two","after_minutes":60}`)) + r := f.call(token, "cancel_followup", `{"id":"`+id+`"}`) + if r.IsError || !strings.Contains(r.Text, "Canceled follow-up "+id) || !strings.Contains(r.Text, "(1 of 3): "+second) { + t.Fatalf("cancel = %v", r) + } + if r := f.call(token, "cancel_followup", `{"id":"`+id+`"}`); !r.IsError || !strings.Contains(r.Text, "no pending follow-up") { + t.Fatalf("a second cancel is refused: %v", r) + } + if r := f.call(token, "cancel_followup", `{"id":"op-1"}`); !r.IsError || !strings.Contains(r.Text, "not a follow-up id") { + t.Fatalf("an operator prompt cannot be canceled: %v", r) + } + other := f.token(t, chatToolSessionScope+"ses_other") + if r := f.call(other, "cancel_followup", `{"id":"`+second+`"}`); !r.IsError { + t.Fatalf("another chat cannot cancel this chat's follow-up: %v", r) + } + if pending := f.service.pendingFollowups("ses_c"); len(pending) != 1 || pending[0].OperationID != second { + t.Fatalf("pending = %+v", pending) + } +} + +// Concurrent schedules never exceed the pending bound. +func TestScheduleFollowupBoundHoldsUnderConcurrency(t *testing.T) { + f, _ := newFollowupFixture(t) + token := f.token(t, chatToolSessionScope+"ses_k") + var wg sync.WaitGroup + var mu sync.Mutex + accepted := 0 + for i := 0; i < 12; i++ { + wg.Add(1) + go func() { + defer wg.Done() + if r := f.call(token, "schedule_followup", `{"message":"m","after_minutes":30}`); !r.IsError { + mu.Lock() + accepted++ + mu.Unlock() + } + }() + } + wg.Wait() + if pending := len(f.service.pendingFollowups("ses_k")); accepted != chattools.MaxPendingFollowups || pending != chattools.MaxPendingFollowups { + t.Fatalf("accepted %d, pending %d", accepted, pending) + } +} + +func TestRunFollowupBounds(t *testing.T) { + f, runs := newFollowupFixture(t) + runs.set(protocol.RunSummary{ID: 5, Status: "succeeded", Outcome: "done"}) + runs.set(protocol.RunSummary{ID: 6, Status: protocol.RunStatusWaiting, CurrentStage: "decide"}) + token := f.token(t, chatToolSessionScope+"ses_bounds") + for _, tc := range []struct{ args, want string }{ + {`{"message":"m","run_id":99}`, "there is no run 99"}, + {`{"message":"m","run_id":0}`, "positive run number"}, + {`{"message":"m","run_id":5}`, "run 5 is already succeeded (done)"}, + {`{"message":"m","run_id":6,"on":"attention"}`, "run 6 is already waiting waiting at stage decide"}, + {`{"message":"m","run_id":6,"after_minutes":5}`, "not both"}, + {`{"message":"m","on":"finished","after_minutes":5}`, "on needs run_id"}, + } { + if r := f.call(token, "schedule_followup", tc.args); !r.IsError || !strings.Contains(r.Text, tc.want) { + t.Errorf("%s: got %v, want %q", tc.args, r, tc.want) + } + } + // A run waiting on a person has not finished: on finished still waits. + if r := f.call(token, "schedule_followup", `{"message":"m","run_id":6}`); r.IsError || !strings.Contains(r.Text, "when run 6 finishes") { + t.Fatalf("finished follow-up on a waiting run = %v", r) + } +} + +// A run-triggered follow-up stays pending while the run works and is +// released, with the run's state, once the run needs the operator. +func TestRunFollowupIsDeliveredWhenTheRunNeedsAttention(t *testing.T) { + previous := shownRunRefreshDelay + shownRunRefreshDelay = 10 * time.Millisecond + t.Cleanup(func() { shownRunRefreshDelay = previous }) + f, runs := newFollowupFixture(t) + runs.set(protocol.RunSummary{ID: 7, Status: "running", CurrentStage: "implement"}) + token := f.token(t, chatToolSessionScope+"ses_t") + r := f.call(token, "schedule_followup", `{"message":"check run 7","run_id":7,"on":"attention"}`) + id := followupID(t, r) + if !strings.HasPrefix(id, chatRunFollowupPrefix+"7-attention-") || !strings.Contains(r.Text, "when run 7 needs the operator or finishes") { + t.Fatalf("schedule = %v", r) + } + pending := f.service.pendingFollowups("ses_t") + if len(pending) != 1 || pending[0].SendAt <= time.Now().Add(6*24*time.Hour).UnixMilli() { + t.Fatalf("the follow-up waits with a 7-day deadline: %+v", pending) + } + f.service.observeRun(protocol.RunEventFrame{RunID: 7}) + time.Sleep(50 * time.Millisecond) + if p := f.service.pendingFollowups("ses_t"); len(p) != 1 || p[0].SendAt == 0 { + t.Fatalf("a still-running run keeps the follow-up waiting: %+v", p) + } + + runs.set(protocol.RunSummary{ID: 7, Status: protocol.RunStatusWaiting, CurrentStage: "decide"}) + f.service.observeRun(protocol.RunEventFrame{RunID: 7}) + awaitReleased(t, f, "ses_t", "run 7 is now waiting waiting at stage decide") + f.service.followups.mu.Lock() + watched := len(f.service.followups.items[7]) + f.service.followups.mu.Unlock() + if watched != 0 { + t.Fatal("a released follow-up is no longer watched") + } +} + +// After a restart the restored queue re-arms the watch, and a run that +// finished meanwhile releases its follow-up at once. +func TestRunFollowupsResumeAfterRestart(t *testing.T) { + f, runs := newFollowupFixture(t) + runs.set(protocol.RunSummary{ID: 8, Status: "running"}) + token := f.token(t, chatToolSessionScope+"ses_r") + followupID(t, f.call(token, "schedule_followup", `{"message":"after restart","run_id":8}`)) + // Forget the in-memory watch, as a restarted server would have. + f.service.followups.mu.Lock() + f.service.followups.items = nil + f.service.followups.mu.Unlock() + runs.set(protocol.RunSummary{ID: 8, Status: "failed", Outcome: "error", CurrentStage: "review"}) + f.service.resumeRunFollowups(context.Background()) + awaitReleased(t, f, "ses_r", "run 8 is now failed (error) at stage review") +} + +func TestShowHTMLWarnsAboutBlockedResourcesAndLightOnlyPages(t *testing.T) { + for _, tc := range []struct { + html string + want []string + none bool + }{ + {html: `<style>@media (prefers-color-scheme: dark){body{color:#eee}}</style><p>ok <a href="https://example.com">link</a></p>`, none: true}, + {html: `<script src="https://cdn.example.com/chart.js"></script><style>:root{color-scheme:light dark}</style>`, want: []string{"JavaScript", "1 remote resource(s) (such as https://cdn.example.com/chart.js)"}}, + {html: `<link rel="stylesheet" href="//fonts.example.com/a.css"><div style="background:url('https://x.example/b.png')"></div>`, want: []string{"2 remote resource(s)", "always shown light"}}, + {html: `<button onclick="go()">x</button><svg style="color:light-dark(#000,#fff)"></svg>`, want: []string{"JavaScript"}}, + } { + warnings := strings.Join(shownHTMLWarnings(tc.html), " ") + if tc.none && warnings != "" { + t.Errorf("%s: unexpected warnings %q", tc.html, warnings) + } + for _, want := range tc.want { + if !strings.Contains(warnings, want) { + t.Errorf("%s: warnings %q lack %q", tc.html, warnings, want) + } + } + } + f := newChatToolFixture(t) + token := f.token(t, chatToolSessionScope+"ses_h") + if r := f.call(token, "show_html", `{"html":"<script>x()</script><p>hi</p>"}`); r.IsError || !strings.Contains(r.Text, "Warning: it contains JavaScript") || !strings.Contains(r.Text, "always shown light") { + t.Fatalf("show_html result = %v", r) + } +} + +func TestAmbiguousCallAdviceFitsTheTool(t *testing.T) { + for tool, want := range map[string]string{ + chattools.ToolShowHTML: "different title", + chattools.ToolShowRun: "different title", + chattools.ToolNotify: "message wording", + chattools.ToolScheduleFollowup: "message wording", + chattools.ToolCancelFollowup: "in a moment", + } { + if got := ambiguousCallAdvice(tool); !strings.Contains(got, want) { + t.Errorf("%s: %q lacks %q", tool, got, want) + } + } +} diff --git a/internal/server/chat_tools_html.go b/internal/server/chat_tools_html.go new file mode 100644 index 00000000..e5a4f23c --- /dev/null +++ b/internal/server/chat_tools_html.go @@ -0,0 +1,56 @@ +package server + +import ( + "fmt" + "regexp" + "strings" +) + +// show_html renders in a sandbox with no scripts and no network, and follows +// the dark theme only when the document declares dark support (the same test +// as the app's artifactHtmlSupportsDark). shownHTMLWarnings tells the model +// when its document relies on what the sandbox blocks, or will stay light, so +// it can fix the view rather than believe it was shown as written. + +var ( + shownHTMLScript = regexp.MustCompile(`(?i)<script\b`) + shownHTMLHandler = regexp.MustCompile(`(?i)<[a-z][^>]*\son[a-z]+\s*=`) + shownHTMLDarkAware = regexp.MustCompile(`(?i)prefers-color-scheme|color-scheme|light-dark\(`) + // A remote reference: an attribute or CSS url()/@import naming an + // http(s) or protocol-relative address. + shownHTMLRemote = regexp.MustCompile(`(?i)(?:\b(?:src|href|srcset|poster|data)\s*=\s*["']?|url\(\s*["']?|@import\s+["'])((?:https?:)?//[^"')\s>]+)`) +) + +// shownHTMLWarnings lists what in html will not work as written, or nil. +func shownHTMLWarnings(html string) []string { + var warnings []string + if shownHTMLScript.MatchString(html) || shownHTMLHandler.MatchString(html) { + warnings = append(warnings, "it contains JavaScript (<script> or on* handlers), which does not run here; use CSS, <details> and inline SVG instead.") + } + var remote []string + seen := map[string]bool{} + lower := strings.ToLower(html) + for _, match := range shownHTMLRemote.FindAllStringSubmatchIndex(html, -1) { + address := html[match[2]:match[3]] + // A link to another page is fine: only resources the page loads are + // blocked. An <a href> is the common case. + if tag := strings.LastIndex(lower[:match[0]], "<"); tag >= 0 && (strings.HasPrefix(lower[tag:], "<a ") || strings.HasPrefix(lower[tag:], "<a\n")) { + continue + } + if !seen[address] { + seen[address] = true + remote = append(remote, address) + } + } + if len(remote) > 0 { + example := remote[0] + if len(example) > 120 { + example = example[:120] + "…" + } + warnings = append(warnings, fmt.Sprintf("it loads %d remote resource(s) (such as %s), which the sandbox blocks: inline styles, fonts and images (data: URLs or inline SVG).", len(remote), example)) + } + if !shownHTMLDarkAware.MatchString(html) { + warnings = append(warnings, "it does not declare dark support, so it is always shown light, on white, even in a dark theme; add @media (prefers-color-scheme: dark) styles, a color-scheme declaration or light-dark() colors.") + } + return warnings +} diff --git a/internal/server/chat_tools_run.go b/internal/server/chat_tools_run.go index 9df28669..bbcff89f 100644 --- a/internal/server/chat_tools_run.go +++ b/internal/server/chat_tools_run.go @@ -83,7 +83,11 @@ func (s *chatToolService) run(ctx context.Context, sessionID, tool, id string, a return fail("Nothing was shown: html is not valid UTF-8.") } item := protocol.ChatShownItem{Kind: protocol.ChatShownHTML, Title: boundedLine(in.Title, 200), HTML: in.HTML, HTMLBytes: len(in.HTML), HeightHint: clampHeightHint(in.HeightHint)} - return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat (%s, sandboxed: scripts and network are disabled; it follows the operator's light or dark theme only if it styles itself for dark mode).", humanBytes(int64(len(in.HTML))))} + text := fmt.Sprintf("Shown in the operator's Pipelines chat (%s, sandboxed: scripts and network are disabled; it follows the operator's light or dark theme only if it styles itself for dark mode).", humanBytes(int64(len(in.HTML)))) + if warnings := shownHTMLWarnings(in.HTML); len(warnings) > 0 { + text += " Warning: " + strings.Join(warnings, " ") + } + return &item, chattools.Result{Text: text} case chattools.ToolShowDiff: var in struct { Path string `json:"path"` @@ -111,11 +115,21 @@ func (s *chatToolService) run(ctx context.Context, sessionID, tool, id string, a Message string `json:"message"` At string `json:"at"` AfterMinutes *int64 `json:"after_minutes"` + RunID *int64 `json:"run_id"` + On string `json:"on"` } if err := decode(&in); err != nil { return fail("Nothing was scheduled: %v", err) } - return nil, s.runScheduleFollowup(ctx, sessionID, in.Message, in.At, in.AfterMinutes) + return nil, s.runScheduleFollowup(ctx, sessionID, in.Message, in.At, in.AfterMinutes, in.RunID, in.On) + case chattools.ToolCancelFollowup: + var in struct { + ID string `json:"id"` + } + if err := decode(&in); err != nil { + return fail("Nothing was canceled: %v", err) + } + return nil, s.runCancelFollowup(ctx, sessionID, in.ID) case chattools.ToolNotify: var in struct { Title string `json:"title"` diff --git a/internal/server/chat_tools_runs.go b/internal/server/chat_tools_runs.go index 32a12b06..2f3910a4 100644 --- a/internal/server/chat_tools_runs.go +++ b/internal/server/chat_tools_runs.go @@ -95,6 +95,7 @@ func (s *chatToolService) watchRun(runID int64, sessionID, itemID string) { // observeRun is the run event hub's observer: a followed run's change is // reread once its burst of events settles. func (s *chatToolService) observeRun(frame protocol.RunEventFrame) { + s.observeRunFollowups(frame) w := &s.watch w.mu.Lock() defer w.mu.Unlock() diff --git a/internal/server/chat_tools_service.go b/internal/server/chat_tools_service.go index f4746d3e..10d875c4 100644 --- a/internal/server/chat_tools_service.go +++ b/internal/server/chat_tools_service.go @@ -56,6 +56,9 @@ type chatToolService struct { // fetch is how web images are downloaded (tests replace its guard). fetch shownImageFetcher watch runWatches + // followups serialises follow-up scheduling and follows the runs that + // run-triggered follow-ups wait on. + followups runFollowupWatches } func newChatToolService(tokens chatToolTokenStore, shown chatShownStore, hub *chatHub, registry operatorRegistry) *chatToolService { @@ -192,7 +195,7 @@ func (s *chatToolService) session(ctx context.Context, token, tool string, argum if _, ok := strings.CutPrefix(scope, chatToolInstanceScope); ok && s.hub != nil { id, ambiguous := s.hub.awaitToolCallSession(ctx, tool, arguments, chatToolCorrelationWait) if ambiguous { - return "", "Pipelines could not tell which chat made this call (another chat made an identical one); retry with a different title." + return "", "Pipelines could not tell which chat made this call (another chat made an identical one); " + ambiguousCallAdvice(tool) } if id == "" { return "", "Pipelines could not match this call to a chat it is showing; the tools work only in chats opened through Pipelines." @@ -202,6 +205,21 @@ func (s *chatToolService) session(ctx context.Context, token, tool string, argum return "", "This chat is not ready for Pipelines tools yet." } +// ambiguousCallAdvice says how to make a call distinguishable from another +// chat's identical one: change an argument the tool has and that does not alter +// what it does. +func ambiguousCallAdvice(tool string) string { + switch tool { + case chattools.ToolShowFile, chattools.ToolShowImage, chattools.ToolShowHTML, chattools.ToolShowDiff, chattools.ToolShowRun: + return "retry with a different title." + case chattools.ToolNotify: + return "retry with slightly different message wording." + case chattools.ToolScheduleFollowup: + return "retry with slightly different message wording." + } + return "retry the call in a moment." +} + // chatSessionDirectory is the chat's recorded working directory, or "". func (s *chatToolService) chatSessionDirectory(ctx context.Context, sessionID string) string { if s.registry == nil { diff --git a/internal/server/retry_interrupted_test.go b/internal/server/retry_interrupted_test.go new file mode 100644 index 00000000..d48787e6 --- /dev/null +++ b/internal/server/retry_interrupted_test.go @@ -0,0 +1,111 @@ +package server + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" +) + +const threeStageModelSource = "# stage a\n\n```prompt\nDo A.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> b\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage b\n\n```prompt\nDo B.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> c\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage c\n\n```prompt\nDo C.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> #success\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n" + +// TestRetryResumesAnInterruptedRunAfterItsLastCompletedStep proves a run the +// server stopped (interrupted) can be retried: it resumes after its last +// completed step without rerunning that prefix, whether the stop came during a +// visit (the interrupted visit runs again) or between visits (the next stage +// starts with the completed visit's handoff). +func TestRetryResumesAnInterruptedRunAfterItsLastCompletedStep(t *testing.T) { + for _, midVisit := range []bool{true, false} { + name := "between-visits" + if midVisit { + name = "mid-visit" + } + t.Run(name, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := pipeline.Open(filepath.Join(t.TempDir(), "interrupted.db")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + if _, err := store.Submit(ctx, "resume", threeStageModelSource); err != nil { + t.Fatal(err) + } + items, _ := store.List(ctx) + d, err := store.Get(ctx, items[0].ID, 1) + if err != nil { + t.Fatal(err) + } + workspace := t.TempDir() + id, _, err := store.CreateRun(ctx, d, "interrupted-"+name, workspace, true, nil, map[string]any{"prompt": "task"}) + if err != nil { + t.Fatal(err) + } + if err := store.BeginStep(ctx, id, 1, "a", map[string]any{"prompt": "task"}); err != nil { + t.Fatal(err) + } + if err := store.FinishStep(ctx, id, protocol.RunStep{Sequence: 1, Stage: "a", Status: "completed", Outcome: "success", Target: "b", Output: map[string]any{"handoff": "from-a"}}); err != nil { + t.Fatal(err) + } + if midVisit { + if err := store.BeginStep(ctx, id, 2, "b", map[string]any{"handoff": "from-a"}); err != nil { + t.Fatal(err) + } + } + if err := store.RecoverRuns(ctx); err != nil { + t.Fatal(err) + } + source, err := store.GetRun(ctx, id) + if err != nil || source.Status != "interrupted" { + t.Fatalf("source run was not interrupted: %+v %v", source, err) + } + + r, err := newRunner(ctx, store) + if err != nil { + t.Fatal(err) + } + calls := map[string]int{} + r.execute = func(_ context.Context, def stage.Definition, input stage.Values) (stage.Result, error) { + calls[def.Key]++ + switch def.Key { + case "b": + if input["handoff"] != "from-a" { + t.Errorf("resumed stage lost the completed handoff: %#v", input) + } + data, err := os.ReadFile(def.Turn.Input) + if err != nil { + t.Fatalf("read input.md: %v", err) + } + if !strings.Contains(string(data), "# Previous attempt") || !strings.Contains(string(data), "This is attempt 2.") { + t.Errorf("resumed stage was not told about the previous attempt:\n%s", data) + } + return stage.Result{Outcome: "success", Output: stage.Values{"handoff": "from-b"}}, nil + case "c": + return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil + } + t.Errorf("unexpected stage %q", def.Key) + return stage.Result{}, nil + } + retried, err := r.retry(protocol.Message{RunID: id, RequestKey: "resume-" + name}) + if err != nil { + t.Fatal(err) + } + r.wg.Wait() + retried, err = store.GetRun(ctx, retried.ID) + if err != nil || retried.Status != "succeeded" || retried.RetrySource != id { + t.Fatalf("interrupted run did not resume to success: %+v %v", retried, err) + } + if calls["a"] != 0 || calls["b"] != 1 || calls["c"] != 1 { + t.Fatalf("resume reran the completed prefix or skipped work: %v", calls) + } + if len(retried.Steps) == 0 || retried.Steps[0].Stage != "b" || retried.Steps[0].Sequence != 2 { + t.Fatalf("resume started at the wrong step: %+v", retried.Steps) + } + }) + } +} diff --git a/internal/server/retry_test.go b/internal/server/retry_test.go index a367f933..ba85eb17 100644 --- a/internal/server/retry_test.go +++ b/internal/server/retry_test.go @@ -356,6 +356,20 @@ func TestRetryResumeReusesPrefixHandoffAndReplaysRequestAfterReopen(t *testing.T if !strings.Contains(string(data), want) { t.Errorf("retry input.md missing override %q:\n%s", want, data) } + // Only the override keys are shown, labelled as the operator's + // correction; the merged input (handoff from A) is not reprinted. + text := string(data) + section := text[strings.Index(text, "# Operator correction"):] + if !strings.Contains(text, "# Operator correction") || strings.Contains(section, "from-a") || strings.Contains(text, "# Retry input") { + t.Errorf("retry input.md did not render only the operator correction:\n%s", data) + } + // The retried stage learns why the source attempt failed. + wantAttempt := fmt.Sprintf("This is attempt %d.", bCalls) + for _, want := range []string{"# Previous attempt", wantAttempt, "failed in stage b", "deliberate failure", "Partial edits"} { + if !strings.Contains(text, want) { + t.Errorf("retry input.md missing %q:\n%s", want, data) + } + } } if bCalls <= 2 { return stage.Result{}, fmt.Errorf("deliberate failure") diff --git a/internal/server/runner.go b/internal/server/runner.go index 6ea8e8e1..8206e3ab 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -662,8 +662,9 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol. if err != nil { return retryCheckpoint{}, err } - if source.Status != "failed" || source.FinishedAt == "" { - return retryCheckpoint{}, fmt.Errorf("retry source %d is not a terminal failed run", sourceID) + interrupted := source.Status == "interrupted" + if (source.Status != "failed" && !interrupted) || source.FinishedAt == "" { + return retryCheckpoint{}, fmt.Errorf("retry source %d is not a terminal failed or interrupted run", sourceID) } if source.PipelineID != pinned.ID { return retryCheckpoint{}, fmt.Errorf("retry source %d belongs to a different pipeline", sourceID) @@ -672,6 +673,28 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol. return retryCheckpoint{}, fmt.Errorf("retry source %d has no failed stage checkpoint", sourceID) } failed := source.Steps[len(source.Steps)-1] + if interrupted && selectedStage == "" { + // A server stop interrupts a run mid-visit (the visit is recorded as + // interrupted, with the input it began with) or between visits (the + // last recorded visit completed and routed to its next stage). Either + // way the run resumes after its last completed step: the interrupted + // visit runs again, or the next stage starts with the handoff the + // completed visit produced. + switch failed.Status { + case "interrupted": + failed.Target = protocol.FailureEnd + case "completed": + if failed.Target == "" || failed.Target == protocol.SuccessEnd || failed.Target == protocol.FailureEnd { + return retryCheckpoint{}, fmt.Errorf("retry source %d has no unfinished stage to resume; use --mode=restart", sourceID) + } + failed = protocol.RunStep{Sequence: failed.Sequence + 1, Stage: failed.Target, Status: "interrupted", Target: protocol.FailureEnd, Input: failed.Output} + if failed.Input == nil { + failed.Input = map[string]any{} + } + default: + return retryCheckpoint{}, fmt.Errorf("retry source %d has no safe interrupted-stage checkpoint; use --mode=restart", sourceID) + } + } if selectedStage != "" { failed = protocol.RunStep{} visits := 0 @@ -705,7 +728,7 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol. return retryCheckpoint{}, fmt.Errorf("retry stage %q has no visit %d", selectedStage, selectedVisit) } } - if (failed.Status != "completed" && failed.Status != "failed") || (selectedStage == "" && failed.Target != protocol.FailureEnd) { + if (failed.Status != "completed" && failed.Status != "failed" && !(interrupted && failed.Status == "interrupted")) || (selectedStage == "" && failed.Target != protocol.FailureEnd) { return retryCheckpoint{}, fmt.Errorf("retry source %d has no safe failed-stage checkpoint", sourceID) } var handoff map[string]any @@ -813,8 +836,10 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) { if original.Executing { return nil, fmt.Errorf("run %d is still executing; wait for it to stop completely before retrying", original.ID) } - if original.Status != "failed" || original.FinishedAt == "" { - return nil, fmt.Errorf("only failed runs can be retried (run %d is %s)", original.ID, original.Status) + // An interrupted run (the server stopped mid-run) resumes after its last + // completed step, like a failed run resumes its failed stage. + if (original.Status != "failed" && original.Status != "interrupted") || original.FinishedAt == "" { + return nil, fmt.Errorf("only failed or interrupted runs can be retried (run %d is %s)", original.ID, original.Status) } if request.RequestKey == "" { return nil, fmt.Errorf("retry requires an idempotency request key") @@ -998,6 +1023,7 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail, return } state := rebuildRetryState(source, checkpoint.failed, storedHandoff) + state.previousAttempt = r.previousAttemptSection(ctx, source, d.Graph, state.key) if override, ok := storedHandoff["override"].(map[string]any); ok { state.retryOverride = stage.Values(override) } @@ -1019,9 +1045,65 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail, input := stage.Values(request.Input) state := newRunState(d.Graph.Stages[0].Key, input) state.memory["input"] = memoryValue{output: original} + if request.RetrySource > 0 { + // A restart from entry still tells its first model visit why the + // source run failed. + if source, err := r.store.GetRun(ctx, request.RetrySource); err == nil { + state.previousAttempt = r.previousAttemptSection(ctx, source, d.Graph, state.key) + } + } r.runLoop(ctx, id, d.Graph, d.Name, workspace, request, state) } +// maxRetryChain bounds the walk that numbers a retry attempt. +const maxRetryChain = 50 + +// previousAttemptSection renders the bounded "# Previous attempt" section for +// a retried run whose first visit is the model stage firstStage: the attempt +// number (counted along the retry chain), the stage the source run stopped in +// and its diagnostic. A first visit that is not a model stage gets nothing, so +// the note never lands on an unrelated later stage. +func (r *runner) previousAttemptSection(ctx context.Context, source *protocol.RunDetail, graph protocol.Graph, firstStage string) string { + if source == nil { + return "" + } + model := false + for _, declared := range graph.Stages { + if declared.Key == firstStage { + model = stage.EffectiveType(declared.Type) == stage.ModelType + } + } + if !model { + return "" + } + parentOf := func(d *protocol.RunDetail) int64 { + if d.RetryOf > 0 { + return d.RetryOf + } + return d.RetrySource + } + attempt := 2 + for previous := parentOf(source); previous > 0 && attempt < maxRetryChain; attempt++ { + ancestor, err := r.store.GetRun(ctx, previous) + if err != nil || ancestor == nil { + break + } + previous = parentOf(ancestor) + } + failedStage, diagnostic := source.CurrentStage, "" + if n := len(source.Steps); n > 0 { + last := source.Steps[n-1] + failedStage, diagnostic = last.Stage, strings.TrimSpace(last.Diagnostic) + } + if diagnostic == "" { + diagnostic = strings.TrimSpace(source.Diagnostic) + } + if diagnostic == "" { + diagnostic = strings.TrimSpace(source.FailureReason) + } + return turn.RenderPreviousAttempt(turn.PreviousAttempt{Attempt: attempt, Stage: failedStage, Diagnostic: diagnostic, Run: source.ID}) +} + // terminalFinish classifies a stage's resolved target. A terminal key yields the // run's final status, outcome and diagnostic; an empty target means the stage // named an undeclared outcome; any other value is a stage key and is not @@ -1098,7 +1180,10 @@ type runState struct { // retryOverride is applied once, after the selected stage's memory bindings // have been resolved. It is intentionally not part of run input or memory. retryOverride stage.Values - priorBudgets map[string]stage.BudgetSnapshot + // previousAttempt is the rendered "# Previous attempt" section a retried + // run's first model visit receives; prepareTurn consumes it. + previousAttempt string + priorBudgets map[string]stage.BudgetSnapshot // adopt names the visit to re-adopt from a previous server process instead // of starting it; it is consumed by the loop's first iteration. adopt *adoptedVisit @@ -1779,11 +1864,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na finish("failed", "error", copyErr.Error()) return } - // Keep the merged values for this visit's input.md: the model reads - // files, not the persisted step row, so the override must be visible - // there. A selected-stage override belongs only to this invocation, - // not to a later visit reached through the stage graph. - retryInput = input + // The step row persists the merged input; input.md shows only the + // operator's override keys: the model reads files, not the step row, + // so the correction must be visible there, without re-printing the + // whole input. A selected-stage override belongs only to this + // invocation, not to a later visit reached through the stage graph. + retryInput = state.retryOverride state.retryOverride = nil } if adopted == nil { diff --git a/internal/server/turns.go b/internal/server/turns.go index 63e8f236..faa84092 100644 --- a/internal/server/turns.go +++ b/internal/server/turns.go @@ -52,15 +52,25 @@ func stageTurnPaths(paths turn.Paths) stage.TurnPaths { // completed turn in full) before the visit starts. A failure here is a run failure: the file // protocol is the stage contract, not best-effort evidence. // -// retryInput is the complete merged input for a selected-stage retry and nil for -// an ordinary visit. A retry override is persisted on the step, but the model -// reads input.md rather than the step row, so the same values must be written -// into the file or the operator's correction is invisible to the model. +// retryInput is the operator's override for a selected-stage retry (only the +// keys it sets) and nil for an ordinary visit. The merged input is persisted on +// the step, but the model reads input.md rather than the step row, so the +// correction must be written into the file or it is invisible to the model. +// A retried run's first visit also gets a bounded "# Previous attempt" section +// saying why the source run failed; it is consumed here so later visits do not +// repeat it. func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage.Values) error { if err := paths.Ensure(); err != nil { return err } input := turnInputWithRetry(state.turnInput(), retryInput) + if state.previousAttempt != "" { + if !strings.HasSuffix(input, "\n") { + input += "\n" + } + input += "\n" + state.previousAttempt + state.previousAttempt = "" + } history := turn.RenderHistory(state.turns) memory := turn.RenderEssential(turn.Essential{ Task: state.prompt, @@ -82,24 +92,26 @@ func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage return nil } -// turnInputWithRetry appends the merged retry input to the ordinary turn input. -// It is rendered as a fenced JSON object because the values are operator data, -// not prose; encoding/json sorts map keys so the file is deterministic. -func turnInputWithRetry(base string, retryInput stage.Values) string { - if len(retryInput) == 0 { +// turnInputWithRetry appends the operator's retry override to the ordinary turn +// input as an "Operator correction": only the keys the operator set, not the +// whole merged input the stage already has. It is rendered as a fenced JSON +// object because the values are operator data, not prose; encoding/json sorts +// map keys so the file is deterministic. +func turnInputWithRetry(base string, override stage.Values) string { + if len(override) == 0 { return base } - encoded, err := json.MarshalIndent(retryInput, "", " ") - if err != nil { - // A retry input that cannot be rendered is still shown as a visible - // section; the stage can choose its error outcome rather than silently - // receiving a correction it cannot see. - return base + "\n\n# Retry input\n\nThe retry input could not be rendered.\n" - } if !strings.HasSuffix(base, "\n") { base += "\n" } - return base + "\n# Retry input\n\nThis retry was given this complete input:\n\n```json\n" + string(encoded) + "\n```\n" + encoded, err := json.MarshalIndent(override, "", " ") + if err != nil { + // A correction that cannot be rendered is still shown as a visible + // section; the stage can choose its error outcome rather than silently + // receiving a correction it cannot see. + return base + "\n# Operator correction\n\nThe operator's retry correction could not be rendered.\n" + } + return base + "\n# Operator correction\n\nThe operator retried this stage with these corrected input values; they override the earlier ones:\n\n```json\n" + string(encoded) + "\n```\n" } // turnInput is the run prompt on the first visit; later visits carry the run diff --git a/internal/server/websocket.go b/internal/server/websocket.go index 33732758..ecaf9733 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -187,6 +187,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin tools.runs = stores[0] tools.broker = options.Chat events.observe(tools.observeRun) + hub.queueResumed = tools.resumeRunFollowups registerChatTools(mux, tools, build.Version) } mux.HandleFunc("GET /discovery", serveServerDiscovery) @@ -631,6 +632,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin hub.reattachSessions(ctx, options.Chat) // Restore live turn ownership before queue rooms can start runners. hub.resumeQueued(ctx, options.Chat) + if hub.queueResumed != nil { + hub.queueResumed(ctx) + } close(ready) hub.observeRunningTurns(ctx, options.Chat) close(done) diff --git a/internal/stage/model_run.go b/internal/stage/model_run.go index 6ff7d0b6..cd920681 100644 --- a/internal/stage/model_run.go +++ b/internal/stage/model_run.go @@ -7,6 +7,7 @@ import ( "time" "git.a-wan.net/alan/pipelines/internal/opencode" + "git.a-wan.net/alan/pipelines/internal/turn" ) func (m ModelStage) Run(ctx context.Context, def Definition, input Values) (Result, error) { @@ -71,7 +72,13 @@ func (m ModelStage) Run(ctx context.Context, def Definition, input Values) (Resu attemptCtx, cancel := context.WithTimeoutCause(ctx, spec.Config.Timeout, &stageTimeoutCause{timeout: spec.Config.Timeout}) // A completed turn without a valid outcome gets one in-session follow-up // asking only for the outcome, rather than a full retry of its work. - text, generateErr := client.Generate(withOutputRepair(attemptCtx, outcomesFor(def.Edges)), spec.Config, prompt) + attemptPrompt := prompt + if attempt > 0 && err != nil { + // An in-stage retry says why the last attempt failed rather than + // resending an identical prompt that invites the same failure. + attemptPrompt = prompt + "\n\n" + turn.RenderPreviousAttempt(turn.PreviousAttempt{Attempt: attempt + 1, Stage: def.Key, Diagnostic: err.Error()}) + } + text, generateErr := client.Generate(withOutputRepair(attemptCtx, outcomesFor(def.Edges)), spec.Config, attemptPrompt) if generateErr == nil && attemptCtx.Err() != nil { generateErr = attemptCtx.Err() } diff --git a/internal/stage/previous_attempt_test.go b/internal/stage/previous_attempt_test.go new file mode 100644 index 00000000..3d42c91e --- /dev/null +++ b/internal/stage/previous_attempt_test.go @@ -0,0 +1,48 @@ +package stage + +import ( + "context" + "strings" + "testing" +) + +type retryableTestError struct{ text string } + +func (e retryableTestError) Error() string { return e.text } +func (e retryableTestError) Retryable() bool { return true } + +// TestInStageRetryTellsTheModelWhyTheLastAttemptFailed proves an in-stage +// retry does not resend an identical prompt: the second attempt carries a +// bounded "# Previous attempt" section with the attempt number, the stage and +// the last failure, while the first attempt is unchanged. +func TestInStageRetryTellsTheModelWhyTheLastAttemptFailed(t *testing.T) { + def := turnDefinition(t) + def.Configs["retries"] = "1" + prompts := []string{} + client := generatorFunc(func(_ context.Context, _ ModelConfig, prompt string) (string, error) { + prompts = append(prompts, prompt) + if len(prompts) == 1 { + return "", retryableTestError{"provider overloaded: " + strings.Repeat("x", 5000)} + } + return "# outcome\nsuccess\n\n# handoff\n\ndone\n", nil + }) + result, err := (ModelStage{Client: client}).Run(context.Background(), def, Values{"prompt": "task"}) + if err != nil || result.Outcome != "success" || len(prompts) != 2 { + t.Fatalf("retry did not succeed: %+v %v prompts=%d", result, err, len(prompts)) + } + if strings.Contains(prompts[0], "# Previous attempt") { + t.Fatalf("first attempt carried a previous-attempt section:\n%s", prompts[0]) + } + second := prompts[1] + if !strings.HasPrefix(second, prompts[0]) { + t.Fatal("retry prompt does not extend the original prompt") + } + for _, want := range []string{"# Previous attempt", "attempt 2 of stage " + def.Key, "provider overloaded", "Partial edits", "[truncated]"} { + if !strings.Contains(second, want) { + t.Fatalf("retry prompt missing %q:\n%s", want, second[len(prompts[0]):]) + } + } + if extra := len(second) - len(prompts[0]); extra > 2600 { + t.Fatalf("previous-attempt section is unbounded: %d bytes", extra) + } +} diff --git a/internal/turn/attempt.go b/internal/turn/attempt.go new file mode 100644 index 00000000..c6918540 --- /dev/null +++ b/internal/turn/attempt.go @@ -0,0 +1,57 @@ +package turn + +import ( + "fmt" + "strings" +) + +// PreviousAttemptCap bounds the diagnostic carried into a "# Previous attempt" +// section. A failure's head usually names the cause, so the head is kept. +const PreviousAttemptCap = 2000 + +// PreviousAttempt describes the attempt that failed before this one: a run +// retry (the source run's failing stage) or a stage's own in-stage retry. +type PreviousAttempt struct { + // Attempt is the 1-based number of the attempt that is about to run. + Attempt int + // Stage is the stage the previous attempt failed in. + Stage string + // Diagnostic is why it failed; it is bounded when rendered. + Diagnostic string + // Run is the failed source run for a run retry; 0 for an in-stage retry. + Run int64 +} + +// RenderPreviousAttempt renders a bounded "# Previous attempt" section that +// tells a retried stage why the last attempt failed, so it does not repeat the +// same mistake, and that partial edits from it may remain in the worktree. +func RenderPreviousAttempt(p PreviousAttempt) string { + var b strings.Builder + b.WriteString("# Previous attempt\n\n") + attempt := p.Attempt + if attempt < 2 { + attempt = 2 + } + stageName := oneLine(p.Stage) + if stageName == "" { + stageName = "unknown" + } + if p.Run > 0 { + fmt.Fprintf(&b, "This is attempt %d. The previous attempt (run %d) failed in stage %s.", attempt, p.Run, capLine(stageName, essentialLineCap)) + } else { + fmt.Fprintf(&b, "This is attempt %d of stage %s. The previous attempt failed.", attempt, capLine(stageName, essentialLineCap)) + } + b.WriteString(" Partial edits from it may still be in the worktree; check them before redoing work.\n") + detail := strings.TrimSpace(p.Diagnostic) + if detail == "" { + b.WriteString("\nNo diagnostic was recorded.\n") + return b.String() + } + if len(detail) > PreviousAttemptCap { + detail = strings.ToValidUTF8(cutAtRune(detail, PreviousAttemptCap), "") + "\n[truncated]" + } + b.WriteString("\nDiagnostic:\n\n~~~\n") + b.WriteString(strings.ReplaceAll(detail, "~~~", "~ ~ ~")) + b.WriteString("\n~~~\n") + return b.String() +} diff --git a/internal/turn/attempt_test.go b/internal/turn/attempt_test.go new file mode 100644 index 00000000..d63840a9 --- /dev/null +++ b/internal/turn/attempt_test.go @@ -0,0 +1,66 @@ +package turn + +import ( + "strings" + "testing" +) + +func TestRenderPreviousAttemptIsBoundedAndNamesTheFailure(t *testing.T) { + text := RenderPreviousAttempt(PreviousAttempt{Attempt: 3, Stage: "land", Run: 42, Diagnostic: "checks failed: go test ./...\n~~~\n" + strings.Repeat("y", 9000)}) + for _, want := range []string{"# Previous attempt", "attempt 3", "run 42", "stage land", "checks failed", "Partial edits", "[truncated]"} { + if !strings.Contains(text, want) { + t.Fatalf("missing %q:\n%s", want, text) + } + } + if len(text) > PreviousAttemptCap+500 { + t.Fatalf("section is %d bytes", len(text)) + } + // A diagnostic cannot close the fence early. + if strings.Count(text, "~~~") != 2 { + t.Fatalf("diagnostic broke the fence:\n%s", text) + } + empty := RenderPreviousAttempt(PreviousAttempt{Stage: "plan"}) + if !strings.Contains(empty, "No diagnostic was recorded.") || !strings.Contains(empty, "attempt 2 of stage plan") { + t.Fatalf("empty diagnostic rendering:\n%s", empty) + } +} + +// TestEssentialMemoryRevisitShowsOwnPreviousHandoff proves a stage that runs +// again (a reviewer after the implementer fixed its findings) sees its own last +// handoff, bounded, besides the immediately previous stage's handoff. +func TestEssentialMemoryRevisitShowsOwnPreviousHandoff(t *testing.T) { + entries := feedbackLoopEntries() + entries = append(entries, MemoryEntry{Stage: "code", Visit: 2, Outcome: "success", Output: "# handoff\n\nFixed the lock leak and added the eviction test.\n"}) + memory := RenderEssential(Essential{Task: "Add a cache.", StageKey: "review", Entries: entries, InputPath: "in.md", HistoryPath: "hist.md"}) + if len(memory) > EssentialCap { + t.Fatalf("essential memory is %d bytes, over the cap", len(memory)) + } + for _, want := range []string{ + "## Previous stage: code · visit 2", + "Fixed the lock leak", + "## This stage's previous visit: review · visit 1 · outcome changes_requested", + "cache.go:42 leaks the lock on the error path.", + } { + if !strings.Contains(memory, want) { + t.Fatalf("memory missing %q:\n%s", want, memory) + } + } + if strings.Contains(memory, "Long preamble.") { + t.Fatalf("own handoff carried non-handoff text:\n%s", memory) + } + + // Long own handoffs are bounded with a pointer to history.md. + entries[2].Output = "# handoff\n\n" + paragraph("finding", 5000) + memory = RenderEssential(Essential{Task: "Add a cache.", StageKey: "review", Entries: entries, InputPath: "in.md", HistoryPath: "hist.md"}) + if len(memory) > EssentialCap || !strings.Contains(memory, "full text in history.md") { + t.Fatalf("own handoff not bounded (%d bytes):\n%s", len(memory), memory) + } + + // No own section on a first visit or when the previous turn is this stage. + for _, key := range []string{"land", "code"} { + memory = RenderEssential(Essential{Task: "Add a cache.", StageKey: key, Entries: entries}) + if strings.Contains(memory, "This stage's previous visit") { + t.Fatalf("%s got an own-handoff section:\n%s", key, memory) + } + } +} diff --git a/internal/turn/essential.go b/internal/turn/essential.go index ce93ad6d..618ebc93 100644 --- a/internal/turn/essential.go +++ b/internal/turn/essential.go @@ -19,6 +19,9 @@ const ( // essentialHandoffMin is the least room a previous stage's handoff gets // when the task also needs more than half of the remaining budget. essentialHandoffMin = 1024 + // essentialOwnHandoffCap bounds a revisiting stage's own last handoff + // (for example a reviewer's earlier must-fix findings it must confirm). + essentialOwnHandoffCap = 768 ) // Essential is everything RenderEssential needs for one visit's memory.md. @@ -63,6 +66,7 @@ func RenderEssential(e Essential) string { fixed.WriteString("\n") var tail strings.Builder + tail.WriteString(renderOwnHandoff(e.Entries, e.StageKey)) if ledger := renderLedger(e.Entries, e.StageKey); ledger != "" { tail.WriteString("\n## Stage ledger\n\n") tail.WriteString(ledger) @@ -180,6 +184,30 @@ func HandoffSection(markdown string) (string, bool) { return section, section != "" } +// renderOwnHandoff returns a bounded section with the stage's own handoff from +// its latest earlier visit, so a revisiting stage (a reviewer confirming its +// previous must-fix findings) sees what it said last time. It is empty on a +// first visit and when that visit is the immediately previous turn, which the +// "Previous stage" section already shows. +func renderOwnHandoff(entries []MemoryEntry, current string) string { + if current == "" { + return "" + } + for i := len(entries) - 1; i >= 0; i-- { + if entries[i].Stage != current { + continue + } + if i == len(entries)-1 { + return "" + } + own := entries[i] + body, source := previousHandoff(own.Output) + title := capLine(fmt.Sprintf("%s · visit %d%s", oneLine(own.Stage), own.Visit, outcomeSuffix(own.Outcome)), 2*essentialLineCap) + return "\n## This stage's previous visit: " + title + "\n\n" + source + truncateWithNote(body, essentialOwnHandoffCap, "history.md") + "\n" + } + return "" +} + func previousHandoff(output string) (string, string) { if section, ok := HandoffSection(output); ok { return strings.TrimSpace(demoteHeadings(section)), ""