Merge main; align lint and skill practices with essential memory/history and the four graded examples

This commit is contained in:
2026-11-04 13:08:47 +00:00
217 changed files with 8560 additions and 1937 deletions
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"path/filepath"
)
var skillFiles = []string{"SKILL.md", "references/orchestration.md", "references/work.md", "references/queue.md", "references/debugging.md", "references/delivery.md", "references/format.md", "references/notifications.md", "references/operations.md", "references/transfer.md", "references/verification.md", "references/control.md", "references/harnesses.md", "references/access.md", "references/schedules.md"}
var skillFiles = []string{"SKILL.md", "references/orchestration.md", "references/work.md", "references/queue.md", "references/debugging.md", "references/delivery.md", "references/format.md", "references/notifications.md", "references/operations.md", "references/transfer.md", "references/verification.md", "references/control.md", "references/harnesses.md", "references/access.md", "references/schedules.md", "references/practices.md"}
func SkillDirectory() (string, error) {
dir := os.Getenv("XDG_CONFIG_HOME")
+14 -6
View File
@@ -35,8 +35,11 @@ explain the gap; ask before authoring. Do not add a task-specific pipeline as a
## Authoring
A definition is Markdown: `# stage <Name>` sections with `prompt`, `configs`,
`tools`, `edges`, and optional `limits`/`checks`. Start from
`examples/`. Use stage names that describe the work:
`tools`, `edges`, and `limits`/`checks` where required: every stage that can
modify the workspace declares `checks` (commands on the `delivery=true` stage,
otherwise `none: <reason>`), and every loop has `limits`. Start from
`examples/` and read `references/practices.md` before writing prompts. Use stage
names that describe the work:
`Plan` · `Code` · `Review` · `UIReview` · `Land` (`Prepare` and `Survey` are
useful variants).
@@ -46,8 +49,10 @@ constraints. The runner enforces turns, tools and limits; prompts do not need to
repeat them. Only `# outcome` is parsed from `output.md`; everything else is
free markdown. Use `links` and `memory` only when they clarify a handoff.
`pipelines validate DRAFT` checks a draft; `pipelines submit DRAFT` publishes a
new immutable version. `pipelines help <command>` has flags.
`pipelines validate DRAFT` checks a draft, including the authoring rules in
`references/practices.md` (errors block submit; `warning:` lines do not but should
be fixed); `pipelines submit DRAFT` publishes a new immutable version.
`pipelines help <command>` has flags.
Schedules are separate saved run configurations: pipeline/version, prompt,
workspace and other run options, plus timing. Never add `# settings` or schedule
@@ -58,10 +63,12 @@ explicitly asks to manage a schedule; scheduling alone is not workflow authoring
## Turns and artifacts
Each visit has `input.md` (the run prompt; later visits add the previous body), `memory.md`
(completed turns), `output.md`, and `private/`. Every run also has one shared
(short essential memory inlined in the prompt: task, previous stage's `# handoff`,
outcome ledger, changed files; 4 KB cap), `history.md` (completed turns in full,
read on demand), `output.md`, and `private/`. Every run also has one shared
`public/` directory, addressed by its absolute path; files there are visible to
later stages and are the stage's real artifacts. `input.md`, `memory.md`,
`output.md` and `session.html` are system evidence for auditing, not stage
`history.md`, `output.md` and `session.html` are system evidence for auditing, not stage
output.
## References
@@ -71,6 +78,7 @@ Read only what the task needs:
| Need | Reference |
| --- | --- |
| Definition syntax and turn files | `references/format.md` |
| Good practices (tokens, checks, prompts, loops) | `references/practices.md` |
| Limits, tools and permissions | `references/control.md` |
| Stages, parallel work, recovery | `references/orchestration.md` |
| CLI, storage and evidence | `references/operations.md` |
+3 -2
View File
@@ -41,8 +41,9 @@ nonterminal edge. Without `on`, entering beyond the cap fails before execution.
Global 30-step/five-visits-per-stage safety limits still apply.
A model stage reads its turn's `input.md` (the run prompt on the first visit,
the previous turn's output afterwards) and `memory.md` (completed turns with the
files each added to `public/`). The `memory` block is retired: it no longer
the previous turn's output afterwards), its inlined, capped `memory.md` (task,
previous stage's `# handoff`, outcome ledger, changed files) and, on demand,
`history.md` (completed turns in full with the files each added to `public/`). The `memory` block is retired: it no longer
selects fields or replaces previous output for model stages, and old definitions
that contain one parse but ignore it. Reviewers therefore see the previous
turn's output and the accumulated memory rather than a field projection.
+87 -23
View File
@@ -4,8 +4,8 @@ Definitions are Markdown made only of `# stage KEY` headings and fenced blocks.
Scheduling belongs to separate saved run configurations, not `# settings` or
schedule blocks in the definition. No unrelated prose outside blocks. The first
stage receives the run prompt in its `input.md`; later stages receive
the previous turn's output. Every visit also gets a `memory.md` of completed
turns. There are no stage `input`, `output`, or `memory` blocks: the model reads
the previous turn's output. Every visit also gets a short `memory.md` (essential
memory, inlined in the prompt) and a full `history.md` of completed turns. There are no stage `input`, `output`, or `memory` blocks: the model reads
the turn files and writes free-form markdown, and only the `# outcome` section is
interpreted. Read `references/control.md` for runner-enforced limits.
@@ -15,7 +15,7 @@ Each model stage requires nonempty `prompt`, `configs`, and `edges` blocks:
# stage worker
```prompt
Perform the task. Write the complete output.md markdown; only `# outcome` is required.
Perform the task.
```
```configs
@@ -42,17 +42,64 @@ An omitted error edge defaults to failure. Execution is sequential; forks choose
one outcome, never execute parallel branches. Cycles are allowed; every stage
must be reachable from entry and have a possible path to a terminal. Use bounded
runner-owned `limits` for feedback loops, never revision counters in model
prompts/outputs. Read `references/control.md` for the exact format.
prompts/outputs: publishing rejects an edge to the same or an earlier stage
(definition order) unless the source stage limits that outcome or the target
stage has `limits` (a human stage's choices are exempt). Read
`references/control.md` for the exact format.
## Checks
Every model stage that can modify the workspace (it declares `edit` or `shell`,
has no `tools` block, or sets `delivery=true`) must declare a `checks` block, so
the author decides where verification happens. Read-only stages need none.
- A `delivery=true` stage lists 1–20 commands, one per line. The server runs them
on the committed candidate (and again on a merged tree) before landing; a
failing command blocks landing. These are the run's deterministic checks.
- Every other stage writes exactly one line, `none: <reason>`, naming where
verification happens instead, for example
`none: focused tests only; the Land delivery gate runs the suite` or
`none: read-only review; shell is used only for git diff`. Commands on a
non-delivery stage are rejected because nothing would run them.
A check must fail when it cannot run. Validation rejects guards that pass
without running anything: `|| true`, `|| :`, `|| exit 0`, `|| echo`,
`[ ! -x tool ] || ...`, `test ! -f ... || ...`, `! command -v tool || ...`,
an `if ...; then ...; fi` with no failing else, and `set +e`. Cover every
language the run can change (a Go-only check list does not verify Flutter work).
`pipelines validate` reports these with the remaining authoring rules
(`references/practices.md`).
## Result format
Each visit gets `input.md`, `memory.md`, `output.md` and `private/` in
`<run>/stages/<seq>-<stage>/`, plus the run-level shared `public/`. The model
reads input and memory and returns the complete `output.md` markdown. The only
required section is the outcome heading, followed by one of the stage's declared
edge words:
Each visit gets `input.md`, `memory.md`, `history.md`, `output.md` and
`private/` in `<run>/stages/<seq>-<stage>/`, plus the run-level shared
`public/`. What a stage receives:
- `memory.md` (essential, hard cap 4 KB, always inlined in the prompt): the run
task, the previous stage's handoff with its outcome and public/ additions, a
one-line-per-stage outcome ledger (latest visit; a revisit is marked) and the
server-captured changed files. A stage must be able to work from this alone.
- `input.md` (on demand): the full run task and the previous turn's full output.
- `history.md` (on demand, never inlined): every completed turn in full, the
format `memory.md` had before essential memory existed.
Stages with `read` are told the two on-demand paths; stages without it get
`input.md` inlined too (capped at 32 KB) but never `history.md`.
The previous stage's handoff is its `# handoff` section (any level, up to the
next heading of the same or higher level); without one the server uses the head
of its output, marked as such. Either is truncated to fit with a pointer to
`input.md`, so nothing depends on the model following the convention. The
prompt asks every stage to start its output with a short handoff: what it did,
files changed, open issues or findings. The only required section is the
outcome heading, followed by one of the stage's declared edge words:
````markdown
# handoff
Fixed both review findings in cache.go; tests pass. No open issues.
# outcome
success
@@ -82,6 +129,14 @@ and accepts integers 0–100; explicit 0 disables execution retries. Optional
`timeout` defaults to `1h` per attempt and accepts positive durations such as
`30m` or `90s`.
A stage that declares a `skipped` edge (for example a UI reviewer) is eligible
for the server skip fallback: when every earlier visit's file-change capture was
complete and recorded no changed files or screenshots, the server completes the
stage as `skipped` without a model call (`reason_source: fallback`). Any recorded
change or incomplete capture runs the model. Optional `auto_skip=false` (values
`true`/`false`, default `true`) always runs the model. Read
`references/operations.md` ("Server skip fallback") for the exact rule.
Optional `reasoning_effort=high` selects a model's reasoning/thinking level for
this stage. Values are `default`, `none` (alias `off`), `minimal`, `low`, `medium`,
`high`, `xhigh`, or `max`. Omission or `default` preserves the harness/model
@@ -123,13 +178,13 @@ run directory; no file list is required. `shell` supports commands appropriate t
the repository's language and tooling, not a language-specific allowlist. A missing
tools block uses local read/glob/grep/edit/shell tools; prefer explicit stage roles.
Planning stages must not label a task blocked simply because they defer edits to
an implementer stage. Bundled starters show the intended role split: a task stage
may read/edit/shell and conditionally use `websearch`/`webfetch`; a planner may
read plus conditional web search/fetch; a three-stage implementer has no web tools
and works from the planner's research with local read/glob/grep/edit/shell; a
reviewer may read plus conditional web; a source-only review stage has no
edit/shell; a research stage uses web search/fetch; a committer has read/glob/grep
and shell but no edit. Never force web access for
an implementer stage. The intended role split: an implementer may
read/glob/grep/edit/shell; a planner reads, plus conditional web search/fetch only
when external knowledge is needed; a reviewer reads and may run read-only checks
with shell but never edits; a source-only review stage has no edit/shell; a
research stage uses web search/fetch; a committer has read/glob/grep and shell but
no edit. The bundled examples (`one-stage`, `two-stages`, `feedback-loop`,
`human-decision`) follow it without web tools. Never force web access for
trivial, fully understood local edits, and return blocked only when required
reliable evidence cannot be obtained rather than whenever one search tool fails.
Keep examples and prompts language-neutral unless the task itself asks for a
@@ -204,6 +259,10 @@ grep
shell
```
```checks
none: commits locally; the manager lands and runs the suite
```
```edges
success -> #success
blocked -> #failure
@@ -211,6 +270,10 @@ error -> #failure
```
````
A landing committer instead sets `delivery=true` in `configs` and lists the
repository's required check commands in `checks`; the server runs them, so its
prompt does not run the suite again.
State this pre-commit checklist in the prompt:
1. Inspect `git status` and the full diff. Stage this run's change, including
@@ -218,9 +281,10 @@ State this pre-commit checklist in the prompt:
exclusion. Do not rely on a model-declared file list.
2. Inspect the staged diff before committing; never commit unrelated work, secrets
or generated artifacts.
3. Run the repository's required checks and record the exact commands and observed
results as evidence. Do not commit when a required check fails; return `blocked`
with the failing output instead.
3. Without a delivery gate, run the repository's required checks once (summary
output) and record the exact commands and observed results as evidence. Do not
commit when a required check fails; return `blocked` with the failing output
instead. With `delivery=true` the server runs the `checks` block; skip this step.
4. Create no empty commit: when nothing is staged, return `success` with a clear
note.
5. Commit with a concise message naming the run's change and report the commit hash;
@@ -231,9 +295,9 @@ State this pre-commit checklist in the prompt:
documentation writer folds notes later (`references/orchestration.md`). An item that
staled no shared document has no note and needs no step 6.
This list is the canonical checklist. The bundled starters `task`, `three-stage` and
`docs-fold` each repeat it in their committer prompt because a template is embedded and
published on its own; keep those copies in sync with this list.
This list is the canonical checklist. Repeat it in each committer prompt, because a
definition is published on its own; keep those copies in sync with this list. The
bundled examples leave changes uncommitted and have no committer.
The committer prepares the complete clean candidate and resolves integration conflicts.
When `delivery=true`, the server executes the declared checks and lands after the
@@ -274,6 +338,6 @@ stage parks the run), `artifacts=markdown`.
Read this skill's `references/notifications.md` for the minimal terminal-path
recipe and optional native publisher format. Prefer hooks for ordinary success/error
alerts; a request to notify is not a request for a new delivery stage. Do not scan
the user's repository for Pipelines docs. Bundled starters are generic and manual-only.
the user's repository for Pipelines docs. Bundled examples are generic and manual-only.
Notification attachment/report support and model availability need real runtime
tests; structural validation alone cannot confirm delivery.
+32 -11
View File
@@ -10,8 +10,9 @@ parallel/distributed task engine or a guarantee that model reports are correct.
- Drafts are editable Markdown plus JSON metadata. Publishing validates and creates
immutable versions; drafts remain retained. Keep context create-only/base-version
guards. Five optional generic starters are task, three-stage, review, research
and debug; a fresh database starts empty. Templates can be created directly with
guards. The four generic examples (one-stage, two-stages, feedback-loop,
human-decision) are the template set; a brand-new database is seeded with them
once, and an existing or already-seeded database never is. Templates can be created directly with
an editable prefilled name or customized first. Editing a bundled repository
template changes no installed or published definition; only explicit authoring
then submission creates a new immutable version.
@@ -190,9 +191,14 @@ The stage's File changes section highlights added/removed lines and hunk headers
node_modules and common environment/key/credential/database paths are excluded.
This is path-based protection, **not secret-content scanning**. Patches may still
contain sensitive text; never publish them without approval.
- Limits: 10,000 entries, 1 MiB/file, 32 MiB/snapshot, five-second snapshot context,
5,000 combined text lines, 64 KiB/patch, 128 KiB serialized file evidence/visit.
Missing/skipped/truncated captures must be described as partial/unavailable.
- Limits: 10,000 entries, 1 MiB/file and 32 MiB/snapshot of retained text,
256 MiB/hashed file, five-second snapshot context, 5,000 combined text lines,
64 KiB/patch, 128 KiB serialized file evidence/visit. Text over the 1 MiB or
32 MiB budget is still compared by hash, and in Git a path the snapshot could
not compare is listed when its `git status` entry changes; such entries carry
`no_patch: true` (and `truncated`) with no patch, and the visit is `partial`.
Missing/skipped/truncated captures must be described as partial/unavailable;
`inspect` adds a run-level `warnings` entry naming every partial/unavailable visit.
- Failed/canceled stages retain changes when execution returns; unconfirmed agent
cleanup is partial. Crashes may have no after-capture. Historical visits say
not recorded—**never infer no edits from absent evidence**.
@@ -200,22 +206,36 @@ The stage's File changes section highlights added/removed lines and hunk headers
changes outside scope, ignored new files and changes reverted before capture can
be absent or mixed in. Capture failure does not change the declared run verdict.
### Server skip fallback (`skipped` edge)
A non-human stage that declares a `skipped` edge is completed by the server, with
no model call, and routed along `skipped` only when **every** earlier visit of the
run recorded `file_changes` with status `complete`, none recorded any changed file,
and none captured an image artifact. The step's verdict reason starts
"Server fallback skip (no model run):" with `reason_source: fallback`. Any changed
file (no path or extension is treated as "not UI"), any partial/unavailable or
missing capture (crash, historical row, human decision, checkpoint-retry prefix)
runs the model, which may still answer `skipped` itself. `auto_skip=false` in the
stage's `configs` disables the fallback for that stage. Never describe a fallback
skip as a model judgement, and never treat it as evidence that nothing changed.
Do not add model output fields, new stages or extra model calls merely to obtain
file diffs: current capture is server-owned. Do not promise full files/rollback.
## Retained stage artifacts
Every model visit gets a file-based turn under the data directory
(`<data>/artifacts/<run>/stages/<seq>-<stage>/`) with `input.md`, `memory.md`,
`output.md` and `private/`; `public/` is run-level and shared by every stage.
(`<data>/artifacts/<run>/stages/<seq>-<stage>/`) with `input.md`, `memory.md`
(capped essential memory, inlined), `history.md` (full earlier turns, read on
demand), `output.md` and `private/`; `public/` is run-level and shared by every stage.
The root is configurable and defaults next to the database. The writable
`private/` and shared `public/` directories are stated in the agent prompt for
every harness, and `PIPELINES_ARTIFACTS_DIR` points at the turn directory for a
locally spawned Pi process. OpenCode V2 tools run inside the shared serve
process, so there the prompt, not the environment, is the reliable carrier.
Turn-local files belong in `private/`; reports, logs and screenshots for later
stages belong in `public/`. The server owns `input.md`, `memory.md` and
`output.md` and never asks the model to write them directly.
stages belong in `public/`. The server owns `input.md`, `memory.md`,
`history.md` and `output.md` and never asks the model to write them directly.
After the visit the server makes one bounded inventory of the turn and public
directories and records each file's name, size, content type (extension, sniff
@@ -223,8 +243,9 @@ fallback) and a relative url; these appear under each step's `artifacts` in
`inspect RUN_ID --json` and the TUI's `A` artifacts view, which groups them by
stage and visit, marks images and shows the recorded count,
capture-pending/not-recorded wording and partial-capture notes. Public entries
carry a `public/` prefix. `input.md`, `memory.md` and `output.md` are the primary
artifacts of every model visit.
carry a `public/` prefix. `input.md`, `memory.md`, `history.md` and `output.md`
are the primary artifacts of every model visit. To see what a late stage was
given, read its `memory.md`; `history.md` is the full record it could consult.
`GET /artifacts/<run>/<step>/<name>` serves the bytes (correct Content-Type and
Content-Length, HEAD, and Range/206/416 via `http.ServeContent`), refusing
traversal, absolute paths, symlink escapes and unknown runs/steps. A pre-turn
@@ -0,0 +1,69 @@
# Good practices
Pipelines are written by models through this skill, and a run's cost is roughly
model calls × context per call. Most waste comes from stages that re-read or
re-generate large output. `pipelines validate` enforces the mechanical rules
below (errors block publishing; warnings print and do not).
## Where work belongs
- **Deterministic checks belong in the server `checks` block, not the model.**
The landing stage sets `delivery=true` and lists the full check commands; the
server runs them on the committed candidate. A model running the suite puts
every log line into its context, and every later call pays for it again.
- **Code runs focused tests only**: the test file or package it touched, with
quiet or summary output. Never the full suite.
- **Review reads the diff, not the repository.** Start from the server-captured
changed-file list the runner adds to the prompt and `git diff --stat`, then read
only the changed hunks and the code around them. Review runs no suites; it judges
the reported checks and names missing coverage.
- **Land/committer relies on server checks.** With a delivery gate its prompt
commits and stops; it does not re-run what the gate runs. Do not claim "the
server lands it" unless a stage has `delivery=true` (error otherwise).
- Every stage that can modify the workspace declares `checks`, even if only
`none: <reason>` (`references/format.md`, Checks). Checks must fail when a tool
is missing: no `|| true`, `[ ! -x tool ] || ...` or similar guards (error).
Cover every language the run can change.
## Prompts
- **Short stage prompts**: the goal and the real constraints. Over 2000 bytes
warns. Shared procedure belongs in project docs or this skill.
- **No runner boilerplate.** The runner already explains `output.md`, the
`# outcome` and `# handoff` sections, allowed outcomes, turn files, tools and
honesty rules (`internal/stage/model_prompt.go`). Repeating them warns.
- **Every outcome a prompt names is a declared edge.** "Return skipped" with no
`skipped` edge, or an undeclared `blocked_retryable`, fails the stage at run
time; validation rejects it (unquoted outcome words such as `skipped`,
`blocked`, `rejected`, `approved`, `advisory`; other back-quoted words after
return/report warn).
## Memory and handoffs
- The runner inlines the **essential memory** (`memory.md`: task, previous
stage's handoff, outcome ledger, changed files; capped) into every prompt, and
asks each stage to start its output with a short `# handoff`: what it did,
outcome, files changed, open findings, in a few lines. Do not repeat that
instruction; say only what this stage's handoff must carry if it is special.
- The **full history** (`history.md`) and full `input.md` are on demand. Never
tell a stage to read the whole history every visit (warning); say when it
needs it, e.g. "read history.md only if the handoff lacks a detail you need".
## Loops and budgets
- **Loops get limits.** An edge back to the same or an earlier stage needs
`limits` on the source outcome or the target (error). Use `max_visits` 2–3.
- **Re-entry gets only findings**: a rejected review hands back must-fix items
with location and fix, not a full re-review, and the implementer fixes those
items rather than redoing the task. Use `advisory` for non-blocking notes so
they do not buy another loop.
- Set **per-stage `budget_tokens`** (and `budget_usd` if wanted) as a runaway
guard on stages that loop or explore, sized a few times a normal visit.
## Commands and scope
- **Quiet commands**: summary flags, `git diff --stat` before a full diff,
`grep`/`glob` before `read`, read file ranges rather than whole files, tail or
filter long logs, never print generated or vendored files.
- **Small task scope**: one independently testable change per run (roughly a
10–15 minute change). Split larger work into several runs in parallel.
+32
View File
@@ -118,3 +118,35 @@ func TestForegroundCommandsAndAgentsFinishWithTheirResult(t *testing.T) {
t.Fatalf("stray notifications list nothing, got %+v", shells)
}
}
// Background commands and subagents run inside the CLI process, so a process
// that exits (crash, idle release, interrupt) ends them: each is reported as
// exited instead of staying "running" with nothing left to report its end.
func TestProcessExitEndsBackgroundTasks(t *testing.T) {
chat, s := backgroundSession(t)
s.handleLine(nil, toolUse(t, "toolu_bg", "Bash", map[string]any{"command": "sleep 600", "run_in_background": true}))
s.handleLine(nil, toolResult(t, "toolu_bg", "Command running in background with ID: b9. Output is being written to: /tmp/b9.output"))
if shells := running(t, chat); len(shells) != 1 {
t.Fatalf("the background command must be running first, got %+v", shells)
}
subs := attachTestSubs(s, 1)
defer detachTestSubs(s, subs)
proc := &process{session: s}
s.mu.Lock()
s.proc = proc
s.mu.Unlock()
s.processExit(proc, nil)
if shells := running(t, chat); len(shells) != 0 {
t.Fatalf("a process exit must end its background tasks, got %+v", shells)
}
select {
case frame := <-subs[0]:
if frame.Kind != protocol.ChatEventShell || frame.Shell == nil || frame.Shell.Status != protocol.ChatShellExited || frame.Shell.Command != "sleep 600" {
t.Fatalf("the exit is published as a shell exit, got %+v", frame)
}
default:
t.Fatal("no shell exit was published")
}
}
+7
View File
@@ -379,7 +379,14 @@ func (s *session) processExit(p *process, err error) {
s.steered = 0
s.awaitFollowUp = false
s.resetStreamLocked()
// Background commands and subagents run inside the CLI process, so its
// exit ends them: report each as exited, or it would stay "running" (in the
// chat list and in chat_shells) with nothing left to report its end.
ended := s.endShellsLocked()
s.mu.Unlock()
for _, shell := range ended {
s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: shell})
}
if !running {
return
}
+16
View File
@@ -791,6 +791,22 @@ func (s *session) finishNotifiedTask(line []byte) {
))
}
// endShellsLocked marks every command still running as exited (with no exit
// code: none was reported) and returns their final states, sorted by id, for
// the caller to publish once s.mu is released. Callers hold s.mu.
func (s *session) endShellsLocked() []*protocol.ChatShell {
var ended []*protocol.ChatShell
for _, snapshot := range s.shells {
if snapshot.shell.Status != protocol.ChatShellRunning {
continue
}
snapshot.shell.Status = protocol.ChatShellExited
ended = append(ended, &protocol.ChatShell{ID: snapshot.shell.ID, Status: snapshot.shell.Status, Command: snapshot.shell.Command})
}
sort.Slice(ended, func(i, j int) bool { return ended[i].ID < ended[j].ID })
return ended
}
// finishBackgroundTasks marks the tasks a Claude Code task notification
// reports as finished, and publishes each one's final state.
func (s *session) finishBackgroundTasks(text string) {
+7
View File
@@ -1004,6 +1004,13 @@ func (a App) Run(ctx context.Context, args []string) error {
if err != nil {
return err
}
if command == "inspect" && r.RunDetail != nil {
// Warnings are also in the JSON; stderr keeps them visible to a reader
// of the human stream without corrupting machine-readable stdout.
for _, warning := range r.RunDetail.Warnings {
a.notice("warning: " + warning)
}
}
return a.output(r.RunDetail)
case "decide":
if len(pos) < 1 || len(pos) > 2 {
+2 -2
View File
@@ -96,7 +96,7 @@ func TestCLIStatusAndStatistics(t *testing.T) {
func TestCLIDraftValidateSubmitAndImmutableHistory(t *testing.T) {
run, store, _ := setup(t)
output, err := run("new", "example", "--template", "task", "--json")
output, err := run("new", "example", "--template", "one-stage", "--json")
if err != nil {
t.Fatal(err)
}
@@ -171,7 +171,7 @@ func TestCLIDraftValidateSubmitAndImmutableHistory(t *testing.T) {
if items[0].Version != 3 {
t.Fatal("invalid submission changed live version", items)
}
for _, command := range [][]string{{"list", "--json"}, {"show", "example", "--json"}, {"templates", "--json"}, {"template", "task", "--source"}, {"drafts", "--json"}, {"runs", "--json"}, {"connection", "--json"}, {"ping"}} {
for _, command := range [][]string{{"list", "--json"}, {"show", "example", "--json"}, {"templates", "--json"}, {"template", "one-stage", "--source"}, {"drafts", "--json"}, {"runs", "--json"}, {"connection", "--json"}, {"ping"}} {
if _, err = run(command...); err != nil {
t.Fatal(command, err)
}
+1 -1
View File
@@ -52,7 +52,7 @@ var notes = map[string]string{
"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.",
"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). `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.",
"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).",
"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.",
+1 -1
View File
@@ -78,7 +78,7 @@ Examples:
Authoring examples — use only when the operator explicitly requested a definition change:
pipelines edit "bug fix" "Add a review step"
pipelines new "release notes" "Summarize changes and notify my phone"
pipelines new "Add a feature" --template task --no-open --json --yes
pipelines new "Add a feature" --template feedback-loop --no-open --json --yes
pipelines validate /path/to/draft.md --json
pipelines submit /path/to/draft.md
+191 -37
View File
@@ -14,6 +14,7 @@ import (
"os/exec"
"sort"
"strings"
"sync/atomic"
"syscall"
"unicode/utf8"
@@ -28,13 +29,37 @@ const (
maxPatchBytes = 128 << 10
maxFilePatchBytes = 64 << 10
maxLines = 5000
binarySniffBytes = 8 << 10
)
// maxHashBytes bounds one hash-only file; larger files are skipped (and, in a
// Git working tree, listed only when their Git status changes). It is a
// variable so package tests can exercise that path without huge files.
var maxHashBytes int64 = 256 << 20
// snapshotBudget is the retained text bytes per snapshot. Files beyond it (or
// beyond the per-file limit) are still compared by content hash and listed
// without a patch, so an over-budget workspace never hides which files changed.
var snapshotBudget atomic.Int64
func init() { snapshotBudget.Store(maxSnapshotBytes) }
// SetSnapshotBudgetForTesting lowers the retained-text budget so tests can
// exercise an over-budget workspace without writing tens of megabytes. It
// returns a function restoring the previous budget. Production never calls it.
func SetSnapshotBudgetForTesting(n int64) (restore func()) {
previous := snapshotBudget.Swap(n)
return func() { snapshotBudget.Store(previous) }
}
type file struct {
data []byte
hash [32]byte
mode fs.FileMode
binary bool
// hashOnly marks a text file compared by content hash only: it exceeded the
// per-file or per-snapshot text budget, so no patch can be produced.
hashOnly bool
}
type Snapshot struct {
@@ -44,6 +69,63 @@ type Snapshot struct {
available bool
diagnostic string
scope string
// gitStatus maps run-relative paths to their porcelain XY status code when
// the run directory is a Git working tree and the status read succeeded
// (gitOK). Compare uses it to list changed paths the content snapshot could
// not compare (time/file limit, unreadable); it never reads HEAD/index content.
gitStatus map[string]string
gitOK bool
}
// readGitStatus reads `git status --porcelain=v1 -z` for the run directory and
// returns its paths relative to that directory. It only reads: optional locks
// are disabled so the index is never refreshed or rewritten.
func readGitStatus(ctx context.Context, directory string) (map[string]string, bool) {
prefixOut, err := exec.CommandContext(ctx, "git", "-c", "core.fsmonitor=false", "-C", directory, "rev-parse", "--show-prefix").Output()
if err != nil {
return nil, false
}
prefix := strings.TrimSpace(string(prefixOut))
cmd := exec.CommandContext(ctx, "git", "--no-optional-locks", "-c", "core.fsmonitor=false", "-C", directory, "status", "--porcelain=v1", "-z", "--no-renames", "--untracked-files=all", "--", ".")
out := &boundedOutput{limit: 4 << 20}
cmd.Stdout = out
if err := cmd.Run(); err != nil {
return nil, false
}
status := map[string]string{}
for _, entry := range strings.Split(out.String(), "\x00") {
if len(entry) < 4 || entry[2] != ' ' {
continue
}
name, ok := strings.CutPrefix(entry[3:], prefix)
if !ok || name == "" {
continue // outside the run directory
}
status[name] = entry[:2]
}
return status, true
}
// hashFile streams f from its start into a content hash without retaining it.
// It returns ok=false when the file exceeds maxHashBytes or cannot be read.
func hashFile(f *os.File) (hash [32]byte, binary bool, ok bool) {
if _, err := f.Seek(0, io.SeekStart); err != nil {
return hash, false, false
}
h := sha256.New()
head := make([]byte, binarySniffBytes)
n, err := io.ReadFull(f, head)
if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) && !errors.Is(err, io.EOF) {
return hash, false, false
}
head = head[:n]
h.Write(head)
copied, err := io.Copy(h, io.LimitReader(f, maxHashBytes+1-int64(n)))
if err != nil || int64(n)+copied > maxHashBytes {
return hash, false, false
}
copy(hash[:], h.Sum(nil))
return hash, bytes.IndexByte(head, 0) >= 0, true
}
func protected(name string) bool {
@@ -130,6 +212,9 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
s.partial = true
s.diagnostic = "Workspace inventory incomplete."
}
if git {
s.gitStatus, s.gitOK = readGitStatus(ctx, directory)
}
// Keep pre-stage paths even if a stage changes .gitignore/the index.
known := map[string]bool{}
for _, name := range names {
@@ -179,7 +264,7 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
continue
}
info, err := root.Lstat(name)
if err != nil || !info.Mode().IsRegular() || info.Size() > maxFileBytes {
if err != nil || !info.Mode().IsRegular() || info.Size() > maxHashBytes {
s.skipped[name] = true
continue
}
@@ -194,28 +279,43 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
s.skipped[name] = true
continue
}
data, readErr := io.ReadAll(io.LimitReader(f, maxFileBytes+1))
if opened.Size() <= maxFileBytes {
data, readErr := io.ReadAll(io.LimitReader(f, maxFileBytes+1))
if readErr != nil {
f.Close()
s.skipped[name] = true
continue
}
if len(data) <= maxFileBytes {
f.Close()
binary := bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data)
hash := sha256.Sum256(data)
hashOnly := false
// Binary changes need only metadata and a hash, never retained patch bytes.
// Counting screenshots against the retained-text budget can otherwise
// exhaust it before any source files are reached in sorted inventory order.
// Text beyond the budget keeps only its hash, so a change to it is still
// listed (without a patch) instead of being skipped unseen.
if binary {
data = nil
} else if int64(used+len(data)) > snapshotBudget.Load() {
data = nil
hashOnly = true
} else {
used += len(data)
}
s.files[name] = file{data: data, hash: hash, mode: opened.Mode().Perm(), binary: binary, hashOnly: hashOnly}
continue
}
// The file grew past the per-file limit while being read: hash it.
}
hash, binary, ok := hashFile(f)
f.Close()
if readErr != nil || len(data) > maxFileBytes {
if !ok {
s.skipped[name] = true
continue
}
binary := bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data)
hash := sha256.Sum256(data)
// Binary changes need only metadata and a hash, never retained patch bytes.
// Counting screenshots against the retained-text budget can otherwise
// exhaust it before any source files are reached in sorted inventory order.
if binary {
data = nil
} else {
if used+len(data) > maxSnapshotBytes {
s.skipped[name] = true
s.partial = true
continue
}
used += len(data)
}
s.files[name] = file{data: data, hash: hash, mode: opened.Mode().Perm(), binary: binary}
s.files[name] = file{hash: hash, mode: opened.Mode().Perm(), binary: binary, hashOnly: !binary}
}
return s
}
@@ -258,6 +358,35 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
sort.Strings(names)
remaining := maxPatchBytes
retained := 0
add := func(change protocol.FileChange) {
if change.Truncated {
result.Status = "partial"
if !change.NoPatch {
result.Diagnostic = "Some patches were omitted/truncated by capture limits."
}
}
encoded, _ := json.Marshal(change)
if retained+len(encoded)+1 > maxPatchBytes {
change.Patch = ""
change.Truncated = true
encoded, _ = json.Marshal(change)
}
if retained+len(encoded)+1 > maxPatchBytes {
result.Omitted++
result.Status = "partial"
result.Diagnostic = "Additional file changes omitted by the retained evidence size limit."
return
}
if change.Truncated {
result.Status = "partial"
}
retained += len(encoded) + 1
result.Files = append(result.Files, change)
}
listed := 0
// decided records every path the content comparison settled (changed or
// not), so the Git-status pass below only speaks for the rest.
decided := map[string]bool{}
for _, name := range names {
if skipped[name] {
continue
@@ -268,6 +397,7 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
if !aOK && before.partial || !bOK && after.partial {
continue
}
decided[name] = true
if aOK && bOK && a.hash == b.hash && a.mode == b.mode {
continue
}
@@ -285,7 +415,12 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
if bOK {
change.AfterMode = fmt.Sprintf("%04o", b.mode)
}
if !change.Binary && a.hash != b.hash {
if !change.Binary && a.hash != b.hash && (a.hashOnly || b.hashOnly) {
// Over-budget content was compared by hash: list it, without a patch.
change.Truncated = true
change.NoPatch = true
listed++
} else if !change.Binary && a.hash != b.hash {
if remaining == 0 || bytes.Count(a.data, []byte("\n"))+bytes.Count(b.data, []byte("\n")) > maxLines {
change.Truncated = true
} else {
@@ -314,27 +449,46 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
}
}
}
if change.Truncated {
result.Status = "partial"
result.Diagnostic = "Some patches were omitted/truncated by capture limits."
add(change)
}
// In a Git working tree, paths the content snapshot could not settle
// (skipped as unreadable/oversized, or beyond the time/file limit) are still
// listed when their Git status changed during the visit. A path dirty with
// the same status before and after cannot be proven changed and stays
// counted as skipped. Protected paths are never listed.
if before.gitOK && after.gitOK {
gitNames := map[string]bool{}
for name := range before.gitStatus {
gitNames[name] = true
}
encoded, _ := json.Marshal(change)
if retained+len(encoded)+1 > maxPatchBytes {
change.Patch = ""
change.Truncated = true
encoded, _ = json.Marshal(change)
for name := range after.gitStatus {
gitNames[name] = true
}
if retained+len(encoded)+1 > maxPatchBytes {
result.Omitted++
result.Status = "partial"
result.Diagnostic = "Additional file changes omitted by the retained evidence size limit."
continue
ordered := make([]string, 0, len(gitNames))
for name := range gitNames {
if !decided[name] && fs.ValidPath(name) && !protected(name) {
ordered = append(ordered, name)
}
}
if change.Truncated {
result.Status = "partial"
sort.Strings(ordered)
for _, name := range ordered {
was, now := before.gitStatus[name], after.gitStatus[name]
if was == now {
continue
}
kind := "modified"
switch {
case now == "" && was == "??", strings.Contains(now, "D"):
kind = "deleted"
case was == "" && (now == "??" || strings.HasPrefix(now, "A")):
kind = "added"
}
add(protocol.FileChange{Path: name, Kind: kind, Truncated: true, NoPatch: true})
listed++
}
retained += len(encoded) + 1
result.Files = append(result.Files, change)
}
if listed > 0 && result.Status == "partial" && result.Omitted == 0 {
result.Diagnostic = "Some changed files exceeded capture limits and are listed without patches; this is not a complete workspace diff."
}
return result
}
+95 -1
View File
@@ -132,9 +132,14 @@ func TestProtectedSymlinkAndLimits(t *testing.T) {
put(t, dir, "large", "small now")
put(t, dir, "normal", "safe\n")
changes := Compare(before, Capture(ctx, dir, before))
if changes.Status != "partial" || len(changes.Files) != 1 || changes.Files[0].Path != "normal" {
// The oversized file is compared by hash and listed without a patch; the
// protected file and the symlink stay excluded.
if changes.Status != "partial" || len(changes.Files) != 2 || changes.Files[0].Path != "large" || changes.Files[1].Path != "normal" {
t.Fatal(changes)
}
if large := changes.Files[0]; !large.NoPatch || !large.Truncated || large.Patch != "" || large.Kind != "modified" {
t.Fatalf("oversized file not listed without patch: %+v", large)
}
for _, f := range changes.Files {
if strings.Contains(f.Patch, "secret") {
t.Fatal("secret retained")
@@ -189,3 +194,92 @@ func TestBinaryFilesDoNotStarveSourceDiffs(t *testing.T) {
}
}
}
func gitRepo(t *testing.T) (string, func(...string)) {
t.Helper()
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git unavailable")
}
dir := t.TempDir()
run := func(args ...string) {
t.Helper()
cmd := exec.Command("git", append([]string{"-C", dir, "-c", "user.email=t@example.invalid", "-c", "user.name=t", "-c", "commit.gpgsign=false"}, args...)...)
if data, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("%v: %v %s", args, err, data)
}
}
run("init", "-q")
return dir, run
}
// TestOverBudgetChangeIsListedWithoutPatch is the run-236 regression: a
// workspace whose text exceeds the snapshot budget must still list the one
// changed file (sorted last, after the budget is exhausted) instead of
// returning files: [] with every late path skipped.
func TestOverBudgetChangeIsListedWithoutPatch(t *testing.T) {
restore := SetSnapshotBudgetForTesting(64)
defer restore()
dir, git := gitRepo(t)
if err := os.MkdirAll(filepath.Join(dir, "web/src"), 0o700); err != nil {
t.Fatal(err)
}
for i := 0; i < 20; i++ {
put(t, dir, fmt.Sprintf("a-%02d.txt", i), strings.Repeat("filler\n", 4))
}
put(t, dir, "web/src/Inbox.test.tsx", "it('works')\n")
git("add", ".")
git("commit", "-qm", "init")
ctx := context.Background()
before := Capture(ctx, dir)
put(t, dir, "web/src/Inbox.test.tsx", "it('works')\nit('more')\n")
changes := Compare(before, Capture(ctx, dir, before))
if len(changes.Files) != 1 || changes.Files[0].Path != "web/src/Inbox.test.tsx" {
t.Fatalf("over-budget change not listed: %+v", changes)
}
if f := changes.Files[0]; f.Kind != "modified" || !f.NoPatch || f.Patch != "" {
t.Fatalf("over-budget change should be listed without patch: %+v", f)
}
if changes.Status != "partial" || changes.Skipped != 0 {
t.Fatalf("status/skipped = %q/%d, want partial/0", changes.Status, changes.Skipped)
}
// Unchanged over-budget files are compared by hash, so a visit that edits
// nothing is a complete, empty capture rather than a partial one.
again := Capture(ctx, dir)
if empty := Compare(again, Capture(ctx, dir, again)); empty.Status != "complete" || len(empty.Files) != 0 {
t.Fatalf("no-op over-budget visit = %+v, want complete and empty", empty)
}
}
// TestGitStatusListsUncomparableChanges proves a file the content snapshot
// skips (here: above the hash bound) is still listed when its Git status
// changes during the visit, while a protected path never is.
func TestGitStatusListsUncomparableChanges(t *testing.T) {
previous := maxHashBytes
maxHashBytes = 16
defer func() { maxHashBytes = previous }()
dir, git := gitRepo(t)
put(t, dir, "big.bin", strings.Repeat("x", 64))
put(t, dir, ".env", "A=1\n")
put(t, dir, "small.txt", "one\n")
git("add", "big.bin", "small.txt")
git("commit", "-qm", "init")
ctx := context.Background()
before := Capture(ctx, dir)
put(t, dir, "big.bin", strings.Repeat("y", 64))
put(t, dir, "fresh.bin", strings.Repeat("z", 64))
put(t, dir, ".env", "A=2\n")
changes := Compare(before, Capture(ctx, dir, before))
got := map[string]string{}
for _, f := range changes.Files {
if !f.NoPatch {
t.Fatalf("git-listed change carries a patch: %+v", f)
}
got[f.Path] = f.Kind
}
if len(got) != 2 || got["big.bin"] != "modified" || got["fresh.bin"] != "added" {
t.Fatalf("git status listing = %v (%+v)", got, changes)
}
if changes.Status != "partial" || !strings.Contains(changes.Diagnostic, "without patches") {
t.Fatalf("status/diagnostic = %q/%q", changes.Status, changes.Diagnostic)
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ import (
)
func TestShowcaseDefinitions(t *testing.T) {
for _, name := range []string{"task", "review", "research", "three-stage"} {
for _, name := range []string{"one-stage", "two-stages", "feedback-loop", "human-decision"} {
t.Run(name, func(t *testing.T) {
source, err := os.ReadFile(filepath.Join("..", "..", "examples", name+".md"))
if err != nil {
+8 -6
View File
@@ -75,7 +75,7 @@ func Lint(g Graph) (errs, warnings []LintFinding) {
}
}
if match := unconditionalHistoryRead(s.Prompt); match != "" {
add(&warnings, s, "history", "prompt asks for %q; stages get the essential memory automatically and should read the full history the runner provides only for a specific need", match)
add(&warnings, s, "history", "prompt asks for %q on every visit; the runner inlines the essential memory (memory.md: task, previous handoff, outcome ledger), so read history.md only for a specific need, e.g. \"read history.md only if the handoff lacks a detail you need\"", match)
}
if n := len(strings.TrimSpace(s.Prompt)); n > MaxPromptBytes {
add(&warnings, s, "prompt-length", "prompt is %d bytes (over %d); keep stage prompts to the goal and real constraints, and move shared procedure into the skill or project docs", n, MaxPromptBytes)
@@ -215,8 +215,8 @@ var deliveryClaim = regexp.MustCompile(`(?i)\bthe server (?:then |will |automati
var runnerBoilerplate = func() []*regexp.Regexp {
var list []*regexp.Regexp
for _, phrase := range []string{
`read these two files before working`,
`memory is the accumulated markdown`,
`rely on this essential memory first`,
`start (?:it|your output|the output) with a short ` + "`?#\\s*handoff",
`return its complete content as your final message`,
`(?:the )?only required section is(?: the)? ` + "`?#?\\s*outcome",
"only `?#\\s*outcome`? (?:section )?is required",
@@ -233,9 +233,11 @@ var runnerBoilerplate = func() []*regexp.Regexp {
return list
}()
// fullHistoryRead matches prompts that ask for the whole run history on every
// visit instead of reading it only for a specific need.
var fullHistoryRead = regexp.MustCompile(`(?i)\b(?:read|review|load|open)\b[^.\n]{0,30}\b(?:entire|full|whole|complete|all of the|all of)\s+(?:run\s+)?(?:memory(?:\.md)?|history|transcript)\b|\bread\s+(?:the\s+)?(?:input\.md\s+and\s+)?memory\.md\b`)
// fullHistoryRead matches prompts that ask for the whole run history
// (history.md, the on-demand record of every turn) instead of reading it only
// for a specific need. memory.md is the capped essential memory the runner
// inlines into every prompt, so naming it is redundant but never costly.
var fullHistoryRead = regexp.MustCompile(`(?i)\b(?:read|review|load|open|check|consult|go through)\b(?:[^.\n]|\.[A-Za-z]){0,30}(?:\bhistory\.md\b|\b(?:entire|full|whole|complete|all of the|all of)\s+(?:run\s+)?(?:history|transcript)\b)`)
var conditional = regexp.MustCompile(`(?i)\b(?:only|when|if|unless)\b`)
+11 -4
View File
@@ -180,8 +180,9 @@ func TestLintWarnings(t *testing.T) {
}{
"runner output boilerplate": {prompt: "Do it. Write the complete output.md markdown; only `# outcome` is required.", rule: "boilerplate"},
"allowed outcomes list": {prompt: "Do it. Allowed outcomes: success, blocked.", rule: "boilerplate"},
"full history read": {prompt: "First read the entire memory.md, then do it.", rule: "history"},
"memory file read": {prompt: "Read input.md and memory.md, then do it.", rule: "history"},
"handoff instruction": {prompt: "Do it. Start your output with a short # handoff section.", rule: "boilerplate"},
"full history read": {prompt: "First read the entire history, then do it.", rule: "history"},
"history file read": {prompt: "Read input.md and history.md, then do it.", rule: "history"},
"long prompt": {prompt: strings.Repeat("Keep it short. ", 200), rule: "prompt-length"},
} {
t.Run(name, func(t *testing.T) {
@@ -191,8 +192,14 @@ func TestLintWarnings(t *testing.T) {
}
})
}
if _, warns := lintRules(t, modelStage("Plan", "Plan the task. Read the full history only when the handoff lacks a detail.", "read", okEdges, "")); len(warns) != 0 {
t.Fatalf("clean prompt warned: %v", warns)
for _, clean := range []string{
"Plan the task. Read history.md only when the handoff lacks a detail.",
"Plan the request in memory.md.",
"Read memory.md for the original request, then plan.",
} {
if _, warns := lintRules(t, modelStage("Plan", clean, "read", okEdges, "")); len(warns) != 0 {
t.Fatalf("clean prompt %q warned: %v", clean, warns)
}
}
}
+57
View File
@@ -0,0 +1,57 @@
package pipeline
import (
"context"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// loadRunUsage fills each listed run's Usage with one grouped aggregate query
// per bounded batch over the stored per-stage usage rows: no GetRun, step load
// or transcript parse per row. It uses the same column sums as the
// history-wide totals, so a listed run's total equals its detail's TotalUsage
// over the same rows; a usage row without its recorded step is never counted.
// A run with no recorded usage keeps Usage nil, and a
// database without the step_usage table lists runs without usage.
func loadRunUsage(ctx context.Context, tx runGraphQuerier, runs []protocol.RunSummary) error {
const batchSize = 100
for start := 0; start < len(runs); start += batchSize {
end := min(start+batchSize, len(runs))
args := make([]any, 0, end-start)
byID := make(map[int64]*protocol.RunSummary, end-start)
for i := start; i < end; i++ {
byID[runs[i].ID] = &runs[i]
args = append(args, runs[i].ID)
}
rows, err := tx.QueryContext(ctx, `SELECT u.run_id,`+usageSumColumns+` `+usageFrom+`
WHERE u.run_id IN (`+strings.TrimSuffix(strings.Repeat("?,", len(args)), ",")+`) GROUP BY u.run_id`, args...)
if err != nil {
if strings.Contains(err.Error(), "no such table") {
return nil
}
return err
}
for rows.Next() {
var id int64
var u protocol.RunUsage
if err := rows.Scan(&id, &u.Stages, &u.TokensTotal, &u.TokensKnownStages, &u.TokensIn, &u.TokensOut, &u.CostUSD, &u.CostKnownStages, &u.SplitUnknownStages, &u.TokensReasoning, &u.CacheRead, &u.CacheWrite, &u.CacheKnownStages); err != nil {
rows.Close()
return err
}
if u.Stages == 0 || byID[id] == nil {
continue
}
u.CostUnknownStages = u.Stages - u.CostKnownStages
u.SplitKnown = u.TokensKnownStages > 0 && u.SplitUnknownStages == 0
u.CacheKnown = u.TokensKnownStages > 0 && u.CacheKnownStages == u.TokensKnownStages
byID[id].Usage = &u
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
}
return nil
}
+176
View File
@@ -0,0 +1,176 @@
package pipeline
import (
"context"
"fmt"
"path/filepath"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// TestListRunsCarriesRunUsageAggregate proves the run list carries each run's
// usage total from the grouped aggregate, equal to the detail's TotalUsage over
// the same rows, marks a partial total by its stage counts, leaves a run with
// no recorded usage absent rather than zero, and stays correct across list
// batches.
func TestListRunsCarriesRunUsageAggregate(t *testing.T) {
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "list-usage.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "list-usage", Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
definition, _ := store.Get(ctx, items[0].ID, 1)
create := func(key string) int64 {
id, _, err := store.CreateRun(ctx, definition, key, "/repo", false, nil, nil)
if err != nil {
t.Fatal(err)
}
return id
}
full := create("full")
finishUsageStep(t, store, full, 1, "one", &protocol.StageUsage{TokensIn: 20_000_000, TokensOut: 2_400_000, TokensTotal: 22_400_000, TokensKnown: true, SplitKnown: true, CostUSD: 1.5, CostKnown: true})
finishUsageStep(t, store, full, 2, "one", &protocol.StageUsage{TokensIn: 10, TokensOut: 5, TokensTotal: 15, TokensKnown: true, SplitKnown: true, CostUSD: .25, CostKnown: true})
partial := create("partial")
finishUsageStep(t, store, partial, 1, "one", &protocol.StageUsage{TokensTotal: 9, TokensKnown: true})
finishUsageStep(t, store, partial, 2, "one", &protocol.StageUsage{CostUSD: .1, CostKnown: true})
none := create("none")
finishUsageStep(t, store, none, 1, "one", nil)
// Enough further runs to push the first ones past one list batch.
const fillerRuns = 105
for i := range fillerRuns {
filler := create(fmt.Sprintf("filler-%d", i))
finishUsageStep(t, store, filler, 1, "one", &protocol.StageUsage{TokensTotal: int64(i + 1), TokensKnown: true})
}
runs, err := store.ListRuns(ctx)
if err != nil {
t.Fatal(err)
}
byID := map[int64]protocol.RunSummary{}
for _, run := range runs {
byID[run.ID] = run
}
for _, id := range []int64{full, partial} {
detail, err := store.GetRun(ctx, id)
if err != nil {
t.Fatal(err)
}
listed := byID[id].Usage
if listed == nil || detail.Usage == nil || *listed != *detail.Usage {
t.Fatalf("run %d list usage %+v != detail usage %+v", id, listed, detail.Usage)
}
}
if got := byID[full].Usage; got.TokensTotal != 22_400_015 || got.TokensIn != 20_000_010 || got.TokensOut != 2_400_005 || !got.SplitKnown || got.CostUSD != 1.75 || got.TokensKnownStages != 2 || got.Stages != 2 {
t.Fatalf("full run usage = %+v", got)
}
if got := byID[partial].Usage; got.TokensTotal != 9 || got.TokensKnownStages != 1 || got.Stages != 2 || got.SplitKnown || got.CostKnownStages != 1 || got.CostUnknownStages != 1 {
t.Fatalf("partial run usage = %+v", got)
}
if got := byID[none].Usage; got != nil {
t.Fatalf("run without usage listed a total: %+v", got)
}
var fillers int64
for _, run := range runs {
if run.ID == full || run.ID == partial || run.ID == none {
continue
}
if run.Usage == nil {
t.Fatalf("filler run %d lost its usage", run.ID)
}
fillers += run.Usage.TokensTotal
}
if fillers != fillerRuns*(fillerRuns+1)/2 {
t.Fatalf("filler totals = %d", fillers)
}
}
// TestRunUsageCountsCacheAndOnlyRecordedSteps proves the cache/reasoning
// components are summed per run (equal in list, detail and stats), a run mixing
// a pre-cache row with a cache-reporting one keeps CacheKnown false, and a usage
// row whose step or run no longer exists (an old history wipe) is counted
// nowhere and left in place.
func TestRunUsageCountsCacheAndOnlyRecordedSteps(t *testing.T) {
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "cache-usage.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "cache-usage", Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
definition, _ := store.Get(ctx, items[0].ID, 1)
cached, _, err := store.CreateRun(ctx, definition, "cached", "/repo", false, nil, nil)
if err != nil {
t.Fatal(err)
}
finishUsageStep(t, store, cached, 1, "one", &protocol.StageUsage{TokensIn: 900_000, TokensOut: 150_000, TokensTotal: 22_400_000, TokensKnown: true, SplitKnown: true, TokensReasoning: 50_000, CacheRead: 21_250_000, CacheWrite: 50_000, CacheKnown: true})
mixed, _, err := store.CreateRun(ctx, definition, "mixed", "/repo", false, nil, nil)
if err != nil {
t.Fatal(err)
}
finishUsageStep(t, store, mixed, 1, "one", &protocol.StageUsage{TokensIn: 3, TokensOut: 4, TokensTotal: 7, TokensKnown: true, SplitKnown: true})
finishUsageStep(t, store, mixed, 2, "one", &protocol.StageUsage{TokensIn: 1, TokensOut: 1, TokensTotal: 10, TokensKnown: true, SplitKnown: true, CacheRead: 8, CacheKnown: true})
// Orphans: one for a run that no longer exists and one for a step the
// listed run never recorded. Foreign keys are off only on this connection.
conn, err := store.db.Conn(ctx)
if err != nil {
t.Fatal(err)
}
if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys=OFF"); err != nil {
t.Fatal(err)
}
orphan := `{"tokens_total":1000000000,"tokens_known":true,"cost_usd":15.67,"cost_known":true}`
for _, key := range [][2]int64{{9999, 1}, {cached, 99}} {
if _, err := conn.ExecContext(ctx, "INSERT INTO step_usage(run_id,sequence,usage_json) VALUES(?,?,?)", key[0], key[1], orphan); err != nil {
t.Fatal(err)
}
}
if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys=ON"); err != nil {
t.Fatal(err)
}
conn.Close()
runs, err := store.ListRuns(ctx)
if err != nil {
t.Fatal(err)
}
listed := map[int64]*protocol.RunUsage{}
for _, run := range runs {
listed[run.ID] = run.Usage
}
for _, id := range []int64{cached, mixed} {
detail, err := store.GetRun(ctx, id)
if err != nil {
t.Fatal(err)
}
if listed[id] == nil || detail.Usage == nil || *listed[id] != *detail.Usage {
t.Fatalf("run %d list usage %+v != detail usage %+v", id, listed[id], detail.Usage)
}
}
if got := listed[cached]; got.TokensTotal != 22_400_000 || got.CacheRead != 21_250_000 || got.CacheWrite != 50_000 || got.TokensReasoning != 50_000 || !got.CacheKnown || got.CacheKnownStages != 1 || got.Stages != 1 || got.CostKnownStages != 0 {
t.Fatalf("cached run usage counted an orphan or lost the cache split: %+v", got)
}
if got := listed[mixed]; got.CacheKnown || got.CacheKnownStages != 1 || got.CacheRead != 8 || got.TokensTotal != 17 {
t.Fatalf("mixed run presented a partial cache split as complete: %+v", got)
}
stats, err := store.UsageStats(ctx)
if err != nil || stats.Usage == nil {
t.Fatalf("stats = %+v err=%v", stats, err)
}
if got := stats.Usage; got.Stages != 3 || got.TokensTotal != 22_400_017 || got.CostUSD != 0 || got.CostKnownStages != 0 || got.CacheRead != 21_250_008 || got.CacheKnown {
t.Fatalf("history totals counted orphan rows: %+v", got)
}
var remaining int
if err := store.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM step_usage").Scan(&remaining); err != nil || remaining != 5 {
t.Fatalf("usage rows were deleted: %d %v", remaining, err)
}
}
+4
View File
@@ -76,6 +76,9 @@ func (s *Store) ListRuns(ctx context.Context) ([]protocol.RunSummary, error) {
if err := loadRunGraphEvidence(ctx, tx, items); err != nil {
return nil, err
}
if err := loadRunUsage(ctx, tx, items); err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, err
}
@@ -300,6 +303,7 @@ strftime('%Y-%m-%dT%H:%M:%SZ',started_at),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ'
// The run total is one pass over the steps already loaded above: it adds no
// query and no transcript parse.
r.Usage = protocol.TotalUsage(r.Steps)
r.Warnings = protocol.RunWarnings(r.Steps)
alerts, err := tx.QueryContext(ctx, `SELECT sequence,event,channel,status,attempts,diagnostic,message_id FROM run_notifications WHERE run_id=? ORDER BY sequence,event,channel`, id)
if err != nil {
return nil, err
+51
View File
@@ -0,0 +1,51 @@
package pipeline
import (
"context"
"database/sql"
"fmt"
"strconv"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// examplesSeededSetting is the server_settings key recording that the example
// pipelines were considered for this database. Once present, SeedExamples never
// adds anything again, so deleting the examples does not bring them back.
const examplesSeededSetting = "examples_seeded"
// SeedExamples publishes the given example definitions as ordinary pipelines,
// but only into a brand-new database: one whose schema this Open created, that
// has no pipelines and has never been seeded. Every call that gets past the
// marker check records the marker, so an existing install that upgrades is
// marked without gaining or rewriting anything, and a later start never seeds.
// Sources must already be bound to the server's default model and harness. It
// returns the number of pipelines created.
func (s *Store) SeedExamples(ctx context.Context, items []protocol.Template) (int, error) {
var marker string
err := s.db.QueryRowContext(ctx, `SELECT value FROM server_settings WHERE key=?`, examplesSeededSetting).Scan(&marker)
if err == nil {
return 0, nil
}
if err != sql.ErrNoRows {
return 0, err
}
seeded := 0
if s.created {
var count int
if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM pipelines`).Scan(&count); err != nil {
return 0, err
}
if count == 0 {
for _, item := range items {
// Create-only: a seed never replaces or versions an existing pipeline.
if _, err := s.Submit(ctx, item.Name, item.Source, true); err != nil {
return seeded, fmt.Errorf("seed example %q: %w", item.Name, err)
}
seeded++
}
}
}
_, err = s.db.ExecContext(ctx, `INSERT INTO server_settings(key,value) VALUES(?,?) ON CONFLICT(key) DO NOTHING`, examplesSeededSetting, strconv.Itoa(seeded))
return seeded, err
}
+94
View File
@@ -0,0 +1,94 @@
package pipeline
import (
"context"
"path/filepath"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func seedItems() []protocol.Template {
return []protocol.Template{
{Key: "a", Name: "Example: a", Source: Template([]string{"one"}, true)},
{Key: "b", Name: "Example: b", Source: Template([]string{"one", "two"}, true)},
}
}
func TestSeedExamplesOnlyIntoABrandNewDatabase(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "new.db")
store, err := Open(path)
if err != nil {
t.Fatal(err)
}
seeded, err := store.SeedExamples(ctx, seedItems())
if err != nil || seeded != 2 {
t.Fatal("brand-new database not seeded", seeded, err)
}
items, _ := store.List(ctx)
if len(items) != 2 || items[0].Name != "Example: a" || items[0].Version != 1 {
t.Fatal("examples are not ordinary version-1 pipelines", items)
}
// A second call in the same process is a no-op.
if seeded, err = store.SeedExamples(ctx, seedItems()); err != nil || seeded != 0 {
t.Fatal("seeded twice", seeded, err)
}
// Removing every example must not bring them back on the next start. There is
// no pipeline delete command yet, so remove the rows directly.
if _, err := store.db.Exec(`DELETE FROM submissions; DELETE FROM pipeline_versions; DELETE FROM pipelines`); err != nil {
t.Fatal(err)
}
store.Close()
store, err = Open(path)
if err != nil {
t.Fatal(err)
}
defer store.Close()
if seeded, err = store.SeedExamples(ctx, seedItems()); err != nil || seeded != 0 {
t.Fatal("deleted examples came back", seeded, err)
}
if items, _ = store.List(ctx); len(items) != 0 {
t.Fatal("deleted examples came back", items)
}
}
func TestSeedExamplesNeverChangesAnExistingInstall(t *testing.T) {
ctx := context.Background()
for _, name := range []string{"empty", "populated"} {
t.Run(name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "existing.db")
store, err := Open(path)
if err != nil {
t.Fatal(err)
}
if name == "populated" {
if _, err := store.Submit(ctx, "mine", Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
}
// Simulate an install from before seeding existed: no marker.
store.Close()
store, err = Open(path)
if err != nil {
t.Fatal(err)
}
if seeded, err := store.SeedExamples(ctx, seedItems()); err != nil || seeded != 0 {
t.Fatal("upgrade seeded examples", seeded, err)
}
store.Close()
store, err = Open(path)
if err != nil {
t.Fatal(err)
}
defer store.Close()
if seeded, err := store.SeedExamples(ctx, seedItems()); err != nil || seeded != 0 {
t.Fatal("later start seeded examples", seeded, err)
}
items, _ := store.List(ctx)
if (name == "empty" && len(items) != 0) || (name == "populated" && (len(items) != 1 || items[0].Name != "mine" || items[0].Version != 1)) {
t.Fatal("upgrade changed pipelines", items)
}
})
}
}
+27 -10
View File
@@ -64,6 +64,31 @@ func (s *Store) UsageStats(ctx context.Context) (*protocol.UsageStats, error) {
return stats, tx.Commit()
}
// usageSumColumns sums step_usage rows into the RunUsage/UsageTotals shape:
// stages, reported total, token-reporting stages, split in/out, cost,
// cost-reporting stages, token stages without a split, then reasoning, cache
// read and cache write sums and the stages that recorded them, in that order. It is
// the one SQL definition of the sum, shared by the history-wide totals and the
// per-run list aggregate, and mirrors protocol.TotalUsage over the same rows.
const usageSumColumns = `COALESCE(COUNT(*),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') THEN json_extract(usage_json,'$.tokens_total') ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') THEN 1 ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.split_known') THEN json_extract(usage_json,'$.tokens_in') ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.split_known') THEN json_extract(usage_json,'$.tokens_out') ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.cost_known') THEN json_extract(usage_json,'$.cost_usd') ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.cost_known') THEN 1 ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') AND NOT COALESCE(json_extract(usage_json,'$.split_known'),0) THEN 1 ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') AND json_extract(usage_json,'$.cache_known') THEN COALESCE(json_extract(usage_json,'$.tokens_reasoning'),0) ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') AND json_extract(usage_json,'$.cache_known') THEN COALESCE(json_extract(usage_json,'$.cache_read'),0) ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') AND json_extract(usage_json,'$.cache_known') THEN COALESCE(json_extract(usage_json,'$.cache_write'),0) ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') AND json_extract(usage_json,'$.cache_known') THEN 1 ELSE 0 END),0)`
// usageFrom is the step_usage rows that belong to a recorded step. A usage row
// whose step (or run) no longer exists, such as one left behind by an old
// history wipe, is never counted, and is not deleted here either. It is the
// same row set the run detail reads through its step loop.
const usageFrom = `FROM step_usage u JOIN run_steps s ON s.run_id=u.run_id AND s.sequence=u.sequence`
// usageTotals is the one extra aggregate query the history-wide usage totals add,
// over the same step_usage rows the per-run figures read. It sums reported totals
// with json_extract, counts token/cost-reporting stages and leaves a stage that
@@ -71,16 +96,7 @@ func (s *Store) UsageStats(ctx context.Context) (*protocol.UsageStats, error) {
// read-only database with no step_usage table yields no totals, not an error.
func usageTotals(ctx context.Context, tx *sql.Tx) (*protocol.UsageTotals, error) {
var totals protocol.UsageTotals
err := tx.QueryRowContext(ctx, `SELECT
COALESCE(COUNT(*),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') THEN json_extract(usage_json,'$.tokens_total') ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') THEN 1 ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.split_known') THEN json_extract(usage_json,'$.tokens_in') ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.split_known') THEN json_extract(usage_json,'$.tokens_out') ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.cost_known') THEN json_extract(usage_json,'$.cost_usd') ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.cost_known') THEN 1 ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') AND NOT COALESCE(json_extract(usage_json,'$.split_known'),0) THEN 1 ELSE 0 END),0)
FROM step_usage`).Scan(&totals.Stages, &totals.TokensTotal, &totals.TokensKnownStages, &totals.TokensIn, &totals.TokensOut, &totals.CostUSD, &totals.CostKnownStages, &totals.SplitUnknownStages)
err := tx.QueryRowContext(ctx, `SELECT `+usageSumColumns+` `+usageFrom).Scan(&totals.Stages, &totals.TokensTotal, &totals.TokensKnownStages, &totals.TokensIn, &totals.TokensOut, &totals.CostUSD, &totals.CostKnownStages, &totals.SplitUnknownStages, &totals.TokensReasoning, &totals.CacheRead, &totals.CacheWrite, &totals.CacheKnownStages)
if err != nil {
if strings.Contains(err.Error(), "no such table") {
return nil, nil
@@ -92,5 +108,6 @@ FROM step_usage`).Scan(&totals.Stages, &totals.TokensTotal, &totals.TokensKnownS
}
totals.CostUnknownStages = totals.Stages - totals.CostKnownStages
totals.SplitKnown = totals.TokensKnownStages > 0 && totals.SplitUnknownStages == 0
totals.CacheKnown = totals.TokensKnownStages > 0 && totals.CacheKnownStages == totals.TokensKnownStages
return &totals, nil
}
+9 -1
View File
@@ -25,6 +25,9 @@ type Store struct {
runnerClaimed bool
done chan struct{}
closeOnce sync.Once
// created reports that this Open created the database schema, i.e. the
// database is brand new. Only then may SeedExamples add pipelines.
created bool
}
// openDB opens one SQLite connection pool for a DSN. Every open path shares it
@@ -44,6 +47,11 @@ func Open(path string) (*Store, error) {
if err != nil {
return nil, err
}
var existing int
if err := db.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='pipelines'`).Scan(&existing); err != nil {
db.Close()
return nil, err
}
_, err = db.Exec(`PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;
CREATE TABLE IF NOT EXISTS pipelines (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE IF NOT EXISTS pipeline_versions (id INTEGER PRIMARY KEY, pipeline_id INTEGER NOT NULL REFERENCES pipelines(id), version INTEGER NOT NULL, source TEXT NOT NULL, content_hash TEXT NOT NULL, graph_json TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, UNIQUE(pipeline_id, version));
@@ -52,7 +60,7 @@ CREATE TABLE IF NOT EXISTS submissions (id INTEGER PRIMARY KEY, name TEXT NOT NU
db.Close()
return nil, err
}
s := &Store{db: db, dir: filepath.Dir(path), path: path, done: make(chan struct{})}
s := &Store{db: db, dir: filepath.Dir(path), path: path, done: make(chan struct{}), created: existing == 0}
if err := s.initRuns(); err != nil {
db.Close()
return nil, err
+27
View File
@@ -85,6 +85,13 @@ const (
// shared list metadata (colour, star, title) changes, carrying the updated
// registry row in ChatSession, so each device's list updates live.
ChatSessionChanged = "chat_session_changed"
// ChatActivityChanged is pushed to every open connection (not only the
// session's room subscribers) when a chat's live activity changes: its turn
// starts or ends, or its count of running background tasks changes. The
// body is ChatActivity. It is sent on those transitions only, never per
// output chunk; a client applies a push only when its Seq is newer than the
// activity it already holds for that session.
ChatActivityChanged = "chat_activity"
// ChatSubscribe attaches a connection to one session's shared live stream so
// it receives every frame any client's turn produces (its own and the other
// devices'), not only the frames of a turn it prompted itself. Any number of
@@ -320,6 +327,26 @@ type ChatSession struct {
// the operator started a fresh session. Clients replace the row with that
// id by this one; it is never part of a listed row.
PreviousID string `json:"previous_id,omitempty"`
// Activity is the server's live view of the session. A server that tracks
// it sets it on every chat_sessions row (its presence, even as an empty
// object, tells a client the server also pushes chat_activity). Older
// servers omit it.
Activity *ChatActivity `json:"activity,omitempty"`
}
// ChatActivity is one session's live activity as the server observes it: a
// turn in flight, and how many background tasks (shells, background commands,
// subagents) the harness reports still running. It rides on chat_sessions rows
// and is pushed as chat_activity. Seq orders one session's snapshots across
// the list reply and the pushes (a later snapshot has a larger Seq, also
// across a server restart); a client keeps the snapshot with the largest Seq.
// Background tasks are counted only while the server observes the session's
// stream, so an unobserved session reports none rather than a stale count.
type ChatActivity struct {
SessionID string `json:"session_id,omitempty"`
TurnRunning bool `json:"turn_running,omitempty"`
BackgroundTasks int `json:"background_tasks,omitempty"`
Seq int64 `json:"seq,omitempty"`
}
// Chat export formats accepted by chat_export.
+2
View File
@@ -199,6 +199,8 @@ type Message struct {
// requests themselves ride on ChatQuery (the session id), matching
// chat_messages/chat_interrupt.
ChatClose *ChatCloseResult `json:"chat_close,omitempty"`
// ChatActivity is the chat_activity push: one session's live activity.
ChatActivity *ChatActivity `json:"chat_activity,omitempty"`
// ChatAnswer is the chat_answer body; the form update arrives through the
// normal chat_event stream.
ChatAnswer *ChatAnswerRequest `json:"chat_answer,omitempty"`
+75 -10
View File
@@ -1,6 +1,9 @@
package protocol
import "strings"
import (
"fmt"
"strings"
)
const (
RunPipeline = "run_pipeline"
@@ -197,6 +200,14 @@ type RunSummary struct {
// session directories and an estimate of its database rows. It is cached
// server-side; 0 means not measured yet (a background backfill fills it).
SizeBytes int64 `json:"size_bytes"`
// Usage is the totalled reported usage of the run's model stages. The run
// list sums it with one SQL aggregate per batch over the stored per-stage
// usage rows; the run detail sums the same rows in one pass over its loaded
// steps (TotalUsage). It is absent for a run with no model usage recorded
// (including historical runs and servers predating the list aggregate), so
// a client shows nothing rather than zero. A total is partial when
// TokensKnownStages < Stages.
Usage *RunUsage `json:"usage,omitempty"`
}
// RunGraphVisit contains only routing and lifecycle facts, never private step
@@ -317,6 +328,14 @@ type StageUsage struct {
SplitKnown bool `json:"split_known,omitempty"`
CostUSD float64 `json:"cost_usd,omitempty"`
CostKnown bool `json:"cost_known"`
// TokensReasoning, CacheRead and CacheWrite are the remaining components of
// a split report (TokensTotal = in + out + reasoning + cache read + cache
// write). They are recorded only when CacheKnown; a row stored before they
// were kept has CacheKnown=false, so its absent counts are unknown, not zero.
TokensReasoning int64 `json:"tokens_reasoning,omitempty"`
CacheRead int64 `json:"cache_read,omitempty"`
CacheWrite int64 `json:"cache_write,omitempty"`
CacheKnown bool `json:"cache_known,omitempty"`
}
// RunUsage is the totalled reported usage of a run's model stages. It is summed
@@ -336,6 +355,41 @@ type RunUsage struct {
SplitUnknownStages int `json:"split_unknown_stages,omitempty"`
CostKnownStages int `json:"cost_known_stages"`
CostUnknownStages int `json:"cost_unknown_stages,omitempty"`
// TokensReasoning, CacheRead and CacheWrite sum the stages that recorded the
// component split (CacheKnownStages). CacheKnown is true only when every
// token-reporting stage did, so fresh (total minus cache read) versus cached
// is never presented from a partial split.
TokensReasoning int64 `json:"tokens_reasoning,omitempty"`
CacheRead int64 `json:"cache_read,omitempty"`
CacheWrite int64 `json:"cache_write,omitempty"`
CacheKnown bool `json:"cache_known,omitempty"`
CacheKnownStages int `json:"cache_known_stages,omitempty"`
}
// RunWarnings derives the run-level warnings from its steps: every visit whose
// retained file-change capture was partial or unavailable is named, because
// such evidence is not a complete workspace diff and must never be read as "no
// edits". Steps with no capture (historical, human or server-skip visits) are
// not flagged here; their File changes section already says "not recorded".
func RunWarnings(steps []RunStep) []string {
var visits []string
for _, step := range steps {
if step.FileChanges == nil || step.FileChanges.Status == "complete" {
continue
}
visits = append(visits, fmt.Sprintf("%s #%d (%s)", step.Stage, step.Sequence, step.FileChanges.Status))
}
if len(visits) == 0 {
return nil
}
const shown = 8
list := visits
extra := ""
if len(list) > shown {
extra = fmt.Sprintf(" and %d more", len(list)-shown)
list = list[:shown]
}
return []string{fmt.Sprintf("File-change capture was incomplete for %d visit(s): %s%s. Recorded file changes are not a complete workspace diff, and no stage is auto-skipped after such a visit.", len(visits), strings.Join(list, ", "), extra)}
}
// TotalUsage sums the per-stage usage of a run's steps into one run total. It is
@@ -360,6 +414,12 @@ func TotalUsage(steps []RunStep) *RunUsage {
splitComplete = false
total.SplitUnknownStages++
}
if usage.CacheKnown {
total.CacheKnownStages++
total.TokensReasoning += usage.TokensReasoning
total.CacheRead += usage.CacheRead
total.CacheWrite += usage.CacheWrite
}
}
if usage.CostKnown {
total.CostKnownStages++
@@ -372,6 +432,7 @@ func TotalUsage(steps []RunStep) *RunUsage {
return nil
}
total.SplitKnown = total.TokensKnownStages > 0 && splitComplete
total.CacheKnown = total.TokensKnownStages > 0 && total.CacheKnownStages == total.TokensKnownStages
return total
}
@@ -400,11 +461,15 @@ type StageFileChanges struct {
}
type FileChange struct {
Path string `json:"path"`
Kind string `json:"kind"` // added, modified, deleted
Patch string `json:"patch,omitempty"`
Binary bool `json:"binary,omitempty"`
Truncated bool `json:"truncated,omitempty"`
Path string `json:"path"`
Kind string `json:"kind"` // added, modified, deleted
Patch string `json:"patch,omitempty"`
Binary bool `json:"binary,omitempty"`
Truncated bool `json:"truncated,omitempty"`
// NoPatch marks a change listed without any patch: the content exceeded the
// capture budget (compared by hash) or the change was seen only in Git
// status. Truncated is also set so older readers show "patch omitted".
NoPatch bool `json:"no_patch,omitempty"`
BeforeMode string `json:"before_mode,omitempty"`
AfterMode string `json:"after_mode,omitempty"`
}
@@ -433,10 +498,10 @@ type RunDetail struct {
Input map[string]any `json:"input"`
Output map[string]any `json:"output"`
Steps []RunStep `json:"steps"`
// Usage is the totalled reported usage of the run's model stages, summed in
// one pass over Steps. It is absent for a run with no model usage recorded
// (including historical runs).
Usage *RunUsage `json:"usage,omitempty"`
// Warnings are run-level, read-time notes an operator should see before
// trusting the evidence, e.g. that a visit's file-change capture was partial.
// Derived from Steps by RunWarnings; absent when there is nothing to flag.
Warnings []string `json:"warnings,omitempty"`
// TitleSource is "model" when Title came from the shared summariser or
// "fallback" when it was derived from the prompt; TitleModel names the model
// that produced a model title. They are retained so a diagnosis can tell the
+6
View File
@@ -37,6 +37,12 @@ type UsageTotals struct {
SplitUnknownStages int `json:"split_unknown_stages,omitempty"`
CostKnownStages int `json:"cost_known_stages"`
CostUnknownStages int `json:"cost_unknown_stages,omitempty"`
// The cache/reasoning components, as in RunUsage.
TokensReasoning int64 `json:"tokens_reasoning,omitempty"`
CacheRead int64 `json:"cache_read,omitempty"`
CacheWrite int64 `json:"cache_write,omitempty"`
CacheKnown bool `json:"cache_known,omitempty"`
CacheKnownStages int `json:"cache_known_stages,omitempty"`
}
type UsageStats struct {
+1 -1
View File
@@ -88,7 +88,7 @@ func (r *runner) scanArtifacts(runID int64, sequence int, directory string, publ
}
// Mandatory runtime evidence must not disappear behind hundreds of private
// captures/public deliverables in the bounded inventory.
for _, name := range []string{"input.md", "memory.md", "output.md", "session.html"} {
for _, name := range []string{"input.md", "memory.md", "history.md", "output.md", "session.html"} {
full := path.Join(rel, name)
if info, err := root.Lstat(full); err == nil && info.Mode().IsRegular() && info.Mode()&fs.ModeSymlink == 0 && info.Size() <= maxArtifactFileBytes {
add(full, name, info)
+124
View File
@@ -0,0 +1,124 @@
package server
import (
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Chat list activity: every listed chat shows whether its turn is running and
// whether background tasks (shells, background commands, subagents) are still
// running after the turn. Room frames reach only the connections that opened
// that chat, so the hub keeps a small per-session summary and pushes each
// change to every connection as chat_activity, and chat_sessions carries the
// current summary on each row.
//
// The summary is derived from the hub's own state only (no broker call, no
// I/O), under the hub mutex, at the points where that state changes: a turn
// admitted or finished, a step announcing or ending a turn, a shell starting
// or exiting, a shell readback reconciling the set, and a room released.
// Anything else, including every text or tool chunk, never touches it.
//
// A session's background tasks are counted only while it has a room, i.e.
// while the hub observes its stream (a viewer, or unattended observation, see
// chat_unattended.go). Once the room is released its shell exits are no
// longer seen, so the count drops to zero rather than going stale.
// chatActivityLocked computes the session's current summary. Callers hold h.mu.
func (h *chatHub) chatActivityLocked(sessionID string) protocol.ChatActivity {
activity := protocol.ChatActivity{SessionID: sessionID}
room := h.rooms[sessionID]
if room == nil {
return activity
}
activity.TurnRunning = room.running || room.observedTurn
activity.BackgroundTasks = h.backgroundTasksLocked(sessionID)
return activity
}
// backgroundTasksLocked counts the session's retained running shells. Callers
// hold h.mu.
func (h *chatHub) backgroundTasksLocked(sessionID string) int {
if turn := h.turns[sessionID]; turn != nil {
return len(turn.shells)
}
return 0
}
// noteActivityLocked recomputes the session's summary and, only when the turn
// state or the background-task count changed, records it under a new sequence
// number and pushes it to every connection. Callers hold h.mu; the push itself
// never blocks (chatSessionChanges writes on its own goroutines).
func (h *chatHub) noteActivityLocked(sessionID string) {
if sessionID == "" {
return
}
next := h.chatActivityLocked(sessionID)
previous := h.activity[sessionID]
if previous.TurnRunning == next.TurnRunning && previous.BackgroundTasks == next.BackgroundTasks {
return
}
if h.activity == nil {
h.activity = map[string]protocol.ChatActivity{}
}
next.Seq = h.nextActivitySeqLocked()
// The record keeps the last sequence of an idle session too, so a list
// row's Seq never moves backwards behind a push a client already applied.
// It holds one small entry per session that was ever active.
h.activity[sessionID] = next
h.sessionChanges.broadcastActivity(next)
}
// nextActivitySeqLocked returns a strictly increasing sequence. It starts from
// the wall clock in microseconds (exact in a JavaScript number) so snapshots
// after a server restart still order after the ones a client held before.
func (h *chatHub) nextActivitySeqLocked() int64 {
if h.activitySeq == 0 {
h.activitySeq = time.Now().UnixMicro()
}
h.activitySeq++
return h.activitySeq
}
// activitySnapshot returns the current summary of each session in ids, each
// with the sequence of its last recorded change. A session that has not
// changed since this server started carries the current sequence instead, so
// it still orders after anything a client kept from a previous server process
// and before any later push.
func (h *chatHub) activitySnapshot(ids []string) map[string]protocol.ChatActivity {
out := make(map[string]protocol.ChatActivity, len(ids))
if h == nil {
return out
}
h.mu.Lock()
defer h.mu.Unlock()
if h.activitySeq == 0 {
h.activitySeq = time.Now().UnixMicro()
}
for _, id := range ids {
activity := h.chatActivityLocked(id)
activity.Seq = h.activitySeq
if recorded, ok := h.activity[id]; ok {
activity.Seq = recorded.Seq
}
out[id] = activity
}
return out
}
// broadcastActivity pushes one session's activity to every connection,
// including the one whose action caused it (it has no reply carrying it).
func (c *chatSessionChanges) broadcastActivity(activity protocol.ChatActivity) {
c.mu.Lock()
targets := make([]func(protocol.Message) error, 0, len(c.clients))
for _, write := range c.clients {
targets = append(targets, write)
}
c.mu.Unlock()
for _, write := range targets {
body := activity
go func() {
_ = write(protocol.Message{Type: protocol.ChatActivityChanged, ChatActivity: &body})
}()
}
}
+184
View File
@@ -0,0 +1,184 @@
package server
import (
"context"
"testing"
"time"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// listedObservedChat is an observedChat whose endpoint lists ses_1, so
// chat_sessions returns its registry row.
type listedObservedChat struct{ *observedChat }
func (c listedObservedChat) Sessions(context.Context) ([]protocol.ChatSession, error) {
return []protocol.ChatSession{{ID: "ses_1"}}, nil
}
// readActivity reads raw frames until the next chat_activity push.
func readActivity(t *testing.T, ctx context.Context, conn *websocket.Conn) protocol.ChatActivity {
t.Helper()
for {
var message protocol.Message
if err := wsjson.Read(ctx, conn, &message); err != nil {
t.Fatalf("read (waiting for chat_activity): %v", err)
}
if message.Type == protocol.ChatActivityChanged {
if message.ChatActivity == nil {
t.Fatal("chat_activity without a body")
}
return *message.ChatActivity
}
}
}
func shellFrame(id, status string) protocol.ChatEventFrame {
return protocol.ChatEventFrame{SessionID: "ses_1", Kind: protocol.ChatEventShell, Shell: &protocol.ChatShell{ID: id, Status: status, Command: "sleep 600"}}
}
func listActivity(t *testing.T, ctx context.Context, conn *websocket.Conn) *protocol.ChatActivity {
t.Helper()
writeChat(t, ctx, conn, protocol.Message{Type: protocol.ChatSessions, ID: "list"})
reply := readUntil(t, ctx, conn, protocol.ChatSessions)
if len(reply.ChatSessions) != 1 || reply.ChatSessions[0].ID != "ses_1" {
t.Fatalf("chat_sessions = %+v", reply.ChatSessions)
}
return reply.ChatSessions[0].Activity
}
// A connection that never opened the chat still learns, from chat_activity,
// when its turn starts and ends and how many background tasks run, and the
// list carries the same summary with the same sequence. Output chunks push
// nothing. After the last viewer leaves, the session stays observed while a
// background task runs, and is released (pushing an idle summary) once the
// last one exits.
func TestChatActivityReachesEveryConnection(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
store := unattendedStore(t, false)
broker := newObservedChat()
server := startQueueServer(t, listedObservedChat{broker}, store)
viewer := dialChatConn(t, server.ctx, server.srv)
list := dialChatConn(t, server.ctx, server.srv)
// A session that never changed still carries a sequence (this server's
// current one), so it orders after anything kept from an earlier process.
initial := listActivity(t, server.ctx, list)
if initial == nil || initial.TurnRunning || initial.BackgroundTasks != 0 || initial.Seq == 0 {
t.Fatalf("idle row activity = %+v, want an empty summary with a sequence", initial)
}
sendPrompt(t, server.ctx, viewer, "p1", "build it", "op-1")
started := readActivity(t, server.ctx, list)
if started.SessionID != "ses_1" || !started.TurnRunning || started.BackgroundTasks != 0 || started.Seq <= initial.Seq {
t.Fatalf("turn start push = %+v", started)
}
broker.push(stepFrameFor(protocol.ChatStepStarted, "turn_1"))
broker.push(textFrame("Working on it."))
broker.push(shellFrame("sh_1", protocol.ChatShellRunning))
withTask := readActivity(t, server.ctx, list)
if !withTask.TurnRunning || withTask.BackgroundTasks != 1 || withTask.Seq <= started.Seq {
t.Fatalf("background task push = %+v (after %+v); a text chunk or the re-announced turn must push nothing", withTask, started)
}
broker.push(stepFrameFor(protocol.ChatStepEnded, "turn_1"))
ended := readActivity(t, server.ctx, list)
if ended.TurnRunning || ended.BackgroundTasks != 1 || ended.Seq <= withTask.Seq {
t.Fatalf("turn end push = %+v", ended)
}
if got := listActivity(t, server.ctx, list); got == nil || got.TurnRunning || got.BackgroundTasks != 1 || got.Seq != ended.Seq {
t.Fatalf("listed activity = %+v, want %+v", got, ended)
}
viewer.CloseNow()
time.Sleep(100 * time.Millisecond) // let the server notice the disconnect
if active, _ := broker.streams(); active != 1 {
t.Fatalf("a running background task was not observed after the viewer left: %d streams", active)
}
broker.push(shellFrame("sh_1", protocol.ChatShellExited))
idle := readActivity(t, server.ctx, list)
if idle.TurnRunning || idle.BackgroundTasks != 0 || idle.Seq <= ended.Seq {
t.Fatalf("task exit push = %+v", idle)
}
waitFor(t, "observer released", func() bool { active, _ := broker.streams(); return active == 0 })
if got := listActivity(t, server.ctx, list); got == nil || got.BackgroundTasks != 0 || got.Seq != idle.Seq {
t.Fatalf("listed activity after release = %+v, want %+v", got, idle)
}
}
// A background task that never reports its exit does not hold the observer
// forever: it is released after chatUnattendedTurnLimit, and the list then
// reports no tasks rather than a stale count.
func TestChatUnreportedBackgroundTaskIsReleased(t *testing.T) {
fastUnattended(t)
t.Setenv("PIPELINES_NTFY_URL", "")
limit := chatUnattendedTurnLimit
chatUnattendedTurnLimit = 300 * time.Millisecond
t.Cleanup(func() { chatUnattendedTurnLimit = limit })
store := unattendedStore(t, false)
broker := newObservedChat()
server := startQueueServer(t, listedObservedChat{broker}, store)
viewer := dialChatConn(t, server.ctx, server.srv)
list := dialChatConn(t, server.ctx, server.srv)
// A reply proves the connection reached its read loop, where it is
// attached to the pushes.
listActivity(t, server.ctx, list)
sendPrompt(t, server.ctx, viewer, "p1", "build it", "op-1")
readActivity(t, server.ctx, list)
broker.push(stepFrameFor(protocol.ChatStepStarted, "turn_1"))
broker.push(shellFrame("sh_1", protocol.ChatShellRunning))
readActivity(t, server.ctx, list)
broker.push(stepFrameFor(protocol.ChatStepEnded, "turn_1"))
readActivity(t, server.ctx, list)
viewer.CloseNow()
time.Sleep(100 * time.Millisecond)
if active, _ := broker.streams(); active != 1 {
t.Fatalf("background task not observed: %d", active)
}
released := readActivity(t, server.ctx, list)
if released.TurnRunning || released.BackgroundTasks != 0 {
t.Fatalf("release push = %+v", released)
}
waitFor(t, "observer released", func() bool { active, _ := broker.streams(); return active == 0 })
if got := listActivity(t, server.ctx, list); got == nil || got.BackgroundTasks != 0 {
t.Fatalf("listed activity after expiry = %+v", got)
}
}
// The hub keeps an unattended room for background tasks only: an idle room
// with none is released when its last client leaves, a room with one is kept.
func TestChatBackgroundTasksKeepUnattendedRoom(t *testing.T) {
fastUnattended(t)
h := newChatHub()
defer func() {
h.mu.Lock()
for _, room := range h.rooms {
room.cancel()
}
h.mu.Unlock()
}()
for _, tasks := range []int{0, 1} {
id := "ses_idle"
if tasks > 0 {
id = "ses_task"
}
h.mu.Lock()
room := h.roomLocked(id)
if tasks > 0 {
h.turnLocked(id).applyShell(&protocol.ChatShell{ID: "sh_1", Status: protocol.ChatShellRunning})
}
sub := &chatSub{hub: h, room: room, clientID: "c", ch: make(chan protocol.Message, 1), done: make(chan struct{})}
room.subs["c"] = sub
h.mu.Unlock()
h.detach(id, sub)
h.mu.Lock()
kept := h.rooms[id] == room
h.mu.Unlock()
if kept != (tasks > 0) {
t.Fatalf("%d background tasks: kept=%v", tasks, kept)
}
}
}
+1 -1
View File
@@ -33,7 +33,7 @@ func TestChatAdoptRecordsTheOwningHarness(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatAdopt || response.ChatSession == nil {
+3 -3
View File
@@ -42,7 +42,7 @@ func subscribeChat(t *testing.T, ctx context.Context, conn *websocket.Conn, id s
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatSubscribe || ack.ID != id {
@@ -55,7 +55,7 @@ func readStepStarted(t *testing.T, ctx context.Context, conn *websocket.Conn) {
t.Helper()
for {
var message protocol.Message
if err := wsjson.Read(ctx, conn, &message); err != nil {
if err := readTestFrame(ctx, conn, &message); err != nil {
t.Fatalf("no step-started frame: %v", err)
}
event := message.ChatEvent
@@ -89,7 +89,7 @@ func TestChatSubscribeIdleHarnessReplaysNoTurn(t *testing.T) {
defer cancel()
for {
var message protocol.Message
err := wsjson.Read(readCtx, conn, &message)
err := readTestFrame(readCtx, conn, &message)
if err != nil {
if !errors.Is(readCtx.Err(), context.DeadlineExceeded) {
t.Fatalf("read: %v", err)
+12 -12
View File
@@ -25,7 +25,7 @@ func TestChatCloseRecordsClosedState(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatClose || response.ID != "cl1" {
@@ -56,7 +56,7 @@ func TestChatCloseRecordsClosedState(t *testing.T) {
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSessions, ID: "l1"}); err != nil {
t.Fatal(err)
}
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatSessions || len(response.ChatSessions) != 1 {
@@ -86,7 +86,7 @@ func TestChatCloseStopsRunningTurn(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conns[0], &ack); err != nil {
if err := readTestFrame(ctx, conns[0], &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatPrompt {
@@ -99,7 +99,7 @@ func TestChatCloseStopsRunningTurn(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conns[1], &response); err != nil {
if err := readTestFrame(ctx, conns[1], &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatClose || response.ID != "cl1" {
@@ -139,7 +139,7 @@ func TestChatCloseKeepsSessionAndMessages(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatClose {
@@ -157,7 +157,7 @@ func TestChatCloseKeepsSessionAndMessages(t *testing.T) {
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatMessages, ID: "ms1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatMessages || len(response.ChatMessages) != 1 || response.ChatMessages[0].ID != "m1" {
@@ -185,7 +185,7 @@ func TestChatReopenClearsClosedState(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatReopen || response.ID != "op1" || response.ChatSession == nil {
@@ -220,7 +220,7 @@ func TestChatPromptReopensClosedSession(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatPrompt {
@@ -247,7 +247,7 @@ func TestChatCloseRefusesNonOperatorSession(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "not an operator") {
@@ -276,7 +276,7 @@ func TestChatCloseRejectsInvalidInput(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "bad" {
@@ -291,7 +291,7 @@ func TestChatCloseRejectsInvalidInput(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(noRegCtx, noRegConn, &response); err != nil {
if err := readTestFrame(noRegCtx, noRegConn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "registry") {
@@ -304,7 +304,7 @@ func TestChatCloseRejectsInvalidInput(t *testing.T) {
if err := wsjson.Write(noBrokerCtx, noBrokerConn, protocol.Message{Type: protocol.ChatClose, ID: "nb", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
if err := wsjson.Read(noBrokerCtx, noBrokerConn, &response); err != nil {
if err := readTestFrame(noBrokerCtx, noBrokerConn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "not configured") {
+1 -1
View File
@@ -18,7 +18,7 @@ func chatColorRequest(id, session string, color *string) protocol.Message {
func readMessage(t *testing.T, ctx context.Context, conn *websocket.Conn) protocol.Message {
t.Helper()
var message protocol.Message
if err := wsjson.Read(ctx, conn, &message); err != nil {
if err := readTestFrame(ctx, conn, &message); err != nil {
t.Fatal(err)
}
return message
+1 -3
View File
@@ -6,8 +6,6 @@ import (
"strings"
"testing"
"github.com/coder/websocket/wsjson"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
@@ -59,7 +57,7 @@ func exportFixture(t *testing.T, backend string) (*pagedChat, context.Context, f
writeChat(t, ctx, conn, message)
for {
var reply protocol.Message
if err := wsjson.Read(ctx, conn, &reply); err != nil {
if err := readTestFrame(ctx, conn, &reply); err != nil {
t.Fatalf("read reply to %s: %v", message.ID, err)
}
if reply.ID == message.ID {
+4
View File
@@ -63,6 +63,10 @@ type chatHub struct {
unattended chatUnattendedTimings
// sessionChanges pushes shared list metadata changes to every connection.
sessionChanges chatSessionChanges
// activity/activitySeq are the last chat-list activity pushed per session
// and its sequence source (chat_activity.go).
activity map[string]protocol.ChatActivity
activitySeq int64
}
// chatPart is the retained form of one part. Text and reasoning deltas append to
+1 -1
View File
@@ -220,7 +220,7 @@ func readChatResponse(t *testing.T, ctx context.Context, ws *websocket.Conn) ([]
func readChatMessage(t *testing.T, ctx context.Context, ws *websocket.Conn) protocol.Message {
t.Helper()
var message protocol.Message
if err := wsjson.Read(ctx, ws, &message); err != nil {
if err := readTestFrame(ctx, ws, &message); err != nil {
t.Fatalf("read: %v", err)
}
if message.Type == protocol.Error {
+5 -5
View File
@@ -224,7 +224,7 @@ func readUntil(t *testing.T, ctx context.Context, conn *websocket.Conn, want str
t.Helper()
for {
var message protocol.Message
if err := wsjson.Read(ctx, conn, &message); err != nil {
if err := readTestFrame(ctx, conn, &message); err != nil {
t.Fatalf("read (waiting for %s): %v", want, err)
}
if message.Type == protocol.Error {
@@ -242,7 +242,7 @@ func nextEvent(t *testing.T, ctx context.Context, conn *websocket.Conn) protocol
t.Helper()
for {
var message protocol.Message
if err := wsjson.Read(ctx, conn, &message); err != nil {
if err := readTestFrame(ctx, conn, &message); err != nil {
t.Fatalf("read event: %v", err)
}
if message.Type == protocol.Error {
@@ -259,7 +259,7 @@ func nextPermission(t *testing.T, ctx context.Context, conn *websocket.Conn, req
t.Helper()
for {
var message protocol.Message
if err := wsjson.Read(ctx, conn, &message); err != nil {
if err := readTestFrame(ctx, conn, &message); err != nil {
t.Fatalf("read permission: %v", err)
}
if message.Type == protocol.Error {
@@ -420,7 +420,7 @@ func TestChatApprovalFirstAnswerWins(t *testing.T) {
// The tablet's later answer is refused, and it never reaches the agent.
writeChat(t, ctx, tablet, protocol.Message{Type: protocol.ChatReply, ID: "a2", ChatReply: &protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: protocol.ChatDecisionAlways, Client: "Pixel 10 Pro Fold"}})
var refused protocol.Message
if err := wsjson.Read(ctx, tablet, &refused); err != nil {
if err := readTestFrame(ctx, tablet, &refused); err != nil {
t.Fatal(err)
}
if refused.Type != protocol.Error || !strings.Contains(refused.Error, "already answered by Pixel 9") {
@@ -484,7 +484,7 @@ func TestChatQueuedPromptFailureSurfaced(t *testing.T) {
for {
var message protocol.Message
if err := wsjson.Read(ctx, tablet, &message); err != nil {
if err := readTestFrame(ctx, tablet, &message); err != nil {
t.Fatalf("read (waiting for the queued prompt failure): %v", err)
}
if message.Type != protocol.Error {
+2 -3
View File
@@ -11,7 +11,6 @@ import (
"time"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/pipeline"
@@ -236,7 +235,7 @@ func TestChatSubscribeListsQueuedPromptsAndUnqueueRemoves(t *testing.T) {
sawUser := false
for {
var message protocol.Message
if err := wsjson.Read(server.ctx, reloaded, &message); err != nil {
if err := readTestFrame(server.ctx, reloaded, &message); err != nil {
t.Fatalf("no delivery reported: %v", err)
}
if event := message.ChatEvent; event != nil && event.Kind == protocol.ChatEventUser && event.OperationID == "op-3" {
@@ -259,7 +258,7 @@ func TestChatSubscribeListsQueuedPromptsAndUnqueueRemoves(t *testing.T) {
writeChat(t, server.ctx, reloaded, protocol.Message{Type: protocol.ChatUnqueue, ID: "rm-late", ChatUnqueue: &protocol.ChatUnqueueRequest{SessionID: "ses_1", OperationID: "op-3"}})
for {
var message protocol.Message
if err := wsjson.Read(server.ctx, reloaded, &message); err != nil {
if err := readTestFrame(server.ctx, reloaded, &message); err != nil {
t.Fatal(err)
}
if message.ID == "rm-late" {
+15
View File
@@ -346,6 +346,8 @@ func (h *chatHub) releaseRoomLocked(room *chatRoom) {
h.clearCompactionLocked(room)
delete(h.rooms, room.sessionID)
room.cancel()
// An unobserved session reports no turn and no background tasks.
h.noteActivityLocked(room.sessionID)
// ReleaseShells is a local identity-cache operation (no broker I/O).
// Complete it before a reconnect can acquire this session's new room.
if releaser, ok := room.broker.(chatShellReleaser); ok {
@@ -477,6 +479,16 @@ func (h *chatHub) emitRoom(source *chatRoom, frame protocol.ChatEventFrame) {
h.releaseRoomLocked(room)
}
}
if frame.Kind == protocol.ChatEventStep || frame.Kind == protocol.ChatEventShell {
h.noteActivityLocked(frame.SessionID)
}
// An unwatched room kept only for its background tasks is done once the
// last of them exits.
if room != nil && frame.Kind == protocol.ChatEventShell && frame.Shell != nil && frame.Shell.Status != protocol.ChatShellRunning &&
room.watching && len(room.subs) == 0 && len(room.queue) == 0 && h.rooms[room.sessionID] == room && !h.keepUnattendedLocked(room, false, true) {
room.watching = false
h.releaseRoomLocked(room)
}
// Shell replay and live lifecycle delivery must enqueue in the same order
// as folding. Otherwise an exit can overtake an older running replay.
if (frame.Kind == protocol.ChatEventShell || frame.Kind == protocol.ChatEventCompaction || frame.Kind == protocol.ChatEventUsage) && !buffered {
@@ -557,6 +569,7 @@ func (h *chatHub) replaceShellsLocked(sessionID string, shells []protocol.ChatSh
for i := range shells {
turn.applyShell(&shells[i])
}
h.noteActivityLocked(sessionID)
}
// finishTurnLocked marks the room's turn finished and releases the turn runner's
@@ -570,6 +583,7 @@ func (h *chatHub) finishTurnLocked(room *chatRoom) {
close(room.turnDone)
room.turnDone = nil
}
h.noteActivityLocked(room.sessionID)
// A queue held behind a turn this room only observed advances now.
signalWake(room.wake)
}
@@ -774,6 +788,7 @@ func (h *chatHub) nextPrompt(room *chatRoom) (*chatQueuedPrompt, chan struct{},
room.nativeTurnID = ""
room.turnDone = make(chan struct{})
done := room.turnDone
h.noteActivityLocked(room.sessionID)
h.mu.Unlock()
return p, done, true
} else {
+14
View File
@@ -86,6 +86,20 @@ func handleChatSessions(ctx context.Context, request protocol.Message, broker ch
session.Color = operator.Color
response.ChatSessions = append(response.ChatSessions, session)
}
// Each row carries the hub's live activity (turn running, background
// tasks), read once for the whole list after the broker call; later
// changes arrive as chat_activity pushes.
if hub != nil {
ids := make([]string, len(response.ChatSessions))
for i := range response.ChatSessions {
ids[i] = response.ChatSessions[i].ID
}
activity := hub.activitySnapshot(ids)
for i := range response.ChatSessions {
row := activity[response.ChatSessions[i].ID]
response.ChatSessions[i].Activity = &row
}
}
_ = write(response)
}
+1 -2
View File
@@ -11,7 +11,6 @@ import (
"time"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
@@ -273,7 +272,7 @@ func dialShellOutputWebsocket(t *testing.T, ctx context.Context, srv *httptest.S
func readShellOutputMessage(t *testing.T, ctx context.Context, ws *websocket.Conn) protocol.Message {
t.Helper()
var message protocol.Message
if err := wsjson.Read(ctx, ws, &message); err != nil {
if err := readTestFrame(ctx, ws, &message); err != nil {
t.Fatal(err)
}
return message
+21 -1
View File
@@ -47,7 +47,7 @@ func TestChatShellReconciliationScratchServer(t *testing.T) {
read := func() protocol.Message {
t.Helper()
var m protocol.Message
if err := wsjson.Read(ctx, conn, &m); err != nil {
if err := readTestFrame(ctx, conn, &m); err != nil {
t.Fatal(err)
}
return m
@@ -215,6 +215,11 @@ func TestChatShellReconciliationBarrier(t *testing.T) {
}
}
sub.close()
if status == protocol.ChatShellRunning {
// Running background tasks keep the room observing with no
// client (chat_unattended.go); release it to end the stream.
releaseKeptRoom(t, h, sub.room)
}
shellBarrierWait(t, b.stopped)
})
}
@@ -257,5 +262,20 @@ func TestChatShellReconciliationCancelReconnectBarrier(t *testing.T) {
t.Fatalf("reconnect state = %+v", got)
}
newSub.close()
releaseKeptRoom(t, h, newSub.room)
shellBarrierWait(t, next.stopped)
}
// releaseKeptRoom asserts room is still kept observing after its last client
// left (it holds running background tasks) and releases it.
func releaseKeptRoom(t *testing.T, h *chatHub, room *chatRoom) {
t.Helper()
h.mu.Lock()
kept := h.rooms[room.sessionID] == room && room.watching
room.watching = false
h.releaseRoomLocked(room)
h.mu.Unlock()
if !kept {
t.Fatal("a room with running background tasks was not kept observing")
}
}
+55 -55
View File
@@ -428,7 +428,7 @@ func readChatTurn(t *testing.T, ctx context.Context, conn *websocket.Conn) []pro
var frames []protocol.ChatEventFrame
for {
var message protocol.Message
if err := wsjson.Read(ctx, conn, &message); err != nil {
if err := readTestFrame(ctx, conn, &message); err != nil {
t.Fatal(err)
}
if message.Type == protocol.Error {
@@ -452,7 +452,7 @@ func TestChatModelsAndSwitch(t *testing.T) {
t.Fatal(err)
}
var reply protocol.Message
if err := wsjson.Read(ctx, conn, &reply); err != nil {
if err := readTestFrame(ctx, conn, &reply); err != nil {
t.Fatal(err)
}
if reply.Type != protocol.ChatModels || len(reply.ChatModels) != 1 || reply.ChatModels[0].ID != "m1" {
@@ -461,7 +461,7 @@ func TestChatModelsAndSwitch(t *testing.T) {
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatModelSelect, ID: "r2", ModelRequest: &protocol.ChatModelRequest{SessionID: "ses_1", Provider: "p1", Model: "m1"}}); err != nil {
t.Fatal(err)
}
if err := wsjson.Read(ctx, conn, &reply); err != nil {
if err := readTestFrame(ctx, conn, &reply); err != nil {
t.Fatal(err)
}
if reply.Type != protocol.ChatModelSelect || reply.ModelRequest == nil || reply.ModelRequest.Model != "m1" {
@@ -487,7 +487,7 @@ func TestChatPromptWritesAttachmentAndForwardsLocalFile(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatPrompt || ack.Error != "" {
@@ -517,7 +517,7 @@ func TestChatPromptStreamsEvents(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatPrompt || ack.ID != "r1" {
@@ -558,7 +558,7 @@ func TestChatPromptRejectsInvalidSession(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "bad" {
@@ -578,7 +578,7 @@ func TestChatPromptRejectsOversizedText(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "64 KiB") {
@@ -595,7 +595,7 @@ func TestChatPromptWithoutBroker(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "not configured") {
@@ -611,7 +611,7 @@ func TestChatMessagesResumesRetainedState(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
readChatTurn(t, ctx, conn)
@@ -619,7 +619,7 @@ func TestChatMessagesResumesRetainedState(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatMessages || response.ID != "r2" || response.ChatHistory == nil {
@@ -692,7 +692,7 @@ func TestChatMessagesReturnsBrokerHistory(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatMessages || response.ID != "r2" {
@@ -735,7 +735,7 @@ func TestChatMessagesThroughRealAdapter(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatMessages || response.ID != "r2" {
@@ -758,7 +758,7 @@ func TestChatMessagesRejectsInvalidSession(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "bad" {
@@ -782,7 +782,7 @@ func TestChatDisconnectCancelsStream(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
select {
@@ -815,7 +815,7 @@ func TestChatInterruptAndReply(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatInterrupt || response.ID != "i1" {
@@ -824,7 +824,7 @@ func TestChatInterruptAndReply(t *testing.T) {
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatReply, ID: "p1", ChatReply: &protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: protocol.ChatDecisionOnce}}); err != nil {
t.Fatal(err)
}
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatReply || response.ID != "p1" {
@@ -909,7 +909,7 @@ func TestChatInterruptEndsRunningPrompt(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatPrompt || ack.ID != "r1" {
@@ -917,7 +917,7 @@ func TestChatInterruptEndsRunningPrompt(t *testing.T) {
}
// The first text delta proves the turn is live and the subscription attached.
var first protocol.Message
if err := wsjson.Read(ctx, conn, &first); err != nil {
if err := readTestFrame(ctx, conn, &first); err != nil {
t.Fatal(err)
}
if first.Type != protocol.ChatEvent || first.ChatEvent == nil || first.ChatEvent.Kind != protocol.ChatEventText || first.ChatEvent.Delta != "working" {
@@ -934,7 +934,7 @@ func TestChatInterruptEndsRunningPrompt(t *testing.T) {
var acked, ended bool
for !acked || !ended {
var message protocol.Message
if err := wsjson.Read(ctx, conn, &message); err != nil {
if err := readTestFrame(ctx, conn, &message); err != nil {
t.Fatal(err)
}
if message.Type == protocol.Error {
@@ -974,7 +974,7 @@ func TestChatInterruptRejectsInvalidSession(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "bad" {
@@ -994,7 +994,7 @@ func TestChatInterruptWithoutBroker(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "not configured") {
@@ -1012,7 +1012,7 @@ func TestChatInterruptErrorReported(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "i1" || !strings.Contains(response.Error, "already finished") {
@@ -1261,7 +1261,7 @@ func TestChatPromptStreamsShellFrame(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
frames := readChatTurn(t, ctx, conn)
@@ -1289,7 +1289,7 @@ func TestChatSubscribeReplaysRunningShell(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conns[0], &ack); err != nil {
if err := readTestFrame(ctx, conns[0], &ack); err != nil {
t.Fatal(err)
}
frames := readChatTurn(t, ctx, conns[0])
@@ -1307,14 +1307,14 @@ func TestChatSubscribeReplaysRunningShell(t *testing.T) {
t.Fatal(err)
}
var subscription protocol.Message
if err := wsjson.Read(ctx, conns[1], &subscription); err != nil {
if err := readTestFrame(ctx, conns[1], &subscription); err != nil {
t.Fatal(err)
}
if subscription.Type != protocol.ChatSubscribe || subscription.ID != "sub1" {
t.Fatalf("subscribe ack = %+v", subscription)
}
var replayed protocol.Message
if err := wsjson.Read(ctx, conns[1], &replayed); err != nil {
if err := readTestFrame(ctx, conns[1], &replayed); err != nil {
t.Fatal(err)
}
if replayed.Type != protocol.ChatEvent || replayed.ChatEvent == nil || replayed.ChatEvent.Kind != protocol.ChatEventShell {
@@ -1338,14 +1338,14 @@ func TestChatSubscribeKeepsStreamWhenShellReadbackFails(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatSubscribe || ack.ID != "sub1" {
t.Fatalf("subscribe ack = %+v", ack)
}
var limited protocol.Message
if err := wsjson.Read(ctx, conn, &limited); err != nil {
if err := readTestFrame(ctx, conn, &limited); err != nil {
t.Fatal(err)
}
if limited.Type != protocol.Error || limited.Error != "background shell visibility is limited" {
@@ -1369,7 +1369,7 @@ func TestChatPromptSubscribesBeforePrompt(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
readChatTurn(t, ctx, conn)
@@ -1422,7 +1422,7 @@ func realAdapterChat(t *testing.T, frames []string) []protocol.ChatEventFrame {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatPrompt || ack.ID != "r1" {
@@ -1509,7 +1509,7 @@ func TestChatPromptRejectsEmptyText(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "empty" {
@@ -1536,7 +1536,7 @@ func TestChatCreateRecordsOperatorSession(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatCreate || response.ID != "c1" || response.ChatSession == nil {
@@ -1582,7 +1582,7 @@ func TestChatCreateEphemeralSessionIsNeverListed(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
// The session is real and usable: it is created, bootstrapped and echoed.
@@ -1858,7 +1858,7 @@ func TestChatCreateDirectoryResolution(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if tc.wantErr != "" {
@@ -1908,7 +1908,7 @@ func TestChatDirectoriesHomeThenBoundedRecents(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatDirectories || response.ID != "d1" {
@@ -1992,7 +1992,7 @@ func TestChatSessionsListsOperatorSessionsOnly(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatSessions || response.ID != "s1" {
@@ -2028,7 +2028,7 @@ func TestChatSessionsNeverListsUntagged(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatSessions || len(response.ChatSessions) != 0 {
@@ -2061,7 +2061,7 @@ func TestChatSessionsMostRecentlyUsedFirst(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if len(response.ChatSessions) != 2 {
@@ -2086,7 +2086,7 @@ func TestChatSessionsFailsClosedWithoutOwnership(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatSessions || len(response.ChatSessions) != 0 {
@@ -2119,14 +2119,14 @@ func TestChatPromptPushesPermissionAndForwardsReply(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatPrompt || ack.ID != "r1" {
t.Fatalf("prompt ack = %+v", ack)
}
var permission protocol.Message
if err := wsjson.Read(ctx, conn, &permission); err != nil {
if err := readTestFrame(ctx, conn, &permission); err != nil {
t.Fatal(err)
}
if permission.Type == protocol.Error {
@@ -2143,7 +2143,7 @@ func TestChatPromptPushesPermissionAndForwardsReply(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatReply || response.ID != "p1" {
@@ -2227,7 +2227,7 @@ func TestChatDisconnectCancelsPermissionPoller(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
select {
@@ -2273,11 +2273,11 @@ func TestChatPermissionPollErrorSurfaced(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "permission poll") {
@@ -2304,7 +2304,7 @@ func TestChatReplyRejectsInvalidInput(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "bad" {
@@ -2324,7 +2324,7 @@ func TestChatReplyWithoutBroker(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "not configured") {
@@ -2346,7 +2346,7 @@ func TestChatPermissionUnsupportedBackendIsQuiet(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatPrompt || ack.ID != "r1" {
@@ -2356,7 +2356,7 @@ func TestChatPermissionUnsupportedBackendIsQuiet(t *testing.T) {
readCtx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer cancel()
var unexpected protocol.Message
if err := wsjson.Read(readCtx, conn, &unexpected); err == nil {
if err := readTestFrame(readCtx, conn, &unexpected); err == nil {
t.Fatalf("unsupported permission surface must not write a frame, got %+v", unexpected)
}
if calls, _ := broker.permissionQuery(); calls != 1 {
@@ -2379,7 +2379,7 @@ func TestChatAdoptRecordsEndpointSession(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatAdopt || response.ID != "a1" || response.ChatSession == nil {
@@ -2410,7 +2410,7 @@ func TestChatAdoptRecordsEndpointSession(t *testing.T) {
t.Fatal(err)
}
var listed protocol.Message
if err := wsjson.Read(ctx, conn, &listed); err != nil {
if err := readTestFrame(ctx, conn, &listed); err != nil {
t.Fatal(err)
}
if listed.Type != protocol.ChatSessions || len(listed.ChatSessions) != 1 || listed.ChatSessions[0].ID != "ses_existing" || listed.ChatSessions[0].Directory != "/work/existing" || listed.ChatSessions[0].Tag != protocol.ChatSessionTagOperator {
@@ -2422,7 +2422,7 @@ func TestChatAdoptRecordsEndpointSession(t *testing.T) {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
if err := readTestFrame(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatPrompt || ack.ID != "p1" {
@@ -2451,7 +2451,7 @@ func TestChatAdoptMissingIDRecordsNothing(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "ses_missing") {
@@ -2480,7 +2480,7 @@ func TestChatAdoptRefusesEmptyDirectory(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "directory") {
@@ -2516,7 +2516,7 @@ func TestChatAdoptRejectsInvalidInputBeforeBroker(t *testing.T) {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
if err := readTestFrame(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error {
+16 -6
View File
@@ -11,15 +11,17 @@ import (
// stream while the session has a room. A room normally lives while a client
// watches the chat, but the operator relies on these notifications precisely
// when no app is open. So a room whose last client leaves stays observing,
// unattended, while its turn is in flight or it holds an unanswered question
// or approval, and is torn down once that work is done. The same unattended
// unattended, while its turn is in flight, it holds an unanswered question or
// approval, or background tasks it started are still running (so the chat list
// sees them finish), and is torn down once that work is done. The same unattended
// observation is started at server start for sessions whose harness reports a
// running turn, so a reply that finishes after a restart still notifies.
//
// Resources are bounded: at most chatUnattendedLimit rooms are kept without a
// client (rooms holding queued prompts are not counted: they were always kept
// until delivered), a stuck turn is released after chatUnattendedTurnLimit,
// and an idle session is never observed.
// until delivered), a stuck turn or a background task that never reports an
// exit is released after chatUnattendedTurnLimit, and an idle session is never
// observed.
// chatUnattendedLimit bounds the rooms kept observing with no client attached
// and no queued prompt.
@@ -63,13 +65,21 @@ type chatTurnProber interface {
// keepUnattendedLocked reports whether a room with no client still has work
// the operator must hear about: a turn in flight (the runner's, or one its
// stream announced), an unresolved approval or question, or a harness that
// reports its own turn running (busy, read by the caller off the hub mutex).
// reports its own turn running (busy, read by the caller off the hub mutex),
// or background tasks still running.
// hold honours the start-up settle window. Queued prompts are the caller's
// concern. Callers hold h.mu.
func (h *chatHub) keepUnattendedLocked(room *chatRoom, busy, hold bool) bool {
if room.running || room.observedTurn || busy || len(room.pending) > 0 || len(room.forms) > 0 {
return true
}
// Running background tasks keep the stream observed so their exits are
// seen and the chat list's indicator clears. This is bounded like a turn:
// the unattended room limit, the chatUnattendedTurnLimit expiry, and the
// harness itself (a Claude Code process that exits ends its tasks).
if h.backgroundTasksLocked(room.sessionID) > 0 {
return true
}
return hold && h.clock().Before(room.holdUntil)
}
@@ -167,7 +177,7 @@ func (h *chatHub) reapUnattended(room *chatRoom) bool {
return false
}
if expired {
log.Printf("chat session %s: released the unattended observer after %s without the turn ending", room.sessionID, h.unattended.turnLimit)
log.Printf("chat session %s: released the unattended observer after %s without its turn or background tasks ending", room.sessionID, h.unattended.turnLimit)
}
room.watching = false
h.releaseRoomLocked(room)
+18 -1
View File
@@ -1,8 +1,12 @@
package server
import (
"git.a-wan.net/alan/pipelines/internal/harness"
"context"
"os"
"git.a-wan.net/alan/pipelines/examples"
"git.a-wan.net/alan/pipelines/internal/harness"
"git.a-wan.net/alan/pipelines/internal/pipeline"
)
func starterDefaults() (string, string) {
@@ -13,3 +17,16 @@ func starterDefaults() (string, string) {
}
return model, backend
}
// SeedExamples adds the bundled example pipelines to a brand-new database, bound
// to the server's configured default model and harness exactly as the template
// picker binds them. It is a no-op for an existing or already-seeded database
// (see pipeline.Store.SeedExamples) and returns the number created.
func SeedExamples(ctx context.Context, store *pipeline.Store) (int, error) {
model, backend := starterDefaults()
items := examples.Catalog()
for i := range items {
items[i].Source = pipeline.WithDefaults(items[i].Source, model, backend)
}
return store.SeedExamples(ctx, items)
}
+13 -12
View File
@@ -105,9 +105,10 @@ func TestStageNotificationEventsAndArtifactAudit(t *testing.T) {
}
}
// Regress the exact research -> report terminal-path recipe from the authoring guide.
// Regress the terminal-path recipe from the authoring guide (research -> report
// there) on the bundled two-stage example's draft -> check.
// A completion-alert request must not require native delivery or change run routing.
func TestResearchTerminalNotificationRecipe(t *testing.T) {
func TestTerminalNotificationRecipe(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "recipe.db"))
@@ -117,15 +118,15 @@ func TestResearchTerminalNotificationRecipe(t *testing.T) {
defer store.Close()
var source string
for _, template := range examples.Catalog() {
if template.Key == "research" {
if template.Key == "two-stages" {
source = template.Source
}
}
if source == "" {
t.Fatal("research template missing")
t.Fatal("two-stages template missing")
}
source = strings.Replace(source, "# stage research", "# stage research\n```notify\non=failure\n```", 1)
source = strings.Replace(source, "# stage report", "# stage report\n```notify\non=success,failure\n```", 1)
source = strings.Replace(source, "# stage draft", "# stage draft\n```notify\non=failure\n```", 1)
source = strings.Replace(source, "# stage check", "# stage check\n```notify\non=success,failure\n```", 1)
if _, err = store.Submit(ctx, "research notification recipe", source); err != nil {
t.Fatal(err)
}
@@ -159,12 +160,12 @@ func TestResearchTerminalNotificationRecipe(t *testing.T) {
name, stage, outcome, status string
executionError, deliveryError bool
}{
{"success", "report", "success", "succeeded", false, false},
{"research blocked", "research", "blocked", "failed", false, false},
{"research execution error", "research", "error", "failed", true, false},
{"report blocked", "report", "blocked", "failed", false, false},
{"report execution error", "report", "error", "failed", true, false},
{"delivery error preserves success", "report", "success", "succeeded", false, true},
{"success", "check", "success", "succeeded", false, false},
{"draft blocked", "draft", "blocked", "failed", false, false},
{"draft execution error", "draft", "error", "failed", true, false},
{"check blocked", "check", "blocked", "failed", false, false},
{"check execution error", "check", "error", "failed", true, false},
{"delivery error preserves success", "check", "success", "succeeded", false, true},
} {
t.Run(test.name, func(t *testing.T) {
deliveryFailure.Store(test.deliveryError)
+32 -19
View File
@@ -951,11 +951,14 @@ type runState struct {
input stage.Values
// changedPaths retains a bounded sample of the run's recorded changed paths
// and changedCount the full total, so the skip guard reads only in-memory
// evidence. uiSurface is latched once any recorded change touched a UI
// surface. Both are folded in by recordChanges (ui_surface.go).
changedPaths []string
changedCount int
uiSurface bool
// evidence. uiSurface is latched once any visit captured a rendered (image)
// artifact. captureIncomplete counts visits whose file-change capture was
// missing, partial or unavailable; any such visit forbids the server skip
// fallback. All are folded in by recordChanges (ui_surface.go).
changedPaths []string
changedCount int
uiSurface bool
captureIncomplete int
// capturedPaths is the full, deduplicated, first-seen-ordered set of the
// run's server-captured changed paths, distinct from the bounded
// changedPaths sample used only by the skip reason. capturedSeen is the
@@ -969,7 +972,7 @@ type runState struct {
artifactDirs []string
// prompt is the original run prompt; lastOutput is the previous visit's
// markdown and turns is every completed turn in order. Together they render
// the next model visit's input.md and memory.md.
// the next model visit's input.md, memory.md and history.md.
prompt string
lastOutput string
turns []turn.MemoryEntry
@@ -1015,12 +1018,12 @@ func rebuildRunState(detail *protocol.RunDetail, decided protocol.RunStep) *runS
state.memory[step.Stage] = memoryValue{output: values, sequence: step.Sequence}
}
state.completed++
state.turns = append(state.turns, turn.MemoryEntry{Stage: step.Stage, Visit: state.visits[step.Stage], Output: turnOutput(step.Output), PublicFiles: added})
state.turns = append(state.turns, turn.MemoryEntry{Stage: step.Stage, Visit: state.visits[step.Stage], Outcome: step.Outcome, Output: turnOutput(step.Output), PublicFiles: added})
state.lastOutput = turnOutput(step.Output)
}
// Seed the UI-surface accumulator from the persisted evidence so a
// resumed run reaches the same skip decision with no extra query.
state.recordChanges(step.FileChanges, step.Artifacts)
state.recordPersistedStep(step)
// Only completed, recorded visits are eligible for a later stage's
// review capability. The path is reconstructed by the runner below.
if step.Status == "completed" {
@@ -1059,10 +1062,10 @@ func rebuildRetryState(detail *protocol.RunDetail, failed protocol.RunStep, hand
state.memory[step.Stage] = memoryValue{output: values, sequence: step.Sequence}
}
state.completed++
state.turns = append(state.turns, turn.MemoryEntry{Stage: step.Stage, Visit: state.visits[step.Stage], Output: turnOutput(step.Output), PublicFiles: added})
state.turns = append(state.turns, turn.MemoryEntry{Stage: step.Stage, Visit: state.visits[step.Stage], Outcome: step.Outcome, Output: turnOutput(step.Output), PublicFiles: added})
state.lastOutput = turnOutput(step.Output)
}
state.recordChanges(step.FileChanges, step.Artifacts)
state.recordPersistedStep(step)
if step.Status == "completed" {
state.artifactDirs = append(state.artifactDirs, filepath.Join("", strconv.Itoa(step.Sequence)))
}
@@ -1073,6 +1076,9 @@ func rebuildRetryState(detail *protocol.RunDetail, failed protocol.RunStep, hand
// retry source's immediate steps (which is what made retry-of-retry fail
// closed with "memory source ... has not completed").
if prefix, ok := handoff["prefix"].(map[string]any); ok {
// The checkpoint carries outputs, not file-change captures, so an inherited
// prefix is unobserved evidence: the server skip fallback must not apply.
state.captureIncomplete++
for _, record := range retryPrefixRecords(handoff["prefix_provenance"]) {
output, exists := prefix[record.stage].(map[string]any)
if !exists {
@@ -1448,6 +1454,10 @@ func stageUsage(snapshot stage.BudgetSnapshot) *protocol.StageUsage {
usage.TokensTotal = snapshot.UsedTokens
if snapshot.SplitKnown {
usage.TokensIn, usage.TokensOut, usage.SplitKnown = snapshot.TokensInput, snapshot.TokensOutput, true
// The rest of the component split is kept too: for a caching harness
// most of the total is cache reads, which a client shows as cached
// rather than fresh tokens.
usage.TokensReasoning, usage.CacheRead, usage.CacheWrite, usage.CacheKnown = snapshot.TokensReasoning, snapshot.CacheRead, snapshot.CacheWrite, true
}
}
if snapshot.USDKnown {
@@ -1591,7 +1601,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
}
}
_, declaresSkip := def.Edges["skipped"]
skip := !isHuman && declaresSkip && !state.uiSurface
skip := !isHuman && declaresSkip && autoSkipEligible(def.Configs, state)
state.nextSequence = sequence + 1
state.visits[key]++
// Publish the run's server-captured changed paths into the input memory
@@ -1683,13 +1693,15 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
r.deliverRunNotificationBatch(time.Now(), 1)
return
}
// A stage that declares a `skipped` route is short-circuited when the run
// has recorded no UI surface: the stage would answer exactly that, so skip
// the model call and its capture work, record the step as completed and
// route along the declared edge. Only a declared route is honoured, and no
// other stage or outcome routing changes.
// Server skip fallback: a stage that declares a `skipped` route is
// short-circuited only when the run's evidence is complete and empty
// (autoSkipEligible, ui_surface.go): every visit recorded a complete
// capture with no file changes and no rendered artifact. Then skip the
// model call and its capture work, record the step as completed with a
// verdict that names the server fallback, and route along the declared
// edge. Partial, unavailable or missing evidence always runs the model.
if skip {
reason := skipReasonLine(state)
reason := skipReasonLine()
step := protocol.RunStep{
Sequence: sequence,
Stage: key,
@@ -1698,6 +1710,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
Output: stage.Values{"summary": reason},
Target: def.Edges["skipped"],
Control: &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads},
Verdict: &protocol.StageVerdict{Reason: reason, ReasonSource: protocol.VerdictReasonFallback},
}
status, outcome, diagnostic, terminal, finishErr := r.finishStage(id, name, workspace, selected, state, step)
if finishErr != nil {
@@ -1722,8 +1735,8 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
return
}
useAgent := stage.EffectiveType(def.Type) == stage.ModelType && (len(tools) > 0 || !explicitTools)
// Every model visit gets a file-based turn: input.md and memory.md are
// written before execution, output.md after it. Creation is part of the
// Every model visit gets a file-based turn: input.md, memory.md and
// history.md are written before execution, output.md after it. Creation is part of the
// protocol, so an unusable turn directory fails the run instead of
// silently degrading to the retired JSON envelope.
artifactsDir := ""
+2 -3
View File
@@ -6,7 +6,6 @@ import (
"time"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
@@ -68,7 +67,7 @@ func readReply(t *testing.T, ctx context.Context, conn *websocket.Conn, id strin
t.Helper()
for {
var reply protocol.Message
if err := wsjson.Read(ctx, conn, &reply); err != nil {
if err := readTestFrame(ctx, conn, &reply); err != nil {
t.Fatalf("read reply %s: %v", id, err)
}
if reply.ID == id {
@@ -140,7 +139,7 @@ func TestChatSearchBudgetNeverBlocksOtherReplies(t *testing.T) {
chatSearch(t, ctx, conn, "c1", "flaky")
writeChat(t, ctx, conn, protocol.Message{Type: protocol.Ping, ID: "p1"})
var first protocol.Message
if err := wsjson.Read(ctx, conn, &first); err != nil {
if err := readTestFrame(ctx, conn, &first); err != nil {
t.Fatal(err)
}
if first.ID != "p1" {
+42 -1
View File
@@ -57,7 +57,7 @@ func TestTemplatesDoNotSeedDatabaseAndCreateOnlyPreservesExisting(t *testing.T)
t.Fatal("invalid template returned to web/CLI", item.Key, err)
}
for _, s := range graph.Stages {
if s.Configs["provider"] != "test-provider" || s.Configs["model"] != "test-model" || s.Configs["harness"] != "opencode" {
if s.Type == "model" && (s.Configs["provider"] != "test-provider" || s.Configs["model"] != "test-model" || s.Configs["harness"] != "opencode") {
t.Fatal("template did not inherit configured defaults", item.Key, s.Configs)
}
}
@@ -87,3 +87,44 @@ func TestTemplatesDoNotSeedDatabaseAndCreateOnlyPreservesExisting(t *testing.T)
t.Fatal("immutable source changed")
}
}
// A brand-new database gets the bundled examples once, bound to the configured
// defaults like the template picker; they are ordinary editable pipelines.
func TestSeedExamplesBindsDefaultsOnABrandNewDatabase(t *testing.T) {
t.Setenv("PIPELINES_HARNESS_CONFIG", filepath.Join(t.TempDir(), "harnesses.json"))
t.Setenv("PIPELINES_DEFAULT_MODEL", "test-provider/test-model")
t.Setenv("PIPELINES_DEFAULT_HARNESS", "opencode")
ctx := context.Background()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "fresh.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
catalog := examples.Catalog()
seeded, err := SeedExamples(ctx, store)
if err != nil || seeded != len(catalog) {
t.Fatal("examples not seeded", seeded, err)
}
items, err := store.List(ctx)
if err != nil || len(items) != len(catalog) {
t.Fatal("seeded pipelines missing", items, err)
}
for _, item := range items {
detail, err := store.Get(ctx, item.ID, 0)
if err != nil || detail.Version != 1 {
t.Fatal(item.Name, err)
}
for _, s := range detail.Graph.Stages {
if s.Type == "model" && (s.Configs["provider"] != "test-provider" || s.Configs["model"] != "test-model" || s.Configs["harness"] != "opencode") {
t.Fatal("seeded example did not bind configured defaults", item.Name, s.Key, s.Configs)
}
}
// Editing a seeded example is an ordinary new version.
if _, err := store.Submit(ctx, item.Name, detail.Source+"\n"); err != nil {
t.Fatal("seeded example not editable", item.Name, err)
}
}
if seeded, err = SeedExamples(ctx, store); err != nil || seeded != 0 {
t.Fatal("examples seeded twice", seeded, err)
}
}
+114
View File
@@ -0,0 +1,114 @@
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"
"git.a-wan.net/alan/pipelines/internal/turn"
)
// TestFeedbackLoopRevisitGetsReviewerHandoffInEssentialMemory runs a real
// 4-stage pipeline with a review loop (plan, code, review -> changes -> code,
// review, land) and checks what each visit's memory.md and history.md hold:
// memory.md stays within its cap and leads the re-entered code stage with the
// reviewer's handoff, while history.md keeps every earlier turn in full.
func TestFeedbackLoopRevisitGetsReviewerHandoffInEssentialMemory(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "loop.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
source := strings.Replace(pipeline.Template([]string{"plan", "code", "review", "land"}, true), "success -> land\n", "success -> land\nchanges -> code\n", 1)
if _, err := store.Submit(ctx, "loop", source); err != nil {
t.Fatal(err)
}
items, err := store.List(ctx)
if err != nil || len(items) != 1 {
t.Fatalf("submit/list: %+v %v", items, err)
}
runner, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
filler := strings.Repeat("Long log line with commands, output and reasoning.\n", 200)
type seen struct{ memory, history string }
visits := map[string][]seen{}
reviews := 0
runner.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
memory, err := os.ReadFile(def.Turn.Memory)
if err != nil {
t.Fatal(err)
}
history, err := os.ReadFile(def.Turn.History)
if err != nil {
t.Fatal(err)
}
visits[def.Key] = append(visits[def.Key], seen{string(memory), string(history)})
body := "# handoff\n\n" + def.Key + " handoff\n\n# log\n\n" + def.Key + " full log\n" + filler
outcome := "success"
if def.Key == "review" {
reviews++
if reviews == 1 {
outcome = "changes"
body = "# notes\n\n" + filler + "\n# handoff\n\nFINDING: lock leaks on the error path in cache.go.\n"
}
}
return stage.Result{Outcome: outcome, Output: stage.Values{"markdown": body}}, nil
}
run, err := runner.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "loop", Workspace: t.TempDir(), Input: map[string]any{"prompt": "Add a cache."}})
if err != nil {
t.Fatal(err)
}
runner.wg.Wait()
detail, err := store.GetRun(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
if detail.Status != "succeeded" || len(detail.Steps) != 6 {
t.Fatalf("run = %q steps=%d: %+v", detail.Status, len(detail.Steps), detail.RunSummary)
}
for key, list := range visits {
for i, visit := range list {
if len(visit.memory) > turn.EssentialCap {
t.Fatalf("%s visit %d memory.md is %d bytes, over the cap", key, i+1, len(visit.memory))
}
}
}
if len(visits["code"]) != 2 {
t.Fatalf("code ran %d times, want 2", len(visits["code"]))
}
revisit := visits["code"][1]
for _, want := range []string{
"Add a cache.",
"## Previous stage: review · visit 1 · outcome changes",
"FINDING: lock leaks on the error path in cache.go.",
"- code · visit 1 · outcome success (this stage's previous visit; detail in history.md)",
} {
if !strings.Contains(revisit.memory, want) {
t.Fatalf("re-entered code memory.md missing %q:\n%s", want, revisit.memory)
}
}
if strings.Contains(revisit.memory, "Long log line") {
t.Fatalf("re-entered code memory.md carried a full log:\n%s", revisit.memory)
}
for _, want := range []string{"## plan · visit 1", "plan full log", "## code · visit 1", "code full log", "## review · visit 1", "FINDING: lock leaks"} {
if !strings.Contains(revisit.history, want) {
t.Fatalf("re-entered code history.md missing %q", want)
}
}
land := visits["land"][0]
if !strings.Contains(land.memory, "## Previous stage: review · visit 2 · outcome success") || !strings.Contains(land.memory, "review handoff") {
t.Fatalf("land memory.md lacks the last review handoff:\n%s", land.memory)
}
if len(land.history) < 10*len(land.memory) {
t.Fatalf("land history %d bytes vs memory %d bytes: essential memory is not compact", len(land.history), len(land.memory))
}
}
+21 -5
View File
@@ -38,7 +38,7 @@ func TestTurnsAccumulateMemoryAndListFilesAsArtifacts(t *testing.T) {
if err != nil {
t.Fatal(err)
}
var secondInput, secondMemory string
var secondInput, secondMemory, secondHistory string
runner.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Turn.Input == "" || def.Turn.Memory == "" || def.Turn.Output == "" || def.Turn.Private == "" || def.Turn.Public == "" {
t.Fatalf("runner did not provide the turn paths: %+v", def.Turn)
@@ -63,6 +63,14 @@ func TestTurnsAccumulateMemoryAndListFilesAsArtifacts(t *testing.T) {
t.Fatal(err)
}
secondMemory = string(data)
if def.Turn.History == "" {
t.Fatalf("runner did not provide the history path: %+v", def.Turn)
}
data, err = os.ReadFile(def.Turn.History)
if err != nil {
t.Fatal(err)
}
secondHistory = string(data)
if _, err := os.Stat(filepath.Join(def.Turn.Private, "secret.txt")); !os.IsNotExist(err) {
t.Fatalf("a later turn received an earlier private file: %v", err)
}
@@ -93,11 +101,19 @@ func TestTurnsAccumulateMemoryAndListFilesAsArtifacts(t *testing.T) {
t.Fatalf("second input.md = %q, want the run task and the previous turn's output", secondInput)
}
for _, want := range []string{"## first · visit 1", "first body", "Files added to public/:\n- public/shared.txt"} {
if !strings.Contains(secondHistory, want) {
t.Fatalf("second history.md missing %q:\n%s", want, secondHistory)
}
}
for _, want := range []string{"# Essential memory", "original task", "## Previous stage: first · visit 1 · outcome success", "first body", "Added to public/: public/shared.txt", "- first · visit 1 · outcome success"} {
if !strings.Contains(secondMemory, want) {
t.Fatalf("second memory.md missing %q:\n%s", want, secondMemory)
}
}
for _, name := range []string{"input.md", "memory.md", "output.md"} {
if len(secondMemory) > turn.EssentialCap {
t.Fatalf("memory.md is %d bytes, over the %d cap", len(secondMemory), turn.EssentialCap)
}
for _, name := range []string{"input.md", "memory.md", "history.md", "output.md"} {
if _, ok := artifactNamed(detail.Steps[1].Artifacts, name); !ok {
t.Fatalf("second visit did not list %s: %+v", name, detail.Steps[1].Artifacts)
}
@@ -125,7 +141,7 @@ func TestRebuildRunStateRestoresPublicFileLists(t *testing.T) {
},
}
state := rebuildRunState(detail, protocol.RunStep{Sequence: 2, Stage: "second", Output: map[string]any{"markdown": "second body\n"}})
memory := turn.RenderMemory(state.turns)
memory := turn.RenderHistory(state.turns)
for _, want := range []string{
"## first · visit 1",
"Files added to public/:\n- public/a.png",
@@ -157,7 +173,7 @@ func TestRebuildRetryStateRestoresPublicFileLists(t *testing.T) {
"prefix_provenance": []any{map[string]any{"stage": "first", "sequence": float64(1)}},
}
state := rebuildRetryState(detail, detail.Steps[1], handoff)
memory := turn.RenderMemory(state.turns)
memory := turn.RenderHistory(state.turns)
if !strings.Contains(memory, "Files added to public/:\n- public/report.pdf") {
t.Fatalf("retry memory lost the inherited public file list:\n%s", memory)
}
@@ -248,7 +264,7 @@ func TestRetryCarriesPublicFilesAcrossAttempts(t *testing.T) {
t.Fatalf("transitive retry did not carry the public file: %q %v", data, err)
}
paths := runner.turnPaths(second.ID, 2, "b")
memory, err := os.ReadFile(paths.MemoryPath)
memory, err := os.ReadFile(paths.HistoryPath)
if err != nil {
t.Fatal(err)
}
+22 -8
View File
@@ -40,14 +40,16 @@ func stageTurnPaths(paths turn.Paths) stage.TurnPaths {
Dir: paths.TurnDir,
Input: paths.InputPath,
Memory: paths.MemoryPath,
History: paths.HistoryPath,
Output: paths.OutputPath,
Private: paths.PrivateDir,
Public: paths.PublicDir,
}
}
// prepareTurn creates the visit layout and writes the model's input.md and
// memory.md before the visit starts. A failure here is a run failure: the file
// prepareTurn creates the visit layout and writes the model's input.md,
// memory.md (essential memory, capped at turn.EssentialCap) and history.md (every
// 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
@@ -59,12 +61,23 @@ func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage
return err
}
input := turnInputWithRetry(state.turnInput(), retryInput)
memory := turn.RenderMemory(state.turns)
if err := os.WriteFile(paths.InputPath, []byte(input), 0o600); err != nil {
return fmt.Errorf("write %s: %w", paths.InputPath, err)
}
if err := os.WriteFile(paths.MemoryPath, []byte(memory), 0o600); err != nil {
return fmt.Errorf("write %s: %w", paths.MemoryPath, err)
history := turn.RenderHistory(state.turns)
memory := turn.RenderEssential(turn.Essential{
Task: state.prompt,
StageKey: paths.StageKey,
Entries: state.turns,
ChangedFiles: state.capturedList(),
InputPath: paths.InputPath,
HistoryPath: paths.HistoryPath,
})
for _, file := range []struct{ path, content string }{
{paths.InputPath, input},
{paths.MemoryPath, memory},
{paths.HistoryPath, history},
} {
if err := os.WriteFile(file.path, []byte(file.content), 0o600); err != nil {
return fmt.Errorf("write %s: %w", file.path, err)
}
}
return nil
}
@@ -126,6 +139,7 @@ func (s *runState) recordTurn(step protocol.RunStep, publicFiles []string) {
s.turns = append(s.turns, turn.MemoryEntry{
Stage: step.Stage,
Visit: s.visits[step.Stage],
Outcome: step.Outcome,
Output: output,
PublicFiles: publicFiles,
})
+154 -72
View File
@@ -2,12 +2,15 @@ package server
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"git.a-wan.net/alan/pipelines/internal/filediff"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
@@ -30,6 +33,12 @@ func uiReviewerSource(withSkip bool) string {
// then returns the persisted detail, the visited keys and the number of verdict
// (model) calls the runner made.
func runUISkip(t *testing.T, source string, files map[string]string) (*protocol.RunDetail, []string, int) {
t.Helper()
return runUISkipIn(t, source, files, t.TempDir())
}
// runUISkipIn is runUISkip against a prepared workspace directory.
func runUISkipIn(t *testing.T, source string, files map[string]string, dir string) (*protocol.RunDetail, []string, int) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -50,7 +59,6 @@ func runUISkip(t *testing.T, source string, files map[string]string) (*protocol.
t.Fatal(err)
}
defer r.wg.Wait()
dir := t.TempDir()
var mu sync.Mutex
var visited []string
verdictCalls := 0
@@ -106,37 +114,28 @@ func executed(visited []string, key string) bool {
return false
}
// TestUISkipShortCircuitsWhenNoSurfaceChanged proves a non-UI change skips the
// ui_reviewer stage with no model call and routes along its declared skip edge.
func TestUISkipShortCircuitsWhenNoSurfaceChanged(t *testing.T) {
detail, visited, verdictCalls := runUISkip(t, uiReviewerSource(true), map[string]string{"implement": "internal/server/fake.go"})
if executed(visited, "ui_reviewer") {
t.Fatalf("ui_reviewer executed a model call; visited=%v", visited)
// assertModelRan fails unless ui_reviewer executed its model and routed through
// its own outcome rather than the server fallback.
func assertModelRan(t *testing.T, detail *protocol.RunDetail, visited []string, verdictCalls int) {
t.Helper()
if !executed(visited, "ui_reviewer") {
t.Fatalf("ui_reviewer was auto-skipped; visited=%v steps=%+v", visited, detail.Steps)
}
if verdictCalls != 1 {
t.Fatalf("verdict (model) calls = %d, want only implement's 1", verdictCalls)
if verdictCalls != 2 {
t.Fatalf("verdict (model) calls = %d, want 2 for both executed stages", verdictCalls)
}
if detail.Status != "succeeded" {
t.Fatalf("run status = %q, want succeeded: %+v", detail.Status, detail.RunSummary)
}
if len(detail.Steps) != 2 {
t.Fatalf("steps = %d, want 2: %+v", len(detail.Steps), detail.Steps)
}
step := detail.Steps[1]
if step.Stage != "ui_reviewer" || step.Status != "completed" || step.Outcome != "skipped" || step.Target != protocol.SuccessEnd {
t.Fatalf("skip step wrong: %+v", step)
}
if step.FileChanges != nil && len(step.FileChanges.Files) != 0 {
t.Fatalf("skip step recorded file changes: %+v", step.FileChanges)
}
reason, _ := step.Output["summary"].(string)
if !strings.Contains(reason, "internal/server/fake.go") {
t.Fatalf("skip reason does not name the checked path: %q", reason)
step := detail.Steps[len(detail.Steps)-1]
if step.Stage != "ui_reviewer" || step.Outcome != "approved" || step.Target != protocol.SuccessEnd {
t.Fatalf("executed step did not route through approved: %+v", step)
}
}
// TestUISkipZeroChangesStillSkips proves the guard also short-circuits when the
// run recorded no file changes at all, with a reason that says so.
// TestUISkipZeroChangesStillSkips proves the fallback short-circuits when every
// visit recorded a complete capture with no file changes, and that the verdict
// says it was a server fallback with no model run.
func TestUISkipZeroChangesStillSkips(t *testing.T) {
detail, visited, verdictCalls := runUISkip(t, uiReviewerSource(true), nil)
if executed(visited, "ui_reviewer") {
@@ -148,48 +147,127 @@ func TestUISkipZeroChangesStillSkips(t *testing.T) {
if detail.Status != "succeeded" || len(detail.Steps) != 2 {
t.Fatalf("run = %q steps=%d, want succeeded/2", detail.Status, len(detail.Steps))
}
if first := detail.Steps[0].FileChanges; first == nil || first.Status != "complete" {
t.Fatalf("implement capture = %+v, want complete", first)
}
step := detail.Steps[1]
if step.Outcome != "skipped" {
t.Fatalf("step outcome = %q, want skipped: %+v", step.Outcome, step)
if step.Stage != "ui_reviewer" || step.Status != "completed" || step.Outcome != "skipped" || step.Target != protocol.SuccessEnd {
t.Fatalf("skip step wrong: %+v", step)
}
if step.FileChanges != nil {
t.Fatalf("skip step recorded a capture: %+v", step.FileChanges)
}
if step.Verdict == nil || step.Verdict.ReasonSource != protocol.VerdictReasonFallback || !strings.HasPrefix(step.Verdict.Reason, serverSkipReasonPrefix) {
t.Fatalf("skip verdict does not name the server fallback: %+v", step.Verdict)
}
reason, _ := step.Output["summary"].(string)
if !strings.Contains(reason, "no recorded file changes") {
if !strings.Contains(reason, "recorded no file changes") {
t.Fatalf("zero-change reason does not state that: %q", reason)
}
if len(detail.Warnings) != 0 {
t.Fatalf("complete run carries warnings: %v", detail.Warnings)
}
}
// TestUISkipRunsStageOnSurfaceChange proves a run that touched a UI surface
// still executes the stage and routes through its normal outcome.
func TestUISkipRunsStageOnSurfaceChange(t *testing.T) {
// TestUISkipRunsModelOnAnyRecordedChange proves no path is classified as "not
// UI": a backend file, a Flutter .dart file, a Kotlin file, a Go TUI file and a
// web .tsx file all make the stage run its model. The fallback never encodes a
// repository layout.
func TestUISkipRunsModelOnAnyRecordedChange(t *testing.T) {
cases := map[string]string{
"android": "android/app/src/main/kotlin/Main.kt",
"internal tui": "internal/tui/view.go",
"presentation": "web/app.tsx",
"go backend": "internal/server/fake.go",
"flutter dart": "app/lib/features/home/home_page.dart",
"kotlin": "android/app/src/main/kotlin/Main.kt",
"go tui": "internal/tui/view.go",
"web tsx": "web/app.tsx",
"docs": "docs/readme.md",
}
for name, path := range cases {
t.Run(name, func(t *testing.T) {
detail, visited, verdictCalls := runUISkip(t, uiReviewerSource(true), map[string]string{"implement": path})
if !executed(visited, "ui_reviewer") {
t.Fatalf("ui_reviewer did not execute on %s; visited=%v", path, visited)
}
if verdictCalls != 2 {
t.Fatalf("verdict (model) calls = %d, want 2 for both executed stages", verdictCalls)
}
if detail.Status != "succeeded" {
t.Fatalf("run status = %q, want succeeded: %+v", detail.Status, detail.RunSummary)
}
step := detail.Steps[len(detail.Steps)-1]
if step.Stage != "ui_reviewer" || step.Outcome != "approved" || step.Target != protocol.SuccessEnd {
t.Fatalf("executed step did not route through approved: %+v", step)
}
assertModelRan(t, detail, visited, verdictCalls)
})
}
}
// TestUISkipPartialCaptureNeverSkips proves a visit whose capture was partial
// (here a protected .env file forces skipped>0) blocks the fallback even when
// it recorded no file changes, and that inspect carries a run-level warning.
func TestUISkipPartialCaptureNeverSkips(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, ".env"), []byte("A=1\n"), 0o600); err != nil {
t.Fatal(err)
}
detail, visited, verdictCalls := runUISkipIn(t, uiReviewerSource(true), nil, dir)
if first := detail.Steps[0].FileChanges; first == nil || first.Status != "partial" || len(first.Files) != 0 {
t.Fatalf("fixture capture = %+v, want partial with no files", first)
}
assertModelRan(t, detail, visited, verdictCalls)
if len(detail.Warnings) != 1 || !strings.Contains(detail.Warnings[0], "implement #1 (partial)") {
t.Fatalf("partial capture warning missing: %v", detail.Warnings)
}
}
// TestUISkipOverBudgetGitWorkspaceRunsModel is the run-236 regression: in a Git
// workspace whose text exceeds the snapshot budget, a stage edits one .tsx file
// sorted after the budget is exhausted. The capture must list that file
// (without a patch) and the next stage, which declares `skipped`, must run its
// model rather than be auto-routed with "no recorded file changes".
func TestUISkipOverBudgetGitWorkspaceRunsModel(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git unavailable")
}
restore := filediff.SetSnapshotBudgetForTesting(256)
defer restore()
dir := t.TempDir()
git := func(args ...string) {
t.Helper()
cmd := exec.Command("git", append([]string{"-C", dir, "-c", "user.email=t@example.invalid", "-c", "user.name=t", "-c", "commit.gpgsign=false"}, args...)...)
if data, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("%v: %v %s", args, err, data)
}
}
git("init", "-q")
target := "web/src/pages/inbox/PortfolioIntelligenceInbox.test.tsx"
if err := os.MkdirAll(filepath.Join(dir, filepath.Dir(target)), 0o700); err != nil {
t.Fatal(err)
}
for i := 0; i < 40; i++ {
if err := os.WriteFile(filepath.Join(dir, fmt.Sprintf("a-%02d.txt", i)), []byte(strings.Repeat("filler line\n", 4)), 0o600); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(filepath.Join(dir, filepath.FromSlash(target)), []byte(strings.Repeat("original test line\n", 8)), 0o600); err != nil {
t.Fatal(err)
}
git("add", ".")
git("commit", "-qm", "fixture")
detail, visited, verdictCalls := runUISkipIn(t, uiReviewerSource(true), map[string]string{"implement": target}, dir)
capture := detail.Steps[0].FileChanges
if capture == nil || len(capture.Files) != 1 || capture.Files[0].Path != target || !capture.Files[0].NoPatch {
t.Fatalf("over-budget capture did not list the edited file: %+v", capture)
}
assertModelRan(t, detail, visited, verdictCalls)
if len(detail.Warnings) == 0 {
t.Fatal("partial capture produced no run-level warning")
}
}
// TestUISkipOptOut proves auto_skip=false makes a `skipped` stage run its model
// even on complete, empty evidence.
func TestUISkipOptOut(t *testing.T) {
source := uiReviewerSource(true)
at := strings.LastIndex(source, "timeout=1h\n")
source = source[:at] + "timeout=1h\nauto_skip=false\n" + source[at+len("timeout=1h\n"):]
detail, visited, verdictCalls := runUISkip(t, source, nil)
assertModelRan(t, detail, visited, verdictCalls)
}
// TestUISkipNeedsDeclaredEdge proves the guard never invents a skip for a stage
// whose definition declares no `skipped` route: it always executes.
// whose definition declares no `skipped` route: it always executes, even on
// complete, empty evidence.
func TestUISkipNeedsDeclaredEdge(t *testing.T) {
detail, visited, verdictCalls := runUISkip(t, uiReviewerSource(false), map[string]string{"implement": "internal/server/fake.go"})
detail, visited, verdictCalls := runUISkip(t, uiReviewerSource(false), nil)
if !executed(visited, "ui_reviewer") {
t.Fatalf("ui_reviewer without a skipped edge did not execute; visited=%v", visited)
}
@@ -205,33 +283,37 @@ func TestUISkipNeedsDeclaredEdge(t *testing.T) {
}
}
func TestUISurfacePathClassification(t *testing.T) {
cases := []struct {
path string
want bool
}{
{"android/app/src/main/kotlin/Main.kt", true},
{"android/README.md", true},
{"internal/tui/view.go", true},
{"internal/tui", true},
{"web/index.html", true},
{"web/app.css", true},
{"web/app.js", true},
{"web/app.ts", true},
{"web/app.jsx", true},
{"web/app.tsx", true},
{"web/Index.HTML", true},
{"internal/server/fake.go", false},
{"androidx/foo.go", false},
{"cmd/pipelines/main.go", false},
{"docs/readme.md", false},
{"README.md", false},
// TestUISkipPersistedEvidence proves the resume/retry seed: a stored server
// fallback step neither adds nor breaks evidence, while a stored visit with no
// capture (a human decision, a crash, a historical row) or a partial one makes
// the evidence incomplete.
func TestUISkipPersistedEvidence(t *testing.T) {
complete := &protocol.StageFileChanges{Status: "complete", Files: []protocol.FileChange{}}
reason := skipReasonLine()
serverSkip := protocol.RunStep{Stage: "ui", Outcome: "skipped", Verdict: &protocol.StageVerdict{Reason: reason, ReasonSource: protocol.VerdictReasonFallback}}
s := &runState{}
s.recordPersistedStep(protocol.RunStep{Stage: "implement", FileChanges: complete})
s.recordPersistedStep(serverSkip)
if !autoSkipEligible(nil, s) {
t.Fatalf("complete evidence plus a server skip is not eligible: %+v", s)
}
for _, tc := range cases {
if got := uiSurfacePath(tc.path); got != tc.want {
t.Errorf("uiSurfacePath(%q) = %v, want %v", tc.path, got, tc.want)
legacy := serverSkip
legacy.Verdict = &protocol.StageVerdict{Reason: "no UI surface changed (no recorded file changes)", ReasonSource: protocol.VerdictReasonFallback}
for name, step := range map[string]protocol.RunStep{
"no capture": {Stage: "gate", Outcome: "approve"},
"partial": {Stage: "implement", FileChanges: &protocol.StageFileChanges{Status: "partial", Files: []protocol.FileChange{}}},
"unavailable": {Stage: "implement", FileChanges: &protocol.StageFileChanges{Status: "unavailable"}},
"legacy skip row": legacy,
} {
s := &runState{}
s.recordPersistedStep(step)
if autoSkipEligible(nil, s) {
t.Errorf("%s: incomplete evidence is eligible for the fallback", name)
}
}
if autoSkipEligible(map[string]string{"auto_skip": "false"}, &runState{}) {
t.Error("auto_skip=false did not opt out")
}
}
func TestUISurfaceArtifactClassification(t *testing.T) {
+56 -50
View File
@@ -3,36 +3,35 @@ package server
import (
"fmt"
"path"
"path/filepath"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// UI-surface classification is the single source of truth for the deterministic
// pre-check that lets a stage declaring a `skipped` route short-circuit when the
// run changed no rendered surface. The path/extension lists live only here; the
// skip guard, its reason and the resumed-run seed all read them.
// The server skip fallback lets a stage that declares a `skipped` route
// short-circuit, without a model call, only when the run's evidence proves there
// is nothing to review: every visit so far recorded a complete file-change
// capture, none of them recorded any change, and no visit captured a rendered
// (image) artifact. Anything else runs the stage's model, which may still choose
// `skipped` itself.
//
// The rule deliberately classifies no path as "not UI". A path/extension list
// encodes one repository's layout (Go TUIs, Flutter .dart, Kotlin, SwiftUI,
// templates, strings files and config can all be rendered surface), and absent
// or partial evidence must never be read as "no edits". A wrong run costs one
// model call; a wrong skip ships an unreviewed UI change.
// maxRetainedChangedPaths bounds how many recorded changed paths a runState
// retains for the skip reason. The full count is kept separately, so the reason
// stays informative without unbounded memory.
// retains as a sample. The full count is kept separately.
const maxRetainedChangedPaths = 32
// uiSurfaceDirs are the workspace prefixes whose changes are a user-facing
// surface. Matching is on a path boundary, so "androidx/" is not "android/".
var uiSurfaceDirs = []string{"android", "internal/tui"}
// serverSkipReasonPrefix starts every server fallback skip reason, so the
// verdict says plainly that no model ran, and so a resumed run recognises its
// own earlier fallback steps (which have no capture of their own).
const serverSkipReasonPrefix = "Server fallback skip (no model run):"
// presentationExtensions are the rendered presentation file types a change can
// touch without living under a surface directory.
var presentationExtensions = map[string]bool{
".html": true,
".css": true,
".js": true,
".ts": true,
".jsx": true,
".tsx": true,
}
// autoSkipConfig is the stage config that opts a stage out of the fallback.
const autoSkipConfig = "auto_skip"
// renderedArtifactExtensions are the image types a captured artifact may carry
// when its content type was not recorded or sniffed as an image.
@@ -44,22 +43,6 @@ var renderedArtifactExtensions = map[string]bool{
".webp": true,
}
// uiSurfacePath reports whether a run-relative, forward-slash workspace path
// changed a user-facing surface: a file under android/ or internal/tui/, or a
// file with a presentation extension. It is O(len(path)) with no I/O.
func uiSurfacePath(p string) bool {
clean := strings.TrimPrefix(path.Clean(filepath.ToSlash(p)), "/")
if clean == "" || clean == "." {
return false
}
for _, dir := range uiSurfaceDirs {
if clean == dir || strings.HasPrefix(clean, dir+"/") {
return true
}
}
return presentationExtensions[strings.ToLower(path.Ext(clean))]
}
// uiSurfaceArtifact reports whether a captured artifact is a rendered surface:
// an image content type, or an image file extension when no type was recorded.
func uiSurfaceArtifact(a protocol.StageArtifact) bool {
@@ -69,19 +52,20 @@ func uiSurfaceArtifact(a protocol.StageArtifact) bool {
return renderedArtifactExtensions[strings.ToLower(path.Ext(a.Name))]
}
// recordChanges folds one completed step's observed changes into the run's
// UI-surface decision. It retains a bounded sample of paths; the count is
// unbounded so the reason can state the true total. It is O(changes) with no I/O.
// recordChanges folds one executed visit's observed changes into the run's
// skip evidence. A nil, partial or unavailable capture marks the run's
// evidence incomplete for the rest of the run. It retains a bounded sample of
// paths; the count is unbounded. It is O(changes) with no I/O.
func (s *runState) recordChanges(changes *protocol.StageFileChanges, artifacts []protocol.StageArtifact) {
if changes == nil || changes.Status != "complete" {
s.captureIncomplete++
}
if changes != nil {
for _, file := range changes.Files {
s.changedCount++
if len(s.changedPaths) < maxRetainedChangedPaths {
s.changedPaths = append(s.changedPaths, file.Path)
}
if !s.uiSurface && uiSurfacePath(file.Path) {
s.uiSurface = true
}
// The full captured set is a separate, unbounded dedupe of the actual
// evidence, unlike the bounded changedPaths sample above.
if file.Path == "" || s.capturedSeen[file.Path] {
@@ -101,16 +85,38 @@ func (s *runState) recordChanges(changes *protocol.StageFileChanges, artifacts [
}
}
// skipReasonLine states, as one bounded line, why the guard skipped a stage: no
// recorded change touched a UI surface. It names the retained checked paths.
func skipReasonLine(state *runState) string {
if state.changedCount == 0 {
return "no UI surface changed (no recorded file changes)"
// recordPersistedStep seeds the skip evidence from a stored step when a run is
// resumed or retried. A server fallback skip executed nothing and carries no
// capture, so it neither adds evidence nor makes it incomplete; every other
// stored visit (including a human decision, during which the workspace was not
// observed) is folded in like a live visit.
func (s *runState) recordPersistedStep(step protocol.RunStep) {
if serverSkipStep(step) {
return
}
line := fmt.Sprintf("no UI surface changed in %d recorded file change(s): %s", state.changedCount, strings.Join(state.changedPaths, ", "))
if extra := state.changedCount - len(state.changedPaths); extra > 0 {
line = fmt.Sprintf("%s (+%d more)", line, extra)
s.recordChanges(step.FileChanges, step.Artifacts)
}
// serverSkipStep reports whether a stored step is a server fallback skip.
func serverSkipStep(step protocol.RunStep) bool {
return step.Outcome == "skipped" && step.FileChanges == nil && step.Verdict != nil &&
step.Verdict.ReasonSource == protocol.VerdictReasonFallback &&
strings.HasPrefix(step.Verdict.Reason, serverSkipReasonPrefix)
}
// autoSkipEligible reports whether the server may skip a stage declaring a
// `skipped` route: the stage has not opted out, every visit so far recorded a
// complete capture, no change was recorded and no rendered artifact captured.
func autoSkipEligible(configs map[string]string, state *runState) bool {
if configs[autoSkipConfig] == "false" {
return false
}
return state.captureIncomplete == 0 && state.changedCount == 0 && !state.uiSurface
}
// skipReasonLine states, as one bounded line, why the server skipped a stage.
func skipReasonLine() string {
line := fmt.Sprintf("%s every earlier visit's file-change capture was complete and recorded no file changes or screenshots.", serverSkipReasonPrefix)
runes := []rune(line)
if len(runes) > protocol.VerdictReasonCap {
return string(runes[:protocol.VerdictReasonCap])
+4 -2
View File
@@ -31,11 +31,13 @@ func TestStageUsageCarriesHonestUnknowns(t *testing.T) {
}{
{"no usage stays absent", stage.BudgetSnapshot{}, nil},
{"split and cost", stage.BudgetSnapshot{UsedTokens: 7, TokensKnown: true, SplitKnown: true, TokensInput: 3, TokensOutput: 4, UsedUSD: .5, USDKnown: true},
&protocol.StageUsage{TokensIn: 3, TokensOut: 4, TokensTotal: 7, TokensKnown: true, SplitKnown: true, CostUSD: .5, CostKnown: true}},
&protocol.StageUsage{TokensIn: 3, TokensOut: 4, TokensTotal: 7, TokensKnown: true, SplitKnown: true, CostUSD: .5, CostKnown: true, CacheKnown: true}},
{"cache and reasoning components carry through", stage.BudgetSnapshot{UsedTokens: 22_400_000, TokensKnown: true, SplitKnown: true, TokensInput: 900_000, TokensOutput: 150_000, TokensReasoning: 50_000, CacheRead: 21_250_000, CacheWrite: 50_000},
&protocol.StageUsage{TokensIn: 900_000, TokensOut: 150_000, TokensTotal: 22_400_000, TokensKnown: true, SplitKnown: true, TokensReasoning: 50_000, CacheRead: 21_250_000, CacheWrite: 50_000, CacheKnown: true}},
{"total only (Pi)", stage.BudgetSnapshot{UsedTokens: 17, TokensKnown: true},
&protocol.StageUsage{TokensTotal: 17, TokensKnown: true}},
{"no cost", stage.BudgetSnapshot{UsedTokens: 5, TokensKnown: true, SplitKnown: true, TokensInput: 5},
&protocol.StageUsage{TokensIn: 5, TokensTotal: 5, TokensKnown: true, SplitKnown: true}},
&protocol.StageUsage{TokensIn: 5, TokensTotal: 5, TokensKnown: true, SplitKnown: true, CacheKnown: true}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
+32
View File
@@ -0,0 +1,32 @@
package server
import (
"context"
"encoding/json"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// readTestFrame reads the next websocket frame into v like wsjson.Read, but
// skips chat_activity pushes. Those reach every connection whenever any
// chat's turn or background-task count changes, so tests that read one
// connection's replies in order would otherwise see them interleaved. Tests of
// chat_activity itself read the raw stream.
func readTestFrame(ctx context.Context, conn *websocket.Conn, v any) error {
for {
var raw json.RawMessage
if err := wsjson.Read(ctx, conn, &raw); err != nil {
return err
}
var head struct {
Type string `json:"type"`
}
if json.Unmarshal(raw, &head) == nil && head.Type == protocol.ChatActivityChanged {
continue
}
return json.Unmarshal(raw, v)
}
}
+2 -2
View File
@@ -209,7 +209,7 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
// artifactsPrompt tells an agent stage where it may write the files it
// produces. The turn directory itself belongs to the server: input.md,
// memory.md and output.md are written by the runner and output.md comes from
// memory.md, history.md and output.md are written by the runner and output.md comes from
// the model's final message. The only writable artifact scopes are this
// visit's private/ directory and the run's shared public/ directory, matching
// the exact paths permissionRules grants. It is empty when the runtime provided
@@ -231,7 +231,7 @@ func artifactsPrompt(directory string, access ArtifactAccess) string {
fmt.Fprintf(&b, " Save artifacts for later stages under %s; files there are shared by the run.", access.WriteShared)
}
if writable {
b.WriteString(" Do not write input.md, memory.md or output.md yourself; the server owns those and writes output.md from your final message.")
b.WriteString(" Do not write input.md, memory.md, history.md or output.md yourself; the server owns those and writes output.md from your final message.")
} else {
b.WriteString(" The server records the turn files as artifacts.")
}
+1 -1
View File
@@ -36,7 +36,7 @@ func TestArtifactsPromptStatesWritableScopes(t *testing.T) {
"/data/artifacts/1/2",
"/data/artifacts/1/2/private",
"/data/artifacts/1/public",
"do not write input.md, memory.md or output.md",
"do not write input.md, memory.md, history.md or output.md",
} {
if !strings.Contains(strings.ToLower(prompt), strings.ToLower(want)) {
t.Fatalf("prompt missing %q: %q", want, prompt)
+12
View File
@@ -0,0 +1,12 @@
package stage
import "testing"
func TestAutoSkipConfig(t *testing.T) {
for value, ok := range map[string]bool{"": true, "true": true, "false": true, "no": false, "FALSE": false, "0": false} {
def := Definition{Type: ModelType, Blocks: map[string]string{"prompt": "task", "configs": "config"}, Configs: map[string]string{"provider": "fixture", "model": "model", "auto_skip": value}}
if _, err := (ModelStage{}).Spec(def); (err == nil) != ok {
t.Errorf("auto_skip=%q: err=%v, want ok=%v", value, err, ok)
}
}
}
+6 -1
View File
@@ -79,7 +79,7 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
}
for key := range def.Configs {
switch key {
case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery":
case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery", "auto_skip":
default:
return ModelSpec{}, fmt.Errorf("unknown config %q", key)
}
@@ -101,6 +101,11 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
if delivery := def.Configs["delivery"]; delivery != "" && delivery != "true" {
return ModelSpec{}, fmt.Errorf("delivery must be true when set")
}
// auto_skip=false opts a stage with a `skipped` edge out of the server skip
// fallback (the runner reads it); true is the default and may be explicit.
if value := def.Configs["auto_skip"]; value != "" && value != "true" && value != "false" {
return ModelSpec{}, fmt.Errorf("auto_skip must be true or false")
}
if def.Configs["delivery"] == "true" && backend != "opencode" {
return ModelSpec{}, fmt.Errorf("delivery is supported only by the opencode harness")
}
+63 -29
View File
@@ -8,6 +8,7 @@ import (
"sort"
"strings"
"time"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/turn"
)
@@ -57,52 +58,54 @@ func modelPrompt(def Definition, spec ModelSpec, input Values) (string, error) {
toolsLine = "This call has these stage tools: " + strings.Join(tools, ", ") + "."
}
// Essential memory (memory.md) is short and capped, so it is inlined for
// every stage: the stage needs no read call to start, and each model call
// re-sends only this bounded context. The full history (history.md) is
// never inlined; a stage with the read tool is pointed at it and at input.md
// for on-demand detail.
memory, readErr := os.ReadFile(def.Turn.Memory)
if readErr != nil {
return "", fmt.Errorf("model stage %s: read turn memory: %w", def.Key, readErr)
}
var b strings.Builder
// Receiving runtime context must not require adding filesystem tools to a
// web-only (or otherwise restricted) stage. Inline it whenever read is not
// declared, without widening the harness's permissions or changing a workflow.
if !slices.Contains(tools, "read") {
memory, readErr := os.ReadFile(def.Turn.Memory)
if readErr != nil {
return "", fmt.Errorf("model stage %s: read turn memory: %w", def.Key, readErr)
canRead := slices.Contains(tools, "read")
switch {
case !canRead && len(tools) == 0:
b.WriteString("This call has no tools, so the server included the turn files below.\n\n")
case !canRead:
b.WriteString("The read tool is not enabled, so the server included the turn files below. Use this supplied context; no extra filesystem access is needed.\n\n")
}
writeTurnFile(&b, "memory.md", def.Turn.Memory, capInline(string(memory), turn.EssentialCap, def.Turn.Memory))
if canRead {
b.WriteString("Rely on this essential memory first. Read on demand only, when you need more detail:\n")
fmt.Fprintf(&b, "- Input (full run task and previous stage output): %s\n", def.Turn.Input)
if def.Turn.History != "" {
fmt.Fprintf(&b, "- History (every earlier turn in full; large): %s\n", def.Turn.History)
}
b.WriteString("\n")
} else {
input, readErr := os.ReadFile(def.Turn.Input)
if readErr != nil {
return "", fmt.Errorf("model stage %s: read turn input: %w", def.Key, readErr)
}
if len(tools) == 0 {
b.WriteString("This call has no tools, so the server included the turn files below.\n\n")
} else {
b.WriteString("The read tool is not enabled, so the server included the turn files below. Use this supplied context; no extra filesystem access is needed.\n\n")
}
fmt.Fprintf(&b, "# memory.md (%s)\n\n%s", def.Turn.Memory, string(memory))
if len(memory) > 0 && !strings.HasSuffix(string(memory), "\n") {
b.WriteString("\n")
}
b.WriteString("\n")
fmt.Fprintf(&b, "# input.md (%s)\n\n%s", def.Turn.Input, string(input))
if len(input) > 0 && !strings.HasSuffix(string(input), "\n") {
b.WriteString("\n")
}
b.WriteString("\n")
} else {
b.WriteString("Read these two files before working:\n")
fmt.Fprintf(&b, "- Memory: %s\n", def.Turn.Memory)
fmt.Fprintf(&b, "- Input: %s\n\n", def.Turn.Input)
b.WriteString("Memory is the accumulated markdown of the run's completed turns, including the files each turn added to public/. Input is the run prompt on the first visit and the previous visit's output afterwards. Read both files before acting.\n\n")
writeTurnFile(&b, "input.md", def.Turn.Input, capInline(string(input), InlineInputCap, def.Turn.Input))
}
b.WriteString("Stage instructions:\n\n")
b.WriteString(strings.TrimSpace(spec.Prompt))
if changed := serverChangedFiles(input); len(changed) > 0 {
b.WriteString("\n\nServer-captured changed files for this run (verified from the workspace, not a model claim):\n")
for _, name := range changed {
for i, name := range changed {
if i == maxPromptChangedFiles {
fmt.Fprintf(&b, "- ... and %d more\n", len(changed)-i)
break
}
fmt.Fprintf(&b, "- %s\n", name)
}
b.WriteString("\nUse this list to distinguish this run's work from pre-existing dirty files.")
}
b.WriteString("\n\nProduce ")
b.WriteString(def.Turn.Output)
b.WriteString(" as markdown; return its complete content as your final message (the server writes that file). The only required section is the outcome, for example:\n\n# outcome\n")
b.WriteString(" as markdown; return its complete content as your final message (the server writes that file). Start it with a short # handoff section (at most about 1 KB): what you did, files changed, and open issues or findings the next stage must act on. The next stage receives only that section as essential memory; the rest of your output stays in history. The only required section is the outcome, for example:\n\n# handoff\n...\n\n# outcome\n")
b.WriteString(preferredOutcome(outcomes))
fmt.Fprintf(&b, "\n\nAllowed outcomes: %s.\n\nEverything else is free-form markdown for the next stage and the operator. The server does not parse or validate any other section. Return the complete output.md content as your final message; do not wrap it in a JSON envelope.\n", strings.Join(outcomes, ", "))
fmt.Fprintf(&b, "\nExecution time: %s. Timezone: %s.\n", time.Now().Format(time.RFC3339), time.Local.String())
@@ -118,6 +121,37 @@ func modelPrompt(def Definition, spec ModelSpec, input Values) (string, error) {
// serverChangedFiles reads the runner's reserved changed-path list from stage
// input, accepting the []string the runner supplies and the []any JSON decoding
// produces for a replayed handoff. Other values are ignored.
// InlineInputCap bounds input.md when it is inlined for a stage without the
// read tool. Such a stage cannot read on demand, so the cap is generous; it only
// stops one pathological previous output from dominating every call.
const InlineInputCap = 32 << 10
// maxPromptChangedFiles bounds the bound server_changed_files list in the
// prompt; the complete list stays in the stage input.
const maxPromptChangedFiles = 50
// writeTurnFile embeds one server-written turn file under a heading naming it.
func writeTurnFile(b *strings.Builder, name, path, content string) {
fmt.Fprintf(b, "# %s (%s)\n\n%s", name, path, content)
if content != "" && !strings.HasSuffix(content, "\n") {
b.WriteString("\n")
}
b.WriteString("\n")
}
// capInline keeps the head of content within limit bytes (at a rune boundary)
// and names the file holding the rest.
func capInline(content string, limit int, path string) string {
if len(content) <= limit {
return content
}
cut := limit
for cut > 0 && !utf8.RuneStart(content[cut]) {
cut--
}
return content[:cut] + fmt.Sprintf("\n\n_[truncated: %d of %d bytes shown; full file at %s]_\n", cut, len(content), path)
}
func serverChangedFiles(input Values) []string {
raw, ok := input["server_changed_files"]
if !ok {
@@ -0,0 +1,60 @@
package stage
import (
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/turn"
)
// TestModelPromptInlinesEssentialMemoryAndPointsAtHistory: every stage gets the
// capped essential memory inline; the full history is never inlined, and a
// stage with read is pointed at input.md and history.md for on-demand detail.
func TestModelPromptInlinesEssentialMemoryAndPointsAtHistory(t *testing.T) {
for _, toolset := range []string{"read\nedit", "websearch", ""} {
t.Run(strings.ReplaceAll(toolset, "\n", "-"), func(t *testing.T) {
def := turnDefinition(t)
def.Blocks["tools"] = toolset
def.Turn.History = filepath.Join(def.Turn.Dir, "history.md")
files := map[string]string{
def.Turn.Memory: "# Essential memory\n\nreviewer finding: lock leak\n" + strings.Repeat("m", 2*turn.EssentialCap),
def.Turn.Input: "full previous output\n",
def.Turn.History: "FULL HISTORY BODY\n",
}
for path, content := range files {
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
}
spec, err := (ModelStage{}).Spec(def)
if err != nil {
t.Fatal(err)
}
prompt, err := modelPrompt(def, spec, nil)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(prompt, "reviewer finding: lock leak") || !strings.Contains(prompt, "_[truncated: ") {
t.Fatalf("essential memory not inlined with its cap: %q", prompt)
}
if strings.Contains(prompt, strings.Repeat("m", turn.EssentialCap+1)) {
t.Fatal("inlined memory exceeded its cap")
}
if strings.Contains(prompt, "FULL HISTORY BODY") {
t.Fatal("history.md was inlined")
}
if !strings.Contains(prompt, "# handoff") {
t.Fatal("prompt does not ask for a handoff section")
}
canRead := strings.Contains(toolset, "read")
if got := strings.Contains(prompt, def.Turn.History); got != canRead {
t.Fatalf("history path named = %v, want %v: %q", got, canRead, prompt)
}
if got := strings.Contains(prompt, "full previous output"); got == canRead {
t.Fatalf("input.md inlined = %v with read = %v", got, canRead)
}
})
}
}
+1 -1
View File
@@ -237,7 +237,7 @@ func TestAgentGeneratePromptCarriesToolsEditScopeAndShellCommands(t *testing.T)
def.Turn.Output,
def.Turn.Private,
def.Turn.Public,
"Do not write input.md, memory.md or output.md",
"Do not write input.md, memory.md, history.md or output.md",
} {
if !strings.Contains(promptBody, want) {
t.Fatalf("agent prompt missing %q: %s", want, promptBody)
+5 -2
View File
@@ -10,14 +10,17 @@ import (
// Values are runtime data, not the prose output contract in a definition.
type Values map[string]any
// TurnPaths is the runtime-provided file layout for one model visit. Input and
// memory are read by the model; Output is written by the server from the model's
// TurnPaths is the runtime-provided file layout for one model visit. Memory is
// the short essential memory the prompt inlines; Input and History are the full
// previous output and run history, read only on demand (History is empty for
// callers that predate it). Output is written by the server from the model's
// returned markdown. Private belongs to this visit; Public is shared by every
// stage in the run.
type TurnPaths struct {
Dir string
Input string
Memory string
History string
Output string
Private string
Public string
+1 -1
View File
@@ -11,7 +11,7 @@ import (
)
func TestShowcaseGraphsRender(t *testing.T) {
for _, name := range []string{"task", "review", "research", "three-stage"} {
for _, name := range []string{"one-stage", "two-stages", "feedback-loop", "human-decision"} {
t.Run(name, func(t *testing.T) {
source, err := os.ReadFile(filepath.Join("..", "..", "examples", name+".md"))
if err != nil {
+1 -1
View File
@@ -38,7 +38,7 @@ func TestTemplateSubmitNamesRetainsAndExplicitlyPublishesSelectedTemplate(t *tes
m.templateOpen, m.keys.templates = true, true
m.defaultModel = "fixture/model"
for i, item := range m.templates {
if item.Key == "review" {
if item.Key == "one-stage" {
m.templateIndex = i
}
}
+3 -3
View File
@@ -21,7 +21,7 @@ func TestUIUXReviewSnapshots(t *testing.T) {
if err := os.MkdirAll(directory, 0700); err != nil {
t.Fatal(err)
}
source, err := os.ReadFile("../../examples/three-stage.md")
source, err := os.ReadFile("../../examples/human-decision.md")
if err != nil {
t.Fatal(err)
}
@@ -36,7 +36,7 @@ func TestUIUXReviewSnapshots(t *testing.T) {
m.loaded = true
m.status = "127.0.0.1:8080"
m.notificationEndpoints = []protocol.NotificationEndpoint{{Destination: "system", ServerURL: "http://100.85.25.33:8090", Topic: "pipelines"}}
m.pipelines = []protocol.PipelineSummary{{ID: 8, Name: "Plan, implement, review", Version: 1, Stages: 3, CreatedAt: "2026-10-08T20:00:00Z", UpdatedAt: "2026-10-08T20:00:00Z"}}
m.pipelines = []protocol.PipelineSummary{{ID: 8, Name: "Example 4: human decision", Version: 1, Stages: 3, CreatedAt: "2026-10-08T20:00:00Z", UpdatedAt: "2026-10-08T20:00:00Z"}}
save := func(name string) {
t.Helper()
view := ansi.Strip(m.View())
@@ -66,7 +66,7 @@ func TestUIUXReviewSnapshots(t *testing.T) {
save("review-stage")
m.runOpen = true
m.keys.runs = true
m.runDetail = &protocol.RunDetail{RunSummary: protocol.RunSummary{ID: 1, Name: "Plan, implement, review", PipelineID: 8, Version: 1, Status: "succeeded", CreatedAt: "2026-10-08T20:00:00Z", FinishedAt: "2026-10-08T20:01:00Z"}, Graph: graph, Steps: []protocol.RunStep{{Sequence: 1, Stage: "planner", Status: "completed", Outcome: "success", Target: "implementer"}, {Sequence: 2, Stage: "implementer", Status: "completed", Outcome: "success", Target: "reviewer"}, {Sequence: 3, Stage: "reviewer", Status: "completed", Outcome: "success", Target: protocol.SuccessEnd, Output: map[string]any{"summary": "Fixture review report", "findings": "Fixture findings"}}}}
m.runDetail = &protocol.RunDetail{RunSummary: protocol.RunSummary{ID: 1, Name: "Example 4: human decision", PipelineID: 8, Version: 1, Status: "succeeded", CreatedAt: "2026-10-08T20:00:00Z", FinishedAt: "2026-10-08T20:01:00Z"}, Graph: graph, Steps: []protocol.RunStep{{Sequence: 1, Stage: "plan", Status: "completed", Outcome: "success", Target: "decide"}, {Sequence: 2, Stage: "decide", Status: "completed", Outcome: "approve", Target: "act"}, {Sequence: 3, Stage: "act", Status: "completed", Outcome: "success", Target: protocol.SuccessEnd, Output: map[string]any{"summary": "Fixture review report", "findings": "Fixture findings"}}}}
m.runStepIndex = 3
save("run")
}
+325
View File
@@ -0,0 +1,325 @@
package turn
import (
"fmt"
"strings"
"unicode/utf8"
)
// EssentialCap is the hard byte cap on a visit's memory.md (essential memory).
// It is small on purpose: the file is inlined into every model call of the
// visit, so its size is paid once per call. Everything else stays on disk in
// history.md and input.md, read only on demand.
const EssentialCap = 4096
const (
essentialLedgerLines = 10
essentialFileLines = 8
essentialLineCap = 100
// 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
)
// Essential is everything RenderEssential needs for one visit's memory.md.
type Essential struct {
// Task is the run prompt.
Task string
// StageKey is the stage about to run; it marks a revisit.
StageKey string
// Entries are the completed turns in order (the same slice history.md is
// rendered from).
Entries []MemoryEntry
// ChangedFiles is the run's server-captured changed-path list.
ChangedFiles []string
// InputPath and HistoryPath are named as the on-demand detail.
InputPath string
HistoryPath string
}
// RenderEssential renders a visit's essential memory: the task, the previous
// stage's handoff, a one-line-per-stage outcome ledger and the changed files.
// The result never exceeds EssentialCap bytes. The previous stage's handoff is
// its "# handoff" section when it wrote one, otherwise the head of its output;
// either is truncated with a pointer to the full text, so the file stays useful
// whether or not a model followed the handoff convention.
func RenderEssential(e Essential) string {
var fixed strings.Builder
fixed.WriteString("# Essential memory\n\n")
fixed.WriteString("Short handoff for this visit; enough for most work.")
if e.InputPath != "" || e.HistoryPath != "" {
fixed.WriteString(" Read on demand only:")
if e.InputPath != "" {
fmt.Fprintf(&fixed, " %s (full task and previous stage output)", e.InputPath)
}
if e.HistoryPath != "" {
if e.InputPath != "" {
fixed.WriteString(";")
}
fmt.Fprintf(&fixed, " %s (every earlier turn in full)", e.HistoryPath)
}
fixed.WriteString(".")
}
fixed.WriteString("\n")
var tail strings.Builder
if ledger := renderLedger(e.Entries, e.StageKey); ledger != "" {
tail.WriteString("\n## Stage ledger\n\n")
tail.WriteString(ledger)
}
if files := renderFiles(e.ChangedFiles); files != "" {
tail.WriteString("\n## Changed files (server-captured)\n\n")
tail.WriteString(files)
}
taskHeading := "\n## Task\n\n"
task := strings.TrimSpace(demoteHeadings(strings.TrimSpace(e.Task)))
if task == "" {
task = "_(no task text)_"
}
var handoffHeading, handoff string
if n := len(e.Entries); n > 0 {
previous := e.Entries[n-1]
title := capLine(fmt.Sprintf("%s · visit %d%s", oneLine(previous.Stage), previous.Visit, outcomeSuffix(previous.Outcome)), 2*essentialLineCap)
handoffHeading = "\n## Previous stage: " + title + "\n\n"
var source string
handoff, source = previousHandoff(previous.Output)
handoffHeading += source
if public := sortedUnique(previous.PublicFiles); len(public) > 0 {
handoff += "\n\nAdded to public/: " + capLine(strings.Join(public, ", "), 2*essentialLineCap)
}
}
// Budget what is left after the fixed parts between the task and the
// handoff. Unused room on either side flows to the other.
reserve := 2 * len(truncationNote(EssentialCap, EssentialCap, "input.md"))
budget := EssentialCap - fixed.Len() - tail.Len() - len(taskHeading) - len(handoffHeading) - 2 - reserve
if budget < 0 {
budget = 0
}
handoffBudget, taskBudget := 0, budget
if handoffHeading != "" {
half := budget / 2
if half < essentialHandoffMin {
half = min(essentialHandoffMin, budget)
}
switch {
case len(task) <= budget-half:
handoffBudget = budget - len(task)
case len(handoff) <= half:
handoffBudget = len(handoff)
default:
handoffBudget = half
}
taskBudget = budget - min(handoffBudget, len(handoff))
}
var b strings.Builder
b.WriteString(fixed.String())
b.WriteString(taskHeading)
b.WriteString(truncateWithNote(task, taskBudget, "input.md"))
b.WriteString("\n")
if handoffHeading != "" {
b.WriteString(handoffHeading)
b.WriteString(truncateWithNote(handoff, handoffBudget, "input.md"))
b.WriteString("\n")
} else {
b.WriteString("\nThis is the first stage of the run; there is no earlier turn.\n")
}
b.WriteString(tail.String())
out := b.String()
if len(out) > EssentialCap {
// Pathological input (very long stage keys or paths); never exceed the
// cap even if the section budgets could not absorb it.
out = truncateWithNote(out, EssentialCap-len(truncationNote(len(out), len(out), "history.md")), "history.md") + "\n"
if len(out) > EssentialCap {
out = cutAtRune(out, EssentialCap)
}
}
return out
}
// HandoffSection returns the body of the first "handoff" heading (any ATX
// level, outside fenced code) up to the next heading of the same or a higher
// level, trimmed. ok is false when there is no such heading or it is empty.
func HandoffSection(markdown string) (string, bool) {
lines := markdownLines(markdown)
var fence fenceState
start, level := -1, 0
end := len(markdown)
for i, line := range lines {
if fence.open() {
if fence.closes(line.text) {
fence = fenceState{}
}
continue
}
if marker, ok := openingFence(line.text); ok {
fence = marker
continue
}
lvl, text, isHeading := atxHeading(line.text)
if !isHeading {
continue
}
if start < 0 {
if strings.EqualFold(text, "handoff") {
start, level = line.next, lvl
}
continue
}
if lvl <= level {
end = lines[i-1].next
break
}
}
if start < 0 {
return "", false
}
section := strings.TrimSpace(markdown[start:end])
return section, section != ""
}
func previousHandoff(output string) (string, string) {
if section, ok := HandoffSection(output); ok {
return strings.TrimSpace(demoteHeadings(section)), ""
}
body := strings.TrimSpace(demoteHeadings(output))
if body == "" {
return "_(no output)_", ""
}
return body, "_(no `# handoff` section; showing the start of its output)_\n\n"
}
func renderLedger(entries []MemoryEntry, current string) string {
if len(entries) == 0 {
return ""
}
type latest struct {
entry MemoryEntry
order int
}
byStage := map[string]*latest{}
order := []string{}
for i, entry := range entries {
if item, ok := byStage[entry.Stage]; ok {
item.entry, item.order = entry, i
continue
}
byStage[entry.Stage] = &latest{entry: entry, order: i}
order = append(order, entry.Stage)
}
var b strings.Builder
skipped := 0
if len(order) > essentialLedgerLines {
skipped = len(order) - essentialLedgerLines
order = order[skipped:]
}
if skipped > 0 {
fmt.Fprintf(&b, "- … %d earlier stages in history.md\n", skipped)
}
for _, key := range order {
item := byStage[key]
line := fmt.Sprintf("%s · visit %d%s", oneLine(key), item.entry.Visit, outcomeSuffix(item.entry.Outcome))
if key == current {
line += " (this stage's previous visit; detail in history.md)"
}
b.WriteString("- ")
b.WriteString(capLine(line, essentialLineCap))
b.WriteString("\n")
}
fmt.Fprintf(&b, "\n%d turns completed.\n", len(entries))
return b.String()
}
func renderFiles(files []string) string {
files = sortedUnique(files)
if len(files) == 0 {
return ""
}
var b strings.Builder
shown := files
if len(shown) > essentialFileLines {
shown = shown[:essentialFileLines]
}
for _, name := range shown {
b.WriteString("- ")
b.WriteString(capLine(oneLine(name), essentialLineCap))
b.WriteString("\n")
}
if more := len(files) - len(shown); more > 0 {
fmt.Fprintf(&b, "- … and %d more\n", more)
}
return b.String()
}
func outcomeSuffix(outcome string) string {
if outcome == "" {
return ""
}
return " · outcome " + oneLine(outcome)
}
func atxHeading(text string) (int, string, bool) {
trimmed := strings.TrimLeft(text, " ")
if len(text)-len(trimmed) > 3 {
return 0, "", false
}
level := 0
for level < len(trimmed) && trimmed[level] == '#' {
level++
}
if level < 1 || level > 6 {
return 0, "", false
}
rest := trimmed[level:]
if rest != "" && rest[0] != ' ' && rest[0] != '\t' {
return 0, "", false
}
return level, strings.TrimSpace(strings.TrimRight(strings.TrimSpace(rest), "#")), true
}
func oneLine(text string) string {
return strings.Join(strings.Fields(text), " ")
}
func capLine(text string, limit int) string {
if len(text) <= limit {
return text
}
return cutAtRune(text, limit-len("…")) + "…"
}
func truncationNote(shown, total int, where string) string {
return fmt.Sprintf("\n\n_[truncated: %d of %d bytes shown; full text in %s]_", shown, total, where)
}
// truncateWithNote returns text unchanged when it fits limit, otherwise its
// head cut at a line (or rune) boundary followed by a pointer to the full text.
func truncateWithNote(text string, limit int, where string) string {
if len(text) <= limit {
return text
}
if limit < 0 {
limit = 0
}
head := cutAtRune(text, limit)
if i := strings.LastIndexByte(head, '\n'); i > limit/2 {
head = head[:i]
}
head = strings.TrimRight(head, " \t\n")
return head + truncationNote(len(head), len(text), where)
}
func cutAtRune(text string, limit int) string {
if limit <= 0 {
return ""
}
if len(text) <= limit {
return text
}
for limit > 0 && !utf8.RuneStart(text[limit]) {
limit--
}
return text[:limit]
}
+167
View File
@@ -0,0 +1,167 @@
package turn
import (
"fmt"
"strings"
"testing"
)
func paragraph(label string, bytes int) string {
line := label + ": detail about the change, the reasoning, the commands run and their output.\n"
return strings.Repeat(line, bytes/len(line)+1)
}
// feedbackLoopEntries is a 4-stage run with a revisit: plan, code, review sends
// the work back, and code is about to run its second visit.
func feedbackLoopEntries() []MemoryEntry {
return []MemoryEntry{
{Stage: "plan", Visit: 1, Outcome: "success", Output: "# handoff\n\nPlan: add the cache layer in two steps.\n\n# plan\n\n" + paragraph("plan", 5000)},
{Stage: "code", Visit: 1, Outcome: "success", Output: "# handoff\n\nImplemented cache.go; tests pass.\n\n# log\n\n" + paragraph("code", 9000), PublicFiles: []string{"public/coverage.html"}},
{Stage: "review", Visit: 1, Outcome: "changes_requested", Output: "# summary\n\nLong preamble.\n\n" + paragraph("review", 7000) + "\n# Handoff\n\n## Findings\n\n1. cache.go:42 leaks the lock on the error path.\n2. Missing test for eviction.\n\n# appendix\n\n" + paragraph("appendix", 3000)},
}
}
func TestEssentialMemoryRevisitShowsReviewerFindingsWithinCap(t *testing.T) {
entries := feedbackLoopEntries()
changed := []string{}
for i := range 20 {
changed = append(changed, fmt.Sprintf("internal/cache/file%02d.go", i))
}
memory := RenderEssential(Essential{
Task: "# Goal\n\nAdd a cache to the lookup service.",
StageKey: "code",
Entries: entries,
ChangedFiles: changed,
InputPath: "/run/stages/04-code/input.md",
HistoryPath: "/run/stages/04-code/history.md",
})
if len(memory) > EssentialCap {
t.Fatalf("essential memory is %d bytes, over the %d cap:\n%s", len(memory), EssentialCap, memory)
}
for _, want := range []string{
"### Goal",
"Add a cache to the lookup service.",
"## Previous stage: review · visit 1 · outcome changes_requested",
"cache.go:42 leaks the lock on the error path.",
"Missing test for eviction.",
"- plan · visit 1 · outcome success",
"- code · visit 1 · outcome success (this stage's previous visit; detail in history.md)",
"- review · visit 1 · outcome changes_requested",
"3 turns completed.",
"- internal/cache/file00.go",
"- … and 12 more",
"/run/stages/04-code/history.md",
"/run/stages/04-code/input.md",
} {
if !strings.Contains(memory, want) {
t.Fatalf("essential memory missing %q:\n%s", want, memory)
}
}
// The findings come before the ledger: they are the first thing a
// re-entered stage reads after the task.
if strings.Index(memory, "leaks the lock") > strings.Index(memory, "## Stage ledger") {
t.Fatalf("reviewer findings are not prominent:\n%s", memory)
}
for _, unwanted := range []string{"Long preamble.", "appendix:", "code: detail", "plan: detail"} {
if strings.Contains(memory, unwanted) {
t.Fatalf("essential memory carried non-handoff text %q:\n%s", unwanted, memory)
}
}
// The full, previous behaviour stays reachable through history.md.
history := RenderHistory(entries)
for _, want := range []string{"## plan · visit 1", "## code · visit 1", "## review · visit 1", "Long preamble.", "appendix: detail", "public/coverage.html"} {
if !strings.Contains(history, want) {
t.Fatalf("history missing %q", want)
}
}
if len(history) < 5*len(memory) {
t.Fatalf("history (%d) is not much larger than essential memory (%d)", len(history), len(memory))
}
}
func TestEssentialMemoryFallsBackToTruncatedOutputWithPointer(t *testing.T) {
entries := []MemoryEntry{{Stage: "code", Visit: 1, Outcome: "success", Output: "Started with the parser.\n" + paragraph("work", 20000)}}
memory := RenderEssential(Essential{Task: "Fix the parser.", 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{"Fix the parser.", "no `# handoff` section", "Started with the parser.", "_[truncated:", "full text in input.md]_"} {
if !strings.Contains(memory, want) {
t.Fatalf("fallback memory missing %q:\n%s", want, memory)
}
}
}
func TestEssentialMemoryCapsEveryPart(t *testing.T) {
long := strings.Repeat("x", 300)
entries := []MemoryEntry{}
for i := range 30 {
entries = append(entries, MemoryEntry{Stage: fmt.Sprintf("stage-%02d-%s", i, long), Visit: 1, Outcome: long, Output: "# handoff\n\n" + paragraph("h", 9000), PublicFiles: []string{"public/" + long}})
}
files := []string{}
for i := range 200 {
files = append(files, fmt.Sprintf("%03d/%s", i, long))
}
memory := RenderEssential(Essential{Task: paragraph("task", 50000), StageKey: "next", Entries: entries, ChangedFiles: files, InputPath: "/in.md", HistoryPath: "/history.md"})
if len(memory) > EssentialCap {
t.Fatalf("essential memory is %d bytes, over the %d cap", len(memory), EssentialCap)
}
for _, want := range []string{"## Task", "task: detail", "## Previous stage:", "h: detail", "earlier stages in history.md", "and 192 more"} {
if !strings.Contains(memory, want) {
t.Fatalf("capped memory missing %q:\n%s", want, memory)
}
}
}
func TestEssentialMemoryFirstVisit(t *testing.T) {
memory := RenderEssential(Essential{Task: "Do it.", StageKey: "plan", InputPath: "in.md", HistoryPath: "hist.md"})
for _, want := range []string{"## Task\n\nDo it.", "first stage of the run"} {
if !strings.Contains(memory, want) {
t.Fatalf("first-visit memory missing %q:\n%s", want, memory)
}
}
}
func TestHandoffSection(t *testing.T) {
cases := []struct {
name, markdown, want string
ok bool
}{
{"absent", "# summary\n\ntext\n", "", false},
{"empty", "# handoff\n\n# next\n", "", false},
{"stops at same level", "# handoff\nkeep\n## sub\nalso keep\n# other\ndrop\n", "keep\n## sub\nalso keep", true},
{"lower level runs to end", "# a\n## Handoff ##\nkeep\n", "keep", true},
{"fenced heading ignored", "```\n# handoff\nno\n```\n# handoff\nyes\n", "yes", true},
{"crlf", "# handoff\r\nkeep\r\n# next\r\n", "keep", true},
}
for _, tc := range cases {
got, ok := HandoffSection(tc.markdown)
if ok != tc.ok || got != tc.want {
t.Fatalf("%s: HandoffSection = %q, %v; want %q, %v", tc.name, got, ok, tc.want, tc.ok)
}
}
}
// TestEssentialMemorySizeOnRealisticRun records what a late stage receives on
// a realistic run, before (memory.md was the full history and the stage was
// told to read it and input.md) and after (only the capped essential memory is
// inlined; input.md and history.md are on demand).
func TestEssentialMemorySizeOnRealisticRun(t *testing.T) {
task := "Add retry with backoff to the uploader, keep the public API, and add tests.\n" + paragraph("task", 1200)
entries := []MemoryEntry{
{Stage: "plan", Visit: 1, Outcome: "success", Output: "# handoff\n\nTwo-step plan; see Plan.\n\n# Plan\n\n" + paragraph("plan", 3500)},
{Stage: "code", Visit: 1, Outcome: "success", Output: "# handoff\n\nAdded backoff.go and tests.\n\n# Log\n\n" + paragraph("code", 6500)},
{Stage: "review", Visit: 1, Outcome: "changes_requested", Output: "# handoff\n\n1. jitter unbounded. 2. no cancel test.\n\n# Review\n\n" + paragraph("review", 4500)},
{Stage: "code", Visit: 2, Outcome: "success", Output: "# handoff\n\nFixed both findings.\n\n# Log\n\n" + paragraph("code2", 5000)},
{Stage: "review", Visit: 2, Outcome: "success", Output: "# handoff\n\nApproved; land it.\n\n# Review\n\n" + paragraph("review2", 3000)},
}
history := RenderHistory(entries)
input := RenderInput(task, entries[len(entries)-1].Output)
memory := RenderEssential(Essential{Task: task, StageKey: "land", Entries: entries, ChangedFiles: []string{"uploader/backoff.go", "uploader/backoff_test.go"}, InputPath: "input.md", HistoryPath: "history.md"})
before := len(history) + len(input)
t.Logf("late stage context: before %d bytes (memory.md %d + input.md %d), after %d bytes inlined (input.md %d and history.md %d on demand)", before, len(history), len(input), len(memory), len(input), len(history))
if len(memory) > EssentialCap || len(memory)*5 > before {
t.Fatalf("essential memory %d bytes is not a large reduction from %d", len(memory), before)
}
}
+1 -1
View File
@@ -19,7 +19,7 @@ func TestLayoutRenderAndParseRoundTrip(t *testing.T) {
if err := os.WriteFile(paths.InputPath, []byte(input), 0o600); err != nil {
t.Fatal(err)
}
memory := RenderMemory([]MemoryEntry{{
memory := RenderHistory([]MemoryEntry{{
Stage: "implementer",
Visit: 1,
Output: "first visit result",
+16 -12
View File
@@ -18,9 +18,12 @@ type Paths struct {
TurnDir string
InputPath string
MemoryPath string
OutputPath string
PrivateDir string
PublicDir string
// HistoryPath is the full accumulated history; MemoryPath is the short,
// capped essential memory that is inlined into the prompt.
HistoryPath string
OutputPath string
PrivateDir string
PublicDir string
}
// Layout returns the deterministic paths for a stage turn. The sequence is
@@ -28,15 +31,16 @@ type Paths struct {
func Layout(runDir string, sequence int, stageKey string) Paths {
turnDir := filepath.Join(runDir, "stages", fmt.Sprintf("%02d-%s", sequence, stageKey))
return Paths{
RunDir: runDir,
Sequence: sequence,
StageKey: stageKey,
TurnDir: turnDir,
InputPath: filepath.Join(turnDir, "input.md"),
MemoryPath: filepath.Join(turnDir, "memory.md"),
OutputPath: filepath.Join(turnDir, "output.md"),
PrivateDir: filepath.Join(turnDir, "private"),
PublicDir: filepath.Join(runDir, "public"),
RunDir: runDir,
Sequence: sequence,
StageKey: stageKey,
TurnDir: turnDir,
InputPath: filepath.Join(turnDir, "input.md"),
MemoryPath: filepath.Join(turnDir, "memory.md"),
HistoryPath: filepath.Join(turnDir, "history.md"),
OutputPath: filepath.Join(turnDir, "output.md"),
PrivateDir: filepath.Join(turnDir, "private"),
PublicDir: filepath.Join(runDir, "public"),
}
}
+10 -9
View File
@@ -9,15 +9,16 @@ import (
func TestLayoutIsDeterministic(t *testing.T) {
runDir := filepath.Join(t.TempDir(), "run")
want := Paths{
RunDir: runDir,
Sequence: 2,
StageKey: "implementer",
TurnDir: filepath.Join(runDir, "stages", "02-implementer"),
InputPath: filepath.Join(runDir, "stages", "02-implementer", "input.md"),
MemoryPath: filepath.Join(runDir, "stages", "02-implementer", "memory.md"),
OutputPath: filepath.Join(runDir, "stages", "02-implementer", "output.md"),
PrivateDir: filepath.Join(runDir, "stages", "02-implementer", "private"),
PublicDir: filepath.Join(runDir, "public"),
RunDir: runDir,
Sequence: 2,
StageKey: "implementer",
TurnDir: filepath.Join(runDir, "stages", "02-implementer"),
InputPath: filepath.Join(runDir, "stages", "02-implementer", "input.md"),
MemoryPath: filepath.Join(runDir, "stages", "02-implementer", "memory.md"),
HistoryPath: filepath.Join(runDir, "stages", "02-implementer", "history.md"),
OutputPath: filepath.Join(runDir, "stages", "02-implementer", "output.md"),
PrivateDir: filepath.Join(runDir, "stages", "02-implementer", "private"),
PublicDir: filepath.Join(runDir, "public"),
}
got := Layout(runDir, 2, "implementer")
if got != want {
+9 -5
View File
@@ -22,23 +22,27 @@ func RenderInput(prompt string, previousOutput string) string {
return "# Run task\n\n" + demoteHeadings(task) + "\n\n# Previous turn output\n\n" + previousOutput
}
// MemoryEntry is one completed turn in a later turn's memory file. Output is
// the turn's markdown body, without the outcome section. PublicFiles are paths
// relative to the run directory, so the public prefix is retained.
// MemoryEntry is one completed turn in a later turn's history.md and essential
// memory.md. Output is the turn's markdown body, without the outcome section.
// Outcome is the routed outcome word, empty when it is not known (an inherited
// retry prefix). PublicFiles are paths relative to the run directory, so the
// public prefix is retained.
type MemoryEntry struct {
Stage string
Visit int
Outcome string
Output string
PublicFiles []string
}
// RenderMemory renders completed turns in the order supplied. Each turn's body
// RenderHistory renders a visit's history.md (the optional full memory, which
// was memory.md before essential memory existed). It renders completed turns in the order supplied. Each turn's body
// is embedded with its own headings demoted two levels, so the turn's "## Stage ·
// visit N" stays the structural section and a body heading can never look like a
// sibling turn (or like the system-written file list). The file list is
// system-written from PublicFiles, sorted and deduplicated, so the result is
// deterministic.
func RenderMemory(entries []MemoryEntry) string {
func RenderHistory(entries []MemoryEntry) string {
var b strings.Builder
for i, entry := range entries {
if i > 0 {
+10 -10
View File
@@ -28,7 +28,7 @@ func TestRenderInputLaterTurnKeepsTheTaskAndThePreviousOutput(t *testing.T) {
}
}
func TestRenderMemory(t *testing.T) {
func TestRenderHistory(t *testing.T) {
entries := []MemoryEntry{
{
Stage: "planner",
@@ -48,18 +48,18 @@ func TestRenderMemory(t *testing.T) {
"## reviewer · visit 2\n\n" +
"No public files.\n\n" +
"Files added to public/:\n- _(none)_\n"
if got := RenderMemory(entries); got != want {
t.Fatalf("RenderMemory() = %q, want %q", got, want)
if got := RenderHistory(entries); got != want {
t.Fatalf("RenderHistory() = %q, want %q", got, want)
}
if again := RenderMemory(entries); again != want {
t.Fatalf("RenderMemory() is not deterministic: %q", again)
if again := RenderHistory(entries); again != want {
t.Fatalf("RenderHistory() is not deterministic: %q", again)
}
}
func TestRenderMemoryDemotesBodyHeadingsButNotFences(t *testing.T) {
func TestRenderHistoryDemotesBodyHeadingsButNotFences(t *testing.T) {
output := "## Notes\n\n```md\n# outcome success\n```\n\n#### Deep\n\nlast line without newline"
entries := []MemoryEntry{{Stage: "build", Visit: 3, Output: output, PublicFiles: []string{"public/report.md"}}}
got := RenderMemory(entries)
got := RenderHistory(entries)
if !strings.Contains(got, "#### Notes") {
t.Fatalf("body heading was not demoted:\n%s", got)
}
@@ -77,8 +77,8 @@ func TestRenderMemoryDemotesBodyHeadingsButNotFences(t *testing.T) {
}
}
func TestRenderMemoryEmpty(t *testing.T) {
if got := RenderMemory(nil); got != "" {
t.Fatalf("RenderMemory(nil) = %q, want empty", got)
func TestRenderHistoryEmpty(t *testing.T) {
if got := RenderHistory(nil); got != "" {
t.Fatalf("RenderHistory(nil) = %q, want empty", got)
}
}