diff --git a/docs/cli.md b/docs/cli.md index c413128d..b293f743 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -898,6 +898,25 @@ Retry replays the entire workflow; earlier edits or notifications are not undone and may happen again. A missing original directory blocks retry rather than silently using your current directory. +`pipelines retry --extra-visits N [--stage KEY]` (wire fields +`retry_extra_visits` 1-5 and `retry_extra_stage`) continues a run whose loop +exhausted its visits (`max_visits`, the five-visit or 30-step cap) where it +stopped instead of re-running the visit that hit the cap: N extra visits go to +every exhausted stage, or with `--stage` to that stage only. Grants are +recorded on the run (`visit_grants`) and inherited by later retries; each +granted visit also lets the 30-step cap grow by one pass over the graph +(bounded at 120). It cannot be combined with `--mode=restart` or `--visit`. + +A resumed retry also inherits the run's findings ledger as it stood before the +retried visit, and receives the failed visit's `output.md` and `private/` +files (bounded: 200 files, 1 MiB each, 8 MiB total) under +`previous-attempt/` in its turn directory, listed in its `input.md`'s +`# Previous attempt` section. + +`pipelines inspect` lists the run's findings ledger (counts, open findings +most severe first, closed IDs) and its extra-visit grants; `--json` carries the +whole ledger (`findings`, with every status change) and `visit_grants`. + Retry is hidden and rejected while a run is executing or agent cleanup remains active, even if a terminal status was already persisted. Run RPCs report `executing` alongside status so clients can distinguish cleanup from completion. diff --git a/internal/author/skill/SKILL.md b/internal/author/skill/SKILL.md index 373158b2..97182a9c 100644 --- a/internal/author/skill/SKILL.md +++ b/internal/author/skill/SKILL.md @@ -42,8 +42,14 @@ preserved branch. `failed` and `interrupted` (server stopped mid-run) runs can b retried: resume reruns the failed or interrupted stage, or starts the next stage after the last completed one. `canceled` runs need a new run or direct work on their branch. A retried stage's `input.md` carries a `# Previous attempt` section -(why the last attempt failed) and, with `--input-file`, a `# Operator correction` -section holding only the overridden keys. +(why the last attempt failed, plus the failed visit's partial `output.md` and +`private/` files copied under `previous-attempt/`) and, with `--input-file`, a +`# Operator correction` section holding only the overridden keys. A run that +failed because a loop exhausted its visits continues with `--extra-visits N +[--stage KEY]`; a run waiting on an exhausted loop (`on_exhausted: decide`) is +answered with `pipelines decide --option accept|continue|abort`. +`inspect` shows the run's findings ledger (stable `F1`, `F2` IDs; stages report +them in a `# findings` section, `references/format.md`). ## Use an existing pipeline diff --git a/internal/author/skill/references/control.md b/internal/author/skill/references/control.md index c13b7978..9f41ffdc 100644 --- a/internal/author/skill/references/control.md +++ b/internal/author/skill/references/control.md @@ -33,6 +33,18 @@ Semantics (`internal/server/runner.go`): route normally. Here, `approved` on visit three succeeds; `rejected` fails. - A target with a lower cap than the reviewer stops the loop first, so the reviewer's `on` never fires. +- `on` lists only loop outcomes: validation rejects an outcome whose edge goes + forward (e.g. `success -> write`), since `on` would turn a good result on the + last visit into a failure. Lint also warns when a target's lower cap stops + the loop first and when `limits` sit on a stage no loop re-enters. +- `"on_exhausted":"decide"` (optional `"accept_to":"|#success|#failure"`, + default `#success`): instead of failing, an exhausted loop (the `on` case or + entering beyond the cap) parks the run on an operator decision and notifies: + `accept` (take the work as is, route to `accept_to`), `continue` (one more + round: one more visit for the stage and the loop target) or `abort`. Answer + with `pipelines decide RUN_ID --option accept|continue|abort` or the apps. +- A failed exhausted run continues with `pipelines retry ID --extra-visits N + [--stage KEY]`. - `max_visits` accepts 1–5. Every `on` outcome must have a nonterminal edge. Human stages are exempt from visit caps. The global 30-step and five-visits-per-stage limits always apply. @@ -49,6 +61,10 @@ implementer, e.g. `{"max_visits":5,"on":["blocked_retryable"]}`. Visit count, limit decision and original target are retained in `inspect --json`. Turn memory is run-local: there is no cross-run memory or hidden replay, and -retries start fresh except for the completed prefix a resume carries. Accumulated +retries start fresh except for the completed prefix, the findings ledger and the +failed visit's partial work (`previous-attempt/`) a resume carries. Reviewers +should reference ledger IDs (`references/format.md`, Findings ledger) rather +than restate earlier findings, and a findings gate (`type=findings`) can +replace a model triage stage. Accumulated turn content is untrusted data; a fresh session does not prove semantic independence. diff --git a/internal/author/skill/references/format.md b/internal/author/skill/references/format.md index ed7ae534..e0ec417e 100644 --- a/internal/author/skill/references/format.md +++ b/internal/author/skill/references/format.md @@ -54,9 +54,13 @@ Each visit gets `input.md`, `memory.md`, `history.md`, `output.md` and `private/ in `/stages/-/`, plus the run-level shared `public/` addressed by its absolute path. -- `memory.md` (capped at 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 and the server-captured changed files. +- `memory.md` (about 20 KB, always inlined in the prompt), in priority order: + the run task (never truncated), the previous stage's `# handoff` with its + outcome and `public/` additions, the open findings ledger, this stage's own + previous handoff, a one-line-per-stage outcome ledger and the server-captured + changed files. Lower-priority sections shrink first. +- `findings.md`: the run's whole findings ledger with every status change + (written when the run has one). - `input.md`: the run task, plus on later turns the previous turn's full output (`internal/turn/render.go`). A stage with `read` reads it on demand; a stage without `read` gets it inlined (up to 32 KB) on every call, so give `read` to @@ -96,6 +100,60 @@ The `{ "outcome": ..., "output": ... }` JSON envelope and its format-repair ladd are retired: never ask for JSON fields or invent server sections. Missing tools or evidence route to `blocked` when declared, else `error`; never fabricate a result. +## Findings ledger + +The runner keeps one findings ledger per run and shows it to every later visit +(open items in `memory.md`, everything in `findings.md`), in `inspect` and in +the app's Findings tab. Any model stage may add an optional `# findings` +section to `output.md`, one item per line: + +````markdown +# findings + +- important introduced internal/cache.go:42: eviction never runs +- nit pre-existing -: helper names are inconsistent +- F3 fixed: evict on write; test added +- F4 dismissed: intended behaviour, documented in README +- F5 settled: operator accepted the trade-off +- F2 open: the fix misses the error path +```` + +A new finding is ` : ` with +severity `critical`, `important`, `minor` or `nit` and origin `introduced` or +`pre-existing`. The runner assigns stable IDs (`F1`, `F2`, ...). A status line +is ` fixed|dismissed|settled|open: `. Dismissed and settled items +are closed for good: re-raising one (same location and summary) or reopening it +is ignored; re-raising a fixed one reopens it. Prompts need not restate this +syntax (the runner explains it); tell reviewers to reference IDs and to raise +only new problems. + +Route on the ledger mechanically with a findings gate instead of a model +triage stage: + +````markdown +# stage triage + +```configs +type=findings +severity=important +origin=introduced +``` + +```limits +{"max_visits":3} +``` + +```edges +open -> implement +clear -> land +``` +```` + +The outcome is `open` when any open finding has at least `severity` (default +`important`) and the given `origin` (default `introduced`; `pre-existing` or +`any`), otherwise `clear`. No model runs. Only `open`, `clear` and `error` +edges are allowed. + ## Configs - `provider`/`model`: exact IDs validated during server setup. Templates @@ -115,6 +173,10 @@ evidence route to `blocked` when declared, else `error`; never fabricate a resul attempts and visits of this stage; totals include cache reads and writes. Set only when the user asks or a measured visit exists (`references/practices.md`). - `delivery=true`: the landing stage's gate (below). OpenCode harness only. +- `resume_session=true`: on a loop visit, resume this stage's previous harness + session instead of starting a cold one (Claude harness only; others start + fresh; a session Claude Code no longer has starts fresh). Use it for + implementers that re-enter after review; keep reviewers fresh. - `auto_skip=false`: disable the server skip fallback for a stage that declares a `skipped` edge (`references/operations.md`, Server skip fallback). diff --git a/internal/cli/app.go b/internal/cli/app.go index 24678ec2..1e20afea 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -59,6 +59,7 @@ type options struct { transcripts bool step int version, expected, limit, retryVisit int + extraVisits int timeout, waitTimeout time.Duration stageModels stageModelFlags } @@ -187,6 +188,7 @@ func (a App) flags(command string) (*flag.FlagSet, *options) { f.StringVar(&o.retryMode, "mode", "resume", "Retry mode: resume failed stage or restart from entry") f.StringVar(&o.retryStage, "stage", "", "Retry this recorded stage (required when it was visited more than once)") f.IntVar(&o.retryVisit, "visit", 0, "1-based occurrence of --stage in the recorded execution") + f.IntVar(&o.extraVisits, "extra-visits", 0, "Grant 1-5 extra visits and continue an exhausted loop; with --stage, only that stage gets them") f.IntVar(&o.version, "version", 0, "Explicit published version of the same pipeline (default: source version)") f.StringVar(&o.retryInputFile, "input-file", "", "JSON object merged into the selected stage input; '-' reads stdin") f.StringVar(&o.notifyMode, "notify", "auto", "Notifications for this retry: auto, on, or off") @@ -1036,7 +1038,19 @@ func (a App) Run(ctx context.Context, args []string) error { if o.retryVisit < 0 { return fmt.Errorf("--visit must be positive") } - r, err := call(protocol.Message{Type: typeName, RunID: id, RequestKey: key, RetryMode: o.retryMode, RetryStage: o.retryStage, RetryVisit: o.retryVisit, RetryVersion: o.version, RetryInput: retryInput, NotifyMode: o.notifyMode}) + message := protocol.Message{Type: typeName, RunID: id, RequestKey: key, RetryMode: o.retryMode, RetryStage: o.retryStage, RetryVisit: o.retryVisit, RetryVersion: o.version, RetryInput: retryInput, NotifyMode: o.notifyMode} + if o.extraVisits != 0 { + if o.extraVisits < 1 || o.extraVisits > 5 { + return fmt.Errorf("--extra-visits must be from 1 to 5") + } + if o.retryVisit > 0 { + return fmt.Errorf("--visit cannot be combined with --extra-visits; --stage names the stage that gets the extra visits") + } + // With --extra-visits, --stage names the stage granted the + // visits; the resume point is the exhausted loop itself. + message.RetryExtraVisits, message.RetryExtraStage, message.RetryStage = o.extraVisits, o.retryStage, "" + } + r, err := call(message) if err != nil { return err } diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 75b8ef9f..d28ffb96 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -27,7 +27,7 @@ var usage = map[string]string{ "wait": "wait [run-id ...] [--timeout DURATION] [--json]", "cancel": "cancel [--json]", "decide": "decide [stage] --option KEY [--feedback TEXT] [--json]", - "retry": "retry [--yes] [--mode resume|restart] [--stage KEY [--visit N]] [--version N] [--input-file FILE|-] [--json [--wait [--wait-timeout DURATION]]]", + "retry": "retry [--yes] [--mode resume|restart] [--stage KEY [--visit N]] [--extra-visits N [--stage KEY]] [--version N] [--input-file FILE|-] [--json [--wait [--wait-timeout DURATION]]]", "title": "title \"\" [--json]", "debug": "debug <run-id> [--json | --no-open]", "chat-adopt": "chat-adopt <session-id> [--harness opencode|claude|codex] [--title TEXT] [--json]", @@ -55,7 +55,7 @@ var notes = map[string]string{ "validate": "Uses the same server parser as submission. Does not persist or activate schedules. Structural validity does not prove runtime/tool availability.", "submit": "Confirm publication at the prompt, or use --yes for explicit automation; schedules activate on acceptance. Managed drafts provide the name and base-version guard. --force never bypasses validation.", "run": "Runs in your current directory after action confirmation (--yes skips it). Select a pipeline and compose a multiline task with Ctrl+S. Stage tools are enabled automatically; no file list or typed RUN confirmation. Cancellation does not undo edits. --title sets an explicit run title; without it the title is derived from the prompt. --model PROVIDER/MODEL overrides the model for every stage of that run; --stage-model STAGE=PROVIDER/MODEL overrides one stage and is repeatable, with a repeated key last-wins. Precedence is per-stage > whole-run > the model pinned in the pipeline version; overrides apply to that run only and never change the pinned definition. An unknown stage key or a malformed provider/model is refused before the run starts, naming the valid stage keys. In JSON mode --wait polls until terminal; --wait-timeout bounds only the client wait after admission and is independent of per-request --timeout. A reached wait limit leaves the run active: inspect read-only with `inspect <run-id> --json`, or reattach with --wait reusing the original --request-key (never an automatic replay or cancel).", - "retry": "Resume a failed or interrupted run's stage by default (an interrupted run resumes its unfinished stage, or the one after its last completed stage), restoring the completed prefix handoff; use --mode=restart to start at entry. --stage selects a recorded stage (use --visit for repeated stages). --input-file accepts a bounded JSON object, merged with replacement at the selected stage and shown to it as an Operator correction; the retried stage also sees why the previous attempt failed; '-' reads stdin. Original history and pinned identity are retained; --version selects an explicit published version of the same pipeline only. --wait-timeout leaves an active retry for later read-only inspection or reattachment with the original --request-key, rather than starting a duplicate retry.", + "retry": "Resume a failed or interrupted run's stage by default (an interrupted run resumes its unfinished stage, or the one after its last completed stage), restoring the completed prefix handoff; use --mode=restart to start at entry. --stage selects a recorded stage (use --visit for repeated stages). --extra-visits N (1-5) continues a loop that exhausted its visits (max_visits, the five-visit or 30-step cap) where it stopped, granting N more visits to the exhausted stage(s), or with --stage to that stage only. --input-file accepts a bounded JSON object, merged with replacement at the selected stage and shown to it as an Operator correction; the retried stage also sees why the previous attempt failed; '-' reads stdin. Original history and pinned identity are retained; --version selects an explicit published version of the same pipeline only. --wait-timeout leaves an active retry for later read-only inspection or reattachment with the original --request-key, rather than starting a duplicate retry.", "list": "Lists active pipelines. Archived pipelines are hidden; --archived lists only them and --all lists both, marking archived ones with their archive time.", "archive": "Retire a pipeline from lists after confirmation (--yes for scripts). Nothing is deleted: versions, runs, artifacts and search history stay and keep its name. An archived pipeline cannot start runs and its name stays reserved (new/submit say so). Archiving is refused while an enabled schedule points at it, naming the schedule; pause or repoint it first. The latest version is sent as a guard, so a publication in between is refused.", "unarchive": "Return an archived pipeline to lists; it can run and take new versions again. Schedules stay paused until you enable them.", diff --git a/internal/cli/inspect.go b/internal/cli/inspect.go index fe53caff..6c7f8b46 100644 --- a/internal/cli/inspect.go +++ b/internal/cli/inspect.go @@ -3,6 +3,7 @@ package cli import ( "encoding/json" "fmt" + "sort" "strings" "unicode/utf8" @@ -48,6 +49,19 @@ func inspectSummary(d *protocol.RunDetail) string { if next := waitingHint(d); next != "" { b.WriteString("\n" + next + "\n") } + b.WriteString(inspectFindings(d)) + if len(d.VisitGrants) > 0 { + keys := make([]string, 0, len(d.VisitGrants)) + for key := range d.VisitGrants { + keys = append(keys, key) + } + sort.Strings(keys) + parts := make([]string, 0, len(keys)) + for _, key := range keys { + parts = append(parts, fmt.Sprintf("%s +%d", key, d.VisitGrants[key])) + } + b.WriteString("\nextra visits: " + strings.Join(parts, ", ") + "\n") + } if handoff := finalHandoff(d); handoff != "" { b.WriteString("\nhandoff:\n" + indent(handoff) + "\n") } else if preview := strings.TrimSpace(d.ResultPreview); preview != "" { diff --git a/internal/cli/inspect_findings.go b/internal/cli/inspect_findings.go new file mode 100644 index 00000000..f31703f7 --- /dev/null +++ b/internal/cli/inspect_findings.go @@ -0,0 +1,66 @@ +package cli + +import ( + "fmt" + "strings" + + "git.a-wan.net/alan/pipelines/internal/findings" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// inspectFindingsOpenCap bounds the open findings the compact summary lists; +// --json carries the whole ledger with every status change. +const inspectFindingsOpenCap = 20 + +// inspectFindings is the compact summary's findings section: counts per +// status, then the open findings (most severe first) and the closed ones by +// ID. Empty when the run has no ledger. +func inspectFindings(d *protocol.RunDetail) string { + if len(d.Findings) == 0 { + return "" + } + counts := findings.Counts(d.Findings) + var b strings.Builder + fmt.Fprintf(&b, "\nfindings: %d open, %d fixed, %d dismissed, %d settled\n", counts[protocol.FindingOpen], counts[protocol.FindingFixed], counts[protocol.FindingDismissed], counts[protocol.FindingSettled]) + shown := 0 + for _, severity := range append(append([]string(nil), findings.Severities...), "") { + for _, item := range d.Findings { + if item.Status != protocol.FindingOpen || (severity != "" && item.Severity != severity) || (severity == "" && findings.SeverityRank(item.Severity) >= 0) { + continue + } + if shown == inspectFindingsOpenCap { + fmt.Fprintf(&b, " … %d more open (--json)\n", counts[protocol.FindingOpen]-shown) + shown++ + } + if shown > inspectFindingsOpenCap { + continue + } + shown++ + b.WriteString(" " + findingLine(item) + "\n") + } + } + for _, status := range []string{protocol.FindingFixed, protocol.FindingDismissed, protocol.FindingSettled} { + var ids []string + for _, item := range d.Findings { + if item.Status == status { + ids = append(ids, item.ID) + } + } + if len(ids) > 0 { + fmt.Fprintf(&b, " %s: %s\n", status, strings.Join(ids, ", ")) + } + } + return b.String() +} + +func findingLine(item protocol.Finding) string { + line := fmt.Sprintf("%s %s · %s · %s", item.ID, item.Status, item.Severity, item.Origin) + if item.Location != "" { + line += " · " + item.Location + } + line += " — " + item.Summary + if item.Reason != "" { + line += " (" + item.Reason + ")" + } + return line +} diff --git a/internal/cli/inspect_findings_test.go b/internal/cli/inspect_findings_test.go new file mode 100644 index 00000000..1fc32736 --- /dev/null +++ b/internal/cli/inspect_findings_test.go @@ -0,0 +1,33 @@ +package cli + +import ( + "bytes" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func TestInspectShowsFindingsAndVisitGrants(t *testing.T) { + run := sampleRun() + run.Findings = []protocol.Finding{ + {ID: "F1", Severity: "nit", Origin: "introduced", Summary: "naming", Status: "open"}, + {ID: "F2", Severity: "critical", Origin: "introduced", Location: "a.go:3", Summary: "panic", Status: "open"}, + {ID: "F3", Severity: "important", Origin: "pre-existing", Summary: "old", Status: "dismissed", Reason: "not ours"}, + {ID: "F4", Severity: "minor", Origin: "introduced", Summary: "doc", Status: "fixed"}, + } + run.VisitGrants = map[string]int{"review": 1} + var out bytes.Buffer + if err := (App{Out: &out}).inspect(run, &options{}); err != nil { + t.Fatal(err) + } + text := out.String() + for _, want := range []string{"findings: 2 open, 1 fixed, 1 dismissed, 0 settled", " F2 open · critical · introduced · a.go:3 — panic", " fixed: F4", " dismissed: F3", "extra visits: review +1"} { + if !strings.Contains(text, want) { + t.Fatalf("inspect missing %q:\n%s", want, text) + } + } + if strings.Index(text, "F2 open") > strings.Index(text, "F1 open") { + t.Fatalf("open findings not most severe first:\n%s", text) + } +} diff --git a/internal/findings/findings.go b/internal/findings/findings.go new file mode 100644 index 00000000..de418fd5 --- /dev/null +++ b/internal/findings/findings.go @@ -0,0 +1,374 @@ +// Package findings is the run-level findings ledger the runner owns. Stages +// report new findings and status changes in an output.md "# findings" section; +// the runner parses them (Parse), applies them to the ledger (Apply), assigns +// stable IDs, persists the ledger and feeds it to later visits (Render). +// +// Section syntax, one item per line (a leading list marker is optional): +// +// - <severity> <origin> <file:line>: <summary> a new finding +// - <severity> <origin>: <summary> a new finding without a location +// - F3 fixed: <how> status change +// - F3 dismissed: <why> - F3 settled: <why> closed for good +// - F3 open: <why the fix is wrong> reopen a fixed finding +// +// severity is critical, important, minor or nit; origin is introduced or +// pre-existing. Unparseable lines are ignored. +package findings + +import ( + "fmt" + "regexp" + "slices" + "strconv" + "strings" + + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/turn" +) + +// Bounds keep the ledger and each item small: it is persisted on the run and +// rendered into every later visit's memory. +const ( + MaxFindings = 200 + MaxNewPerVisit = 50 + maxSummaryBytes = 300 + maxLocationBytes = 200 + maxReasonBytes = 300 + maxEvents = 20 +) + +// Severities in rank order, most severe first. +var Severities = []string{protocol.SeverityCritical, protocol.SeverityImportant, protocol.SeverityMinor, protocol.SeverityNit} + +var severityAliases = map[string]string{ + "critical": protocol.SeverityCritical, "blocker": protocol.SeverityCritical, + "important": protocol.SeverityImportant, "major": protocol.SeverityImportant, + "minor": protocol.SeverityMinor, + "nit": protocol.SeverityNit, "nitpick": protocol.SeverityNit, "trivial": protocol.SeverityNit, +} + +var originAliases = map[string]string{ + "introduced": protocol.OriginIntroduced, "new": protocol.OriginIntroduced, + "pre-existing": protocol.OriginPreExisting, "preexisting": protocol.OriginPreExisting, + "pre_existing": protocol.OriginPreExisting, "existing": protocol.OriginPreExisting, +} + +var statusWords = map[string]string{ + "fixed": protocol.FindingFixed, "resolved": protocol.FindingFixed, + "dismissed": protocol.FindingDismissed, "rejected": protocol.FindingDismissed, "wontfix": protocol.FindingDismissed, + "settled": protocol.FindingSettled, "accepted": protocol.FindingSettled, + "open": protocol.FindingOpen, "reopen": protocol.FindingOpen, "reopened": protocol.FindingOpen, +} + +// SeverityRank is 0 for critical through 3 for nit, and -1 when unknown. +func SeverityRank(severity string) int { + return slices.Index(Severities, severity) +} + +// NormalizeSeverity returns the canonical severity or "". +func NormalizeSeverity(word string) string { return severityAliases[strings.ToLower(word)] } + +// NormalizeOrigin returns the canonical origin, "any", or "". +func NormalizeOrigin(word string) string { + if strings.EqualFold(word, "any") { + return "any" + } + return originAliases[strings.ToLower(word)] +} + +// New is a finding a stage raised; Change is a status change it reported. +type New struct { + Severity, Origin, Location, Summary string +} + +type Change struct { + ID, Status, Reason string +} + +// Report is one visit's parsed "# findings" section. +type Report struct { + New []New + Changes []Change +} + +var ( + listMarker = regexp.MustCompile(`^\s*(?:[-*+]|\d+[.)])\s+`) + findingID = regexp.MustCompile(`^(?i)F(\d+)$`) +) + +// Parse reads the "# findings" section of a turn's output. It returns an empty +// report when there is none. +func Parse(markdown string) Report { + section, ok := turn.Section(markdown, "findings") + if !ok { + return Report{} + } + var report Report + fence := "" + for _, line := range strings.Split(section, "\n") { + trimmed := strings.TrimSpace(line) + if fence != "" { + if strings.HasPrefix(trimmed, fence) { + fence = "" + } + continue + } + if strings.HasPrefix(trimmed, "```") || strings.HasPrefix(trimmed, "~~~") { + fence = trimmed[:3] + continue + } + line = strings.TrimSpace(listMarker.ReplaceAllString(line, "")) + line = strings.Trim(line, "`") + if line == "" { + continue + } + if change, ok := parseChange(line); ok { + report.Changes = append(report.Changes, change) + continue + } + if item, ok := parseNew(line); ok { + report.New = append(report.New, item) + } + } + return report +} + +// splitReason splits "word: reason", "word — reason" or "word - reason". +func splitReason(text string) (string, string) { + for _, sep := range []string{": ", " — ", " – ", " - "} { + if head, tail, ok := strings.Cut(text, sep); ok { + return strings.TrimSpace(head), strings.TrimSpace(tail) + } + } + return strings.TrimSpace(strings.TrimSuffix(text, ":")), "" +} + +func parseChange(line string) (Change, bool) { + fields := strings.Fields(line) + if len(fields) < 2 { + return Change{}, false + } + id := strings.TrimSuffix(strings.TrimSuffix(fields[0], ":"), ",") + match := findingID.FindStringSubmatch(id) + if match == nil { + return Change{}, false + } + rest := strings.TrimSpace(strings.TrimPrefix(line, fields[0])) + word, reason := splitReason(rest) + status, ok := statusWords[strings.ToLower(strings.Trim(word, "*_`"))] + if !ok { + return Change{}, false + } + return Change{ID: "F" + match[1], Status: status, Reason: capText(reason, maxReasonBytes)}, true +} + +func parseNew(line string) (New, bool) { + fields := strings.Fields(line) + if len(fields) < 2 { + return New{}, false + } + severity := NormalizeSeverity(strings.Trim(fields[0], "*_[]:")) + if severity == "" { + return New{}, false + } + originWord := fields[1] + noLocation := strings.HasSuffix(originWord, ":") + origin := originAliases[strings.ToLower(strings.Trim(originWord, "*_[]:"))] + if origin == "" { + return New{}, false + } + rest := strings.TrimSpace(line[strings.Index(line, originWord)+len(originWord):]) + var location, summary string + if noLocation { + summary = rest + } else { + summary = rest + for _, sep := range []string{": ", " — "} { + // The location is one token (a path, file:line or "-"); a + // multi-word head is prose and stays in the summary. + if head, tail, ok := strings.Cut(rest, sep); ok && !strings.ContainsAny(strings.TrimSpace(head), " \t") { + location, summary = strings.Trim(strings.TrimSpace(head), "`"), strings.TrimSpace(tail) + break + } + } + } + if location == "-" { + location = "" + } + summary = strings.TrimSpace(summary) + if summary == "" { + return New{}, false + } + return New{Severity: severity, Origin: origin, Location: capText(location, maxLocationBytes), Summary: capText(summary, maxSummaryBytes)}, true +} + +func capText(text string, limit int) string { + text = strings.Join(strings.Fields(text), " ") + if len(text) <= limit { + return text + } + cut := limit - len("…") + for cut > 0 && cut < len(text) && (text[cut]&0xC0) == 0x80 { + cut-- + } + return text[:cut] + "…" +} + +// Outcome summarises what Apply did, for logs and tests. +type Outcome struct { + Added []string + Changed []string + Ignored []string +} + +func key(location, summary string) string { + return strings.ToLower(location) + "\x00" + strings.ToLower(summary) +} + +// Apply folds one visit's report into the ledger and returns the new ledger. +// IDs are assigned in order (F1, F2, ...) and never reused. A new finding that +// repeats an open one is ignored, one that repeats a fixed one reopens it, and +// one that repeats a dismissed or settled one is ignored: those are closed for +// good. Reopening a dismissed or settled finding is ignored for the same +// reason. +func Apply(ledger []protocol.Finding, report Report, stageKey string, sequence int) ([]protocol.Finding, Outcome) { + out := append([]protocol.Finding(nil), ledger...) + var result Outcome + byID := map[string]int{} + byKey := map[string]int{} + next := 1 + for i, item := range out { + byID[item.ID] = i + byKey[key(item.Location, item.Summary)] = i + if n, err := strconv.Atoi(strings.TrimPrefix(item.ID, "F")); err == nil && n >= next { + next = n + 1 + } + } + setStatus := func(i int, status, reason string) { + item := out[i] + item.Events = append(append([]protocol.FindingEvent(nil), item.Events...), protocol.FindingEvent{Sequence: sequence, Stage: stageKey, Status: status, Reason: reason}) + if len(item.Events) > maxEvents { + item.Events = item.Events[len(item.Events)-maxEvents:] + } + item.Status, item.Reason = status, reason + item.UpdatedBy, item.UpdatedSequence = stageKey, sequence + out[i] = item + } + for _, change := range report.Changes { + i, ok := byID[change.ID] + if !ok { + result.Ignored = append(result.Ignored, change.ID+": unknown id") + continue + } + current := out[i].Status + if current == change.Status { + continue + } + if change.Status == protocol.FindingOpen && (current == protocol.FindingDismissed || current == protocol.FindingSettled) { + result.Ignored = append(result.Ignored, change.ID+": "+current+" findings are closed") + continue + } + setStatus(i, change.Status, change.Reason) + result.Changed = append(result.Changed, change.ID) + } + added := 0 + for _, item := range report.New { + if i, ok := byKey[key(item.Location, item.Summary)]; ok { + switch out[i].Status { + case protocol.FindingFixed: + setStatus(i, protocol.FindingOpen, "raised again by "+stageKey) + result.Changed = append(result.Changed, out[i].ID) + default: + result.Ignored = append(result.Ignored, out[i].ID+": already "+out[i].Status) + } + continue + } + if added >= MaxNewPerVisit || len(out) >= MaxFindings { + result.Ignored = append(result.Ignored, "over the findings limit: "+item.Summary) + continue + } + added++ + id := fmt.Sprintf("F%d", next) + next++ + out = append(out, protocol.Finding{ + ID: id, Severity: item.Severity, Origin: item.Origin, Location: item.Location, Summary: item.Summary, + Status: protocol.FindingOpen, RaisedBy: stageKey, RaisedSequence: sequence, + Events: []protocol.FindingEvent{{Sequence: sequence, Stage: stageKey, Status: protocol.FindingOpen}}, + }) + byID[id] = len(out) - 1 + byKey[key(item.Location, item.Summary)] = len(out) - 1 + result.Added = append(result.Added, id) + } + return out, result +} + +// Before returns the ledger as it stood before visit sequence: findings raised +// at or after it are dropped and later events are rolled back. A retry resuming +// at sequence starts from this ledger. +func Before(ledger []protocol.Finding, sequence int) []protocol.Finding { + var out []protocol.Finding + for _, item := range ledger { + if item.RaisedSequence >= sequence { + continue + } + var events []protocol.FindingEvent + for _, event := range item.Events { + if event.Sequence < sequence { + events = append(events, event) + } + } + item.Events = events + item.Status, item.Reason, item.UpdatedBy, item.UpdatedSequence = protocol.FindingOpen, "", "", 0 + if n := len(events); n > 0 { + last := events[n-1] + item.Status, item.Reason = last.Status, last.Reason + if n > 1 || last.Status != protocol.FindingOpen || last.Sequence != item.RaisedSequence { + item.UpdatedBy, item.UpdatedSequence = last.Stage, last.Sequence + } + } + out = append(out, item) + } + return out +} + +// Gate is a mechanical routing condition on the ledger: open findings at or +// above MinSeverity whose origin matches (Origin "any" matches both). +type Gate struct { + MinSeverity string + Origin string +} + +// Matching returns the open findings the gate counts. +func (g Gate) Matching(ledger []protocol.Finding) []protocol.Finding { + limit := SeverityRank(g.MinSeverity) + if limit < 0 { + limit = SeverityRank(protocol.SeverityImportant) + } + var out []protocol.Finding + for _, item := range ledger { + if item.Status != protocol.FindingOpen { + continue + } + rank := SeverityRank(item.Severity) + if rank < 0 || rank > limit { + continue + } + if g.Origin != "any" && g.Origin != "" && item.Origin != g.Origin { + continue + } + if g.Origin == "" && item.Origin != protocol.OriginIntroduced { + continue + } + out = append(out, item) + } + return out +} + +// Counts returns the number of findings per status. +func Counts(ledger []protocol.Finding) map[string]int { + counts := map[string]int{} + for _, item := range ledger { + counts[item.Status]++ + } + return counts +} diff --git a/internal/findings/findings_test.go b/internal/findings/findings_test.go new file mode 100644 index 00000000..139bfd0b --- /dev/null +++ b/internal/findings/findings_test.go @@ -0,0 +1,143 @@ +package findings + +import ( + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +const reviewOutput = "# outcome\n\nrejected\n\n# handoff\n\nTwo issues.\n\n# findings\n\n" + + "- important introduced internal/cache.go:42: eviction never runs\n" + + "- nit pre-existing -: odd naming in helpers\n" + + "- minor introduced: missing doc comment\n" + + "* blocker new `cmd/main.go`: panics on empty input\n" + + "- this line is prose and ignored\n" + + "\n```\n- critical introduced x.go:1: inside a fence\n```\n" + + "\n# details\n\n- critical introduced y.go:2: outside the section\n" + +func TestParseNewFindingsAndIgnoresProse(t *testing.T) { + report := Parse(reviewOutput) + if len(report.New) != 4 || len(report.Changes) != 0 { + t.Fatalf("report = %+v", report) + } + want := []New{ + {Severity: "important", Origin: "introduced", Location: "internal/cache.go:42", Summary: "eviction never runs"}, + {Severity: "nit", Origin: "pre-existing", Location: "", Summary: "odd naming in helpers"}, + {Severity: "minor", Origin: "introduced", Location: "", Summary: "missing doc comment"}, + {Severity: "critical", Origin: "introduced", Location: "cmd/main.go", Summary: "panics on empty input"}, + } + for i := range want { + if report.New[i] != want[i] { + t.Errorf("new[%d] = %+v, want %+v", i, report.New[i], want[i]) + } + } + if got := Parse("# outcome\n\nsuccess\n"); len(got.New)+len(got.Changes) != 0 { + t.Fatalf("no section should parse empty: %+v", got) + } +} + +func TestParseStatusChanges(t *testing.T) { + report := Parse("# findings\n\n- F1 fixed: added eviction\n- f2 dismissed — style only\n- F3: settled - agreed with operator\n- F4 open: fix incomplete\n- F5 maybe: unknown word\n") + want := []Change{{"F1", "fixed", "added eviction"}, {"F2", "dismissed", "style only"}, {"F3", "settled", "agreed with operator"}, {"F4", "open", "fix incomplete"}} + if len(report.Changes) != len(want) { + t.Fatalf("changes = %+v", report.Changes) + } + for i := range want { + if report.Changes[i] != want[i] { + t.Errorf("change[%d] = %+v, want %+v", i, report.Changes[i], want[i]) + } + } +} + +func TestApplyAssignsStableIDsAndEnforcesClosedItems(t *testing.T) { + ledger, out := Apply(nil, Parse(reviewOutput), "review", 2) + if strings.Join(out.Added, ",") != "F1,F2,F3,F4" || len(ledger) != 4 { + t.Fatalf("added %v ledger %d", out.Added, len(ledger)) + } + ledger, out = Apply(ledger, Parse("# findings\n- F1 fixed: evicts now\n- F2 dismissed: out of scope\n- F9 fixed: nope\n"), "implement", 3) + if strings.Join(out.Changed, ",") != "F1,F2" || len(out.Ignored) != 1 { + t.Fatalf("outcome %+v", out) + } + // A reviewer re-raising the dismissed F2 is ignored; re-raising the fixed F1 reopens it; + // reopening the dismissed F2 by id is ignored; a genuinely new item gets F5. + ledger, out = Apply(ledger, Parse("# findings\n- nit pre-existing -: odd naming in helpers\n- important introduced internal/cache.go:42: eviction never runs\n- F2 open: still bad\n- minor introduced a.go:1: new thing\n"), "review", 4) + if strings.Join(out.Added, ",") != "F5" || strings.Join(out.Changed, ",") != "F1" || len(out.Ignored) != 2 { + t.Fatalf("outcome %+v", out) + } + byID := map[string]protocol.Finding{} + for _, item := range ledger { + byID[item.ID] = item + } + if byID["F1"].Status != "open" || byID["F2"].Status != "dismissed" || byID["F2"].Reason != "out of scope" || byID["F1"].UpdatedSequence != 4 { + t.Fatalf("ledger %+v", ledger) + } + // Before rolls the ledger back to the state a retry at sequence 4 starts from. + before := Before(ledger, 4) + if len(before) != 4 { + t.Fatalf("before = %d items", len(before)) + } + for _, item := range before { + if item.ID == "F1" && (item.Status != "fixed" || item.UpdatedSequence != 3) { + t.Fatalf("F1 before 4 = %+v", item) + } + if item.ID == "F3" && (item.Status != "open" || item.UpdatedSequence != 0) { + t.Fatalf("F3 before 4 = %+v", item) + } + } + if got := Before(ledger, 2); len(got) != 0 { + t.Fatalf("before 2 = %+v", got) + } + // IDs continue after the highest existing one. + _, out = Apply(before, Parse("# findings\n- minor introduced b.go:1: another\n"), "review", 4) + if strings.Join(out.Added, ",") != "F5" { + t.Fatalf("added %v", out.Added) + } +} + +func TestGateMatching(t *testing.T) { + ledger, _ := Apply(nil, Parse(reviewOutput), "review", 1) + if got := (Gate{MinSeverity: "important", Origin: "introduced"}).Matching(ledger); len(got) != 2 { + t.Fatalf("important introduced = %+v", got) + } + if got := (Gate{}).Matching(ledger); len(got) != 2 { + t.Fatalf("defaults = %+v", got) + } + if got := (Gate{MinSeverity: "nit", Origin: "any"}).Matching(ledger); len(got) != 4 { + t.Fatalf("nit any = %+v", got) + } + if got := (Gate{MinSeverity: "critical", Origin: "pre-existing"}).Matching(ledger); len(got) != 0 { + t.Fatalf("critical pre-existing = %+v", got) + } + ledger, _ = Apply(ledger, Parse("# findings\n- F1 fixed: done\n- F4 settled: accepted\n"), "implement", 2) + if got := (Gate{}).Matching(ledger); len(got) != 0 { + t.Fatalf("after fixes = %+v", got) + } +} + +func TestRenderMemoryIsBoundedAndListsOpenFirst(t *testing.T) { + ledger, _ := Apply(nil, Parse(reviewOutput), "review", 1) + ledger, _ = Apply(ledger, Parse("# findings\n- F2 dismissed: not ours\n"), "implement", 2) + text := RenderMemory(ledger, 4096) + if !strings.Contains(text, "F4 · critical") || strings.Index(text, "F4 · critical") > strings.Index(text, "F1 · important") { + t.Fatalf("open findings not ordered by severity:\n%s", text) + } + if !strings.Contains(text, "Closed (do not re-raise):\n- F2 dismissed") || !strings.Contains(text, "never re-raise") { + t.Fatalf("closed list or instructions missing:\n%s", text) + } + var many []protocol.Finding + for i := 0; i < 150; i++ { + many, _ = Apply(many, Report{New: []New{{Severity: "minor", Origin: "introduced", Location: "f.go:" + strings.Repeat("1", i%7+1), Summary: strings.Repeat("x", 40) + string(rune('a'+i%26)) + strings.Repeat("y", i)}}}, "review", 1) + } + small := RenderMemory(many, 2048) + if len(small) > 2048 || !strings.Contains(small, "more in findings.md") { + t.Fatalf("bounded render is %d bytes:\n%s", len(small), small) + } + if RenderMemory(nil, 4096) != "" { + t.Fatal("empty ledger renders a section") + } + file := RenderFile(ledger) + if !strings.Contains(file, "## Dismissed") || !strings.Contains(file, "#2 implement → dismissed: not ours") { + t.Fatalf("file:\n%s", file) + } +} diff --git a/internal/findings/render.go b/internal/findings/render.go new file mode 100644 index 00000000..b184f20d --- /dev/null +++ b/internal/findings/render.go @@ -0,0 +1,122 @@ +package findings + +import ( + "fmt" + "strings" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// Syntax is the one-paragraph reporting instruction shared by the memory +// section and the model prompt. +const Syntax = "Report findings in an optional `# findings` section of output.md, one per line: a new one as `- <critical|important|minor|nit> <introduced|pre-existing> <file:line or ->: <summary>`; a status change to a ledger item as `- F3 fixed: <how>`, `- F3 dismissed: <why>` or `- F3 settled: <why>` (`- F3 open: <why>` reopens a fixed one). The runner assigns IDs; reference them, and never re-raise a dismissed or settled finding." + +func line(item protocol.Finding) string { + location := "" + if item.Location != "" { + location = " · " + item.Location + } + return fmt.Sprintf("%s · %s · %s%s — %s", item.ID, item.Severity, item.Origin, location, item.Summary) +} + +// RenderMemory is the ledger section of a visit's essential memory: every open +// finding (most severe first) and a short list of closed ones, bounded by +// limit bytes. It is empty when the ledger is. +func RenderMemory(ledger []protocol.Finding, limit int) string { + if len(ledger) == 0 { + return "" + } + counts := Counts(ledger) + var b strings.Builder + fmt.Fprintf(&b, "\n## Findings ledger (runner-owned)\n\n%d open, %d fixed, %d dismissed, %d settled. Full ledger: findings.md beside this file.\n\n", + counts[protocol.FindingOpen], counts[protocol.FindingFixed], counts[protocol.FindingDismissed], counts[protocol.FindingSettled]) + footer := "\n" + Syntax + "\n" + budget := limit - b.Len() - len(footer) + var body strings.Builder + write := func(text string) bool { + if body.Len()+len(text) > budget { + return false + } + body.WriteString(text) + return true + } + omitted := 0 + if counts[protocol.FindingOpen] > 0 { + write("Open:\n") + for _, severity := range append(append([]string(nil), Severities...), "") { + for _, item := range ledger { + if item.Status != protocol.FindingOpen || (severity != "" && item.Severity != severity) || (severity == "" && SeverityRank(item.Severity) >= 0) { + continue + } + if !write("- " + line(item) + "\n") { + omitted++ + } + } + } + } + closed := []string{} + for _, item := range ledger { + if item.Status == protocol.FindingDismissed || item.Status == protocol.FindingSettled { + closed = append(closed, fmt.Sprintf("- %s %s — %s", item.ID, item.Status, capText(item.Summary, 80))) + } + } + if len(closed) > 0 { + write("\nClosed (do not re-raise):\n") + for _, text := range closed { + if !write(text + "\n") { + omitted++ + } + } + } + var fixed []string + for _, item := range ledger { + if item.Status == protocol.FindingFixed { + fixed = append(fixed, item.ID) + } + } + if len(fixed) > 0 { + if !write("\nFixed: " + strings.Join(fixed, ", ") + "\n") { + omitted++ + } + } + if omitted > 0 { + fmt.Fprintf(&body, "- … %d more in findings.md\n", omitted) + } + b.WriteString(body.String()) + b.WriteString(footer) + return b.String() +} + +// RenderFile is findings.md: the whole ledger with every item's history. +func RenderFile(ledger []protocol.Finding) string { + var b strings.Builder + b.WriteString("# Findings ledger\n\nRunner-owned; IDs are stable for the run. " + Syntax + "\n") + if len(ledger) == 0 { + b.WriteString("\nNo findings yet.\n") + return b.String() + } + for _, status := range []string{protocol.FindingOpen, protocol.FindingFixed, protocol.FindingDismissed, protocol.FindingSettled} { + first := true + for _, item := range ledger { + if item.Status != status { + continue + } + if first { + fmt.Fprintf(&b, "\n## %s\n\n", strings.ToUpper(status[:1])+status[1:]) + first = false + } + fmt.Fprintf(&b, "- %s (raised by %s, visit #%d)\n", line(item), item.RaisedBy, item.RaisedSequence) + for _, event := range item.Events { + if event.Sequence == item.RaisedSequence && event.Status == protocol.FindingOpen && event.Reason == "" { + continue + } + reason := "" + if event.Reason != "" { + reason = ": " + event.Reason + } + fmt.Fprintf(&b, " - #%d %s → %s%s\n", event.Sequence, event.Stage, event.Status, reason) + } + } + } + return b.String() +} diff --git a/internal/pipeline/control.go b/internal/pipeline/control.go index 5fb6fb05..3dceee13 100644 --- a/internal/pipeline/control.go +++ b/internal/pipeline/control.go @@ -61,6 +61,14 @@ func parseControl(s *Stage, fields map[string]string) error { } seen[outcome] = true } + switch s.Limits.OnExhausted { + case "", "fail", "decide": + default: + return fmt.Errorf("on_exhausted must be fail or decide") + } + if s.Limits.AcceptTo != "" && s.Limits.OnExhausted != "decide" { + return fmt.Errorf("accept_to needs \"on_exhausted\":\"decide\"") + } delete(fields, "limits") } if text, ok := fields["memory"]; ok { @@ -86,6 +94,9 @@ func validateControl(s Stage, stages map[string]bool) error { return fmt.Errorf("stage %s: limit outcome %q must name a nonterminal edge", s.Key, outcome) } } + if target := s.Limits.AcceptTo; target != "" && !protocol.IsTerminal(target) && !stages[target] { + return fmt.Errorf("stage %s: accept_to %q is not a stage, #success or #failure", s.Key, target) + } } for _, ref := range s.Memory { owner, _, _ := strings.Cut(ref, ".") diff --git a/internal/pipeline/lint.go b/internal/pipeline/lint.go index d0bd6a37..8df300d8 100644 --- a/internal/pipeline/lint.go +++ b/internal/pipeline/lint.go @@ -90,6 +90,23 @@ func Lint(g Graph) (errs, warnings []LintFinding) { } } } + lintLoops(g, i, index, func(list *[]LintFinding, rule, format string, args ...any) { + if list == nil { + list = &warnings + } + add(list, s, rule, format, args...) + }, &errs) + if model && s.Configs["resume_session"] == "true" { + if !reentered(g, i, index) { + add(&warnings, s, "resume_session", "resume_session=true has no effect: no edge loops back to %s, so it never has a previous session to resume", s.Key) + } + if s.Configs["harness"] != stage.ClaudeBackend { + add(&warnings, s, "resume_session", "resume_session is supported only by harness=claude; this stage starts a fresh session on every visit") + } + if reason := mutatingReason(s); reason == "" { + add(&warnings, s, "resume_session", "resume_session on a read-only stage carries its earlier verdicts into later visits; keep reviewers on fresh sessions and resume only implementers") + } + } if stage.EffectiveType(s.Type) == stage.HumanType { continue // a person bounds a human stage's loop } @@ -106,6 +123,63 @@ func Lint(g Graph) (errs, warnings []LintFinding) { return errs, warnings } +// lintLoops checks a stage's limits block against the graph: an `on` outcome +// must be a loop (back edge or self-loop), because `on` turns that outcome into +// a failure on the last allowed visit; a forward `success` there makes a good +// result fail the run. It also warns when the limits can never apply. +func lintLoops(g Graph, i int, index map[string]int, add func(list *[]LintFinding, rule, format string, args ...any), errs *[]LintFinding) { + s := g.Stages[i] + if s.Limits == nil { + return + } + for _, outcome := range s.Limits.On { + target, ok := s.Edges[outcome] + if !ok || protocol.IsTerminal(target) { + continue + } + if index[target] > i { + add(errs, "limits", "limits.on lists %q, but %s -> %s is a forward edge, not a loop back; on the last allowed visit the runner routes a listed outcome to #failure, so a %s there would fail the run. List only outcomes whose edge returns to %s or an earlier stage (for example \"rejected\"), or drop \"on\"", outcome, outcome, target, outcome, s.Key) + continue + } + if limits := g.Stages[index[target]].Limits; limits != nil && index[target] != i && limits.MaxVisits < s.Limits.MaxVisits { + add(nil, "limits", "%s has max_visits %d, lower than this stage's %d: the loop stops at %s first, so on [%q] never fires; give %s a cap at least %d or leave it unlimited", target, limits.MaxVisits, s.Limits.MaxVisits, target, outcome, target, s.Limits.MaxVisits) + } + } + if !reentered(g, i, index) { + add(nil, "limits", "limits has no effect: no edge loops back to %s, so it is visited once per run; move the limits to the stage that sends the run back, or remove them", s.Key) + } + if s.Limits.OnExhausted == "decide" && stage.EffectiveType(s.Type) == stage.HumanType { + add(nil, "limits", "on_exhausted=decide on a human stage has no effect; human stages are exempt from visit caps") + } +} + +// reentered reports whether stage i lies on a cycle, i.e. whether a run can +// visit it more than once. +func reentered(g Graph, i int, index map[string]int) bool { + key := g.Stages[i].Key + seen := map[string]bool{} + var stack []string + for _, target := range g.Stages[i].Edges { + stack = append(stack, target) + } + for len(stack) > 0 { + next := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if next == key { + return true + } + j, ok := index[next] + if !ok || seen[next] || protocol.IsTerminal(next) { + continue + } + seen[next] = true + for _, target := range g.Stages[j].Edges { + stack = append(stack, target) + } + } + return false +} + // mutatingReason names why a model stage can change the workspace, or "". func mutatingReason(s Stage) string { if s.Configs["delivery"] == "true" { diff --git a/internal/pipeline/lint_loops_test.go b/internal/pipeline/lint_loops_test.go new file mode 100644 index 00000000..75822f53 --- /dev/null +++ b/internal/pipeline/lint_loops_test.go @@ -0,0 +1,109 @@ +package pipeline + +import ( + "strings" + "testing" +) + +func TestLintRejectsForwardLimitOutcomes(t *testing.T) { + // Research runs 100/101: "on" listed the forward success edge, so a good + // result on the last allowed visit failed the run. + source := lintSource( + modelStage("research", "Research.", "read", "success -> write\nretry -> research\nerror -> #failure", "```limits\n{\"max_visits\":3,\"on\":[\"success\",\"retry\"]}\n```"), + modelStage("write", "Write.", "read", "success -> #success\nerror -> #failure", ""), + ) + errs, _ := lintRules(t, source) + if len(errs["limits"]) != 1 || !strings.Contains(errs["limits"][0], `limits.on lists "success", but success -> write is a forward edge`) { + t.Fatalf("limits errors = %v", errs["limits"]) + } +} + +func TestLintWarnsAboutIneffectiveLoopSettings(t *testing.T) { + checks := "```checks\nnone: focused tests only\n```" + source := lintSource( + modelStage("implement", "Implement.", "read\nedit", "success -> review\nerror -> #failure", checks+"\n\n```limits\n{\"max_visits\":2}\n```"), + modelStage("review", "Review.", "read", "approved -> land\nrejected -> implement\nerror -> #failure", "```limits\n{\"max_visits\":3,\"on\":[\"rejected\"],\"on_exhausted\":\"decide\",\"accept_to\":\"land\"}\n```"), + modelStage("land", "Land.", "read", "success -> #success\nerror -> #failure", "```limits\n{\"max_visits\":2}\n```"), + ) + errs, warns := lintRules(t, source) + if len(errs["limits"]) != 0 { + t.Fatalf("unexpected errors %v", errs) + } + joined := strings.Join(warns["limits"], "\n") + for _, want := range []string{"implement has max_visits 2, lower than this stage's 3", "stage land: limits: limits has no effect"} { + if !strings.Contains(joined, want) { + t.Fatalf("warnings missing %q:\n%s", want, joined) + } + } + if strings.Contains(joined, "stage review: limits: limits has no effect") || strings.Contains(joined, "stage implement: limits: limits has no effect") { + t.Fatalf("review and implement are on a loop:\n%s", joined) + } +} + +func TestLintWarnsAboutResumeSession(t *testing.T) { + stageWith := func(key, tools, edges, configs, extra string) string { + return "# stage " + key + "\n\n```prompt\nWork.\n```\n\n```configs\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\n" + configs + "\n```\n\n```tools\n" + tools + "\n```\n\n```edges\n" + edges + "\n```\n\n" + extra + "\n" + } + source := lintSource( + stageWith("implement", "read\nedit", "success -> review\nerror -> #failure", "resume_session=true", "```checks\nnone: focused\n```"), + stageWith("review", "read", "approved -> #success\nrejected -> implement\nerror -> #failure", "resume_session=true", "```limits\n{\"max_visits\":3,\"on\":[\"rejected\"]}\n```"), + ) + _, warns := lintRules(t, source) + joined := strings.Join(warns["resume_session"], "\n") + for _, want := range []string{"stage implement: resume_session: resume_session is supported only by harness=claude", "stage review: resume_session: resume_session on a read-only stage"} { + if !strings.Contains(joined, want) { + t.Fatalf("warnings missing %q:\n%s", want, joined) + } + } + if strings.Contains(joined, "has no effect") { + t.Fatalf("both stages loop:\n%s", joined) + } +} + +func TestParseValidatesExhaustionSettings(t *testing.T) { + base := func(limits string) string { + return lintSource( + modelStage("implement", "Implement.", "read", "success -> review\nerror -> #failure", ""), + modelStage("review", "Review.", "read", "approved -> #success\nrejected -> implement\nerror -> #failure", "```limits\n"+limits+"\n```"), + ) + } + for limits, want := range map[string]string{ + `{"max_visits":3,"on_exhausted":"ask"}`: "on_exhausted must be fail or decide", + `{"max_visits":3,"accept_to":"implement"}`: "accept_to needs", + `{"max_visits":3,"on_exhausted":"decide","accept_to":"nowhere"}`: "accept_to \"nowhere\" is not a stage", + } { + if _, err := Parse(base(limits)); err == nil || !strings.Contains(err.Error(), want) { + t.Fatalf("%s: err = %v, want %q", limits, err, want) + } + } + if _, err := Parse(base(`{"max_visits":3,"on":["rejected"],"on_exhausted":"decide","accept_to":"#success"}`)); err != nil { + t.Fatal(err) + } +} + +func TestParseFindingsGateStage(t *testing.T) { + gate := func(configs, edges string) string { + return lintSource( + modelStage("review", "Review.", "read", "success -> triage\nerror -> #failure", ""), + "# stage triage\n\n```configs\ntype=findings\n"+configs+"\n```\n\n```edges\n"+edges+"\n```\n", + modelStage("fix", "Fix.", "read", "success -> review\nerror -> #failure", ""), + ) + } + g, err := Parse(gate("severity=minor\norigin=any", "open -> fix\nclear -> #success")) + if err != nil { + t.Fatal(err) + } + if g.Stages[1].Type != "findings" { + t.Fatalf("type = %q", g.Stages[1].Type) + } + for _, tc := range []struct{ configs, edges, want string }{ + {"severity=huge", "open -> fix\nclear -> #success", "severity must be"}, + {"origin=old", "open -> fix\nclear -> #success", "origin must be"}, + {"", "open -> fix", "requires an edge for outcome clear"}, + {"", "open -> fix\nclear -> #success\nmaybe -> fix", "outcomes are open and clear"}, + } { + if _, err := Parse(gate(tc.configs, tc.edges)); err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("%+v: err = %v", tc, err) + } + } +} diff --git a/internal/pipeline/retention.go b/internal/pipeline/retention.go index 8fa1df23..d06d9102 100644 --- a/internal/pipeline/retention.go +++ b/internal/pipeline/retention.go @@ -645,6 +645,7 @@ func deleteRunRows(ctx context.Context, tx *sql.Tx, ids []int64) error { {"attention_dismissals", "run_id"}, {"run_schedule_origin", "run_id"}, {"run_stage_skills", "run_id"}, + {"run_loop_state", "run_id"}, {"run_steps", "run_id"}, } { if err := deleteRetentionBatch(ctx, tx, table.name, table.column, ids); err != nil && !missingTable(err) { diff --git a/internal/pipeline/run_loop_state.go b/internal/pipeline/run_loop_state.go new file mode 100644 index 00000000..60177915 --- /dev/null +++ b/internal/pipeline/run_loop_state.go @@ -0,0 +1,91 @@ +package pipeline + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// initRunLoopState records the runner-owned loop state of a run: its findings +// ledger and the extra visits granted to its stages (by a retry with +// --extra-visits or a "continue" exhaustion decision). One row per run, written +// by the runner as the state changes. +func (s *Store) initRunLoopState() error { + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS run_loop_state ( +run_id INTEGER PRIMARY KEY REFERENCES pipeline_runs(id), +findings_json TEXT NOT NULL DEFAULT '[]', +grants_json TEXT NOT NULL DEFAULT '{}')`) + return err +} + +// SetRunFindings replaces a run's findings ledger. +func (s *Store) SetRunFindings(ctx context.Context, runID int64, ledger []protocol.Finding) error { + if ledger == nil { + ledger = []protocol.Finding{} + } + encoded, err := json.Marshal(ledger) + if err != nil { + return err + } + _, err = s.db.ExecContext(ctx, `INSERT INTO run_loop_state(run_id,findings_json) VALUES(?,?) +ON CONFLICT(run_id) DO UPDATE SET findings_json=excluded.findings_json`, runID, string(encoded)) + return err +} + +// SetRunVisitGrants replaces a run's extra-visit grants. +func (s *Store) SetRunVisitGrants(ctx context.Context, runID int64, grants map[string]int) error { + if grants == nil { + grants = map[string]int{} + } + encoded, err := json.Marshal(grants) + if err != nil { + return err + } + _, err = s.db.ExecContext(ctx, `INSERT INTO run_loop_state(run_id,grants_json) VALUES(?,?) +ON CONFLICT(run_id) DO UPDATE SET grants_json=excluded.grants_json`, runID, string(encoded)) + return err +} + +// AddRunVisitGrant adds extra visits for one stage and returns the new grants. +func (s *Store) AddRunVisitGrant(ctx context.Context, runID int64, stageKey string, extra int) (map[string]int, error) { + _, grants, err := runLoopState(ctx, s.db, runID) + if err != nil { + return nil, err + } + if grants == nil { + grants = map[string]int{} + } + grants[stageKey] += extra + return grants, s.SetRunVisitGrants(ctx, runID, grants) +} + +func runLoopState(ctx context.Context, q interface { + QueryRowContext(context.Context, string, ...any) *sql.Row +}, runID int64) ([]protocol.Finding, map[string]int, error) { + var ledgerJSON, grantsJSON string + err := q.QueryRowContext(ctx, `SELECT findings_json,grants_json FROM run_loop_state WHERE run_id=?`, runID).Scan(&ledgerJSON, &grantsJSON) + if errors.Is(err, sql.ErrNoRows) || missingTable(err) { + return nil, nil, nil + } + if err != nil { + return nil, nil, err + } + var ledger []protocol.Finding + if err := json.Unmarshal([]byte(ledgerJSON), &ledger); err != nil { + return nil, nil, err + } + var grants map[string]int + if err := json.Unmarshal([]byte(grantsJSON), &grants); err != nil { + return nil, nil, err + } + if len(ledger) == 0 { + ledger = nil + } + if len(grants) == 0 { + grants = nil + } + return ledger, grants, nil +} diff --git a/internal/pipeline/run_size.go b/internal/pipeline/run_size.go index ea555902..0d0da006 100644 --- a/internal/pipeline/run_size.go +++ b/internal/pipeline/run_size.go @@ -87,6 +87,7 @@ var runDBBytesQuery = func() string { {"retry_checkpoints", "run_id=?1", []string{"mode", "handoff_json", "source_hash"}}, {"run_schedule_origin", "run_id=?1", []string{"name"}}, {"run_stage_skills", "run_id=?1", []string{"skills_json"}}, + {"run_loop_state", "run_id=?1", []string{"findings_json", "grants_json"}}, } terms := make([]string, 0, len(parts)) for _, p := range parts { diff --git a/internal/pipeline/runs.go b/internal/pipeline/runs.go index 823cdf2b..2a49d217 100644 --- a/internal/pipeline/runs.go +++ b/internal/pipeline/runs.go @@ -310,6 +310,9 @@ strftime('%Y-%m-%dT%H:%M:%SZ',started_at),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ' return nil, err } stepSkills(r.Steps, r.StageSkills) + if r.Findings, r.VisitGrants, err = runLoopState(ctx, tx, id); err != nil { + return nil, err + } // 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) diff --git a/internal/pipeline/runs_mutate.go b/internal/pipeline/runs_mutate.go index e1ad0efb..9461d437 100644 --- a/internal/pipeline/runs_mutate.go +++ b/internal/pipeline/runs_mutate.go @@ -279,7 +279,33 @@ JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version } var edges map[string]string found := false + // A loop that exhausted its visits on a stage with on_exhausted=decide + // parks the run on a decision step under that (non-human) stage's key; its + // evidence carries the option targets. + var exhausted map[string]any + var latestOutput string + if err := tx.QueryRowContext(ctx, `SELECT output_json FROM run_steps WHERE run_id=? AND stage_key=? ORDER BY sequence DESC LIMIT 1`, id, stageKey).Scan(&latestOutput); err == nil { + var evidence map[string]any + if json.Unmarshal([]byte(latestOutput), &evidence) == nil { + if exhausted = protocol.ExhaustedInfo(evidence); exhausted != nil { + edges = map[string]string{} + if targets, ok := exhausted["targets"].(map[string]any); ok { + for option, target := range targets { + if text, ok := target.(string); ok { + edges[option] = text + } + } + } + found = true + } + } + } else if err != sql.ErrNoRows { + return protocol.RunStep{}, false, err + } for _, declared := range graph.Stages { + if exhausted != nil { + break + } if declared.Key == stageKey { if stage.EffectiveType(declared.Type) != stage.HumanType { return protocol.RunStep{}, false, fmt.Errorf("stage %s is not a human decision stage", stageKey) @@ -327,6 +353,11 @@ JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version // successful decision is not presented as a stop or error; the derived // verdict reads the feedback as the step's reason. output := map[string]any{protocol.DecisionOptionKey: option, protocol.DecisionFeedbackKey: feedback} + if exhausted != nil { + // Keep the marker: a decided exhaustion step is a decision, never a + // visit, when the run's state is rebuilt from its steps. + output[protocol.ExhaustedKey] = exhausted + } encoded, err := json.Marshal(output) if err != nil { return protocol.RunStep{}, false, err diff --git a/internal/pipeline/skills.go b/internal/pipeline/skills.go index f1b44f5c..997ac889 100644 --- a/internal/pipeline/skills.go +++ b/internal/pipeline/skills.go @@ -23,6 +23,9 @@ CREATE TABLE IF NOT EXISTS skill_files (name TEXT NOT NULL, version INTEGER NOT if err != nil { return err } + if err := s.initRunLoopState(); err != nil { + return err + } return s.initStageSkills() } diff --git a/internal/protocol/artifact_group.go b/internal/protocol/artifact_group.go index c0556ee2..94c17872 100644 --- a/internal/protocol/artifact_group.go +++ b/internal/protocol/artifact_group.go @@ -13,7 +13,7 @@ const ( // TurnArtifactNames are the files the server itself writes into a model visit's // turn directory. They are always debugging files. -var TurnArtifactNames = []string{"input.md", "memory.md", "history.md", "output.md", "session.html"} +var TurnArtifactNames = []string{"input.md", "memory.md", "history.md", "findings.md", "output.md", "session.html"} // IsDebug reports whether the artifact is a runner-internal debugging file. func (a StageArtifact) IsDebug() bool { return a.Group == ArtifactGroupDebug } diff --git a/internal/protocol/findings.go b/internal/protocol/findings.go new file mode 100644 index 00000000..970a459b --- /dev/null +++ b/internal/protocol/findings.go @@ -0,0 +1,64 @@ +package protocol + +// Finding is one item of a run's findings ledger. The runner owns the ledger: +// stages report new findings and status changes in an output.md "# findings" +// section, and the runner assigns the stable ID (F1, F2, ...), keeps the latest +// status and records every change as an event. +type Finding struct { + ID string `json:"id"` + Severity string `json:"severity"` + Origin string `json:"origin"` + Location string `json:"location,omitempty"` + Summary string `json:"summary"` + Status string `json:"status"` + // Reason is the latest status change's reason. + Reason string `json:"reason,omitempty"` + RaisedBy string `json:"raised_by"` + RaisedSequence int `json:"raised_sequence"` + UpdatedBy string `json:"updated_by,omitempty"` + UpdatedSequence int `json:"updated_sequence,omitempty"` + Events []FindingEvent `json:"events,omitempty"` +} + +// FindingEvent is one status change of a finding, in the visit that made it. +type FindingEvent struct { + Sequence int `json:"sequence"` + Stage string `json:"stage"` + Status string `json:"status"` + Reason string `json:"reason,omitempty"` +} + +// Finding severities (most severe first), statuses and origins. +const ( + SeverityCritical = "critical" + SeverityImportant = "important" + SeverityMinor = "minor" + SeverityNit = "nit" + + FindingOpen = "open" + FindingFixed = "fixed" + FindingDismissed = "dismissed" + FindingSettled = "settled" + + OriginIntroduced = "introduced" + OriginPreExisting = "pre-existing" +) + +// ExhaustedKey marks a waiting (then decided) step the runner created when a +// loop exhausted its visits on a stage with on_exhausted=decide. The value is a +// map with stage, visit, max_visits and targets (option -> target). Such a step +// is a decision, never a stage visit. +const ExhaustedKey = "exhausted" + +// Exhaustion decision options. +const ( + ExhaustedAccept = "accept" + ExhaustedContinue = "continue" + ExhaustedAbort = "abort" +) + +// ExhaustedInfo reads the exhaustion marker from a step output, or nil. +func ExhaustedInfo(output map[string]any) map[string]any { + info, _ := output[ExhaustedKey].(map[string]any) + return info +} diff --git a/internal/protocol/message.go b/internal/protocol/message.go index f856d401..3e726239 100644 --- a/internal/protocol/message.go +++ b/internal/protocol/message.go @@ -50,6 +50,12 @@ type Stage struct { type StageLimits struct { MaxVisits int `json:"max_visits"` On []string `json:"on,omitempty"` + // OnExhausted is "fail" (the default) or "decide": the runner parks the run + // on an operator decision (accept / continue / abort) instead of failing + // when this stage's loop exhausts its visits. + OnExhausted string `json:"on_exhausted,omitempty"` + // AcceptTo is the target of the "accept" decision (default #success). + AcceptTo string `json:"accept_to,omitempty"` } type NotificationPolicy struct { @@ -208,6 +214,11 @@ type Message struct { RetryVisit int `json:"retry_visit,omitempty"` RetryVersion int `json:"retry_version,omitempty"` RetryInput map[string]any `json:"retry_input,omitempty"` + // RetryExtraVisits (1-5) grants extra visits to a resumed loop: to + // RetryExtraStage when set, otherwise to the stage(s) that exhausted their + // visits. The resume continues the exhausted loop instead of failing again. + RetryExtraVisits int `json:"retry_extra_visits,omitempty"` + RetryExtraStage string `json:"retry_extra_stage,omitempty"` // Search is the broad, read-only search traffic over pipelines, versions, // runs, steps, field text and artifacts. See search.go for the per-type // payloads and the ranking/kind/bound vocabulary. diff --git a/internal/protocol/runs.go b/internal/protocol/runs.go index 27d3129c..629634e0 100644 --- a/internal/protocol/runs.go +++ b/internal/protocol/runs.go @@ -532,6 +532,11 @@ type RunDetail struct { // run's stages, stage services and checks ran with: files and variable // names only, never values. Absent for runs that predate it. Environment *RunEnvironment `json:"environment,omitempty"` + // Findings is the run's runner-owned findings ledger, in ID order. + Findings []Finding `json:"findings,omitempty"` + // VisitGrants are extra visits per stage granted by a retry with + // --extra-visits or a "continue" exhaustion decision. + VisitGrants map[string]int `json:"visit_grants,omitempty"` } // RunEnvironment is the directory environment a run resolved for its diff --git a/internal/server/artifacts.go b/internal/server/artifacts.go index 2f31970a..1e849a1f 100644 --- a/internal/server/artifacts.go +++ b/internal/server/artifacts.go @@ -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", "history.md", "output.md", "session.html"} { + for _, name := range []string{"input.md", "memory.md", "history.md", "findings.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) diff --git a/internal/server/loop_control_test.go b/internal/server/loop_control_test.go new file mode 100644 index 00000000..309a02ae --- /dev/null +++ b/internal/server/loop_control_test.go @@ -0,0 +1,238 @@ +package server + +import ( + "context" + "errors" + "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" +) + +// loopSource is implement -> review, with review's rejected looping back. +// extraReview is spliced into the review stage (limits etc.). +func loopSource(extraReview string) string { + source := pipeline.Template([]string{"implement", "review"}, true) + source = strings.Replace(source, "# stage review", "# stage review\n\n"+extraReview, 1) + return strings.Replace(source, "success -> #success", "success -> #success\nrejected -> implement", 1) +} + +func loopRunner(t *testing.T, source string) (*runner, *pipeline.Store, int64) { + t.Helper() + ctx := context.Background() + store, err := pipeline.Open(filepath.Join(t.TempDir(), "run.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { store.Close() }) + if _, err := store.Submit(ctx, "loop", source); err != nil { + t.Fatal(err) + } + items, _ := store.List(ctx) + r, err := newRunnerAt(ctx, store, t.TempDir()) + if err != nil { + t.Fatal(err) + } + return r, store, items[0].ID +} + +func markdown(text string) stage.Result { + outcome := strings.TrimSpace(strings.SplitN(strings.TrimPrefix(text, "# outcome\n"), "\n", 2)[0]) + return stage.Result{Outcome: outcome, Output: stage.Values{"markdown": text}} +} + +// TestFindingsLedgerAndGateRouteTheLoop runs implement -> review -> triage +// (a findings gate) and checks the ledger: stable IDs, status changes from a +// later visit, the ledger in memory.md and findings.md, a dismissed finding a +// reviewer re-raises staying dismissed, and the gate routing mechanically. +func TestFindingsLedgerAndGateRouteTheLoop(t *testing.T) { + source := pipeline.Template([]string{"implement", "review"}, true) + source = strings.Replace(source, "success -> #success", "success -> triage", 1) + source += "# stage triage\n\n```limits\n{\"max_visits\":3}\n```\n\n```configs\ntype=findings\nseverity=important\norigin=introduced\n```\n\n```edges\nopen -> implement\nclear -> #success\n```\n" + r, store, pipelineID := loopRunner(t, source) + calls := map[string]int{} + var implementMemory, implementLedgerFile string + r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) { + calls[def.Key]++ + switch { + case def.Key == "implement" && calls["implement"] == 2: + memory, _ := os.ReadFile(def.Turn.Memory) + implementMemory = string(memory) + ledger, _ := os.ReadFile(filepath.Join(def.Turn.Dir, "findings.md")) + implementLedgerFile = string(ledger) + return markdown("# outcome\nsuccess\n\n# handoff\nFixed F1.\n\n# findings\n- F1 fixed: added the eviction\n- F2 dismissed: style only\n"), nil + case def.Key == "implement": + return markdown("# outcome\nsuccess\n\n# handoff\nDone.\n"), nil + case calls["review"] == 1: + return markdown("# outcome\nsuccess\n\n# handoff\nTwo findings.\n\n# findings\n- important introduced cache.go:42: eviction never runs\n- important pre-existing util.go:7: odd helper\n- nit introduced cache.go:1: naming\n"), nil + default: + // Re-raises the dismissed F2: it must stay dismissed. + return markdown("# outcome\nsuccess\n\n# handoff\nLooks good.\n\n# findings\n- important pre-existing util.go:7: odd helper\n"), nil + } + } + run := startRun(t, r, pipelineID, "findings") + detail, err := store.GetRun(context.Background(), run.ID) + if err != nil { + t.Fatal(err) + } + if detail.Status != "succeeded" || calls["implement"] != 2 || calls["review"] != 2 { + t.Fatalf("status %s calls %v diag %q", detail.Status, calls, detail.Diagnostic) + } + var routes []string + for _, step := range detail.Steps { + if step.Stage == "triage" { + routes = append(routes, step.Outcome+"->"+step.Target) + } + } + if strings.Join(routes, ",") != "open->implement,clear->#success" { + t.Fatalf("gate routes %v", routes) + } + status := map[string]string{} + for _, item := range detail.Findings { + status[item.ID] = item.Status + } + if len(detail.Findings) != 3 || status["F1"] != "fixed" || status["F2"] != "dismissed" || status["F3"] != "open" { + t.Fatalf("ledger %+v", detail.Findings) + } + if !strings.Contains(implementMemory, "## Findings ledger (runner-owned)") || !strings.Contains(implementMemory, "F1 · important · introduced · cache.go:42 — eviction never runs") || !strings.Contains(implementMemory, "never re-raise") { + t.Fatalf("implement memory lacks the ledger:\n%s", implementMemory) + } + if !strings.Contains(implementLedgerFile, "# Findings ledger") || !strings.Contains(implementLedgerFile, "F2 · important · pre-existing") { + t.Fatalf("findings.md:\n%s", implementLedgerFile) + } +} + +// TestExhaustedLoopAsksTheOperator covers on_exhausted=decide: the last allowed +// review asks for another round, the run waits on a decision, "continue" grants +// one more visit and "accept" finishes the run. +func TestExhaustedLoopAsksTheOperator(t *testing.T) { + r, store, pipelineID := loopRunner(t, loopSource("```limits\n{\"max_visits\":2,\"on\":[\"rejected\"],\"on_exhausted\":\"decide\"}\n```")) + calls := map[string]int{} + r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) { + calls[def.Key]++ + if def.Key == "review" { + return markdown("# outcome\nrejected\n\n# handoff\nStill wrong.\n"), nil + } + return markdown("# outcome\nsuccess\n\n# handoff\nDone.\n"), nil + } + run := startRun(t, r, pipelineID, "exhausted") + ctx := context.Background() + detail, _ := store.GetRun(ctx, run.ID) + last := detail.Steps[len(detail.Steps)-1] + if detail.Status != protocol.RunStatusWaiting || last.Status != protocol.StepStatusWaiting || last.Stage != "review" || protocol.ExhaustedInfo(last.Output) == nil { + t.Fatalf("not waiting on an exhaustion decision: %s %+v", detail.Status, last) + } + if got := strings.Join(protocol.WaitingOptions(last.Output), ","); got != "abort,accept,continue" { + t.Fatalf("options %s", got) + } + if _, err := r.decide(protocol.Message{RunID: run.ID, Option: "continue"}); err != nil { + t.Fatal(err) + } + r.wg.Wait() + detail, _ = store.GetRun(ctx, run.ID) + if detail.Status != protocol.RunStatusWaiting || calls["review"] != 3 || calls["implement"] != 3 { + t.Fatalf("one more round did not run: %s calls %v", detail.Status, calls) + } + if detail.VisitGrants["review"] != 1 || detail.VisitGrants["implement"] != 1 { + t.Fatalf("grants %v", detail.VisitGrants) + } + if _, err := r.decide(protocol.Message{RunID: run.ID, Option: "accept"}); err != nil { + t.Fatal(err) + } + r.wg.Wait() + detail, _ = store.GetRun(ctx, run.ID) + if detail.Status != "succeeded" { + t.Fatalf("accept did not finish the run: %s %q", detail.Status, detail.Diagnostic) + } +} + +// TestRetryWithExtraVisitsContinuesTheLoop retries a run whose review loop was +// exhausted: without extra visits the retry fails again at once; with +// --extra-visits it continues at the implementer and the next review approves. +func TestRetryWithExtraVisitsContinuesTheLoop(t *testing.T) { + r, store, pipelineID := loopRunner(t, loopSource("```limits\n{\"max_visits\":2,\"on\":[\"rejected\"]}\n```")) + calls := map[string]int{} + approve := false + r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) { + calls[def.Key]++ + if def.Key == "review" { + if approve { + return markdown("# outcome\nsuccess\n\n# handoff\nApproved.\n"), nil + } + return markdown("# outcome\nrejected\n\n# handoff\nStill wrong.\n\n# findings\n- important introduced a.go:1: still wrong\n"), nil + } + return markdown("# outcome\nsuccess\n\n# handoff\nDone.\n"), nil + } + run := startRun(t, r, pipelineID, "extra") + ctx := context.Background() + detail, _ := store.GetRun(ctx, run.ID) + if detail.Status != "failed" || calls["review"] != 2 { + t.Fatalf("source run: %s %v", detail.Status, calls) + } + if _, err := r.retry(protocol.Message{RunID: run.ID, RequestKey: "x", RetryExtraVisits: 9}); err == nil { + t.Fatal("extra visits over the bound accepted") + } + if _, err := r.retry(protocol.Message{RunID: run.ID, RequestKey: "y", RetryExtraVisits: 1, RetryExtraStage: "nope"}); err == nil { + t.Fatal("unknown extra-visits stage accepted") + } + approve = true + retried, err := r.retry(protocol.Message{RunID: run.ID, RequestKey: "retry-extra", RetryExtraVisits: 1}) + if err != nil { + t.Fatal(err) + } + r.wg.Wait() + detail, _ = store.GetRun(ctx, retried.ID) + if detail.Status != "succeeded" || calls["implement"] != 3 || calls["review"] != 3 { + t.Fatalf("retry: %s %q calls %v", detail.Status, detail.Diagnostic, calls) + } + if detail.Steps[0].Stage != "implement" || detail.VisitGrants["review"] != 1 { + t.Fatalf("retry did not continue at the implementer with a review grant: %+v %v", detail.Steps[0], detail.VisitGrants) + } + if len(detail.Findings) != 1 || detail.Findings[0].ID != "F1" { + t.Fatalf("retry did not inherit the ledger: %+v", detail.Findings) + } +} + +// TestRetryCarriesThePartialWorkOfTheFailedVisit checks that the retried +// visit receives the failed visit's private/ files and output.md under +// previous-attempt/ and that its input.md names them. +func TestRetryCarriesThePartialWorkOfTheFailedVisit(t *testing.T) { + r, store, pipelineID := loopRunner(t, pipeline.Template([]string{"implement"}, true)) + fail := true + var retriedInput, carried string + r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) { + if fail { + _ = os.WriteFile(filepath.Join(def.Turn.Private, "notes.md"), []byte("half done: parser rewritten"), 0o600) + _ = os.WriteFile(def.Turn.Output, []byte("# outcome\nsuccess\n\npartial"), 0o600) + return stage.Result{}, errors.New("timed out") + } + input, _ := os.ReadFile(def.Turn.Input) + retriedInput = string(input) + notes, _ := os.ReadFile(filepath.Join(def.Turn.Dir, "previous-attempt", "private", "notes.md")) + carried = string(notes) + return markdown("# outcome\nsuccess\n\n# handoff\nFinished.\n"), nil + } + run := startRun(t, r, pipelineID, "carry") + fail = false + retried, err := r.retry(protocol.Message{RunID: run.ID, RequestKey: "carry-retry"}) + if err != nil { + t.Fatal(err) + } + r.wg.Wait() + detail, _ := store.GetRun(context.Background(), retried.ID) + if detail.Status != "succeeded" { + t.Fatalf("retry %s %q", detail.Status, detail.Diagnostic) + } + if carried != "half done: parser rewritten" { + t.Fatalf("private notes not carried: %q", carried) + } + for _, want := range []string{"# Previous attempt", "## Partial work from the failed attempt", "- output.md (", "- private/notes.md ("} { + if !strings.Contains(retriedInput, want) { + t.Fatalf("input.md missing %q:\n%s", want, retriedInput) + } + } +} diff --git a/internal/server/loop_state.go b/internal/server/loop_state.go new file mode 100644 index 00000000..6a881f56 --- /dev/null +++ b/internal/server/loop_state.go @@ -0,0 +1,278 @@ +package server + +import ( + "context" + "fmt" + "log" + "os" + "path/filepath" + "strings" + "time" + + "git.a-wan.net/alan/pipelines/internal/findings" + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" + "git.a-wan.net/alan/pipelines/internal/turn" +) + +// Loop control: per-stage visit caps (raised by grants), the findings ledger, +// mechanical findings gates and operator decisions on exhausted loops. + +const ( + // maxStageVisits is the global per-stage visit cap before grants. + maxStageVisits = 5 + // maxRunSteps is the global step cap before grants. + maxRunSteps = 30 + // maxExtraVisits bounds one grant (a retry's --extra-visits). + maxExtraVisits = 5 + // maxRunStepsWithGrants is the absolute step cap however much is granted. + maxRunStepsWithGrants = 120 +) + +func graphHasStage(g protocol.Graph, key string) bool { + for _, s := range g.Stages { + if s.Key == key { + return true + } + } + return false +} + +// visitCaps returns a stage's effective max_visits and hard per-stage cap, +// both raised by the extra visits granted to it. +func (s *runState) visitCaps(selected protocol.Stage) (limit, hard int) { + limit = maxStageVisits + if selected.Limits != nil { + limit = selected.Limits.MaxVisits + } + extra := s.grants[selected.Key] + return limit + extra, maxStageVisits + extra +} + +// stepLimit is the run's total step cap: 30 plus, for every granted visit, +// room for one more pass through the graph, bounded. +func (s *runState) stepLimit(graph protocol.Graph) int { + total := maxRunSteps + for _, extra := range s.grants { + total += extra * max(len(graph.Stages), 1) + } + return min(total, maxRunStepsWithGrants) +} + +// grant adds extra visits to each named stage. +func (s *runState) grant(stages []string, extra int) { + if s.grants == nil { + s.grants = map[string]int{} + } + for _, key := range stages { + s.grants[key] += extra + } +} + +// exhaustedContinuation turns the last step of a run that a visit cap stopped +// into the checkpoint that continues its loop: the stage the routing was +// heading to, with the stopped step's output as its input. ok is false when +// the run did not stop on a cap. +func exhaustedContinuation(last protocol.RunStep) (protocol.RunStep, bool) { + if last.Status != "completed" { + return last, false + } + target := last.Target + if last.Control != nil && last.Control.LimitReached && last.Control.ModelTarget != "" { + target = last.Control.ModelTarget + } + if target == "" || protocol.IsTerminal(target) { + return last, false + } + input := last.Output + if input == nil { + input = map[string]any{} + } + return protocol.RunStep{Sequence: last.Sequence + 1, Stage: target, Status: "failed", Target: protocol.FailureEnd, Input: input}, true +} + +// exhaustedStages are the non-human stages whose next visit their caps refuse, +// plus next (the stage the run continues with) when nothing else is. +func exhaustedStages(graph protocol.Graph, state *runState, next string) []string { + var out []string + for _, declared := range graph.Stages { + if stage.EffectiveType(declared.Type) == stage.HumanType { + continue + } + limit, hard := state.visitCaps(declared) + if visits := state.visits[declared.Key]; visits > 0 && (visits >= limit || visits >= hard) { + out = append(out, declared.Key) + } + } + if len(out) == 0 && next != "" { + out = append(out, next) + } + return out +} + +// applyLimitOn applies a stage's limits.on on its last allowed visit: a listed +// outcome is kept but routed to #failure, or, with on_exhausted=decide, keeps +// its route and the caller parks the run on an operator decision (park true). +func applyLimitOn(step *protocol.RunStep, selected protocol.Stage, visit, maxVisits int) (park bool) { + if selected.Limits == nil || visit < maxVisits || step.Target == "" || protocol.IsTerminal(step.Target) { + return false + } + for _, outcome := range selected.Limits.On { + if outcome != step.Outcome { + continue + } + step.Control.LimitReached = true + step.Control.ModelTarget = step.Target + if decidesOnExhaustion(selected) { + return true + } + step.Target = protocol.FailureEnd + step.Diagnostic = fmt.Sprintf("Pipelines stopped %s after %d visits on outcome %s", selected.Key, maxVisits, step.Outcome) + return false + } + return false +} + +// isExhaustionStep reports whether a recorded step is a runner-created +// exhaustion decision rather than a stage visit. +func isExhaustionStep(step protocol.RunStep) bool { + return protocol.ExhaustedInfo(step.Output) != nil +} + +func decidesOnExhaustion(s protocol.Stage) bool { + return s.Limits != nil && s.Limits.OnExhausted == "decide" +} + +// parkExhausted parks the run on an operator decision because stage selected +// exhausted its visits: accept the work as it is (accept_to, default +// #success), continue for one more round (continueTo, with one more visit +// granted) or abort. It mirrors a human stage's wait: one waiting step and no +// live goroutine; the decision resumes the run through decide. +func (r *runner) parkExhausted(ctx context.Context, id int64, name, workspace string, state *runState, sequence int, selected protocol.Stage, visit, maxVisits int, continueTo string) error { + accept := protocol.SuccessEnd + if selected.Limits != nil && selected.Limits.AcceptTo != "" { + accept = selected.Limits.AcceptTo + } + targets := map[string]any{protocol.ExhaustedAccept: accept, protocol.ExhaustedContinue: continueTo, protocol.ExhaustedAbort: protocol.FailureEnd} + prompt := fmt.Sprintf("Stage %s used its %d allowed visits and the loop is not finished. Choose accept to take the work as it is (continues to %s), continue for one more round (one more visit; continues to %s), or abort to fail the run.", selected.Key, maxVisits, accept, continueTo) + options := []string{protocol.ExhaustedAbort, protocol.ExhaustedAccept, protocol.ExhaustedContinue} + evidence := protocol.NewWaitingEvidence(prompt, options) + evidence[protocol.ExhaustedKey] = map[string]any{"stage": selected.Key, "visit": visit, "max_visits": maxVisits, "targets": targets} + if err := r.store.BeginStep(ctx, id, sequence, selected.Key, state.input); err != nil { + return err + } + state.nextSequence = sequence + 1 + r.mu.Lock() + if err := r.store.MarkWaiting(ctx, id, sequence, selected.Key, evidence); err != nil { + r.mu.Unlock() + return err + } + r.emitRun(protocol.RunEventFrame{ + RunID: id, + Workspace: workspace, + Status: protocol.RunStatusWaiting, + CurrentStage: selected.Key, + CompletedSteps: state.completed, + Step: &protocol.RunStepDelta{Sequence: sequence, Stage: selected.Key, Status: protocol.StepStatusWaiting}, + }, false) + delete(r.active, id) + r.mu.Unlock() + r.deliverRunNotificationBatch(time.Now(), 1) + return nil +} + +// grantForDecision records the extra visit a "continue" exhaustion decision +// allows: one more visit for the exhausted stage and for the stage the loop +// continues with. +func (r *runner) grantForDecision(ctx context.Context, detail *protocol.RunDetail, step protocol.RunStep) { + info := protocol.ExhaustedInfo(step.Output) + if info == nil || step.Outcome != protocol.ExhaustedContinue { + return + } + stages := []string{} + if key, ok := info["stage"].(string); ok && key != "" { + stages = append(stages, key) + } + if step.Target != "" && !protocol.IsTerminal(step.Target) && (len(stages) == 0 || stages[0] != step.Target) { + stages = append(stages, step.Target) + } + for _, key := range stages { + grants, err := r.store.AddRunVisitGrant(ctx, detail.ID, key, 1) + if err != nil { + log.Printf("run %d: grant a visit to %s: %v", detail.ID, key, err) + continue + } + detail.VisitGrants = grants + } +} + +// recordFindings folds a completed visit's "# findings" section into the run's +// ledger and persists it. A ledger write failure is logged, never fatal: the +// stage's own output keeps the findings. +func (r *runner) recordFindings(id int64, state *runState, step protocol.RunStep) { + markdown, _ := step.Output["markdown"].(string) + report := findings.Parse(markdown) + if len(report.New) == 0 && len(report.Changes) == 0 { + return + } + ledger, outcome := findings.Apply(state.findings, report, step.Stage, step.Sequence) + state.findings = ledger + if len(outcome.Ignored) > 0 { + log.Printf("run %d stage %s #%d: findings ignored: %s", id, step.Stage, step.Sequence, strings.Join(outcome.Ignored, "; ")) + } + r.persistFindings(id, ledger) +} + +func (r *runner) persistFindings(id int64, ledger []protocol.Finding) { + save, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := r.store.SetRunFindings(save, id, ledger); err != nil { + log.Printf("run %d: save findings ledger: %v", id, err) + } +} + +func (r *runner) persistGrants(id int64, grants map[string]int) { + save, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := r.store.SetRunVisitGrants(save, id, grants); err != nil { + log.Printf("run %d: save visit grants: %v", id, err) + } +} + +// findingsGateStep evaluates a findings stage against the ledger. +func findingsGateStep(def stage.Definition, state *runState, sequence int) protocol.RunStep { + gate, _ := stage.FindingsGate(def) + matched := gate.Matching(state.findings) + outcome := stage.FindingsClear + reason := fmt.Sprintf("No open findings at %s or above (origin %s).", gate.MinSeverity, gate.Origin) + ids := make([]string, 0, len(matched)) + for _, item := range matched { + ids = append(ids, item.ID) + } + if len(matched) > 0 { + outcome = stage.FindingsOpen + reason = fmt.Sprintf("%d open finding(s) at %s or above (origin %s): %s.", len(matched), gate.MinSeverity, gate.Origin, strings.Join(ids, ", ")) + } + return protocol.RunStep{ + Sequence: sequence, + Stage: def.Key, + Status: "completed", + Outcome: outcome, + Output: stage.Values{"summary": reason, "findings": ids}, + Target: def.Edges[outcome], + Verdict: &protocol.StageVerdict{Reason: reason, ReasonSource: protocol.VerdictReasonFallback}, + } +} + +// writeFindingsFile writes the visit's findings.md (the whole ledger) next to +// memory.md when the run has a ledger. +func writeFindingsFile(paths turn.Paths, ledger []protocol.Finding) error { + if len(ledger) == 0 { + return nil + } + name := filepath.Join(paths.TurnDir, "findings.md") + if err := os.WriteFile(name, []byte(findings.RenderFile(ledger)), 0o600); err != nil { + return fmt.Errorf("write %s: %w", name, err) + } + return nil +} diff --git a/internal/server/retry_carry.go b/internal/server/retry_carry.go new file mode 100644 index 00000000..79561faf --- /dev/null +++ b/internal/server/retry_carry.go @@ -0,0 +1,107 @@ +package server + +import ( + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "sort" + "strings" + "syscall" +) + +// Bounds on the partial work a retried visit inherits from the failed one. +const ( + carryMaxFiles = 200 + carryMaxFileBytes = 1 << 20 + carryMaxTotal = 8 << 20 + carryDir = "previous-attempt" +) + +// carryPartialWork copies a failed visit's output.md and private/ files +// (bounded) into the retried visit's turn directory under previous-attempt/ +// and returns the markdown that tells the stage about them, or "" when there +// was nothing to carry. Symlinks and special files are skipped; the source is +// read through os.Root so nothing outside the failed turn is reachable. +func carryPartialWork(sourceTurn, targetTurn string) string { + source, err := os.OpenRoot(sourceTurn) + if err != nil { + return "" + } + defer source.Close() + var names []string + if info, err := source.Lstat("output.md"); err == nil && info.Mode().IsRegular() { + names = append(names, "output.md") + } + skipped := 0 + _ = fs.WalkDir(source.FS(), "private", func(name string, entry fs.DirEntry, walkErr error) error { + if walkErr != nil { + return nil + } + if entry.Type().IsRegular() { + names = append(names, name) + } + return nil + }) + sort.Strings(names[min(1, len(names)):]) + target := filepath.Join(targetTurn, carryDir) + var copied []string + total := int64(0) + for _, name := range names { + if len(copied) >= carryMaxFiles { + skipped++ + continue + } + info, err := source.Lstat(name) + if err != nil || !info.Mode().IsRegular() || info.Size() > carryMaxFileBytes || total+info.Size() > carryMaxTotal { + skipped++ + continue + } + if err := copyCarried(source, name, filepath.Join(target, filepath.FromSlash(name))); err != nil { + skipped++ + continue + } + total += info.Size() + copied = append(copied, fmt.Sprintf("%s (%d bytes)", name, info.Size())) + } + if len(copied) == 0 { + return "" + } + var b strings.Builder + b.WriteString("\n## Partial work from the failed attempt\n\n") + fmt.Fprintf(&b, "The failed visit's output.md and private/ files are copied, read-only, into %s:\n\n", target) + for _, line := range copied { + b.WriteString("- " + line + "\n") + } + if skipped > 0 { + fmt.Fprintf(&b, "- … %d more not copied (over the size or count bound)\n", skipped) + } + b.WriteString("\nReuse what is still valid instead of redoing it.\n") + return b.String() +} + +func copyCarried(source *os.Root, name, destination string) error { + if path.Clean(name) != name || strings.HasPrefix(name, "../") { + return errors.New("invalid name") + } + src, err := source.OpenFile(name, os.O_RDONLY|syscall.O_NOFOLLOW, 0) + if err != nil { + return err + } + defer src.Close() + if err := os.MkdirAll(filepath.Dir(destination), 0o700); err != nil { + return err + } + dst, err := os.OpenFile(destination, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) + if err != nil { + return err + } + _, copyErr := io.Copy(dst, io.LimitReader(src, carryMaxFileBytes)) + if closeErr := dst.Close(); copyErr == nil { + copyErr = closeErr + } + return copyErr +} diff --git a/internal/server/runner.go b/internal/server/runner.go index c2b8330a..6d48f1ed 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -16,6 +16,7 @@ import ( "git.a-wan.net/alan/pipelines/internal/claude" "git.a-wan.net/alan/pipelines/internal/filediff" + "git.a-wan.net/alan/pipelines/internal/findings" "git.a-wan.net/alan/pipelines/internal/harness" "git.a-wan.net/alan/pipelines/internal/opencode" "git.a-wan.net/alan/pipelines/internal/pipeline" @@ -415,7 +416,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc } if created { if request.RetrySource > 0 && request.RetryMode != "restart" { - checkpoint, checkpointErr := r.retrySourceCheckpointSelected(request.RetrySource, d, request.RetryStage, request.RetryVisit, request.RetryInput) + checkpoint, checkpointErr := r.retrySourceCheckpointSelected(request.RetrySource, d, request.RetryStage, request.RetryVisit, request.RetryInput, request.RetryExtraVisits) if checkpointErr != nil { return nil, checkpointErr } @@ -758,10 +759,10 @@ func retryStageContractEqual(left, right protocol.Stage) bool { } func (r *runner) retrySourceCheckpoint(sourceID int64, pinned *protocol.PipelineDetail) (retryCheckpoint, error) { - return r.retrySourceCheckpointSelected(sourceID, pinned, "", 0, nil) + return r.retrySourceCheckpointSelected(sourceID, pinned, "", 0, nil, 0) } -func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.PipelineDetail, selectedStage string, selectedVisit int, override map[string]any) (retryCheckpoint, error) { +func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.PipelineDetail, selectedStage string, selectedVisit int, override map[string]any, extraVisits int) (retryCheckpoint, error) { source, err := r.store.GetRun(r.ctx, sourceID) if err != nil { return retryCheckpoint{}, err @@ -777,6 +778,13 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol. return retryCheckpoint{}, fmt.Errorf("retry source %d has no failed stage checkpoint", sourceID) } failed := source.Steps[len(source.Steps)-1] + if extraVisits > 0 && selectedStage == "" && !interrupted { + // More visits for an exhausted loop: continue the loop where the cap + // stopped it instead of re-running the visit that hit it. + if next, ok := exhaustedContinuation(failed); ok { + failed = next + } + } if interrupted && selectedStage == "" { // A server stop interrupts a run mid-visit (the visit is recorded as // interrupted, with the input it began with) or between visits (the @@ -846,6 +854,9 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol. // stage's memory bindings must be resolved from the original prefix before // this override is applied at invocation time. handoff = map[string]any{"input": failed.Input, "override": override, "sequence": failed.Sequence, "stage": failed.Stage, "visit": failed.Sequence} + if extraVisits > 0 { + handoff["extra_visits"] = extraVisits + } prefix, prefixRecords, prefixErr := r.retryPrefix(sourceID, source, failed.Sequence) if prefixErr != nil { return retryCheckpoint{}, prefixErr @@ -971,6 +982,20 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) { if mode != "resume" && mode != "restart" { return nil, fmt.Errorf("retry mode must be resume or restart") } + if request.RetryExtraVisits < 0 || request.RetryExtraVisits > maxExtraVisits { + return nil, fmt.Errorf("extra visits must be from 1 to %d", maxExtraVisits) + } + if request.RetryExtraVisits > 0 && (mode != "resume" || request.RetryStage != "" || request.RetryVisit > 0) { + return nil, fmt.Errorf("extra visits continue the exhausted loop; they cannot be combined with --mode=restart or a selected stage visit") + } + if request.RetryExtraStage != "" { + if request.RetryExtraVisits == 0 { + return nil, fmt.Errorf("an extra-visits stage needs extra visits") + } + if !graphHasStage(original.Graph, request.RetryExtraStage) { + return nil, fmt.Errorf("stage %q is not part of run %d", request.RetryExtraStage, original.ID) + } + } version := original.Version if request.RetryVersion > 0 { version = request.RetryVersion @@ -980,7 +1005,7 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) { return nil, err } if mode == "resume" { - if _, err := r.retrySourceCheckpointSelected(original.ID, d, request.RetryStage, request.RetryVisit, request.RetryInput); err != nil { + if _, err := r.retrySourceCheckpointSelected(original.ID, d, request.RetryStage, request.RetryVisit, request.RetryInput, request.RetryExtraVisits); err != nil { return nil, err } } @@ -988,7 +1013,7 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) { if notifyMode == "" { notifyMode, _ = r.store.RunNotifyMode(r.ctx, original.ID) } - return r.start(protocol.Message{PipelineID: original.PipelineID, Version: version, RequestKey: request.RequestKey, RetryMode: mode, RetrySource: original.ID, RetryStage: request.RetryStage, RetryVisit: request.RetryVisit, RetryInput: request.RetryInput, Workspace: original.Workspace, Input: original.Input, AllowTools: original.AllowTools, WritePaths: original.WritePaths, Model: original.Model, StageModels: original.StageModels, NotifyMode: notifyMode, OutputFormat: original.OutputFormat}, original.ID) + return r.start(protocol.Message{PipelineID: original.PipelineID, Version: version, RequestKey: request.RequestKey, RetryMode: mode, RetrySource: original.ID, RetryStage: request.RetryStage, RetryVisit: request.RetryVisit, RetryInput: request.RetryInput, RetryExtraVisits: request.RetryExtraVisits, RetryExtraStage: request.RetryExtraStage, Workspace: original.Workspace, Input: original.Input, AllowTools: original.AllowTools, WritePaths: original.WritePaths, Model: original.Model, StageModels: original.StageModels, NotifyMode: notifyMode, OutputFormat: original.OutputFormat}, original.ID) } func (r *runner) cancel(id int64) error { @@ -1066,6 +1091,8 @@ func (r *runner) decide(request protocol.Message) (*protocol.RunDetail, error) { return nil, err } if applied { + // "continue" on an exhausted loop grants the visit it needs. + r.grantForDecision(r.ctx, detail, step) // Re-seed the identity so the resumed frames (this one and the resumed // loop's) carry it even after a restart, when no creation was observed. r.rememberRunIdentity(detail.ID, identityOfRunSummary(detail.RunSummary)) @@ -1107,7 +1134,7 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail, r.finishRunState(id, d.Name, workspace, "failed", "error", err.Error(), 0, 0, "", nil) return } - checkpoint, err := r.retrySourceCheckpointSelected(request.RetrySource, d, request.RetryStage, request.RetryVisit, request.RetryInput) + checkpoint, err := r.retrySourceCheckpointSelected(request.RetrySource, d, request.RetryStage, request.RetryVisit, request.RetryInput, request.RetryExtraVisits) if err != nil { r.finishRunState(id, d.Name, workspace, "failed", "error", err.Error(), 0, 0, "", nil) return @@ -1138,6 +1165,30 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail, r.finishRunState(id, d.Name, workspace, "failed", "error", err.Error(), 0, 0, "", nil) return } + // The ledger as it stood before the retried visit, the source's grants + // plus any new ones, and the failed visit's partial work. + state.findings = findings.Before(source.Findings, checkpoint.failed.Sequence) + if len(state.findings) > 0 { + r.persistFindings(id, state.findings) + } + for key, extra := range source.VisitGrants { + state.grant([]string{key}, extra) + } + if request.RetryExtraVisits > 0 { + stages := []string{request.RetryExtraStage} + if request.RetryExtraStage == "" { + stages = exhaustedStages(d.Graph, state, state.key) + } + state.grant(stages, request.RetryExtraVisits) + } + if len(state.grants) > 0 { + r.persistGrants(id, state.grants) + } + for _, step := range source.Steps { + if step.Sequence == checkpoint.failed.Sequence && step.Stage == checkpoint.failed.Stage && step.Status != "completed" { + state.carryFrom = r.turnPaths(source.ID, step.Sequence, step.Stage).TurnDir + } + } r.runLoop(ctx, id, d.Graph, d.Name, workspace, request, state) return } @@ -1291,6 +1342,15 @@ type runState struct { // adopt names the visit to re-adopt from a previous server process instead // of starting it; it is consumed by the loop's first iteration. adopt *adoptedVisit + // findings is the run's findings ledger; grants are extra visits per stage + // (loop_state.go). sessions is each stage's latest harness session, which + // a resume_session stage continues on its next visit. + findings []protocol.Finding + grants map[string]int + sessions map[string]string + // carryFrom is the failed source visit's turn directory whose private/ + // and output.md the retried visit receives; prepareTurn consumes it. + carryFrom string } func newRunState(key string, input stage.Values) *runState { @@ -1308,7 +1368,24 @@ func rebuildRunState(detail *protocol.RunDetail, decided protocol.RunStep) *runS } publicSeen := map[string]bool{} state.priorBudgets = map[string]stage.BudgetSnapshot{} + state.findings = append([]protocol.Finding(nil), detail.Findings...) + for key, extra := range detail.VisitGrants { + state.grant([]string{key}, extra) + } for _, step := range detail.Steps { + if isExhaustionStep(step) { + // A runner-created exhaustion decision is not a stage visit. + if step.Sequence >= state.nextSequence { + state.nextSequence = step.Sequence + 1 + } + continue + } + if step.SessionID != "" { + if state.sessions == nil { + state.sessions = map[string]string{} + } + state.sessions[step.Stage] = step.SessionID + } // The runtime stamps this cumulative snapshot on every executed model // visit. Reusing it preserves per-stage limits across export recovery. var audit struct { @@ -1366,6 +1443,9 @@ func rebuildRetryState(detail *protocol.RunDetail, failed protocol.RunStep, hand if step.Sequence >= failed.Sequence { break } + if isExhaustionStep(step) { + continue + } state.visits[step.Stage]++ added := publicArtifacts(step.Artifacts, publicSeen) if step.Status == "completed" { @@ -1440,7 +1520,7 @@ func (r *runner) retryPrefix(sourceID int64, source *protocol.RunDetail, failedS } publicBySequence := retryPublicBySequence(source, failedSequence) for _, step := range source.Steps { - if step.Sequence >= failedSequence || step.Status != "completed" { + if step.Sequence >= failedSequence || step.Status != "completed" || isExhaustionStep(step) { continue } prefix[step.Stage] = step.Output @@ -1921,7 +2001,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na } effectiveModels = resolved } - for sequence := state.nextSequence; sequence <= 30; sequence++ { + for sequence := state.nextSequence; sequence <= state.stepLimit(graph); sequence++ { if ctx.Err() != nil { canceled() return @@ -1953,21 +2033,28 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na } } isHuman := stage.EffectiveType(def.Type) == stage.HumanType - maxVisits := 5 - if selected.Limits != nil { - maxVisits = selected.Limits.MaxVisits - } + // Both caps include the extra visits granted to the stage. + maxVisits, hardVisits := state.visitCaps(selected) // Validate the next visit without consuming it. An already-exhausted // stage must not begin work it can never execute. - if !isHuman { - if state.visits[key]+1 > 5 { + if !isHuman && (state.visits[key]+1 > hardVisits || state.visits[key]+1 > maxVisits) { + if decidesOnExhaustion(selected) { + // on_exhausted=decide: ask the operator instead of failing. + if err := r.parkExhausted(ctx, id, name, workspace, state, sequence, selected, state.visits[key], min(maxVisits, hardVisits), key); err != nil { + if ctx.Err() != nil { + canceled() + return + } + finish("failed", "error", err.Error()) + } + return + } + if state.visits[key]+1 > hardVisits { finish("failed", "error", "stage visit budget exceeded") return } - if state.visits[key]+1 > maxVisits { - finish("failed", "error", fmt.Sprintf("stage %s visit limit reached (%d)", key, maxVisits)) - return - } + finish("failed", "error", fmt.Sprintf("stage %s visit limit reached (%d)", key, maxVisits)) + return } // adopted is the visit a previous server process began and left running // across its restart: its step row, turn files and session already exist. @@ -2072,6 +2159,34 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na r.deliverRunNotificationBatch(time.Now(), 1) return } + if stage.EffectiveType(def.Type) == stage.FindingsType { + // A findings gate routes mechanically on the run's ledger: no + // model, no capture, no turn files. + step := findingsGateStep(def, state, sequence) + step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads} + park := applyLimitOn(&step, selected, state.visits[key], maxVisits) + status, outcome, diagnostic, terminal, finishErr := r.finishStage(id, name, workspace, selected, state, step) + if finishErr != nil { + finish("failed", "error", finishErr.Error()) + return + } + state.recordTurn(step, nil) + state.completed++ + r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusRunning, CurrentStage: key, CompletedSteps: state.completed, + Step: &protocol.RunStepDelta{Sequence: step.Sequence, Stage: step.Stage, Status: step.Status, Outcome: step.Outcome, Target: step.Target, Diagnostic: step.Diagnostic}}, false) + if terminal { + finish(status, outcome, diagnostic) + return + } + if park { + if err := r.parkExhausted(ctx, id, name, workspace, state, state.nextSequence, selected, state.visits[key], maxVisits, step.Target); err != nil { + finish("failed", "error", err.Error()) + } + return + } + state.key = step.Target + continue + } // 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 @@ -2237,6 +2352,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na client.Transcript = piClient.Transcript } else if modelConfig.Harness == stage.ClaudeBackend { claudeClient := &stage.ClaudeStageClient{Directory: workspace, Tools: tools, WritePaths: request.WritePaths, ArtifactsDir: artifactsDir, Skills: def.Skills} + if def.Configs["resume_session"] == "true" && adopted == nil && state.visits[key] > 1 { + // A loop visit continues the stage's previous session. + claudeClient.ResumeSessionID = state.sessions[key] + } claudeClient.OnOwnership = func(session, reference string, active bool) error { c, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() @@ -2428,18 +2547,13 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na return } step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads} - if err == nil && selected.Limits != nil && state.visits[key] >= maxVisits { - for _, outcome := range selected.Limits.On { - if outcome == step.Outcome { - step.Control.LimitReached = true - step.Control.ModelTarget = step.Target - step.Target = protocol.FailureEnd - step.Diagnostic = fmt.Sprintf("Pipelines stopped %s after %d visits on outcome %s", key, maxVisits, step.Outcome) - } - } + parkExhausted := false + if err == nil { + parkExhausted = applyLimitOn(&step, selected, state.visits[key], maxVisits) } if panicked { step.Target = protocol.FailureEnd + parkExhausted = false } _, _, _, failedTerminal := terminalFinish(step.Target, step.Stage, step.Outcome, step.Diagnostic) if exportRequired && !completeSessionExport(sessionExport) && !(err != nil && failedTerminal && step.Target != protocol.SuccessEnd) { @@ -2503,6 +2617,9 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na if artifactsDir != "" { state.artifactDirs = append(state.artifactDirs, strconv.Itoa(sequence)) } + if stage.EffectiveType(def.Type) == stage.ModelType { + r.recordFindings(id, state, step) + } } else if step.Status == "failed" && step.Target != "" && step.Target != protocol.FailureEnd && step.Target != protocol.SuccessEnd { // The error edge leads to another stage: tell it what failed. @@ -2531,10 +2648,24 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na canceled() return } + if stageSession != "" { + if state.sessions == nil { + state.sessions = map[string]string{} + } + state.sessions[key] = stageSession + } if terminal { finish(status, outcome, diagnostic) return } + if parkExhausted { + // on_exhausted=decide: the last allowed visit asked for another + // round; the operator decides instead of the run failing. + if err := r.parkExhausted(ctx, id, name, workspace, state, state.nextSequence, selected, state.visits[key], maxVisits, step.Target); err != nil { + finish("failed", "error", err.Error()) + } + return + } state.key = step.Target } finish("failed", "error", "total stage budget exceeded") diff --git a/internal/server/turns.go b/internal/server/turns.go index faa84092..f358a1ed 100644 --- a/internal/server/turns.go +++ b/internal/server/turns.go @@ -14,6 +14,7 @@ import ( "strings" "syscall" + "git.a-wan.net/alan/pipelines/internal/findings" "git.a-wan.net/alan/pipelines/internal/protocol" "git.a-wan.net/alan/pipelines/internal/stage" "git.a-wan.net/alan/pipelines/internal/turn" @@ -71,6 +72,15 @@ func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage input += "\n" + state.previousAttempt state.previousAttempt = "" } + if state.carryFrom != "" { + // The failed visit's partial work, copied into this visit's turn. + input += carryPartialWork(state.carryFrom, paths.TurnDir) + state.carryFrom = "" + } + if err := writeFindingsFile(paths, state.findings); err != nil { + return err + } + ledger := state.findings history := turn.RenderHistory(state.turns) memory := turn.RenderEssential(turn.Essential{ Task: state.prompt, @@ -79,6 +89,7 @@ func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage ChangedFiles: state.capturedList(), InputPath: paths.InputPath, HistoryPath: paths.HistoryPath, + Findings: func(limit int) string { return findings.RenderMemory(ledger, limit) }, }) for _, file := range []struct{ path, content string }{ {paths.InputPath, input}, diff --git a/internal/stage/claude_stage.go b/internal/stage/claude_stage.go index 6d659863..3d0c6ec8 100644 --- a/internal/stage/claude_stage.go +++ b/internal/stage/claude_stage.go @@ -58,6 +58,9 @@ type ClaudeStageClient struct { Policy ToolPolicy OnOwnership func(string, string, bool) error WorkStarted bool + // ResumeSessionID, when set, resumes that earlier session of this stage + // (resume_session=true on a loop visit) instead of starting a new one. + ResumeSessionID string // operatorPlugins are this visit's generated skills-only plugin roots for // the operator's own skills (see OperatorSkills). @@ -245,6 +248,12 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr return "", err } env := claudeStageEnvironment(c.environment(ctx), c.ArtifactsDir) + // resume_session: continue the stage's previous session when Claude Code + // still has it; otherwise this visit starts fresh. + resumeFirst := false + if c.ResumeSessionID != "" && claudeSessionExists(claudeConfigDir(env), c.ResumeSessionID) { + c.SessionID, resumeFirst = c.ResumeSessionID, true + } // User settings are not loaded, so the operator's skills are offered as // skills-only plugins generated for this visit, never their plugins. if c.operatorPlugins, err = writeOperatorSkillPlugins(filepath.Join(c.Reference, "operator-skills"), OperatorSkills(claudeConfigDir(env))); err != nil { @@ -272,7 +281,7 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr } owned = true } - if text, err = c.run(ctx, env, c.args(config, tools, effort, false), config.Model, prompt); err != nil { + if text, err = c.run(ctx, env, c.args(config, tools, effort, resumeFirst), config.Model, prompt); err != nil { return "", err } // One outcome repair follow-up in the same session. @@ -345,6 +354,17 @@ func claudeConfigDir(env []string) string { return "" } +// claudeSessionExists reports whether Claude Code keeps a transcript for the +// session (projects/<project>/<id>.jsonl under its config directory), so a +// resume cannot fail on a session that was cleaned up. +func claudeSessionExists(configDir, id string) bool { + if configDir == "" || id == "" || strings.ContainsAny(id, `/\*?[`) { + return false + } + matches, _ := filepath.Glob(filepath.Join(configDir, "projects", "*", id+".jsonl")) + return len(matches) > 0 +} + func newClaudeSessionID() (string, error) { var b [16]byte if _, err := rand.Read(b[:]); err != nil { diff --git a/internal/stage/findings_gate.go b/internal/stage/findings_gate.go new file mode 100644 index 00000000..c3a33b35 --- /dev/null +++ b/internal/stage/findings_gate.go @@ -0,0 +1,77 @@ +package stage + +import ( + "context" + "fmt" + + "git.a-wan.net/alan/pipelines/internal/findings" +) + +// FindingsType is the mechanical triage stage: it routes on the run's findings +// ledger instead of asking a model. Outcome `open` when any open finding is at +// or above `severity` (default important) with a matching `origin` (default +// introduced; `pre-existing` or `any`), otherwise `clear`. +const FindingsType = "findings" + +// Findings gate outcomes. +const ( + FindingsOpen = "open" + FindingsClear = "clear" +) + +type FindingsStage struct{} + +func (FindingsStage) Validate(def Definition) error { + if EffectiveType(def.Type) != FindingsType { + return fmt.Errorf("expected findings stage") + } + for name := range def.Blocks { + switch name { + case "configs", "edges", "output", "prompt", "limits": + case "skills": + return errSkillsModelOnly("findings") + default: + return fmt.Errorf("unexpected block %q for findings stage", name) + } + } + if _, err := FindingsGate(def); err != nil { + return err + } + for outcome := range def.Edges { + switch outcome { + case FindingsOpen, FindingsClear, "error": + default: + return fmt.Errorf("findings stage outcomes are open and clear, not %q", outcome) + } + } + for _, outcome := range []string{FindingsOpen, FindingsClear} { + if _, ok := def.Edges[outcome]; !ok { + return fmt.Errorf("findings stage requires an edge for outcome %s", outcome) + } + } + return nil +} + +// FindingsGate reads a findings stage's severity and origin configs. +func FindingsGate(def Definition) (findings.Gate, error) { + gate := findings.Gate{MinSeverity: "important", Origin: "introduced"} + for key, value := range def.Configs { + switch key { + case "severity": + if gate.MinSeverity = findings.NormalizeSeverity(value); gate.MinSeverity == "" { + return gate, fmt.Errorf("severity must be critical, important, minor or nit") + } + case "origin": + if gate.Origin = findings.NormalizeOrigin(value); gate.Origin == "" { + return gate, fmt.Errorf("origin must be introduced, pre-existing or any") + } + default: + return gate, fmt.Errorf("unknown findings config %q", key) + } + } + return gate, nil +} + +func (FindingsStage) Run(context.Context, Definition, Values) (Result, error) { + return Result{}, fmt.Errorf("findings stage is resolved by the runner from the run's ledger, not executed") +} diff --git a/internal/stage/model.go b/internal/stage/model.go index 78356b72..551b2678 100644 --- a/internal/stage/model.go +++ b/internal/stage/model.go @@ -84,7 +84,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", "auto_skip": + case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery", "auto_skip", "resume_session": default: return ModelSpec{}, fmt.Errorf("unknown config %q", key) } @@ -111,6 +111,11 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) { if value := def.Configs["auto_skip"]; value != "" && value != "true" && value != "false" { return ModelSpec{}, fmt.Errorf("auto_skip must be true or false") } + // resume_session=true resumes the stage's previous harness session on a + // loop visit (Claude only; other harnesses start fresh). The runner reads it. + if value := def.Configs["resume_session"]; value != "" && value != "true" && value != "false" { + return ModelSpec{}, fmt.Errorf("resume_session must be true or false") + } if def.Configs["delivery"] == "true" && backend != "opencode" { return ModelSpec{}, fmt.Errorf("delivery is supported only by the opencode harness") } diff --git a/internal/stage/model_prompt.go b/internal/stage/model_prompt.go index 1b7ee346..b170856c 100644 --- a/internal/stage/model_prompt.go +++ b/internal/stage/model_prompt.go @@ -10,6 +10,7 @@ import ( "time" "unicode/utf8" + "git.a-wan.net/alan/pipelines/internal/findings" "git.a-wan.net/alan/pipelines/internal/turn" ) @@ -75,7 +76,7 @@ func modelPrompt(def Definition, spec ModelSpec, input Values) (string, error) { 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)) + writeTurnFile(&b, "memory.md", def.Turn.Memory, capInline(string(memory), turn.EssentialMax, 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) @@ -110,6 +111,9 @@ func modelPrompt(def Definition, spec ModelSpec, input Values) (string, error) { b.WriteString(" The next stage receives only the handoff as essential memory. For example:\n\n# outcome\n") b.WriteString(preferredOutcome(outcomes)) b.WriteString("\n\n# handoff\nWhat you did, files changed, open issues for the next stage.\n\n# details\n...\n") + b.WriteString("\n") + b.WriteString(findings.Syntax) + b.WriteString("\n") fmt.Fprintf(&b, "\nExecution time: %s. Timezone: %s.\n", time.Now().Format(time.RFC3339), time.Local.String()) if def.Turn.Public != "" { fmt.Fprintf(&b, "\nShared artifacts go to %s; files there are visible to every later stage. That absolute path is the shared folder: a relative public/ inside the workspace is a different, unshared directory. Turn-local work goes to %s and is not handed to later stages.\n", def.Turn.Public, def.Turn.Private) diff --git a/internal/stage/model_prompt_memory_test.go b/internal/stage/model_prompt_memory_test.go index cf3efe81..6e0961c4 100644 --- a/internal/stage/model_prompt_memory_test.go +++ b/internal/stage/model_prompt_memory_test.go @@ -19,7 +19,7 @@ func TestModelPromptInlinesEssentialMemoryAndPointsAtHistory(t *testing.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.Memory: "# Essential memory\n\nreviewer finding: lock leak\n" + strings.Repeat("m", 2*turn.EssentialMax), def.Turn.Input: "full previous output\n", def.Turn.History: "FULL HISTORY BODY\n", } @@ -39,7 +39,7 @@ func TestModelPromptInlinesEssentialMemoryAndPointsAtHistory(t *testing.T) { 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)) { + if strings.Contains(prompt, strings.Repeat("m", turn.EssentialMax+1)) { t.Fatal("inlined memory exceeded its cap") } if strings.Contains(prompt, "FULL HISTORY BODY") { diff --git a/internal/stage/stage.go b/internal/stage/stage.go index 0dc747a2..ebcd2240 100644 --- a/internal/stage/stage.go +++ b/internal/stage/stage.go @@ -72,7 +72,7 @@ func NewRegistry(types map[string]Stage) *Registry { } func DefaultRegistry() *Registry { - return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}}) + return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}, FindingsType: FindingsStage{}}) } func EffectiveType(name string) string { diff --git a/internal/turn/essential.go b/internal/turn/essential.go index 618ebc93..c6c8dffc 100644 --- a/internal/turn/essential.go +++ b/internal/turn/essential.go @@ -6,22 +6,32 @@ import ( "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 +// EssentialCap is the byte budget of a visit's memory.md (essential memory). +// The file is inlined into every model call of the visit, so it stays bounded; +// everything else stays on disk in history.md and input.md, read on demand. +// +// The run task is never truncated (up to EssentialTaskMax): a task larger than +// the budget grows the file to the task plus essentialMinRest for the other +// sections, so EssentialMax is the absolute bound. +const ( + EssentialCap = 20 << 10 + EssentialTaskMax = 64 << 10 + essentialMinRest = 4 << 10 + EssentialMax = EssentialTaskMax + essentialMinRest + 1024 +) 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 // essentialOwnHandoffCap bounds a revisiting stage's own last handoff // (for example a reviewer's earlier must-fix findings it must confirm). - essentialOwnHandoffCap = 768 + essentialOwnHandoffCap = 4 << 10 + // essentialFindingsCap bounds the findings ledger section. + essentialFindingsCap = 8 << 10 + // essentialReserve keeps room for the short trailing sections when the + // previous handoff is long. + essentialReserve = 1536 ) // Essential is everything RenderEssential needs for one visit's memory.md. @@ -38,108 +48,94 @@ type Essential struct { // InputPath and HistoryPath are named as the on-demand detail. InputPath string HistoryPath string + // Findings renders the run's findings ledger section within limit bytes + // (empty when there is no ledger). Nil means no section. + Findings func(limit int) 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. +// RenderEssential renders a visit's essential memory. Sections in priority +// order: the task (never truncated), the previous stage's handoff, the open +// findings ledger, this stage's own previous handoff, a one-line-per-stage +// outcome ledger and the changed files. Lower-priority sections shrink or are +// dropped first. The result fits EssentialCap unless the task alone needs +// more (see EssentialMax). 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. 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.") + var b strings.Builder + b.WriteString("# Essential memory\n\n") + b.WriteString("Short handoff for this visit; enough for most work.") if e.InputPath != "" || e.HistoryPath != "" { - fixed.WriteString(" Read on demand only:") + b.WriteString(" Read on demand only:") if e.InputPath != "" { - fmt.Fprintf(&fixed, " %s (full task and previous stage output)", e.InputPath) + fmt.Fprintf(&b, " %s (full task and previous stage output)", e.InputPath) } if e.HistoryPath != "" { if e.InputPath != "" { - fixed.WriteString(";") + b.WriteString(";") } - fmt.Fprintf(&fixed, " %s (every earlier turn in full)", e.HistoryPath) + fmt.Fprintf(&b, " %s (every earlier turn in full)", e.HistoryPath) } - fixed.WriteString(".") + b.WriteString(".") } - fixed.WriteString("\n") + b.WriteString("\n") - var tail strings.Builder - tail.WriteString(renderOwnHandoff(e.Entries, e.StageKey)) - if ledger := renderLedger(e.Entries, e.StageKey); ledger != "" { - tail.WriteString("\n## Stage ledger\n\n") - tail.WriteString(ledger) - } - 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 len(task) > EssentialTaskMax { + task = truncateWithNote(task, EssentialTaskMax, "input.md") + } + b.WriteString("\n## Task\n\n") + b.WriteString(task) + b.WriteString("\n") + + limit := EssentialCap + if need := b.Len() + essentialMinRest; need > limit { + limit = need + } + room := func() int { return limit - b.Len() } + 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 + handoff, source := previousHandoff(previous.Output) 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")) + heading := "\n## Previous stage: " + title + "\n\n" + source + budget := room() - len(heading) - 1 - essentialReserve - len(truncationNote(EssentialMax, EssentialMax, "input.md")) + b.WriteString(heading) + b.WriteString(truncateWithNote(handoff, max(budget, 256), "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) + + if e.Findings != nil { + if section := e.Findings(min(essentialFindingsCap, room()-essentialReserve/2)); section != "" && len(section) <= room() { + b.WriteString(section) } } + if own := renderOwnHandoff(e.Entries, e.StageKey, min(essentialOwnHandoffCap, room()-essentialReserve/2)); own != "" && len(own) <= room() { + b.WriteString(own) + } + if ledger := renderLedger(e.Entries, e.StageKey); ledger != "" { + if section := "\n## Stage ledger\n\n" + ledger; len(section) <= room() { + b.WriteString(section) + } + } + if files := renderFiles(e.ChangedFiles); files != "" { + if section := "\n## Changed files (server-captured)\n\n" + files; len(section) <= room() { + b.WriteString(section) + } + } + out := b.String() + if len(out) > EssentialMax { + // Pathological input; never exceed the absolute bound. + out = cutAtRune(out, EssentialMax) + } return out } @@ -147,6 +143,14 @@ func RenderEssential(e Essential) string { // 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) { + return Section(markdown, "handoff") +} + +// Section returns the body of the first heading named name (case-insensitive, +// 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 Section(markdown, name string) (string, bool) { lines := markdownLines(markdown) var fence fenceState start, level := -1, 0 @@ -167,7 +171,7 @@ func HandoffSection(markdown string) (string, bool) { continue } if start < 0 { - if strings.EqualFold(text, "handoff") { + if strings.EqualFold(text, name) { start, level = line.next, lvl } continue @@ -189,8 +193,8 @@ func HandoffSection(markdown string) (string, bool) { // previous must-fix findings) sees what it said last time. It is empty on a // first visit and when that visit is the immediately previous turn, which the // "Previous stage" section already shows. -func renderOwnHandoff(entries []MemoryEntry, current string) string { - if current == "" { +func renderOwnHandoff(entries []MemoryEntry, current string, limit int) string { + if current == "" || limit < 256 { return "" } for i := len(entries) - 1; i >= 0; i-- { @@ -203,7 +207,9 @@ func renderOwnHandoff(entries []MemoryEntry, current string) string { own := entries[i] body, source := previousHandoff(own.Output) title := capLine(fmt.Sprintf("%s · visit %d%s", oneLine(own.Stage), own.Visit, outcomeSuffix(own.Outcome)), 2*essentialLineCap) - return "\n## This stage's previous visit: " + title + "\n\n" + source + truncateWithNote(body, essentialOwnHandoffCap, "history.md") + "\n" + heading := "\n## This stage's previous visit: " + title + "\n\n" + source + budget := limit - len(heading) - 1 - len(truncationNote(EssentialMax, EssentialMax, "history.md")) + return heading + truncateWithNote(body, max(budget, 0), "history.md") + "\n" } return "" } diff --git a/internal/turn/essential_test.go b/internal/turn/essential_test.go index f097b082..5b96d79f 100644 --- a/internal/turn/essential_test.go +++ b/internal/turn/essential_test.go @@ -103,7 +103,7 @@ func TestEssentialMemoryCapsEveryPart(t *testing.T) { 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"}) + memory := RenderEssential(Essential{Task: paragraph("task", 5000), 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) } @@ -114,6 +114,38 @@ func TestEssentialMemoryCapsEveryPart(t *testing.T) { } } +// TestEssentialMemoryNeverTruncatesTheTask proves a task larger than the +// budget is kept whole and the other sections share a bounded remainder, with +// the previous handoff and the findings ledger ahead of the outcome ledger. +func TestEssentialMemoryNeverTruncatesTheTask(t *testing.T) { + task := paragraph("task", 30000) + "THE END OF THE TASK" + entries := []MemoryEntry{ + {Stage: "implement", Visit: 1, Outcome: "success", Output: "# handoff\n\n" + paragraph("handoff", 9000)}, + {Stage: "review", Visit: 1, Outcome: "rejected", Output: "# handoff\n\nReview handoff: fix F1.\n"}, + } + findings := func(limit int) string { + return "\n## Findings ledger (runner-owned)\n\n- F1 · important · introduced — leak\n" + } + memory := RenderEssential(Essential{Task: task, StageKey: "implement", Entries: entries, Findings: findings, InputPath: "/in.md", HistoryPath: "/history.md"}) + if !strings.Contains(memory, "THE END OF THE TASK") || strings.Contains(memory[:strings.Index(memory, "THE END")], "_[truncated") { + t.Fatalf("task was truncated") + } + if len(memory) > len(task)+essentialMinRest+512 || len(memory) > EssentialMax { + t.Fatalf("memory %d bytes is not bounded by the task (%d) plus the minimum rest", len(memory), len(task)) + } + handoff, ledger, own := strings.Index(memory, "Review handoff: fix F1."), strings.Index(memory, "## Findings ledger"), strings.Index(memory, "## This stage's previous visit") + if handoff < 0 || ledger < handoff { + t.Fatalf("handoff and findings missing or out of order:\n%s", memory[len(task)-200:]) + } + if own >= 0 && own < ledger { + t.Fatalf("own handoff ahead of the findings ledger") + } + small := RenderEssential(Essential{Task: "Small task.", StageKey: "implement", Entries: entries, Findings: findings}) + if len(small) > EssentialCap || !strings.Contains(small, "## Stage ledger") || !strings.Contains(small, "handoff: detail") { + t.Fatalf("small-task memory (%d bytes):\n%s", len(small), small) + } +} + 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"} {