Runs park on usage limits; failure classes, harness error policy, run budgets

- A stage refused for a Claude usage limit no longer fails its run: the
  runner tries the chats' Claude account auto-switch (per-home setting) and
  reruns the visit, else parks the run in the new waiting_quota status
  (persisted, with reset/resume time in run summaries, details and events)
  and resumes the same visit at reset + 1 min, also after a restart.
  resume_run / `pipelines resume` resumes now; cancel works on parked runs.
  The rerun visit gets a "# Previous attempt" interruption note. Subscription
  limits no longer say "top up the provider account".
- run/retry into an account known to be limited are deferred (quota_policy
  defer/refuse/now; CLI refuses under --json/--yes unless --defer or --now).
- failure_class on runs (quota, loop_exhausted, timeout, permission_denied,
  harness_error, blocked, environment, canceled, interrupted, budget,
  check_failed, other) in RunSummary/RunDetail/events, CLI inspect/runs/wait/
  stats and the app failure line.
- Claude permission denials (permission_denials / refused tool results) fail
  a blocked visit with permission_denied naming the tool use.
- Harness failures are classified transient vs deterministic; deterministic
  ones (and a repeated empty readback) skip error self-loops; transient
  self-loops back off 15 s, 1 min, 4 min.
- Whole-run USD budget: run --budget, server default (run-budget /
  get/set_run_settings); 80% warning notification, stop with class budget.
- App: waiting_quota status/filter with resume time, Resume now and Cancel,
  failure class wording. Docs and skill references updated.

Merges main (check stage, delivery gate, Claude stage restart survival,
schedule changes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 14:34:53 +00:00
193 changed files with 11295 additions and 505 deletions
+10 -2
View File
@@ -31,7 +31,10 @@ interrupted, and 1 for a client error (unknown id, connection, `--timeout`).
Do not poll with repeated `pipelines runs` calls, and do not tell the user a run
is done, or will be reported, without a wait covering it. `wait` keeps blocking
while a run is `waiting` on a human stage and prints how to answer it
(`pipelines decide <id> --option KEY`, the user's choice only).
(`pipelines decide <id> --option KEY`, the user's choice only), and through
`waiting_quota` (parked for a usage limit; it resumes itself after the reset).
Never retry into a known usage limit; read `failure_class` before acting
(`references/debugging.md`).
A run started from a repository's main checkout runs in its own worktree
(`<repo>-runs/...`, branch `pipelines/run-...`); a failed run keeps that tree and
@@ -64,7 +67,12 @@ Start from `pipelines templates` and `pipelines new NAME --template KEY`
(`research`, `task`); these fill in
the server's provider/model. Read `references/format.md` and
`references/practices.md` before writing prompts. Stage names: `plan` ·
`implement` · `review` · `ui-review` · `decide` (human) · `land`.
`implement` · `verify` (check) · `review` · `ui-review` · `decide` (human) ·
`land`. A `type=check` stage runs listed shell commands on the server, no
model, and routes on `pass`/`fail`: put one before review and use one with
`delivery=true` as the landing gate rather than having a model run the suite.
Stages with `shell` but no `edit` must not change the workspace (the server fails the
visit); give reviewers a `permissions.shell` allow-list.
Keep prompts short and objective: what the stage should produce and any real
constraints. The runner enforces turns, tools and limits and explains the output
@@ -47,6 +47,15 @@ transient environment or tooling problem, keeping `blocked -> #failure` for a
criterion that genuinely cannot be met; that self-loop needs `limits` on the
implementer, e.g. `{"max_visits":5,"on":["blocked_retryable"]}`.
Error edges are runner-policed too. A stage error that would fail the same way
again goes to `#failure` instead of following `error -> <same stage>`: a
deterministic harness failure (authentication, an invalid argument or model, a
configuration the harness refuses), a tool permission denial, a spent run budget,
or the same empty-readback failure twice in a row. A transient one (network,
5xx/overloaded, timeouts) follows the self-loop after a backoff of 15 s, then 1 min,
then 4 min. A provider usage limit never follows the error edge: the run switches
Claude accounts or parks in `waiting_quota` (`references/debugging.md`).
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
@@ -10,6 +10,37 @@
4. Verify the repair with a focused regression; run broader checks once relevant
inputs settle. Do not raise retry/time budgets to hide a reproducible defect.
Read the run's `failure_class` first (in `inspect`, `runs`, `wait` and the app's
failure line; `stats` counts them):
| class | meaning and next action |
|---|---|
| `quota` | provider usage/balance refused; a Claude window parks instead (below), so this means an exhausted paid balance or a failed park |
| `loop_exhausted` | a stage's visit limit or the 30-step cap; fix the cause the loop kept hitting |
| `timeout` | a stage attempt ran past its `timeout`; check whether work landed before raising it |
| `permission_denied` | the stage's tool use was refused (named in the diagnostic) and it gave up; widen `tools`/write paths or change the task |
| `harness_error` | the harness failed (transport, readback, cleanup); a deterministic one was not looped |
| `blocked` | a stage deliberately routed to `#failure` (its own outcome); read its handoff |
| `environment` | harness missing or signed out, workspace/env/delivery access problems |
| `budget` | the run's `--budget`/default run budget (or a stage budget) was spent |
| `check_failed` | a verification target or delivery gate check failed |
| `canceled`, `interrupted`, `other` | operator cancel, server stop, anything else |
A Claude stage refused for a usage limit is never failed and never retried into
the limit. The server first switches the Claude home to another saved account
with usage left (when that home's auto-switch is on) and runs the visit again;
otherwise the run is parked in `waiting_quota` with `quota_wait.resets_at`/
`resume_at` and resumes the same visit a minute after the reset, also after a
restart. The visit that runs again is told in `# Previous attempt` that it was
interrupted and that partial edits may be in the worktree. Do not retry or cancel a
parked run to "unstick" it: `pipelines wait ID` waits through it,
`pipelines resume ID --yes` resumes it now (only when the limit is known to be
lifted) and `pipelines cancel ID --yes` stops it. While an account is known to be
limited, `run`/`retry` under `--json`/`--yes` are refused with the reset time;
pass `--defer` to queue the run for the reset or `--now` only when you know the
limit is gone. A run's `--budget USD` (or the server's `pipelines run-budget`)
warns at 80% and stops at 100% with class `budget`.
`pipelines retry ID --yes --json` resumes the failed stage; `--stage KEY [--visit N]` picks a
recorded stage, `--input-file FILE|-` merges a bounded JSON correction (shown to
the stage as `# Operator correction`), `--version N` a published version of the
+3 -3
View File
@@ -9,9 +9,9 @@ request does not authorize publication, execution or deployment.
Inspect actual source and diffs, run relevant tests and record exact results.
A model summary, committed branch or successful merge is not proof of runtime
behavior. Missing or partial diff capture must be reported as incomplete.
With delivery=true, the stage returns a clean candidate and the server checks and
lands it, first merging a moved main and re-checking the merged tree; only a real
conflict fails. Direct recovery can complete a reviewed merge without another pipeline.
With delivery=true (a model land stage on any harness, or a check stage), the
server checks and lands the candidate, first merging a moved main and
re-checking the merged tree; only a real conflict fails. Direct recovery can complete a reviewed merge without another pipeline.
Keep artifacts under the supplied run/stage artifact directory. Mark unverified
builds as WIP. Verify any download URL serves the real bytes before reporting it.
+82 -8
View File
@@ -2,8 +2,8 @@
A definition is Markdown made only of `# stage KEY` headings and fenced blocks;
no prose outside blocks. Blocks: `prompt`, `configs`, `tools`, `skills`, `edges`,
`checks`, `limits` (`references/control.md`), `permissions` and `notify`
(`references/notifications.md`). There are no memory, links, input or output
`checks`, `limits` (`references/control.md`), `permissions`, `notify`
(`references/notifications.md`) and, on check stages, `commands`. There are no memory, links, input or output
blocks; stages communicate through `output.md` (`# handoff`) and `public/`.
Schedules are saved run configurations, never definition blocks
(`references/schedules.md`).
@@ -102,8 +102,9 @@ evidence route to `blocked` when declared, else `error`; never fabricate a resul
(`pipelines new NAME --template KEY`) fill them in; copy those IDs into a
hand-written draft. Availability needs `pipelines provider-check`.
- `harness=opencode|pi|claude`; omission means OpenCode (`references/harnesses.md`).
`claude` needs `provider=anthropic` and a Claude model ID, and accepts no
`permissions` block, `delivery=true` or run write paths.
`claude` needs `provider=anthropic` and a Claude model ID; its `permissions`
block may hold only a `shell` allow-list (no `edit` patterns or run write
paths).
- `retries` 0–100, default 2 (three attempts). Retries cover transport failures
and timeouts; a stage with `edit`/`shell` (or no tools block) never replays
admitted work.
@@ -114,7 +115,13 @@ evidence route to `blocked` when declared, else `error`; never fabricate a resul
- `budget_usd`, `budget_tokens`: positive caps on reported usage, shared across
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.
A whole-run cap is not a definition setting: it is the run's `--budget USD` or
the server default (`pipelines run-budget`), and every stage's cost counts
towards it (80% warning, stop with failure class `budget` at 100%).
- `delivery=true`: the landing stage's gate (below), on any harness, or on a
check stage.
- `allow_workspace_changes=true`: lets a stage with `shell` but no `edit` leave file changes
in the run directory (below).
- `auto_skip=false`: disable the server skip fallback for a stage that declares a
`skipped` edge (`references/operations.md`, Server skip fallback).
@@ -134,6 +141,20 @@ patterns) and `shell` (exact commands) arrays. It narrows declared tools; it nev
enables a missing one. Empty arrays deny; wildcards, chaining, redirects and
traversal are rejected. With restricted edits and shell enabled, list shell too:
`{"edit":["README.md","plugin/*.qml"],"shell":["bash -n install.sh"]}`.
On `harness=claude` only `shell` is accepted; each entry becomes a Claude Code
rule (`go test ./...` -> `Bash(go test ./...)`) and an entry ending in ` *` is a
prefix (`git diff *` -> `Bash(git diff:*)`, any arguments; claude only). Claude
Code checks each part of a chained command, and every other command is
refused. A read-only reviewer: `{"shell":["git diff *","git log *","go test ./..."]}`.
A stage whose `tools` block has `shell` but not `edit` must leave the run directory as it
found it: the server compares the workspace before and after the visit and
fails the visit (`permission denied: ... changed the workspace (added x, ...)`,
following the `error` edge) when any file changed, outside the run's artifact
directories and a harness state directory inside the workspace. Committing is
not a change; merging or generating files is. Set
`allow_workspace_changes=true` on a stage that legitimately writes (for
example a land stage that merges main itself).
Named MCP entries are an explicit allowlist for unattended Claude stages:
`mcp:ai-memory` allows that server's tools, while `mcp:linear/list_issues`
@@ -190,6 +211,56 @@ A check must fail when it cannot run: validation rejects `|| true`, `|| :`,
`|| exit 0`, `|| echo`, negated file tests, `! command -v tool ||`, an `if` with no
failing else, and `set +e`. Cover every language the run can change.
## Check stages
`type=check` runs shell commands on the server, without a model, and routes on
`pass` or `fail`. Use it before review, so a reviewer never sees a red tree, and
as the landing gate instead of a model stage that runs the suite itself.
````markdown
# stage verify
```configs
type=check
command_timeout=15m
```
```commands
uv run ruff check .
uv run ty check
uv run pytest -q
```
```edges
pass -> review
fail -> implement
```
```limits
{"max_visits":3}
```
````
- `commands` (required): 1-20 lines, one `sh -c` command each, run in order
from the run directory with its workspace environment; blank and `#` lines are
ignored. The first failure stops the rest (`not_run`) unless `keep_going=true`.
Lint rejects silent guards (`|| true`) as for `checks`.
- Configs: `command_timeout` (per command, default `30m`), `timeout` (the whole
stage, default `1h`), `keep_going=true|false`, `delivery=true`. No prompt,
tools, model or skills.
- Edges: `pass` and `fail` are required and are the only outcomes besides
`error` (an infrastructure failure). A `fail` loop back needs `limits`.
- Output: the step records each command's status (`passed`, `failed`,
`timed_out`, `not_run`), exit code, duration and output (64 KB per failing
command, head and tail kept), plus a one-line summary as its verdict. Its
`# handoff` names the failing commands with the tail of their output, and the
full outputs follow, so the next stage sees exactly what failed.
- `delivery=true` makes it the landing gate: the server commits what the run
left uncommitted (run worktrees), merges a moved `main`, runs the commands in
a fresh worktree of the commit and fast-forwards `main` on `pass`. A failing
command is `fail` with `main` untouched; a gate problem (dirty checkout,
conflict, refused fast-forward) is `error`.
## Human stages
`type=human` pauses the run until a person picks one of its non-`error` edges
@@ -201,14 +272,17 @@ wait survives restarts and is never killed by a stage timeout or `max_visits`.
## Land stage and delivery gate
A workflow that commits its change ends in `land`: a model stage with
`read`/`glob`/`grep`/`shell`, no `edit`, that commits locally. Its prompt states:
A workflow that commits its change ends in `land`: either a check stage with
`delivery=true` (above; no model, the server commits and lands), or a model
stage with `read`/`glob`/`grep`/`shell`, no `edit`, that commits locally. A model
land stage's prompt states:
1. Commit only this run's changes (server list + git status).
2. Check the staged diff for unrelated work and secrets.
3. No empty commit, push, amend or rebase. Report the hash.
With `delivery=true` and `checks` commands, after `land` succeeds the server:
With `delivery=true` and `checks` commands (any harness), after `land` succeeds
the server:
commits whatever the run left uncommitted when the item is the run's own
worktree (see "Run worktrees" below); requires the item checkout to be clean,
untracked files included (the main checkout need not be: the final
@@ -92,7 +92,7 @@ Use the authoritative `CLI_PREFIX` from the prompt:
without changing its input or steps. The stored prompt is unchanged, and
listing/renaming never calls a model.
- `CLI_PREFIX inspect RUN_ID`: compact summary — a header (status, outcome,
duration, diagnostic), one line per step (stage, status, outcome, duration,
duration, `failure_class`, diagnostic, run budget), one line per step (stage, status, outcome, duration,
first diagnostic line), how to answer a `waiting` run and the final `# handoff`
(bounded). `--step N` prints one step in full without its transcript (add
`--transcripts` for it), `--transcripts` alone appends every transcript, and
@@ -111,13 +111,19 @@ Use the authoritative `CLI_PREFIX` from the prompt:
complete tool history.
- `CLI_PREFIX decide RUN_ID [STAGE] --option KEY [--feedback TEXT] [--json]`: answer
a run `waiting` on a `type=human` stage (`references/format.md`).
- A run in `waiting_quota` is parked for a provider usage limit and resumes on its
own after `quota_wait.resume_at`; `CLI_PREFIX resume RUN_ID --yes` resumes it now,
`cancel` stops it (`references/debugging.md`). `run`/`retry` take `--budget USD`
(whole-run cap) and `--now`/`--defer` for a known usage limit;
`CLI_PREFIX run-budget [USD|off]` shows or sets the server default run budget.
- Without a terminal on stdin/stdout (an agent's shell, a pipe, CI) `run` behaves
as `--json` and never opens the full-screen view, `tui` refuses, and every
confirmation fails at once naming `--yes` instead of prompting: pass
`run NAME "TASK" --json --yes` and `retry RUN_ID --yes --json`.
- `CLI_PREFIX wait RUN_ID ...`: one line per run as it finishes (a failed run's
stage and first diagnostic line); while a run waits on a human it prints
`waiting at STAGE — answer with: pipelines decide ID --option KEY` once (stderr
`waiting at STAGE — answer with: pipelines decide ID --option KEY` once and
waits through `waiting_quota` (the run resumes on its own) (stderr
under `--json`). Exit status: 0 every run succeeded, 2 a run failed, was
canceled or interrupted, 1 a client error (unknown id, connection, `--timeout`
reached; the run is untouched). `run --wait` and `retry --wait` also exit 2
+13
View File
@@ -224,3 +224,16 @@ func (c *Chat) noteRejectedLocked(email string, until time.Time) {
c.rejectedUntil[email] = until
}
}
// IsUsageLimitText reports whether text is Claude Code's usage-limit refusal.
func IsUsageLimitText(text string) bool { return usageLimitText.MatchString(text) }
// UsageLimitResetIn reads the reset time a usage-limit refusal's text names
// (as of at); ok is false when the text is not a usage-limit refusal or names
// no reset. Pipeline stages use it when no rate_limit_event said.
func UsageLimitResetIn(text string, at time.Time) (time.Time, bool) {
if !usageLimitText.MatchString(text) {
return time.Time{}, false
}
return usageLimitReset(text, at)
}
+19
View File
@@ -119,6 +119,25 @@ func TestInspectStepAndTranscriptsAndJSON(t *testing.T) {
}
}
func TestInspectStepListsCheckCommandsAndRepairs(t *testing.T) {
d := &protocol.RunDetail{ID: 7, Steps: []protocol.RunStep{{Sequence: 1, Stage: "verify", Status: "completed", Outcome: "fail",
Control: &protocol.ControlEvidence{OutcomeRepairs: 1},
Output: map[string]any{"markdown": "# outcome\n\nfail\n", "checks": []any{
map[string]any{"command": "go vet ./...", "status": "passed", "exit_code": float64(0), "duration_ms": float64(1200)},
map[string]any{"command": "go test ./...", "status": "failed", "exit_code": float64(1), "duration_ms": float64(51000)},
}}}}}
var out bytes.Buffer
if err := (App{Out: &out}).inspect(d, &options{step: 1}); err != nil {
t.Fatal(err)
}
text := out.String()
for _, want := range []string{"outcome repair follow-ups: 1", "passed exit 0 1.2s go vet ./...", "failed exit 1 51.0s go test ./..."} {
if !strings.Contains(text, want) {
t.Fatalf("missing %q:\n%s", want, text)
}
}
}
func TestWaitLineNamesFailingStageAndDiagnostic(t *testing.T) {
line := waitLine(sampleRun())
if !strings.Contains(line, "failed at implement · go test failed") || strings.Contains(line, "long detail line") {
+143 -7
View File
@@ -61,6 +61,43 @@ type options struct {
version, expected, limit, retryVisit int
timeout, waitTimeout time.Duration
stageModels stageModelFlags
// quotaNow / quotaDefer choose what run and retry do about a known usage
// limit; budgetUSD caps the whole run.
quotaNow, quotaDefer bool
budgetUSD float64
}
// quotaPolicy is the run/retry request's protocol.QuotaPolicy: --now starts
// anyway, --defer queues the run for the reset, and otherwise a person at a
// prompt gets the deferral while --json/--yes automation is refused, so an
// agent never burns a retry into a known limit by accident.
func (o *options) quotaPolicy() (string, error) {
switch {
case o.quotaNow && o.quotaDefer:
return "", fmt.Errorf("--now and --defer are exclusive")
case o.quotaNow:
return protocol.QuotaNow, nil
case o.quotaDefer:
return protocol.QuotaDefer, nil
case o.json || o.yes:
return protocol.QuotaRefuse, nil
}
return protocol.QuotaDefer, nil
}
// quotaFlags registers --now, --defer and --budget for run and retry.
func quotaFlags(f *flag.FlagSet, o *options) {
f.BoolVar(&o.quotaNow, "now", false, "Start even though the Claude account is known to be out of usage until its reset")
f.BoolVar(&o.quotaDefer, "defer", false, "When the Claude account is known to be out of usage, queue the run to start at the reset (default at a prompt; --json/--yes refuse instead)")
f.Float64Var(&o.budgetUSD, "budget", 0, "Cap this run's reported model cost in USD (warns at 80%, stops at 100%; default: the server's run budget)")
}
// quotaHint adds the CLI flags to a refusal for a known usage limit.
func quotaHint(err error) error {
if err != nil && strings.Contains(err.Error(), "not starting into a known limit") {
return fmt.Errorf("%w (pass --defer to queue it for the reset, or --now to start anyway)", err)
}
return err
}
// stageModelFlags collects the repeatable --stage-model STAGE=PROVIDER/MODEL
@@ -172,6 +209,7 @@ func (a App) flags(command string) (*flag.FlagSet, *options) {
f.Var(o.stageModels, "stage-model", "Override one stage's model; repeatable (STAGE=PROVIDER/MODEL); beats --model")
f.BoolVar(&o.wait, "wait", false, "In JSON mode, wait for a terminal run state")
f.DurationVar(&o.waitTimeout, "wait-timeout", 0, "Client limit for --wait after the run is admitted (0 waits until terminal); separate from per-request --timeout")
quotaFlags(f, o)
case "runs":
f.StringVar(&o.name, "pipeline", "", "Filter by exact pipeline name or ID")
f.BoolVar(&o.yes, "yes", false, "Confirm `runs rm` without an interactive prompt")
@@ -190,10 +228,11 @@ func (a App) flags(command string) (*flag.FlagSet, *options) {
f.IntVar(&o.version, "version", 0, "Explicit published version of the same pipeline (default: source version)")
f.StringVar(&o.retryInputFile, "input-file", "", "JSON object merged into the selected stage input; '-' reads stdin")
f.StringVar(&o.notifyMode, "notify", "auto", "Notifications for this retry: auto, on, or off")
quotaFlags(f, o)
case "inspect":
f.IntVar(&o.step, "step", 0, "Show one step (its sequence number) in full, without its transcript")
f.BoolVar(&o.transcripts, "transcripts", false, "Include stage transcripts (long)")
case "cancel", "draft-delete":
case "cancel", "draft-delete", "resume":
f.BoolVar(&o.yes, "yes", false, "Confirm this action without an interactive prompt")
case "retention":
f.StringVar(&o.db, "db", "", "Existing database path (default: standard data directory)")
@@ -605,6 +644,12 @@ func (a App) Run(ctx context.Context, args []string) error {
}
fmt.Fprintln(a.Out, line)
}
if u.WaitingQuota > 0 {
fmt.Fprintf(a.Out, "%d run(s) waiting for a usage limit to reset\n", u.WaitingQuota)
}
if line := failureClassLine(u.FailureClasses); line != "" {
fmt.Fprintln(a.Out, "Why runs did not succeed: "+line)
}
fmt.Fprint(a.Out, "\nPipeline\tRuns\tSucceeded\tFailed\tActive\n")
for _, p := range u.Pipelines {
fmt.Fprintf(a.Out, "%s\t%d\t%d\t%d\t%d\n", p.Name, p.Total, p.Succeeded, p.Failed, p.Active)
@@ -843,7 +888,14 @@ func (a App) Run(ctx context.Context, args []string) error {
}
case "runs":
for _, run := range r.Runs {
fmt.Fprintf(a.Out, "%d\t%s\t%s\tv%d\t%s\n", run.ID, run.Label(), run.Name, run.Version, run.Status)
status := run.Status
if run.FailureClass != "" && run.Status != protocol.RunStatusCanceled {
status += " (" + protocol.FailureClassLabel(run.FailureClass) + ")"
}
if run.QuotaWait != nil {
status += " (resumes " + localClock(run.QuotaWait.ResumeAt) + ")"
}
fmt.Fprintf(a.Out, "%d\t%s\t%s\tv%d\t%s\n", run.ID, run.Label(), run.Name, run.Version, status)
}
case "ping":
fmt.Fprintln(a.Out, "Connected ·", r.Time)
@@ -1036,10 +1088,17 @@ 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})
policy, err := o.quotaPolicy()
if err != nil {
return err
}
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, QuotaPolicy: policy, BudgetUSD: o.budgetUSD})
if err != nil {
return quotaHint(err)
}
if r.RunDetail != nil && r.RunDetail.Status == protocol.RunStatusWaitingQuota {
a.notice(quotaWaitLine(r.RunDetail))
}
return a.finishRun(ctx, r, o, call)
}
r, err := call(protocol.Message{Type: typeName, RunID: id, RequestKey: key, RetryMode: o.retryMode})
@@ -1055,6 +1114,62 @@ func (a App) Run(ctx context.Context, args []string) error {
return a.inspect(r.RunDetail, o)
}
return a.output(r.RunDetail)
case "resume":
value, err := one()
if err != nil {
return err
}
id, err := strconv.ParseInt(value, 10, 64)
if err != nil || id <= 0 {
return fmt.Errorf("run ID must be positive")
}
if err := a.confirmAction(fmt.Sprintf("Resume run #%d now, before its usage limit is known to have reset?", id), o.yes); err != nil {
return err
}
r, err := call(protocol.Message{Type: protocol.ResumeRun, RunID: id})
if err != nil {
return err
}
if r.RunDetail == nil {
return fmt.Errorf("server did not return run detail")
}
if o.json {
return a.output(r.RunDetail)
}
_, err = fmt.Fprintf(a.Out, "Resumed run #%d: %s\n", r.RunDetail.ID, r.RunDetail.Status)
return err
case "run-budget":
if len(pos) > 1 {
return fmt.Errorf("run-budget takes at most one value: USD or off")
}
request := protocol.Message{Type: protocol.GetRunSettings}
if len(pos) == 1 {
value := strings.TrimSpace(strings.TrimPrefix(pos[0], "$"))
limit := 0.0
if value != "off" && value != "0" {
limit, err = strconv.ParseFloat(value, 64)
if err != nil || limit <= 0 {
return fmt.Errorf("run-budget takes a positive USD amount or off")
}
}
request = protocol.Message{Type: protocol.SetRunSettings, RunSettings: &protocol.RunSettings{DefaultBudgetUSD: limit}}
}
r, err := call(request)
if err != nil {
return err
}
if r.RunSettings == nil {
return fmt.Errorf("server did not return run settings; update pipelines-server")
}
if o.json {
return a.output(r.RunSettings)
}
if r.RunSettings.DefaultBudgetUSD <= 0 {
_, err = fmt.Fprintln(a.Out, "Default run budget: off (runs are capped only by their own --budget and their stages' budget_usd)")
} else {
_, err = fmt.Fprintf(a.Out, "Default run budget: $%.2f per run (warns at 80%%, stops at 100%%)\n", r.RunSettings.DefaultBudgetUSD)
}
return err
case "decide":
if len(pos) < 1 || len(pos) > 2 {
return fmt.Errorf("decide requires a run ID and an optional stage key")
@@ -1389,7 +1504,15 @@ func (a App) run(ctx context.Context, pos []string, o *options, call callFunc, r
if o.wait || o.key != "" || o.version > 0 {
return fmt.Errorf("--wait, --request-key and --version require --json")
}
_, err := tea.NewProgram(tui.NewRun(ctx, o.url, tui.RunOptions{Pipeline: o.name, Prompt: o.prompt, Title: o.title, Workspace: workspace, Yes: o.yes, AllowTools: o.allow, WritePaths: paths, Model: o.model, StageModels: o.stageModels, NotifyMode: o.notifyMode, OutputFormat: o.outputFormat}), tea.WithContext(ctx), tea.WithAltScreen()).Run()
policy, err := o.quotaPolicy()
if err != nil {
return err
}
_, err = tea.NewProgram(tui.NewRun(ctx, o.url, tui.RunOptions{Pipeline: o.name, Prompt: o.prompt, Title: o.title, Workspace: workspace, Yes: o.yes, AllowTools: o.allow, WritePaths: paths, Model: o.model, StageModels: o.stageModels, NotifyMode: o.notifyMode, OutputFormat: o.outputFormat, QuotaPolicy: policy, BudgetUSD: o.budgetUSD}), tea.WithContext(ctx), tea.WithAltScreen()).Run()
return err
}
policy, err := o.quotaPolicy()
if err != nil {
return err
}
if o.name == "" || strings.TrimSpace(o.prompt) == "" {
@@ -1411,9 +1534,12 @@ func (a App) run(ctx context.Context, pos []string, o *options, call callFunc, r
if key == "" {
key = fmt.Sprintf("cli-%d-%d", os.Getpid(), time.Now().UnixNano())
}
r, err := call(protocol.Message{Type: protocol.RunPipeline, PipelineID: p.ID, Version: version, RequestKey: key, Workspace: workspace, Title: o.title, Input: map[string]any{"prompt": o.prompt}, AllowTools: o.allow, WritePaths: paths, Model: o.model, StageModels: o.stageModels, NotifyMode: o.notifyMode, OutputFormat: o.outputFormat})
r, err := call(protocol.Message{Type: protocol.RunPipeline, PipelineID: p.ID, Version: version, RequestKey: key, Workspace: workspace, Title: o.title, Input: map[string]any{"prompt": o.prompt}, AllowTools: o.allow, WritePaths: paths, Model: o.model, StageModels: o.stageModels, NotifyMode: o.notifyMode, OutputFormat: o.outputFormat, QuotaPolicy: policy, BudgetUSD: o.budgetUSD})
if err != nil {
return err
return quotaHint(err)
}
if r.RunDetail != nil && r.RunDetail.Status == protocol.RunStatusWaitingQuota {
a.notice(quotaWaitLine(r.RunDetail))
}
return a.finishRun(ctx, r, o, call)
}
@@ -1480,6 +1606,9 @@ func (a App) finishRun(ctx context.Context, r protocol.Message, o *options, call
if hint := waitingHint(r.RunDetail); hint != "" {
message += "; " + hint
}
if line := quotaWaitLine(r.RunDetail); line != "" {
message += "; " + line
}
return &StatusError{Code: WaitRunsUnsuccessful, Message: message}
}
return nil
@@ -1526,6 +1655,10 @@ func (a App) wait(ctx context.Context, pos []string, o *options, call callFunc)
announced := map[int64]string{}
onActive := func(r protocol.Message) {
hint := waitingHint(r.RunDetail)
if hint == "" {
// A run parked for a usage limit resumes on its own; say when.
hint = quotaWaitLine(r.RunDetail)
}
if hint == "" || announced[r.RunDetail.ID] == hint {
return
}
@@ -1644,7 +1777,7 @@ func runInProgress(status string) bool {
// runInProgress plus a run parked on a human decision (waiting), which has not
// finished either.
func runUnfinished(status string) bool {
return runInProgress(status) || status == protocol.RunStatusWaiting
return runInProgress(status) || status == protocol.RunStatusWaiting || status == protocol.RunStatusWaitingQuota
}
// runIDs extracts the ids of the runs still active when a wait limit passed.
@@ -1681,6 +1814,9 @@ func waitLine(d *protocol.RunDetail) string {
if outcome := strings.TrimSpace(d.Outcome); outcome != "" {
line += " (" + outcome + ")"
}
if d.FailureClass != "" && d.Status != protocol.RunStatusCanceled {
line += " [" + d.FailureClass + "]"
}
if stage := strings.TrimSpace(d.CurrentStage); stage != "" {
line += " · " + stage
}
+6 -2
View File
@@ -21,13 +21,15 @@ var usage = map[string]string{
"import": "import [FILE.zip] [--all] [--on-conflict ask|keep|both|import] [--yes] [--json]",
"templates": "templates [--json]",
"template": "template <key> [--source | --json]",
"run": "run [name|id] [prompt] [--yes] [--title TITLE] [--model PROVIDER/MODEL] [--stage-model STAGE=PROVIDER/MODEL ...] [--json [--wait [--wait-timeout DURATION]]]",
"run": "run [name|id] [prompt] [--yes] [--title TITLE] [--model PROVIDER/MODEL] [--stage-model STAGE=PROVIDER/MODEL ...] [--budget USD] [--now | --defer] [--json [--wait [--wait-timeout DURATION]]]",
"runs": "runs [--pipeline NAME] [--json] | runs rm <run-id> [run-id ...] [--yes] [--json]",
"inspect": "inspect <run-id> [--step N] [--transcripts] [--json]",
"wait": "wait <run-id> [run-id ...] [--timeout DURATION] [--json]",
"cancel": "cancel <run-id> [--json]",
"resume": "resume <run-id> [--yes] [--json]",
"run-budget": "run-budget [USD|off] [--json]",
"decide": "decide <run-id> [stage] --option KEY [--feedback TEXT] [--json]",
"retry": "retry <run-id> [--yes] [--mode resume|restart] [--stage KEY [--visit N]] [--version N] [--input-file FILE|-] [--json [--wait [--wait-timeout DURATION]]]",
"retry": "retry <run-id> [--yes] [--mode resume|restart] [--stage KEY [--visit N]] [--version N] [--input-file FILE|-] [--budget USD] [--now | --defer] [--json [--wait [--wait-timeout DURATION]]]",
"title": "title <run-id> \"<title>\" [--json]",
"debug": "debug <run-id> [--json | --no-open]",
"chat-adopt": "chat-adopt <session-id> [--harness opencode|claude|codex] [--title TEXT] [--json]",
@@ -63,6 +65,8 @@ var notes = map[string]string{
"title": "Rename a run's operator-facing title after the fact without touching its input, steps or execution. The title is collapsed to a single bounded line and recorded as explicitly set. `pipelines runs` and `pipelines inspect` then show it.",
"inspect": "Print a compact summary of a run: status, outcome and duration, one line per step (stage, status, outcome, duration, first diagnostic line), how to answer a run waiting on a person and the bounded final handoff. --step N prints that step in full (output, diagnostic, file changes, artifacts) without its transcript; --transcripts adds transcripts (to every step, or to --step N); --json prints the complete run record (or just --step N), including transcripts.",
"wait": "Block until each named run reaches a terminal status - succeeded, failed, canceled or interrupted, and also through a run waiting on a person - then print one line per run with its id, status and outcome, its stage, how long it took and, for an unsuccessful run, the failing stage and the first line of its diagnostic. While a run waits on a person it prints once how to answer: waiting at STAGE — answer with: pipelines decide ID --option KEY (on stderr under --json). Several ids wait together in one command. Exit status: 0 when every run succeeded; 2 when any run failed, was canceled or interrupted (every run is still reported); 1 for a client-side failure: an unknown run id, a connection that could not be established, or --timeout expiring while a run is still active. A timeout says so plainly, never cancels, retries or otherwise touches a run, and is never reported as its outcome. Read-only: it needs no workspace, is not refused by the workspace guard and writes nothing. --json prints the final run envelope instead of the line (one envelope for one id, an array for several).",
"resume": "Resume a run parked in waiting_quota now instead of at its usage-limit reset: the interrupted stage visit runs again (told it was interrupted and that partial edits may be in the worktree), or a run deferred before its first stage starts. The server resumes parked runs on its own a minute after the reset, also after a restart; use this only when you know the limit is lifted (for example you switched Claude accounts). Cancel a parked run with pipelines cancel.",
"run-budget": "Show or set the server's default whole-run budget in USD (off removes it). A run without its own --budget is capped at this amount of reported model cost: the operator is notified at 80% and the run stops with failure class budget at 100%. Stage budget_usd/budget_tokens in a definition still cap each stage.",
"decide": "Choose an option for a run waiting on a human stage. The run must be `waiting`; the option must be one of that stage's non-error edges. The stage is inferred from the run's current stage unless named. The choice and optional --feedback are recorded as the step's evidence (visible in inspect and the TUI) and the run resumes along the chosen edge. An unknown option is refused with the valid list; a repeated decision for an already-decided visit does not double-apply. Works across a server restart because the wait is persisted.",
"debug": "Open a fresh configured harness conversation to investigate a run using inspect/show/runs CLI queries. --harness opencode|pi|nvim chooses another configured harness or read-only nvim packet. Does not resume implementation or retry. --json returns the prompt without launching anything.",
"rpc": "Accepts a JSON protocol envelope; '-' reads stdin. Every TUI server operation is available here too. Mutating commands are not dry runs. The omni-search command is `search` (fields query, optional kind and limit) and answers with ranked `search_results`.",
+31
View File
@@ -36,9 +36,15 @@ func inspectSummary(d *protocol.RunDetail) string {
if d.RetryOf > 0 {
fmt.Fprintf(&b, "retry of run %d (%s)\n", d.RetryOf, d.RetryMode)
}
if d.FailureClass != "" {
b.WriteString("failure class: " + d.FailureClass + " (" + protocol.FailureClassLabel(d.FailureClass) + ")\n")
}
if line := firstLine(d.Diagnostic); line != "" {
b.WriteString("diagnostic: " + line + "\n")
}
if budget := d.Budget; budget != nil {
fmt.Fprintf(&b, "budget: $%.2f of $%.2f (%s)\n", budget.SpentUSD, budget.LimitUSD, budget.Source)
}
if len(d.Steps) > 0 {
b.WriteString("\nsteps:\n")
}
@@ -48,6 +54,9 @@ func inspectSummary(d *protocol.RunDetail) string {
if next := waitingHint(d); next != "" {
b.WriteString("\n" + next + "\n")
}
if next := quotaWaitLine(d); next != "" {
b.WriteString("\n" + next + "\n")
}
if handoff := finalHandoff(d); handoff != "" {
b.WriteString("\nhandoff:\n" + indent(handoff) + "\n")
} else if preview := strings.TrimSpace(d.ResultPreview); preview != "" {
@@ -93,9 +102,23 @@ func inspectStep(d *protocol.RunDetail, sequence int, transcripts bool) (string,
if step.SessionID != "" {
b.WriteString("session: " + step.SessionID + "\n")
}
if step.Control != nil && step.Control.OutcomeRepairs > 0 {
fmt.Fprintf(&b, "outcome repair follow-ups: %d\n", step.Control.OutcomeRepairs)
}
if diagnostic := strings.TrimSpace(step.Diagnostic); diagnostic != "" {
b.WriteString("\ndiagnostic:\n" + indent(diagnostic) + "\n")
}
if checks, ok := step.Output["checks"].([]any); ok && len(checks) > 0 {
b.WriteString("\nchecks:\n")
for _, entry := range checks {
check, _ := entry.(map[string]any)
command, _ := check["command"].(string)
status, _ := check["status"].(string)
exit, _ := check["exit_code"].(float64)
duration, _ := check["duration_ms"].(float64)
fmt.Fprintf(&b, " %-9s exit %-3d %6.1fs %s\n", status, int(exit), duration/1000, command)
}
}
if markdown, ok := step.Output["markdown"].(string); ok && strings.TrimSpace(markdown) != "" {
b.WriteString("\noutput:\n" + indent(strings.TrimSpace(markdown)) + "\n")
} else if len(step.Output) > 0 {
@@ -199,6 +222,14 @@ func failureDetail(d *protocol.RunDetail) (stage, diagnostic string) {
// failureNote names the failing stage and its first diagnostic line.
func failureNote(d *protocol.RunDetail) string {
note := failureNoteText(d)
if d.FailureClass != "" && d.FailureClass != protocol.FailureCanceled && note != "" {
return "[" + d.FailureClass + "] " + note
}
return note
}
func failureNoteText(d *protocol.RunDetail) string {
stage, diagnostic := failureDetail(d)
switch {
case stage != "" && diagnostic != "":
+51
View File
@@ -0,0 +1,51 @@
package cli_test
import (
"context"
"encoding/json"
"strconv"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func TestCLIRunBudgetAndResume(t *testing.T) {
run, store, _ := setup(t)
if out, err := run("run-budget"); err != nil || !strings.Contains(out, "off") {
t.Fatal(out, err)
}
if _, err := run("run-budget", "-3"); err == nil {
t.Fatal("a negative default budget was accepted")
}
out, err := run("run-budget", "12.5", "--json")
if err != nil {
t.Fatal(err)
}
var settings protocol.RunSettings
if err := json.Unmarshal([]byte(out), &settings); err != nil || settings.DefaultBudgetUSD != 12.5 {
t.Fatal(out, err)
}
if _, err := store.Submit(context.Background(), "human-budget", cliHumanSource); err != nil {
t.Fatal(err)
}
// A run's own --budget beats the default and is recorded on the run.
out, err = run("run", "human-budget", "ship it", "--json", "--yes", "--budget", "3")
if err != nil {
t.Fatal(err)
}
var started protocol.Message
if err := json.Unmarshal([]byte(out), &started); err != nil || started.RunDetail == nil {
t.Fatal(out, err)
}
if b := started.RunDetail.Budget; b == nil || b.LimitUSD != 3 || b.Source != "run" {
t.Fatalf("run budget %+v", b)
}
// Only a run parked for a usage limit can be resumed.
if _, err := run("resume", strconv.FormatInt(started.RunDetail.ID, 10), "--yes"); err == nil || !strings.Contains(err.Error(), "not waiting for a usage limit") {
t.Fatal("resume of a run that is not parked:", err)
}
if _, err := run("cancel", strconv.FormatInt(started.RunDetail.ID, 10), "--yes"); err != nil {
t.Fatal(err)
}
}
+52
View File
@@ -0,0 +1,52 @@
package cli
import (
"fmt"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// localClock renders an RFC 3339 instant as local wall-clock time ("15:04",
// with the date when it is not today).
func localClock(value string) string {
at, err := time.Parse(time.RFC3339, value)
if err != nil {
return value
}
at = at.Local()
if y, m, d := at.Date(); y == time.Now().Year() && m == time.Now().Month() && d == time.Now().Day() {
return at.Format("15:04")
}
return at.Format("15:04 on 2 Jan")
}
// quotaWaitLine tells a reader (or agent) what a run parked for a usage
// limit does next and how to act on it; "" for any other run.
func quotaWaitLine(d *protocol.RunDetail) string {
if d == nil || d.Status != protocol.RunStatusWaitingQuota || d.QuotaWait == nil {
return ""
}
w := d.QuotaWait
what := "starts"
if w.Sequence > 0 {
what = "resumes stage " + w.Stage
}
account := ""
if w.Account != "" {
account = " of " + w.Account
}
return fmt.Sprintf("run %d is waiting for the Claude usage limit%s to reset at %s; it %s automatically at %s — resume now: pipelines resume %d; cancel: pipelines cancel %d; wait: pipelines wait %d", d.ID, account, localClock(w.ResetsAt), what, localClock(w.ResumeAt), d.ID, d.ID, d.ID)
}
// failureClassLine summarizes failure class counts in protocol order.
func failureClassLine(counts map[string]int) string {
var parts []string
for _, class := range protocol.FailureClasses {
if n := counts[class]; n > 0 {
parts = append(parts, fmt.Sprintf("%d %s", n, protocol.FailureClassLabel(class)))
}
}
return strings.Join(parts, " · ")
}
+59
View File
@@ -0,0 +1,59 @@
package cli
import (
"errors"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func TestQuotaPolicyRefusesAutomationUnlessAsked(t *testing.T) {
for _, tc := range []struct {
o options
want string
}{
{options{}, protocol.QuotaDefer},
{options{json: true}, protocol.QuotaRefuse},
{options{yes: true}, protocol.QuotaRefuse},
{options{json: true, quotaDefer: true}, protocol.QuotaDefer},
{options{yes: true, quotaNow: true}, protocol.QuotaNow},
} {
if got, err := tc.o.quotaPolicy(); err != nil || got != tc.want {
t.Errorf("%+v: %q %v, want %q", tc.o, got, err, tc.want)
}
}
both := options{quotaNow: true, quotaDefer: true}
if _, err := both.quotaPolicy(); err == nil {
t.Fatal("--now with --defer was accepted")
}
refusal := quotaHint(errors.New("the Claude usage limit of a@b resets at 09:00 on 4 Dec; not starting into a known limit: ..."))
if !strings.Contains(refusal.Error(), "--defer") || !strings.Contains(refusal.Error(), "--now") {
t.Fatal(refusal)
}
}
func TestQuotaWaitLineAndFailureClassWording(t *testing.T) {
reset := time.Now().Add(time.Hour).UTC()
parked := &protocol.RunDetail{RunSummary: protocol.RunSummary{ID: 7, Status: protocol.RunStatusWaitingQuota, QuotaWait: &protocol.RunQuotaWait{ResetsAt: reset.Format(time.RFC3339), ResumeAt: reset.Add(time.Minute).Format(time.RFC3339), Sequence: 3, Stage: "implement", Account: "a@example.com"}}}
line := quotaWaitLine(parked)
for _, want := range []string{"run 7", "a@example.com", "resumes stage implement", reset.Local().Format("15:04"), "pipelines resume 7", "pipelines cancel 7"} {
if !strings.Contains(line, want) {
t.Fatalf("%q lacks %q", line, want)
}
}
if !strings.Contains(inspectSummary(parked), "pipelines resume 7") {
t.Fatal("inspect does not say how to resume a parked run")
}
failed := &protocol.RunDetail{RunSummary: protocol.RunSummary{ID: 8, Status: "failed", FailureClass: protocol.FailurePermissionDenied, Diagnostic: "tool permission denied: Bash(git push)"}}
if note := failureNote(failed); !strings.HasPrefix(note, "[permission_denied]") {
t.Fatal(note)
}
if summary := inspectSummary(failed); !strings.Contains(summary, "failure class: permission_denied (permission denied)") {
t.Fatal(summary)
}
if line := failureClassLine(map[string]int{protocol.FailureQuota: 25, protocol.FailureBlocked: 3}); line != "25 usage limit · 3 blocked" {
t.Fatal(line)
}
}
+117
View File
@@ -0,0 +1,117 @@
package filediff
import (
"crypto/sha256"
"fmt"
"io/fs"
"path"
"strings"
)
// Policy no-patch reasons: the change is listed, completely, without a patch
// by design rather than because a capture limit ran out, so it never makes a
// capture partial.
const (
reasonSymlink = "symlink" // a symbolic link; its target is compared
reasonLarge = "large" // over the hash bound; compared by size, mtime and mode
reasonGenerated = "generated" // a lockfile, minified bundle or source map
)
// cacheDirs are tool caches, virtual environments and dependency trees. Their
// untracked files are left out of the inventory entirely (never "skipped"):
// they are regenerated by tools, not authored by a stage. Tracked files below
// them are still compared, without a patch.
var cacheDirs = map[string]bool{
"node_modules": true, "bower_components": true, ".git": true,
"__pycache__": true, ".venv": true, "venv": true, ".tox": true, ".nox": true,
".mypy_cache": true, ".pytest_cache": true, ".ruff_cache": true, ".hypothesis": true, ".eggs": true,
".next": true, ".nuxt": true, ".svelte-kit": true, ".turbo": true, ".parcel-cache": true, ".pnpm-store": true,
".dart_tool": true, ".gradle": true, ".terraform": true,
}
// buildDirs are conventional build output directories. Untracked files below
// one are left out only when Git tracks nothing there, so a new source file
// in a real `build/` source directory is still captured.
var buildDirs = map[string]bool{"build": true, "dist": true, "out": true, "target": true, "coverage": true}
// generatedNames are lockfiles: tool output whose diff is noise.
var generatedNames = map[string]bool{
"package-lock.json": true, "npm-shrinkwrap.json": true, "yarn.lock": true, "pnpm-lock.yaml": true,
"bun.lockb": true, "cargo.lock": true, "go.sum": true, "poetry.lock": true, "uv.lock": true,
"pipfile.lock": true, "gemfile.lock": true, "composer.lock": true, "pubspec.lock": true,
"flake.lock": true, "mix.lock": true, "podfile.lock": true, "packages.lock.json": true,
}
// inCacheDir reports whether any directory component of name is a cache dir.
func inCacheDir(name string) bool {
parts := strings.Split(name, "/")
for _, part := range parts[:len(parts)-1] {
if cacheDirs[part] {
return true
}
}
return false
}
// generatedFile reports a file whose diff is tool output: a lockfile, a
// minified bundle, a source map, compiled Python, or anything below a cache
// directory.
func generatedFile(name string) bool {
base := strings.ToLower(path.Base(name))
if generatedNames[base] || strings.HasSuffix(base, ".min.js") || strings.HasSuffix(base, ".min.css") ||
strings.HasSuffix(base, ".map") || strings.HasSuffix(base, ".pyc") {
return true
}
return inCacheDir(name)
}
// excludedUntracked reports an untracked path that is tool output rather than
// stage work: below a cache directory, compiled Python, or below a build
// directory where Git tracks nothing (trackedDirs holds every directory that
// contains a tracked file).
func excludedUntracked(name string, trackedDirs map[string]bool) bool {
if inCacheDir(name) || strings.HasSuffix(name, ".pyc") {
return true
}
parts := strings.Split(name, "/")
for i, part := range parts[:len(parts)-1] {
if buildDirs[part] && !trackedDirs[strings.Join(parts[:i+1], "/")] {
return true
}
}
return false
}
// trackedDirectories returns every ancestor directory of the tracked names.
func trackedDirectories(names []string) map[string]bool {
dirs := map[string]bool{}
for _, name := range names {
for dir := path.Dir(name); dir != "." && dir != "/" && !dirs[dir]; dir = path.Dir(dir) {
dirs[dir] = true
}
}
return dirs
}
// policyReason is the policy no-patch reason of a changed path, preferring
// the stage-end side (a file that became a symlink is a symlink change).
func policyReason(a file, aOK bool, b file, bOK bool) string {
if bOK && b.reason != "" {
return b.reason
}
if aOK && a.reason != "" {
return a.reason
}
return ""
}
// metaHash fingerprints a file by its metadata alone, without reading it: a
// protected (secret) file is never opened, and a huge file is not hashed.
func metaHash(info fs.FileInfo) [32]byte {
return sha256.Sum256(fmt.Appendf(nil, "meta\x00%d\x00%d\x00%o", info.Size(), info.ModTime().UnixNano(), info.Mode()))
}
// linkHash fingerprints a symbolic link by its target.
func linkHash(target string) [32]byte {
return sha256.Sum256([]byte("symlink\x00" + target))
}
+73
View File
@@ -0,0 +1,73 @@
package filediff
import (
"context"
"os"
"path/filepath"
"testing"
)
// A committed symlink no longer makes every capture partial, and a symlink a
// stage creates (a read-only reviewer's stray link) is listed.
func TestSymlinksAreComparedByTarget(t *testing.T) {
dir, git := gitRepo(t)
put(t, dir, "real.md", "skill\n")
if err := os.Symlink("real.md", filepath.Join(dir, "linked")); err != nil {
t.Fatal(err)
}
git("add", "real.md", "linked")
git("commit", "-qm", "init")
ctx := context.Background()
before := Capture(ctx, dir)
if quiet := Compare(before, Capture(ctx, dir, before)); quiet.Status != "complete" || quiet.Skipped != 0 || len(quiet.Files) != 0 {
t.Fatalf("an untouched symlink: %+v", quiet)
}
if err := os.Symlink("/etc", filepath.Join(dir, "stray")); err != nil {
t.Fatal(err)
}
changes := Compare(before, Capture(ctx, dir, before))
if changes.Status != "complete" || len(changes.Files) != 1 {
t.Fatalf("%+v", changes)
}
if f := changes.Files[0]; f.Path != "stray" || f.Kind != "added" || f.NoPatchReason != reasonSymlink || f.Truncated {
t.Fatalf("%+v", f)
}
}
func TestToolOutputIsExcludedOrListedWithoutPatch(t *testing.T) {
dir, git := gitRepo(t)
for _, name := range []string{"build/keep.sh", "go.sum", "src/a.go"} {
if err := os.MkdirAll(filepath.Join(dir, filepath.Dir(name)), 0o700); err != nil {
t.Fatal(err)
}
put(t, dir, name, "v1\n")
}
git("add", ".")
git("commit", "-qm", "init")
ctx := context.Background()
before := Capture(ctx, dir)
for _, name := range []string{"node_modules/x/index.js", "dist/app.js", "src/__pycache__/a.pyc", "build/new.sh"} {
if err := os.MkdirAll(filepath.Join(dir, filepath.Dir(name)), 0o700); err != nil {
t.Fatal(err)
}
put(t, dir, name, "generated\n")
}
put(t, dir, "go.sum", "v2\n")
put(t, dir, "src/a.go", "v2\n")
changes := Compare(before, Capture(ctx, dir, before))
got := map[string]string{}
for _, f := range changes.Files {
got[f.Path] = f.NoPatchReason
}
// Untracked caches and an untracked build directory are left out; a new
// file in a tracked build directory is stage work; a lockfile has no patch.
want := map[string]string{"build/new.sh": "", "go.sum": reasonGenerated, "src/a.go": ""}
if len(got) != len(want) || changes.Status != "complete" {
t.Fatalf("got %v (%+v)", got, changes)
}
for name, reason := range want {
if r, ok := got[name]; !ok || r != reason {
t.Fatalf("%s: got %q (%v)", name, r, got)
}
}
}
+121 -21
View File
@@ -26,12 +26,12 @@ import (
)
const (
maxFiles = 10000
maxFiles = 20000
maxFileBytes = 1 << 20
maxSnapshotBytes = 32 << 20
maxPatchBytes = 128 << 10
maxFilePatchBytes = 64 << 10
maxLines = 5000
maxPatchBytes = 512 << 10
maxFilePatchBytes = 128 << 10
maxLines = 20000
binarySniffBytes = 8 << 10
)
@@ -82,6 +82,12 @@ type file struct {
// already holds it, and a later capture recovers it only if the file
// changed. This keeps the text budget for files Git has no baseline for.
blob string
// reason is a policy no-patch reason (symlink, large, generated): the
// change is listed completely, without a patch, and no content is kept.
reason string
// secret marks a protected file fingerprinted by metadata only. It is
// never read or listed; a change to it makes the capture partial.
secret bool
}
// baseline is stage-start content recovered from Git for a changed file whose
@@ -108,6 +114,9 @@ type Snapshot struct {
// the previous snapshot; missing records why one could not be recovered.
baselines map[string]baseline
missing map[string]string
// excluded holds untracked tool output left out of the inventory, so
// the Git-status pass does not list it either.
excluded map[string]bool
}
// gitCommand runs git for directory with the run's directory environment
@@ -245,7 +254,7 @@ func protected(name string) bool {
if template(part) {
continue
}
if part == ".git" || part == "secrets" || part == ".ssh" || part == ".aws" || part == ".gnupg" || part == ".kube" || part == "node_modules" {
if part == ".git" || part == "secrets" || part == ".ssh" || part == ".aws" || part == ".gnupg" || part == ".kube" {
return true
}
if part == ".env" || strings.HasPrefix(part, ".env.") || strings.HasSuffix(part, ".env") || strings.HasSuffix(part, ".pem") || strings.HasSuffix(part, ".key") || strings.HasSuffix(part, ".db") || strings.HasSuffix(part, ".db-wal") || strings.HasSuffix(part, ".db-shm") || strings.HasSuffix(part, ".sqlite") || strings.HasSuffix(part, ".sqlite3") || part == "auth.json" || part == "credentials.json" {
@@ -278,16 +287,43 @@ func (b *boundedOutput) Write(p []byte) (int, error) {
// inventory lists the files to snapshot. Git is only read, never altered;
// the baseline is still stage-start content (see Capture and recoverBaselines).
func inventory(ctx context.Context, directory string, root *os.Root) ([]string, bool, error) {
func inventory(ctx context.Context, directory string, root *os.Root, excluded map[string]bool) ([]string, bool, error) {
probe := gitCommand(ctx, directory, "-c", "core.fsmonitor=false", "-C", directory, "rev-parse", "--is-inside-work-tree")
if data, err := probe.Output(); err == nil && strings.TrimSpace(string(data)) == "true" {
cmd := gitCommand(ctx, directory, "-c", "core.fsmonitor=false", "-C", directory, "ls-files", "--cached", "--others", "--exclude-standard", "--deduplicate", "-z", "--", ".")
out := &boundedOutput{limit: 2 << 20}
cmd.Stdout = out
if err := cmd.Run(); err != nil {
return nil, true, fmt.Errorf("Git file inventory unavailable")
list := func(args ...string) ([]string, error) {
cmd := gitCommand(ctx, directory, append([]string{"-c", "core.fsmonitor=false", "-C", directory, "ls-files"}, append(args, "-z", "--", ".")...)...)
out := &boundedOutput{limit: 2 << 20}
cmd.Stdout = out
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("Git file inventory unavailable")
}
text := strings.TrimSuffix(out.String(), "\x00")
if text == "" {
return nil, nil
}
return strings.Split(text, "\x00"), nil
}
return strings.Split(strings.TrimSuffix(out.String(), "\x00"), "\x00"), true, nil
tracked, err := list("--cached", "--deduplicate")
if err != nil {
return nil, true, err
}
untracked, err := list("--others", "--exclude-standard")
if err != nil {
return nil, true, err
}
// Untracked tool output (caches, dependency trees, untracked build
// directories) is not stage work: leave it out instead of letting it
// crowd the inventory and the budgets.
trackedDirs := trackedDirectories(tracked)
names := tracked
for _, name := range untracked {
if excludedUntracked(name, trackedDirs) {
excluded[name] = true
} else {
names = append(names, name)
}
}
return names, true, nil
}
if ctx.Err() != nil {
return nil, false, ctx.Err()
@@ -300,6 +336,9 @@ func inventory(ctx context.Context, directory string, root *os.Root) ([]string,
if err != nil {
return err
}
if name != "." && entry.IsDir() && cacheDirs[entry.Name()] {
return fs.SkipDir // tool output, not stage work
}
if name != "." && protected(name) {
names = append(names, name)
if entry.IsDir() {
@@ -319,7 +358,7 @@ func inventory(ctx context.Context, directory string, root *os.Root) ([]string,
}
func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snapshot {
s := &Snapshot{files: map[string]file{}, skipped: map[string]bool{}}
s := &Snapshot{files: map[string]file{}, skipped: map[string]bool{}, excluded: map[string]bool{}}
root, err := os.OpenRoot(directory)
if err != nil {
s.diagnostic = "Workspace snapshot unavailable."
@@ -327,7 +366,7 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
}
defer root.Close()
s.available = true
names, git, err := inventory(ctx, directory, root)
names, git, err := inventory(ctx, directory, root, s.excluded)
s.scope = "Workspace regular files"
if git {
s.scope = "Git tracked and nonignored files in the run directory"
@@ -379,12 +418,13 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
s.diagnostic = "Workspace capture reached its time/file limit."
break
}
if !fs.ValidPath(name) || protected(name) {
if !fs.ValidPath(name) {
s.skipped[name] = true
continue
}
// Reject symlinks in every component, including aliases to sensitive paths.
valid := true
// Never follow a symlink: a path through a symlinked directory is
// skipped, and a symlink itself is compared by its target only.
valid, link := true, false
parts := strings.Split(name, "/")
for j := range parts {
info, err := root.Lstat(strings.Join(parts[:j+1], "/"))
@@ -392,6 +432,10 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
valid = false
break
} // tracked deletion
if err == nil && info.Mode()&os.ModeSymlink != 0 && j == len(parts)-1 {
link = true
break
}
if err != nil || info.Mode()&os.ModeSymlink != 0 {
s.skipped[name] = true
valid = false
@@ -402,10 +446,38 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
continue
}
info, err := root.Lstat(name)
if err != nil || !info.Mode().IsRegular() || info.Size() > maxHashBytes {
if err != nil {
s.skipped[name] = true
continue
}
if protected(name) {
// A secret is never opened: its metadata shows whether it changed,
// so an untouched .env no longer makes every capture partial.
if info.IsDir() {
s.skipped[name] = true
} else {
s.files[name] = file{hash: metaHash(info), secret: true}
}
continue
}
if link {
target, err := root.Readlink(name)
if err != nil {
s.skipped[name] = true
continue
}
s.files[name] = file{hash: linkHash(target), size: int64(len(target)), mode: info.Mode().Perm(), reason: reasonSymlink}
continue
}
if !info.Mode().IsRegular() {
s.skipped[name] = true
continue
}
if info.Size() > maxHashBytes {
s.files[name] = file{hash: metaHash(info), size: info.Size(), mode: info.Mode().Perm(), reason: reasonLarge}
continue
}
generated := generatedFile(name)
f, err := root.OpenFile(name, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0)
if err != nil {
s.skipped[name] = true
@@ -440,6 +512,9 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
// listed (without a patch) instead of being skipped unseen.
switch {
case binary:
case generated:
// Tool output: compared by hash, listed without a patch.
entry.reason = reasonGenerated
case seen && p.hash == entry.hash && !p.binary:
// Unchanged since the previous snapshot: share its representation
// without spending this snapshot's budget on it again.
@@ -463,7 +538,11 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
s.skipped[name] = true
continue
}
s.files[name] = file{hash: hash, size: opened.Size(), mode: opened.Mode().Perm(), binary: binary, hashOnly: !binary, limit: reasonFileSize}
entry := file{hash: hash, size: opened.Size(), mode: opened.Mode().Perm(), binary: binary, hashOnly: !binary, limit: reasonFileSize}
if generated && !binary {
entry.hashOnly, entry.limit, entry.reason = false, "", reasonGenerated
}
s.files[name] = entry
}
if prev != nil {
s.recoverBaselines(ctx, directory, prev, used)
@@ -584,6 +663,14 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
result.Files = append(result.Files, change)
}
listed := 0
secretChanges := 0
defer func() {
if secretChanges > 0 {
result.Skipped += secretChanges
result.Status = "partial"
result.Diagnostic = "A protected file (secrets, credentials, databases) changed; it is never read or listed, so this is not a complete workspace diff."
}
}()
// decided records every path the content comparison settled (changed or
// not), so the Git-status pass below only speaks for the rest.
decided := map[string]bool{}
@@ -598,7 +685,13 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
continue
}
decided[name] = true
if aOK && bOK && a.hash == b.hash && a.mode == b.mode {
if aOK && bOK && a.hash == b.hash && a.mode == b.mode && a.secret == b.secret {
continue
}
if a.secret || b.secret {
// A protected file changed: never listed, so the capture is honest
// about being incomplete.
secretChanges++
continue
}
kind := "modified"
@@ -615,6 +708,13 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
if bOK {
change.AfterMode = fmt.Sprintf("%04o", b.mode)
}
if reason := policyReason(a, aOK, b, bOK); reason != "" {
// Listed completely by design (a symlink, a huge or generated
// file), without a patch; not a capture limit.
change.NoPatchReason = reason
add(change)
continue
}
// A clean-at-start file kept only its Git blob id; its start content
// comes from the after snapshot's verified Git recovery.
aData, unavailable := a.data, ""
@@ -690,7 +790,7 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
}
ordered := make([]string, 0, len(gitNames))
for name := range gitNames {
if !decided[name] && fs.ValidPath(name) && !protected(name) {
if !decided[name] && fs.ValidPath(name) && !protected(name) && !before.excluded[name] && !after.excluded[name] {
ordered = append(ordered, name)
}
}
+20 -11
View File
@@ -248,10 +248,10 @@ func TestOverBudgetChangeIsListedWithoutPatch(t *testing.T) {
}
}
// TestGitStatusListsUncomparableChanges proves a file the content snapshot
// skips (here: above the hash bound) is still listed when its Git status
// changes during the visit, while a protected path never is.
func TestGitStatusListsUncomparableChanges(t *testing.T) {
// TestHugeFilesAreListedByMetadata proves a file above the hash bound is
// listed completely (by size, mtime and mode, without a patch), while a
// protected path is never listed and its change marks the capture partial.
func TestHugeFilesAreListedByMetadata(t *testing.T) {
previous := maxHashBytes
maxHashBytes = 16
defer func() { maxHashBytes = previous }()
@@ -263,21 +263,30 @@ func TestGitStatusListsUncomparableChanges(t *testing.T) {
git("commit", "-qm", "init")
ctx := context.Background()
before := Capture(ctx, dir)
put(t, dir, "big.bin", strings.Repeat("y", 64))
if quiet := Compare(before, Capture(ctx, dir, before)); quiet.Status != "complete" || quiet.Skipped != 0 {
t.Fatalf("an untouched secret and huge file made the capture %+v", quiet)
}
put(t, dir, "big.bin", strings.Repeat("y", 65))
put(t, dir, "fresh.bin", strings.Repeat("z", 64))
put(t, dir, ".env", "A=2\n")
changes := Compare(before, Capture(ctx, dir, before))
got := map[string]string{}
for _, f := range changes.Files {
if !f.NoPatch {
t.Fatalf("git-listed change carries a patch: %+v", f)
if f.Patch != "" || f.NoPatchReason != reasonLarge || f.Truncated {
t.Fatalf("huge-file change: %+v", f)
}
got[f.Path] = f.Kind
}
if len(got) != 2 || got["big.bin"] != "modified" || got["fresh.bin"] != "added" {
t.Fatalf("git status listing = %v (%+v)", got, changes)
if len(got) != 2 || got["big.bin"] != "modified" || got["fresh.bin"] != "added" || changes.Status != "complete" {
t.Fatalf("listing = %v (%+v)", got, changes)
}
if changes.Status != "partial" || !strings.Contains(changes.Diagnostic, "without patches") {
put(t, dir, ".env", "A=2\n")
changes = Compare(before, Capture(ctx, dir, before))
for _, f := range changes.Files {
if f.Path == ".env" {
t.Fatal("a protected path was listed")
}
}
if changes.Status != "partial" || !strings.Contains(changes.Diagnostic, "protected") {
t.Fatalf("status/diagnostic = %q/%q", changes.Status, changes.Diagnostic)
}
}
+89
View File
@@ -0,0 +1,89 @@
package pipeline
import (
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/stage"
)
func checkStageSource(key, commands, configs, edges string) string {
return "# stage " + key + "\n\n```configs\ntype=check\n" + configs + "\n```\n\n```commands\n" + commands + "\n```\n\n```edges\n" + edges + "\n```\n"
}
// A check stage sits between implement and review: a red tree goes back to
// the implementer with the failing output, never to the reviewer.
func TestParseCheckStageBeforeReview(t *testing.T) {
source := lintSource(
modelStage("implement", "Make the change.", "read\nedit\nshell", "success -> verify\nerror -> #failure", "```checks\nnone: the verify stage runs the suite\n```"),
checkStageSource("verify", "go vet ./...\ngo test ./...", "command_timeout=15m", "pass -> review\nfail -> implement"),
modelStage("review", "Review the diff.", "read\nglob\ngrep", "success -> #success\nerror -> #failure", ""),
)
g, err := ParseDefinition(source)
if err != nil {
t.Fatal(err)
}
verify := g.Stages[1]
if verify.Type != stage.CheckType || verify.Blocks["commands"] != "go vet ./...\ngo test ./..." || verify.Configs["command_timeout"] != "15m" {
t.Fatalf("parsed %+v", verify)
}
if verify.Edges["error"] != "#failure" || !verify.FallbackError {
t.Fatal("check stage error edge", verify.Edges)
}
def := StageDefinition(verify)
if _, err := stage.CheckStageSpec(def); err != nil {
t.Fatal("stored definition no longer validates:", err)
}
errs, _ := Lint(g)
var rules []string
for _, finding := range errs {
rules = append(rules, finding.String())
}
// fail -> implement loops back: the existing loop rule asks for a limit.
if len(errs) != 1 || errs[0].Rule != "limits" {
t.Fatalf("lint %v", rules)
}
limited := strings.Replace(source, "```configs\ntype=check", "```limits\n{\"max_visits\":3}\n```\n\n```configs\ntype=check", 1)
if g, err = ParseDefinition(limited); err != nil {
t.Fatal(err)
}
if errs, _ := Lint(g); len(errs) != 0 {
t.Fatal(errs)
}
}
func TestCheckStageRejectsModelBlocksAndSilentGuards(t *testing.T) {
if _, err := ParseDefinition(checkStageSource("verify", "go test ./...", "model=x", "pass -> #success\nfail -> #failure")); err == nil {
t.Fatal("model config accepted on a check stage")
}
if _, err := ParseDefinition(checkStageSource("verify", "", "", "pass -> #success\nfail -> #failure")); err == nil {
t.Fatal("empty commands accepted")
}
g, err := ParseDefinition(checkStageSource("verify", "ruff check . || true", "", "pass -> #success\nfail -> #failure"))
if err != nil {
t.Fatal(err)
}
errs, _ := Lint(g)
if len(errs) != 1 || errs[0].Rule != "commands" {
t.Fatal(errs)
}
}
// A delivery check stage is the landing gate: its commands are the checks the
// server runs on the committed candidate before fast-forwarding main.
func TestCheckStageAsLandingGateSatisfiesDeliveryLint(t *testing.T) {
source := lintSource(
modelStage("implement", "Make the change; the delivery gate lands it.", "read\nedit\nshell", "success -> land\nerror -> #failure", "```checks\nnone: the land gate runs the suite\n```"),
checkStageSource("land", "go test ./...", "delivery=true", "pass -> #success\nfail -> #failure"),
)
g, err := ParseDefinition(source)
if err != nil {
t.Fatal(err)
}
if errs, _ := Lint(g); len(errs) != 0 {
t.Fatal(errs)
}
if enabled, err := stage.DeliveryEnabled(StageDefinition(g.Stages[1])); err != nil || !enabled {
t.Fatal(enabled, err)
}
}
+7
View File
@@ -90,6 +90,13 @@ func Lint(g Graph) (errs, warnings []LintFinding) {
}
}
}
if stage.EffectiveType(s.Type) == stage.CheckType {
for _, line := range strings.Split(s.Blocks["commands"], "\n") {
if guard := silentGuard(line); guard != "" {
add(&errs, s, "commands", "command %q can pass without running anything (%s); a missing tool must fail the check, so remove the guard", strings.TrimSpace(line), guard)
}
}
}
if stage.EffectiveType(s.Type) == stage.HumanType {
continue // a person bounds a human stage's loop
}
+3
View File
@@ -42,6 +42,9 @@ FROM pipeline_runs r JOIN pipelines p ON p.id=r.pipeline_id
case "waiting":
title = "Run needs your decision"
body = "waiting for a human decision"
case protocol.RunStatusWaitingQuota:
title = "Run paused for a usage limit"
body = "waiting for the usage limit to reset"
case "failed", "interrupted", "succeeded":
if status == "failed" && failureKind == "expected" && mode != "on" {
settings, err := readNotificationSettings(ctx, tx)
+266
View File
@@ -0,0 +1,266 @@
package pipeline
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Usage-limit parking, failure classes and run budgets (see protocol
// run_quota.go). A parked run keeps everything it needs to continue in its
// own row, so it survives a restart without a goroutine: the reset and resume
// times, the interrupted visit (0 for a run deferred before its first stage),
// and for a deferred run its admitted launch request.
func (s *Store) initRunQuota() error {
for _, column := range []string{"failure_class", "quota_resets_at", "quota_resume_at", "quota_stage", "quota_account", "deferred_json", "budget_source"} {
if err := s.addColumnIfMissing("pipeline_runs", column, "TEXT NOT NULL DEFAULT ''"); err != nil {
return err
}
}
for _, column := range []string{"quota_sequence", "budget_warned"} {
if err := s.addColumnIfMissing("pipeline_runs", column, "INTEGER NOT NULL DEFAULT 0"); err != nil {
return err
}
}
if err := s.addColumnIfMissing("pipeline_runs", "budget_usd", "REAL NOT NULL DEFAULT 0"); err != nil {
return err
}
// quota_limits remembers, per Claude account, until when a stage was
// refused for usage, so a new run or retry is not launched into it.
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS quota_limits (account TEXT PRIMARY KEY, resets_at TEXT NOT NULL)`)
return err
}
// defaultFailureClass is the class of a run that stopped without the runner
// naming one: a cancel, an interruption, a deliberate #failure route
// (blocked) or anything else.
func defaultFailureClass(status, failureKind string) string {
switch status {
case protocol.RunStatusCanceled:
return protocol.FailureCanceled
case "interrupted":
return protocol.FailureInterrupted
case "failed":
if failureKind == "expected" {
return protocol.FailureBlocked
}
return protocol.FailureOther
}
return ""
}
// failureClassCounts counts finished unsuccessful runs by failure class.
func failureClassCounts(ctx context.Context, tx *sql.Tx) (map[string]int, error) {
rows, err := tx.QueryContext(ctx, `SELECT status,failure_kind,failure_class,COUNT(*) FROM pipeline_runs WHERE status IN ('failed','canceled','interrupted') GROUP BY status,failure_kind,failure_class`)
if err != nil {
return nil, err
}
defer rows.Close()
counts := map[string]int{}
for rows.Next() {
var status, kind, class string
var n int
if err := rows.Scan(&status, &kind, &class, &n); err != nil {
return nil, err
}
if class == "" {
class = defaultFailureClass(status, kind)
}
counts[class] += n
}
if err := rows.Err(); err != nil {
return nil, err
}
if len(counts) == 0 {
return nil, nil
}
return counts, nil
}
// SetRunFailureClass records the runner's classification of an unfinished
// run just before it is finished; FinishRun keeps it for a failure and
// clears it for a success.
func (s *Store) SetRunFailureClass(ctx context.Context, id int64, class string) error {
_, err := s.db.ExecContext(ctx, `UPDATE pipeline_runs SET failure_class=? WHERE id=? AND finished_at IS NULL`, class, id)
return err
}
func quotaTime(t time.Time) string {
if t.IsZero() {
return ""
}
return t.UTC().Format(time.RFC3339)
}
// ParkRunForQuota parks an executing run in waiting_quota. sequence is the
// interrupted visit (its step is already finished as failed) or 0 for a run
// deferred before its first stage, whose launch request is deferred.
func (s *Store) ParkRunForQuota(ctx context.Context, id int64, sequence int, stageKey, account string, resetsAt, resumeAt time.Time, diagnostic, deferred string) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET status=?,quota_resets_at=?,quota_resume_at=?,quota_sequence=?,quota_stage=?,quota_account=?,deferred_json=?,diagnostic=?,current_stage=CASE WHEN ?<>'' THEN ? ELSE current_stage END
WHERE id=? AND status IN ('queued','running') AND cancel_requested=0 AND cleanup_unconfirmed=0
AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_active=1)`,
protocol.RunStatusWaitingQuota, quotaTime(resetsAt), quotaTime(resumeAt), sequence, stageKey, account, deferred, diagnostic, stageKey, stageKey, id)); err != nil {
return fmt.Errorf("%w: %v", ErrInvalidRunTransition, err)
}
if err := enqueueRunTransitionNotification(ctx, tx, id); err != nil {
return err
}
return tx.Commit()
}
// QuotaParking is a parked run's resume record.
type QuotaParking struct {
RunID int64
Sequence int
Stage string
Account string
ResetsAt time.Time
ResumeAt time.Time
Deferred string
}
func scanQuotaParking(row interface{ Scan(...any) error }) (QuotaParking, error) {
var p QuotaParking
var resets, resume string
if err := row.Scan(&p.RunID, &p.Sequence, &p.Stage, &p.Account, &resets, &resume, &p.Deferred); err != nil {
return p, err
}
p.ResetsAt, _ = time.Parse(time.RFC3339, resets)
p.ResumeAt, _ = time.Parse(time.RFC3339, resume)
return p, nil
}
// QuotaParkedRuns lists every run parked in waiting_quota.
func (s *Store) QuotaParkedRuns(ctx context.Context) ([]QuotaParking, error) {
rows, err := s.db.QueryContext(ctx, `SELECT id,quota_sequence,quota_stage,quota_account,quota_resets_at,quota_resume_at,deferred_json FROM pipeline_runs WHERE status=? AND cancel_requested=0 ORDER BY id`, protocol.RunStatusWaitingQuota)
if err != nil {
return nil, err
}
defer rows.Close()
var parked []QuotaParking
for rows.Next() {
p, err := scanQuotaParking(rows)
if err != nil {
return nil, err
}
parked = append(parked, p)
}
return parked, rows.Err()
}
// UnparkQuotaRun moves a parked run back to running and returns its resume
// record. It fails with ErrInvalidRunTransition when the run is not parked
// (already resumed, canceled or deleted), so a resume happens at most once.
func (s *Store) UnparkQuotaRun(ctx context.Context, id int64) (QuotaParking, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return QuotaParking{}, err
}
defer tx.Rollback()
p, err := scanQuotaParking(tx.QueryRowContext(ctx, `SELECT id,quota_sequence,quota_stage,quota_account,quota_resets_at,quota_resume_at,deferred_json FROM pipeline_runs WHERE id=? AND status=? AND cancel_requested=0`, id, protocol.RunStatusWaitingQuota))
if err == sql.ErrNoRows {
return QuotaParking{}, fmt.Errorf("%w: run %d is not waiting for a usage limit", ErrInvalidRunTransition, id)
}
if err != nil {
return QuotaParking{}, err
}
status := protocol.RunStatusRunning
if p.Sequence == 0 {
status = protocol.RunStatusQueued
}
if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET status=?,quota_resets_at='',quota_resume_at='',quota_sequence=0,quota_stage='',deferred_json='',diagnostic='' WHERE id=? AND status=?`, status, id, protocol.RunStatusWaitingQuota)); err != nil {
return QuotaParking{}, err
}
return p, tx.Commit()
}
// RecordQuotaLimit remembers that account is out of usage until resetsAt.
func (s *Store) RecordQuotaLimit(ctx context.Context, account string, resetsAt time.Time) error {
if strings.TrimSpace(account) == "" || resetsAt.IsZero() {
return nil
}
_, err := s.db.ExecContext(ctx, `INSERT INTO quota_limits(account,resets_at) VALUES(?,?)
ON CONFLICT(account) DO UPDATE SET resets_at=CASE WHEN excluded.resets_at>resets_at THEN excluded.resets_at ELSE resets_at END`, account, quotaTime(resetsAt))
return err
}
// QuotaLimit reports until when account is known to be out of usage; ok is
// false when no limit is known or it has already reset.
func (s *Store) QuotaLimit(ctx context.Context, account string, now time.Time) (time.Time, bool, error) {
var value string
err := s.db.QueryRowContext(ctx, `SELECT resets_at FROM quota_limits WHERE account=?`, account).Scan(&value)
if err == sql.ErrNoRows {
return time.Time{}, false, nil
}
if err != nil {
return time.Time{}, false, err
}
at, err := time.Parse(time.RFC3339, value)
if err != nil || !at.After(now) {
return time.Time{}, false, nil
}
return at, true, nil
}
// AnyQuotaLimit reports whether any account is known to be limited past now,
// so admission resolves a run's account only when it can matter.
func (s *Store) AnyQuotaLimit(ctx context.Context, now time.Time) (bool, error) {
var any bool
err := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM quota_limits WHERE resets_at>?)`, quotaTime(now)).Scan(&any)
return any, err
}
// SetRunBudget records a run's whole-run USD cap and where it came from.
func (s *Store) SetRunBudget(ctx context.Context, id int64, limitUSD float64, source string) error {
_, err := s.db.ExecContext(ctx, `UPDATE pipeline_runs SET budget_usd=?,budget_source=? WHERE id=?`, limitUSD, source, id)
return err
}
// MarkRunBudgetWarned records the 80% warning once; it reports whether this
// call was the first.
func (s *Store) MarkRunBudgetWarned(ctx context.Context, id int64) (bool, error) {
res, err := s.db.ExecContext(ctx, `UPDATE pipeline_runs SET budget_warned=1 WHERE id=? AND budget_warned=0`, id)
if err != nil {
return false, err
}
n, err := res.RowsAffected()
return n == 1, err
}
// runDefaultBudgetSetting is the server_settings key of the default run cap.
const runDefaultBudgetSetting = "run.default_budget_usd"
// RunSettings reads the server-wide run defaults.
func (s *Store) RunSettings(ctx context.Context) (protocol.RunSettings, error) {
var settings protocol.RunSettings
value, found, err := s.ServerSetting(ctx, runDefaultBudgetSetting)
if err != nil || !found {
return settings, err
}
_, _ = fmt.Sscanf(value, "%g", &settings.DefaultBudgetUSD)
if settings.DefaultBudgetUSD < 0 {
settings.DefaultBudgetUSD = 0
}
return settings, nil
}
// SetRunSettings records the server-wide run defaults.
func (s *Store) SetRunSettings(ctx context.Context, settings protocol.RunSettings) (protocol.RunSettings, error) {
if settings.DefaultBudgetUSD < 0 || settings.DefaultBudgetUSD != settings.DefaultBudgetUSD || settings.DefaultBudgetUSD > 1e6 {
return protocol.RunSettings{}, fmt.Errorf("default_budget_usd must be 0 (no cap) or a positive USD amount")
}
if err := s.SetServerSetting(ctx, runDefaultBudgetSetting, fmt.Sprintf("%g", settings.DefaultBudgetUSD)); err != nil {
return protocol.RunSettings{}, err
}
return s.RunSettings(ctx)
}
+3
View File
@@ -46,6 +46,9 @@ WHERE u.run_id IN (`+strings.TrimSuffix(strings.Repeat("?,", len(args)), ",")+`)
u.SplitKnown = u.TokensKnownStages > 0 && u.SplitUnknownStages == 0
u.CacheKnown = u.TokensKnownStages > 0 && u.CacheKnownStages == u.TokensKnownStages
byID[id].Usage = &u
if byID[id].Budget != nil {
byID[id].Budget.SpentUSD = u.CostUSD
}
}
err = rows.Err()
rows.Close()
+24
View File
@@ -0,0 +1,24 @@
package pipeline
import (
"context"
"encoding/json"
)
// RunWritePaths returns the write paths a run declared (relative to its
// workspace; empty when it declared none). The workspace reservation check
// reads it only when two runs' workspaces nest outside any repository.
func (s *Store) RunWritePaths(ctx context.Context, id int64) ([]string, error) {
var encoded string
if err := s.db.QueryRowContext(ctx, "SELECT write_paths FROM pipeline_runs WHERE id=?", id).Scan(&encoded); err != nil {
return nil, err
}
var paths []string
if encoded == "" {
return nil, nil
}
if err := json.Unmarshal([]byte(encoded), &paths); err != nil {
return nil, err
}
return paths, nil
}
+18 -2
View File
@@ -27,14 +27,27 @@ CASE WHEN r.status='waiting' THEN COALESCE((SELECT sequence FROM session_export_
EXISTS(SELECT 1 FROM run_schedule_origin WHERE run_id=r.id),
COALESCE((SELECT schedule_id FROM run_schedule_origin WHERE run_id=r.id),0),
COALESCE((SELECT name FROM run_schedule_origin WHERE run_id=r.id),''),
MAX(r.size_bytes,0)
MAX(r.size_bytes,0),
r.failure_class,r.quota_resets_at,r.quota_resume_at,r.quota_sequence,r.quota_stage,r.quota_account,r.budget_usd,r.budget_source,r.budget_warned
` + runFrom + ` JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version`
func scanRun(row interface{ Scan(...any) error }, r *protocol.RunSummary) error {
var output, stageModels string
if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &r.FailureKind, &r.FailureReason, &output, &r.CompletedSteps, &r.Workspace, &r.Title, &r.Model, &stageModels, &r.NotifyMode, &r.CancelRequested, &r.CleanupUnconfirmed, &r.OutputFormat, &r.ExportPendingSequence, &r.Scheduled, &r.ScheduleID, &r.ScheduleName, &r.SizeBytes); err != nil {
var quota protocol.RunQuotaWait
var budget protocol.RunBudget
if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &r.FailureKind, &r.FailureReason, &output, &r.CompletedSteps, &r.Workspace, &r.Title, &r.Model, &stageModels, &r.NotifyMode, &r.CancelRequested, &r.CleanupUnconfirmed, &r.OutputFormat, &r.ExportPendingSequence, &r.Scheduled, &r.ScheduleID, &r.ScheduleName, &r.SizeBytes, &r.FailureClass, &quota.ResetsAt, &quota.ResumeAt, &quota.Sequence, &quota.Stage, &quota.Account, &budget.LimitUSD, &budget.Source, &budget.Warned); err != nil {
return err
}
if r.Status == protocol.RunStatusWaitingQuota {
r.QuotaWait = &quota
}
if budget.LimitUSD > 0 {
r.Budget = &budget
}
if r.FailureClass == "" {
// Rows that predate the column still say why they stopped.
r.FailureClass = defaultFailureClass(r.Status, r.FailureKind)
}
if stageModels != "" && stageModels != "{}" {
if err := json.Unmarshal([]byte(stageModels), &r.StageModels); err != nil {
return err
@@ -313,6 +326,9 @@ strftime('%Y-%m-%dT%H:%M:%SZ',started_at),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ'
// The run total is one pass over the steps already loaded above: it adds no
// query and no transcript parse.
r.Usage = protocol.TotalUsage(r.Steps)
if r.Budget != nil && r.Usage != nil {
r.Budget.SpentUSD = r.Usage.CostUSD
}
r.Warnings = protocol.RunWarnings(r.Steps)
if r.Environment != nil {
for _, warning := range r.Environment.Warnings {
+1 -1
View File
@@ -99,7 +99,7 @@ func (s *Store) CreateRunTitled(ctx context.Context, d *protocol.PipelineDetail,
// Acquire the SQLite writer lock while checking the original saved
// revision and occurrence. Edits/deletes between claim and admission
// invalidate admission, including while a title was being generated.
result, err := tx.ExecContext(ctx, `UPDATE saved_schedule_events SET status='admitted' WHERE schedule_id=? AND due=? AND revision=? AND status='claimed' AND run_id IS NULL AND EXISTS(SELECT 1 FROM saved_schedules WHERE id=? AND revision=? AND enabled=1 AND deleted=0)`, origin.ID, origin.Due.UTC().Format(time.RFC3339Nano), origin.Revision, origin.ID, origin.Revision)
result, err := tx.ExecContext(ctx, `UPDATE saved_schedule_events SET status='admitted' WHERE schedule_id=? AND due=? AND revision=? AND status IN ('claimed','delayed') AND run_id IS NULL AND EXISTS(SELECT 1 FROM saved_schedules WHERE id=? AND revision=? AND enabled=1 AND deleted=0)`, origin.ID, origin.Due.UTC().Format(time.RFC3339Nano), origin.Revision, origin.ID, origin.Revision)
if err != nil {
return 0, false, err
}
+10 -4
View File
@@ -355,8 +355,9 @@ func (s *Store) CancelWaiting(ctx context.Context, id int64) error {
}
defer tx.Rollback()
res, err := tx.ExecContext(ctx, `UPDATE pipeline_runs SET status='canceled',cancel_requested=1,
diagnostic=CASE WHEN EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id) THEN 'Canceled while awaiting session export; computed visit retained' ELSE 'Canceled while waiting for a decision' END,
finished_at=CURRENT_TIMESTAMP WHERE id=? AND (status=? OR (status IN ('failed','interrupted') AND EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id)))`, id, protocol.RunStatusWaiting)
diagnostic=CASE WHEN EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id) THEN 'Canceled while awaiting session export; computed visit retained' WHEN status=? THEN 'Canceled while waiting for the usage limit to reset' ELSE 'Canceled while waiting for a decision' END,
failure_class='canceled',quota_resets_at='',quota_resume_at='',deferred_json='',
finished_at=CURRENT_TIMESTAMP WHERE id=? AND (status IN (?,?) OR (status IN ('failed','interrupted') AND EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id)))`, protocol.RunStatusWaitingQuota, id, protocol.RunStatusWaiting, protocol.RunStatusWaitingQuota)
if err != nil {
return err
}
@@ -377,7 +378,7 @@ finished_at=CURRENT_TIMESTAMP WHERE id=? AND (status=? OR (status IN ('failed','
func (s *Store) Cancel(ctx context.Context, id int64) error {
return affected(s.db.ExecContext(ctx, `UPDATE pipeline_runs SET cancel_requested=1,
diagnostic=CASE WHEN cleanup_unconfirmed=1 THEN diagnostic ELSE 'Stop requested; waiting for execution and cleanup to stop' END
WHERE id=? AND (status IN ('queued','running','waiting') OR (status IN ('failed','interrupted') AND EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id)))`, id))
WHERE id=? AND (status IN ('queued','running','waiting','waiting_quota') OR (status IN ('failed','interrupted') AND EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id)))`, id))
}
func (s *Store) FinishRun(ctx context.Context, id int64, status, outcome, diagnostic string, output map[string]any) error {
@@ -391,14 +392,19 @@ func (s *Store) FinishRun(ctx context.Context, id int64, status, outcome, diagno
}
defer tx.Rollback()
failureKind, failureReason := classifyRunFailure(ctx, tx, id, status, diagnostic)
// A class the runner recorded for this run (SetRunFailureClass) wins over
// the derived default; a success carries none.
derivedClass := defaultFailureClass(status, failureKind)
if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET
status=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE ? END,
outcome=CASE WHEN cancel_requested=1 THEN '' ELSE ? END,
diagnostic=CASE WHEN cancel_requested=1 THEN 'Canceled by operator; execution stopped' ELSE ? END,
failure_kind=CASE WHEN cancel_requested=1 THEN '' ELSE ? END,
failure_reason=CASE WHEN cancel_requested=1 THEN '' ELSE ? END,
failure_class=CASE WHEN cancel_requested=1 THEN 'canceled' WHEN ?='' THEN '' WHEN failure_class<>'' THEN failure_class ELSE ? END,
quota_resets_at='',quota_resume_at='',deferred_json='',
output_json=?,finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cleanup_unconfirmed=0
AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_active=1)`, status, outcome, diagnostic, failureKind, failureReason, string(data), id)); err != nil {
AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_active=1)`, status, outcome, diagnostic, failureKind, failureReason, derivedClass, derivedClass, string(data), id)); err != nil {
return err
}
if err := enqueueRunTransitionNotification(ctx, tx, id); err != nil {
+5 -2
View File
@@ -85,6 +85,9 @@ CREATE TABLE IF NOT EXISTS retry_checkpoints (
return err
}
}
if err := s.initRunQuota(); err != nil {
return err
}
if err := s.dropResourceSchema(); err != nil {
return err
}
@@ -245,11 +248,11 @@ func (s *Store) RecoverRunsKeeping(ctx context.Context, keep map[int64]bool, rea
if _, err := tx.ExecContext(ctx, "UPDATE run_steps SET diagnostic=? WHERE run_id=? AND status='interrupted' AND sequence=(SELECT MAX(sequence) FROM run_steps WHERE run_id=?)", "Server restarted; "+reason, id, id); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='interrupted',diagnostic=?,failure_kind='unexpected',failure_reason=?,finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cancel_requested=0 AND cleanup_unconfirmed=0", "Server restarted; "+reason+"; run was not resumed", "Server restarted; "+reason+"; run was not resumed", id); err != nil {
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='interrupted',diagnostic=?,failure_kind='unexpected',failure_reason=?,failure_class='interrupted',finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cancel_requested=0 AND cleanup_unconfirmed=0", "Server restarted; "+reason+"; run was not resumed", "Server restarted; "+reason+"; run was not resumed", id); err != nil {
return err
}
}
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE 'interrupted' END,diagnostic='Server stopped; owned sessions stopped; run was not resumed',failure_kind=CASE WHEN cancel_requested=1 THEN '' ELSE 'unexpected' END,failure_reason=CASE WHEN cancel_requested=1 THEN '' ELSE 'Server stopped; owned sessions stopped; run was not resumed' END,finished_at=CURRENT_TIMESTAMP WHERE status IN ('queued','running') AND status<>? AND cleanup_unconfirmed=0"+runFilter, append([]any{protocol.RunStatusWaiting}, keptArgs...)...); err != nil {
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE 'interrupted' END,diagnostic='Server stopped; owned sessions stopped; run was not resumed',failure_kind=CASE WHEN cancel_requested=1 THEN '' ELSE 'unexpected' END,failure_reason=CASE WHEN cancel_requested=1 THEN '' ELSE 'Server stopped; owned sessions stopped; run was not resumed' END,failure_class=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE 'interrupted' END,finished_at=CURRENT_TIMESTAMP WHERE status IN ('queued','running') AND status<>? AND cleanup_unconfirmed=0"+runFilter, append([]any{protocol.RunStatusWaiting}, keptArgs...)...); err != nil {
return err
}
// An export checkpoint is a paused handoff, not an interrupted model call.
+9
View File
@@ -409,6 +409,15 @@ func (s *Store) FinishSavedSchedule(ctx context.Context, id int64, due time.Time
return err
}
// SavedScheduleOccurrence reads one occurrence's history entry: its status
// (claimed, delayed, admitted, started, skipped, skipped_missed, skipped_day),
// diagnostic and admitted run (0 when none).
func (s *Store) SavedScheduleOccurrence(ctx context.Context, id int64, due time.Time) (status, diagnostic string, runID int64, err error) {
var run sql.NullInt64
err = s.db.QueryRowContext(ctx, `SELECT status,diagnostic,run_id FROM saved_schedule_events WHERE schedule_id=? AND due=?`, id, due.UTC().Format(time.RFC3339Nano)).Scan(&status, &diagnostic, &run)
return status, diagnostic, run.Int64, err
}
// ScheduleAdmission is an internal capability, never decoded from public messages.
type ScheduleAdmission struct {
ID, Revision int64
+6
View File
@@ -61,6 +61,12 @@ func (s *Store) UsageStats(ctx context.Context) (*protocol.UsageStats, error) {
return nil, err
}
stats.Usage = usage
if stats.FailureClasses, err = failureClassCounts(ctx, tx); err != nil {
return nil, err
}
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM pipeline_runs WHERE status=?`, protocol.RunStatusWaitingQuota).Scan(&stats.WaitingQuota); err != nil {
return nil, err
}
return stats, tx.Commit()
}
+8
View File
@@ -208,6 +208,14 @@ type Message struct {
RetryVisit int `json:"retry_visit,omitempty"`
RetryVersion int `json:"retry_version,omitempty"`
RetryInput map[string]any `json:"retry_input,omitempty"`
// QuotaPolicy says what a run/retry does when the Claude account its
// stages use is known to be out of usage: defer (default), refuse or now.
QuotaPolicy string `json:"quota_policy,omitempty"`
// BudgetUSD caps the whole run's reported model cost (0 = the server
// default, if any).
BudgetUSD float64 `json:"budget_usd,omitempty"`
// RunSettings is the get/set_run_settings body and reply.
RunSettings *RunSettings `json:"run_settings,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.
+3
View File
@@ -53,6 +53,9 @@ const (
// NotificationChatNotify is an agent's own notify tool call. Its priority
// is the tool's: low 2, default 3, high 4.
NotificationChatNotify = "chat_notify"
// NotificationSchedule says a scheduled run was delayed (its workspace was
// busy) or skipped. It is low priority (2).
NotificationSchedule = "schedule"
)
// DefaultNotificationPriority is ntfy's default priority, which every ntfy
+113
View File
@@ -0,0 +1,113 @@
package protocol
// Usage-limit parking, failure classes and run budgets.
//
// A run whose stage is refused for a provider usage limit is not failed: it
// is parked in RunStatusWaitingQuota with the reset time and resumes the same
// stage visit automatically a minute after the reset (or when the operator
// sends ResumeRun). A run or retry admitted while the same Claude account is
// known to be limited is deferred the same way before its first stage.
const (
// RunStatusWaitingQuota parks a run until a provider usage limit resets.
// It is not terminal: FinishedAt stays empty and no goroutine holds it.
RunStatusWaitingQuota = "waiting_quota"
// ResumeRun resumes a run parked in waiting_quota now; the reply is Run.
ResumeRun = "resume_run"
// GetRunSettings / SetRunSettings read and change the server-wide run
// defaults; both reply RunSettingsReply carrying RunSettings.
GetRunSettings = "get_run_settings"
SetRunSettings = "set_run_settings"
RunSettingsReply = "run_settings"
)
// Quota policies a run/retry request may carry for a known usage limit of the
// account its Claude stages would use.
const (
// QuotaDefer (also the empty default) admits the run parked in
// waiting_quota until the limit resets.
QuotaDefer = "defer"
// QuotaRefuse rejects the request with the reset time instead.
QuotaRefuse = "refuse"
// QuotaNow starts the run immediately anyway.
QuotaNow = "now"
)
// Failure classes the runner records on a run that did not succeed. The
// value is empty for a run that succeeded, is running or is parked.
const (
FailureQuota = "quota"
FailureLoopExhausted = "loop_exhausted"
FailureTimeout = "timeout"
FailurePermissionDenied = "permission_denied"
FailureHarnessError = "harness_error"
FailureBlocked = "blocked"
FailureEnvironment = "environment"
FailureCanceled = "canceled"
FailureInterrupted = "interrupted"
FailureBudget = "budget"
FailureCheckFailed = "check_failed"
FailureOther = "other"
)
// FailureClasses lists every failure class in display order.
var FailureClasses = []string{FailureQuota, FailureLoopExhausted, FailureTimeout, FailurePermissionDenied, FailureHarnessError, FailureBlocked, FailureEnvironment, FailureCanceled, FailureInterrupted, FailureBudget, FailureCheckFailed, FailureOther}
// FailureClassLabel is the short operator-facing wording of a class.
func FailureClassLabel(class string) string {
switch class {
case FailureQuota:
return "usage limit"
case FailureLoopExhausted:
return "loop limit reached"
case FailureTimeout:
return "timed out"
case FailurePermissionDenied:
return "permission denied"
case FailureHarnessError:
return "harness error"
case FailureBlocked:
return "blocked"
case FailureEnvironment:
return "environment problem"
case FailureCanceled:
return "canceled"
case FailureInterrupted:
return "interrupted"
case FailureBudget:
return "budget exhausted"
case FailureCheckFailed:
return "check failed"
case FailureOther:
return "failed"
}
return class
}
// RunQuotaWait describes a run parked in waiting_quota. ResetsAt is when the
// limit resets (RFC 3339, UTC) and ResumeAt when the server resumes the run.
// Sequence is the interrupted visit (0 when the run is deferred before its
// first stage). Account names the Claude home/account that hit the limit,
// when known.
type RunQuotaWait struct {
ResetsAt string `json:"resets_at"`
ResumeAt string `json:"resume_at"`
Sequence int `json:"sequence,omitempty"`
Stage string `json:"stage,omitempty"`
Account string `json:"account,omitempty"`
}
// RunBudget is a run's whole-run USD cap and what it spent so far. LimitUSD
// is 0 when the run has no cap. Warned is set once the 80% warning was sent.
type RunBudget struct {
LimitUSD float64 `json:"limit_usd"`
Source string `json:"source,omitempty"`
SpentUSD float64 `json:"spent_usd"`
Warned bool `json:"warned,omitempty"`
}
// RunSettings are the server-wide run defaults. DefaultBudgetUSD caps every
// run that names no budget of its own (0 = no default cap).
type RunSettings struct {
DefaultBudgetUSD float64 `json:"default_budget_usd"`
}
+3
View File
@@ -60,6 +60,9 @@ type RunEventFrame struct {
FinishedAt string `json:"finished_at,omitempty"`
FailureKind string `json:"failure_kind,omitempty"`
FailureReason string `json:"failure_reason,omitempty"`
FailureClass string `json:"failure_class,omitempty"`
// QuotaWait is present on a frame that parks the run in waiting_quota.
QuotaWait *RunQuotaWait `json:"quota_wait,omitempty"`
// Artifacts is the number of files recorded for the referenced step, so a
// client can surface artifact capture without reading the step.
Artifacts int `json:"artifacts,omitempty"`
+18 -4
View File
@@ -189,8 +189,15 @@ type RunSummary struct {
Diagnostic string `json:"diagnostic"`
FailureKind string `json:"failure_kind,omitempty"`
FailureReason string `json:"failure_reason,omitempty"`
ResultPreview string `json:"result_preview,omitempty"`
CompletedSteps int `json:"completed_steps"`
// FailureClass is the runner's classification of a run that did not
// succeed (see FailureClasses); empty otherwise and for historical rows.
FailureClass string `json:"failure_class,omitempty"`
// QuotaWait is set while Status is waiting_quota.
QuotaWait *RunQuotaWait `json:"quota_wait,omitempty"`
// Budget is the run's whole-run USD cap; absent when the run has none.
Budget *RunBudget `json:"budget,omitempty"`
ResultPreview string `json:"result_preview,omitempty"`
CompletedSteps int `json:"completed_steps"`
// Model and StageModels are the launch-time overrides this run records so it
// stays reproducible: Model covers every model stage and StageModels overrides
// individual stages by key. They are empty for a run that used the pinned
@@ -458,6 +465,9 @@ type ControlEvidence struct {
LimitReached bool `json:"limit_reached,omitempty"`
ModelTarget string `json:"model_target,omitempty"`
Memory map[string]MemoryRead `json:"memory,omitempty"`
// OutcomeRepairs counts the "missing # outcome" repair follow-ups the
// server sent during this visit (0 when the first answer was valid).
OutcomeRepairs int `json:"outcome_repairs,omitempty"`
}
// StageFileChanges is observed workspace evidence, not a model's claim of authorship.
@@ -483,9 +493,13 @@ type FileChange struct {
NoPatch bool `json:"no_patch,omitempty"`
// NoPatchReason says why a content change has no (complete) patch:
// "binary", "file_size" (text over 1 MiB), "budget" (snapshot text budget),
// "lines" (over 5,000 combined lines), "evidence_size" (per-visit retained
// "lines" (over 20,000 combined lines), "evidence_size" (per-visit retained
// evidence limit), "git_status" (seen only in Git status) or "baseline"
// (stage-start content unrecoverable). Empty when a patch was recorded.
// (stage-start content unrecoverable). Policy reasons, which list the
// change completely and leave Truncated unset: "symlink" (target
// compared), "large" (over the hash bound; size/mtime/mode compared) and
// "generated" (lockfile, minified bundle, source map, cache file).
// Empty when a patch was recorded.
NoPatchReason string `json:"no_patch_reason,omitempty"`
BeforeMode string `json:"before_mode,omitempty"`
AfterMode string `json:"after_mode,omitempty"`
+6
View File
@@ -52,4 +52,10 @@ type UsageStats struct {
// Usage is the history-wide sum of the per-run reported usage. It is absent
// for a database with no recorded model usage (including a pre-upgrade one).
Usage *UsageTotals `json:"usage,omitempty"`
// FailureClasses counts the runs that did not succeed by failure class
// (canceled and interrupted included); rows that predate the class are
// counted as blocked or other, as their runs read.
FailureClasses map[string]int `json:"failure_classes,omitempty"`
// WaitingQuota counts the runs parked for a usage limit now.
WaitingQuota int `json:"waiting_quota,omitempty"`
}
+1 -1
View File
@@ -126,7 +126,7 @@ func TestChatTurnDiffMarksBoundedPatchesTruncated(t *testing.T) {
dir := gitRepo(t, map[string]string{"a.txt": "x\n"})
h := turnDiffHub(t, dir)
h.startRoomTurnDiff("ses_1")
writeTurnFile(t, dir, "big.txt", strings.Repeat("line\n", 6000))
writeTurnFile(t, dir, "big.txt", strings.Repeat("line\n", 21000))
endDiffTurn(h, "ses_1")
turns := recordedTurns(t, h, "ses_1")
if len(turns) != 1 || !turns[0].Truncated || turns[0].Files != 1 || turns[0].Status != "partial" {
+146
View File
@@ -0,0 +1,146 @@
package server
import (
"context"
"errors"
"fmt"
"os"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
// errDeliveryChecksFailed marks a delivery check stage whose commands ran and
// failed on the candidate: that is the stage's fail outcome, not an error.
var errDeliveryChecksFailed = errors.New("delivery checks failed")
// runCheckStage executes a check stage. Without delivery its commands run in
// place in the run workspace. With delivery=true it is the landing gate: the
// server commits the run's leftovers, merges a moved main, runs the commands
// in a fresh candidate worktree of the commit and fast-forwards main only when
// every command passes. A failing command is the fail outcome (main is not
// touched); a gate failure (dirty checkout, conflict, refused fast-forward) is
// an error.
func (r *runner) runCheckStage(ctx context.Context, def stage.Definition, workspace string, delivery bool, landing stage.LandingAccess, runID int64) (stage.Result, error) {
spec, err := stage.CheckStageSpec(def)
if err != nil {
return stage.Result{}, err
}
if !delivery {
def.Workspace = workspace
return stage.CheckStage{}.Run(ctx, def, nil)
}
ctx, cancel := context.WithTimeout(ctx, spec.Timeout)
defer cancel()
var report stage.CheckReport
note, err := verifyDeliveryWith(ctx, workspace, landing, r.deliveryCommitMessage(runID), func(ctx context.Context, candidate string) error {
report = stage.RunCheckCommands(ctx, candidate, spec)
if report.Failed() {
return errDeliveryChecksFailed
}
return nil
})
if err != nil && !errors.Is(err, errDeliveryChecksFailed) {
return stage.Result{}, err
}
result := stage.CheckResult(def.Key, spec, report)
markdown, _ := result.Output["markdown"].(string)
gate := "Delivery gate: the checks ran on a fresh worktree of the committed item; main was not changed."
if err == nil {
gate = "Delivery gate: the checks passed on a fresh worktree of the committed item and main was fast-forwarded to it."
}
if note != "" {
gate += " " + strings.TrimPrefix(note, "delivery gate: ") + "."
}
result.Output["markdown"] = strings.Replace(markdown, "\n## Commands\n", "\n"+gate+"\n\n## Commands\n", 1)
return result, nil
}
// checkVerdict is the check stage's one-line verdict: its own summary, never
// a model's paraphrase of the command output.
func checkVerdict(output stage.Values) *protocol.StageVerdict {
summary, _ := output["summary"].(string)
if strings.TrimSpace(summary) == "" {
return nil
}
return &protocol.StageVerdict{Reason: summary, ReasonSource: protocol.VerdictReasonFallback}
}
// readOnlyViolation reports the files a stage with shell but without edit
// left changed in the run directory: its shell is for reading, testing and
// committing, not for writing. A stage without shell cannot write at all (a
// change during it is not its own), and a stage with edit may write. Paths
// under the stage's artifacts directory, the run's shared public directory and
// a harness state directory that lives inside the workspace (for example
// CLAUDE_CONFIG_DIR) are the harness's or the run's own and are not counted.
// It returns "" when the stage may change files or none changed.
func readOnlyViolation(def stage.Definition, tools []string, explicitTools bool, changes *protocol.StageFileChanges, workspace string, ignored []string) string {
if stage.EffectiveType(def.Type) != stage.ModelType || !explicitTools || def.Configs["allow_workspace_changes"] == "true" || changes == nil {
return ""
}
shell := false
for _, tool := range tools {
if tool == "edit" {
return ""
}
shell = shell || tool == "shell"
}
if !shell {
return ""
}
var prefixes []string
for _, dir := range ignored {
if rel, ok := workspaceRelative(workspace, dir); ok {
prefixes = append(prefixes, rel+"/")
}
}
var changed []string
for _, file := range changes.Files {
skip := false
for _, prefix := range prefixes {
if prefix == "./" || strings.HasPrefix(file.Path+"/", prefix) {
skip = true
break
}
}
if !skip {
changed = append(changed, file.Kind+" "+file.Path)
}
}
if len(changed) == 0 && changes.Omitted == 0 {
return ""
}
listed := changed
if len(listed) > 20 {
listed = append(append([]string(nil), listed[:20]...), fmt.Sprintf("and %d more", len(changed)-20))
}
if changes.Omitted > 0 {
listed = append(listed, fmt.Sprintf("%d more omitted from the capture", changes.Omitted))
}
return fmt.Sprintf("permission denied: stage %s has no edit tool but changed the workspace (%s); the visit fails. If this stage is meant to change files, add edit to its tools or set allow_workspace_changes=true", def.Key, strings.Join(listed, ", "))
}
// workspaceEnv is the environment a command in workspace runs with: the run's
// directory environment when one applies, else the server's.
func workspaceEnv(ctx context.Context, workspace string) []string {
if env := workenv.CommandEnv(ctx, workspace); env != nil {
return env
}
return os.Environ()
}
// workspaceRelative returns dir relative to workspace when dir is inside it.
func workspaceRelative(workspace, dir string) (string, bool) {
workspace = strings.TrimSuffix(workspace, "/")
dir = strings.TrimSuffix(dir, "/")
if workspace == "" || dir == "" {
return "", false
}
if dir == workspace {
return ".", true
}
rel, ok := strings.CutPrefix(dir, workspace+"/")
return rel, ok && rel != ""
}
+206
View File
@@ -0,0 +1,206 @@
package server
import (
"context"
"os"
"path/filepath"
"strings"
"sync/atomic"
"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"
)
func checkModelStage(key, tools, edges, configs string) string {
return "# stage " + key + "\n\n```prompt\nDo the work.\n```\n\n```tools\n" + tools + "\n```\n\n```edges\n" + edges + "\n```\n\n```configs\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n" + configs + "\n```\n\n"
}
func checkTypeStage(key, commands, edges, configs string) string {
return "# stage " + key + "\n\n```limits\n{\"max_visits\":3}\n```\n\n```configs\ntype=check\n" + configs + "\n```\n\n```commands\n" + commands + "\n```\n\n```edges\n" + edges + "\n```\n\n"
}
func startSource(t *testing.T, ctx context.Context, source, workspace string, execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error)) (*protocol.RunDetail, *pipeline.Store) {
t.Helper()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "runner.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { store.Close() })
if _, err := store.Submit(ctx, "check", source); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
r.execute = execute
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: t.Name(), Workspace: workspace, Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, err := store.GetRun(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
return detail, store
}
// A failing check sends the run back to the implementer with the failing
// output in its input; the reviewer only runs once the tree is green.
func TestCheckStageRoutesFailureOutputBackToTheImplementer(t *testing.T) {
ctx := context.Background()
workspace := t.TempDir()
source := checkModelStage("implement", "read\nedit\nshell", "success -> verify\nerror -> #failure", "") +
checkTypeStage("verify", "echo checking\ntest -f fixed || { echo 'FAIL: fixed is missing' >&2; exit 4; }", "pass -> review\nfail -> implement", "") +
checkModelStage("review", "read\nglob\ngrep", "success -> #success\nerror -> #failure", "")
var visits atomic.Int32
var secondInput string
detail, _ := startSource(t, ctx, source, workspace, func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == "implement" {
if visits.Add(1) == 2 {
data, _ := os.ReadFile(def.Turn.Input)
secondInput = string(data)
if err := os.WriteFile(filepath.Join(workspace, "fixed"), []byte("yes\n"), 0o600); err != nil {
return stage.Result{}, err
}
}
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "done"}}, nil
})
if detail.Status != "succeeded" {
t.Fatalf("run %s: %s %+v", detail.Status, detail.Diagnostic, detail.Steps)
}
var stages []string
for _, step := range detail.Steps {
stages = append(stages, step.Stage+":"+step.Outcome)
}
if got := strings.Join(stages, " "); got != "implement:success verify:fail implement:success verify:pass review:success" {
t.Fatal(got)
}
for _, want := range []string{"1 of 2 checks failed", "exit code 4", "FAIL: fixed is missing"} {
if !strings.Contains(secondInput, want) {
t.Fatalf("implementer input lacks %q:\n%s", want, secondInput)
}
}
failed := detail.Steps[1]
if failed.Verdict == nil || !strings.HasPrefix(failed.Verdict.Reason, "1 of 2 checks failed") {
t.Fatalf("verdict %+v", failed.Verdict)
}
checks, _ := failed.Output["checks"].([]any)
if len(checks) != 2 || failed.Provider != "" || failed.SessionID != "" {
t.Fatalf("check step %+v", failed)
}
}
// A delivery check stage is the landing gate: the run's uncommitted work is
// committed, the commands run on a fresh candidate and main fast-forwards;
// a failing command is the fail outcome and leaves main alone.
func TestDeliveryCheckStageLandsOnlyAGreenCandidate(t *testing.T) {
for _, test := range []struct {
name, command, status string
landed bool
}{
{"pass", "test -f work", "succeeded", true},
{"fail", "test -f absent", "failed", false},
} {
t.Run(test.name, func(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
main := filepath.Join(root, "main")
runGit(t, root, "init", "-b", "main", main)
runGit(t, main, "config", "user.email", "test@example.invalid")
runGit(t, main, "config", "user.name", "test")
if err := os.WriteFile(filepath.Join(main, "README"), []byte("base\n"), 0o600); err != nil {
t.Fatal(err)
}
runGit(t, main, "add", "README")
runGit(t, main, "commit", "-m", "base")
item := filepath.Join(root, "item")
runGit(t, main, "worktree", "add", "-b", "item", item)
if err := os.WriteFile(filepath.Join(item, "work"), []byte("change\n"), 0o600); err != nil {
t.Fatal(err)
}
runGit(t, item, "add", "work")
runGit(t, item, "commit", "-m", "work")
before := runGitOutput(t, main, "rev-parse", "HEAD")
source := checkTypeStage("land", test.command, "pass -> #success\nfail -> #failure", "delivery=true")
detail, _ := startSource(t, ctx, source, item, nil)
if detail.Status != test.status || len(detail.Steps) != 1 {
t.Fatalf("run %s %q %+v", detail.Status, detail.Diagnostic, detail.Steps)
}
step := detail.Steps[0]
markdown, _ := step.Output["markdown"].(string)
if !strings.Contains(markdown, "Delivery gate") || step.Output["delivery"] != true {
t.Fatalf("gate evidence missing: %q", markdown)
}
landed := runGitOutput(t, main, "rev-parse", "HEAD") == runGitOutput(t, item, "rev-parse", "HEAD")
if landed != test.landed || (!test.landed && runGitOutput(t, main, "rev-parse", "HEAD") != before) {
t.Fatalf("landed = %v, want %v", landed, test.landed)
}
})
}
}
// A stage without edit that changes the workspace fails its visit and names
// the files; allow_workspace_changes=true opts a stage out.
func TestReadOnlyStageThatChangesFilesFails(t *testing.T) {
ctx := context.Background()
for _, test := range []struct {
name, configs, status string
}{
{"enforced", "", "failed"},
{"allowed", "allow_workspace_changes=true", "succeeded"},
} {
t.Run(test.name, func(t *testing.T) {
workspace := t.TempDir()
if err := os.WriteFile(filepath.Join(workspace, "main.go"), []byte("package main\n"), 0o600); err != nil {
t.Fatal(err)
}
source := checkModelStage("review", "read\nglob\ngrep\nshell", "success -> #success\nerror -> #failure", test.configs)
detail, _ := startSource(t, ctx, source, workspace, func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
if err := os.Symlink("/etc", filepath.Join(workspace, "stray-link")); err != nil {
return stage.Result{}, err
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "looks fine"}}, nil
})
if detail.Status != test.status {
t.Fatalf("run %s %q", detail.Status, detail.Diagnostic)
}
if test.status == "failed" {
diagnostic := detail.Steps[0].Diagnostic
if !strings.Contains(diagnostic, "permission denied") || !strings.Contains(diagnostic, "added stray-link") || !strings.Contains(diagnostic, "allow_workspace_changes") {
t.Fatal(diagnostic)
}
}
})
}
}
func TestReadOnlyViolationIgnoresHarnessAndRunDirectories(t *testing.T) {
def := stage.Definition{Key: "review", Type: stage.ModelType, Configs: map[string]string{}}
changes := &protocol.StageFileChanges{Files: []protocol.FileChange{
{Path: ".claude-profile/.claude.json", Kind: "modified"},
{Path: "artifacts/x/out.md", Kind: "added"},
}}
ignored := []string{"/w/.claude-profile", "/w/artifacts/x"}
if v := readOnlyViolation(def, []string{"read", "shell"}, true, changes, "/w", ignored); v != "" {
t.Fatal(v)
}
changes.Files = append(changes.Files, protocol.FileChange{Path: "src/a.go", Kind: "modified"})
if v := readOnlyViolation(def, []string{"read", "shell"}, true, changes, "/w", ignored); !strings.Contains(v, "modified src/a.go") || strings.Contains(v, ".claude.json") {
t.Fatal(v)
}
for name, ok := range map[string]bool{
"edit tool": readOnlyViolation(def, []string{"edit", "shell"}, true, changes, "/w", nil) == "",
"no shell (cannot write)": readOnlyViolation(def, []string{"read"}, true, changes, "/w", nil) == "",
"no tools block (legacy bundle)": readOnlyViolation(def, nil, false, changes, "/w", nil) == "",
} {
if !ok {
t.Fatal(name, "was enforced")
}
}
}
+17 -8
View File
@@ -43,6 +43,20 @@ const deliveryCleanupTimeout = 10 * time.Second
// own `merge --ff-only`, which refuses without touching anything when a local
// change or untracked file would be overwritten.
func verifyDelivery(ctx context.Context, workspace string, access stage.LandingAccess, checks []string, commitMessage string) (string, error) {
return verifyDeliveryWith(ctx, workspace, access, commitMessage, func(ctx context.Context, candidate string) error {
for _, check := range checks {
if err := runDeliveryCheck(ctx, candidate, check); err != nil {
return err
}
}
return nil
})
}
// verifyDeliveryWith is verifyDelivery with the candidate checks supplied as
// a function of the fresh candidate worktree: a check stage records each
// command's result there instead of stopping at the first error.
func verifyDeliveryWith(ctx context.Context, workspace string, access stage.LandingAccess, commitMessage string, check func(context.Context, string) error) (string, error) {
lock, err := acquireDeliveryLock(ctx, access.LockPath)
if err != nil {
return "", err
@@ -82,7 +96,7 @@ func verifyDelivery(ctx context.Context, workspace string, access stage.LandingA
note = fmt.Sprintf("delivery gate: canonical main moved to %s; merged it into item %s as %s and re-ran checks on the merged tree", shortCommit(mainHead), shortCommit(itemHead), shortCommit(merged))
itemHead = merged
}
if err := runDeliveryCandidate(ctx, workspace, itemHead, checks); err != nil {
if err := runDeliveryCandidate(ctx, workspace, itemHead, check); err != nil {
if note != "" {
return note, fmt.Errorf("%s; %w", note, err)
}
@@ -199,7 +213,7 @@ func acquireDeliveryLock(ctx context.Context, path string) (*os.File, error) {
}
}
func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, checks []string) error {
func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, check func(context.Context, string) error) error {
candidate, err := os.MkdirTemp(filepath.Dir(workspace), ".pipelines-delivery-")
if err != nil {
return fmt.Errorf("create delivery candidate: %w", err)
@@ -212,12 +226,7 @@ func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, check
return fmt.Errorf("create delivery candidate: %w: %s", err, strings.TrimSpace(string(output)))
}
defer cleanupDeliveryCandidate(workspace, candidate)
for _, check := range checks {
if err := runDeliveryCheck(ctx, candidate, check); err != nil {
return err
}
}
return nil
return check(ctx, candidate)
}
// cleanupDeliveryCandidate always uses its own bounded context: the stage context
+75 -2
View File
@@ -122,10 +122,13 @@ func TestCleanupUnconfirmedReservesWorkspaceAcrossRecovery(t *testing.T) {
func TestWorkspaceOverlapIncludesParentsDescendantsAndSymlinks(t *testing.T) {
_, r, pipelineID := concurrentStore(t)
// One repository: its folder and a folder inside it are one shared tree.
workspace := t.TempDir()
child := filepath.Join(workspace, "child")
if err := os.Mkdir(child, 0700); err != nil {
t.Fatal(err)
for _, dir := range []string{filepath.Join(workspace, ".git"), child} {
if err := os.Mkdir(dir, 0700); err != nil {
t.Fatal(err)
}
}
alias := filepath.Join(t.TempDir(), "alias")
if err := os.Symlink(child, alias); err != nil {
@@ -176,3 +179,73 @@ func TestWorkspaceOverlapSeparatesNestedRepositories(t *testing.T) {
}
}
}
// Two folders outside any repository (the operator's ~/caplens and a sibling
// project folder under it) are not one tree merely because neither is in a
// repository: nested, they overlap only where the outer run's declared write
// paths reach the inner folder. The same folder always overlaps.
func TestWorkspaceOverlapNonRepositoryFolders(t *testing.T) {
hub := t.TempDir()
brief := filepath.Join(hub, "brief")
notes := filepath.Join(hub, "notes", "deep")
for _, dir := range []string{brief, notes} {
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
}
paths := func(p ...string) func() []string { return func() []string { return p } }
for _, test := range []struct {
a, b string
aPaths, bPaths func() []string
want bool
}{
{hub, hub, nil, nil, true},
{brief, brief, nil, nil, true},
{hub, brief, nil, nil, false},
{brief, hub, nil, nil, false},
{brief, notes, nil, nil, false},
{hub, brief, paths("notes"), nil, false},
{hub, brief, paths("brief"), nil, true},
{hub, notes, paths("notes"), nil, true},
{hub, notes, paths("notes/deep/file.md"), nil, true},
{notes, hub, nil, paths("notes"), true},
{notes, hub, paths("notes"), nil, false}, // The inner run's paths do not reach out.
{hub, brief, paths("."), nil, true},
} {
if got := workspaceScopesOverlap(test.a, test.b, test.aPaths, test.bPaths); got != test.want {
t.Errorf("overlap(%s, %s) = %v, want %v", test.a, test.b, got, test.want)
}
}
// Nested repository rules stay: a repository inside a plain folder is its
// own tree whatever the folder's write paths.
repo := filepath.Join(hub, "repo")
if err := os.MkdirAll(filepath.Join(repo, ".git"), 0700); err != nil {
t.Fatal(err)
}
if workspaceScopesOverlap(hub, repo, paths("repo"), nil) {
t.Fatal("a repository inside a plain folder overlaps it")
}
// End to end: a scheduled brief in the hub is admitted while a run works in
// a sibling folder below it, and refused only when it declares a write
// path reaching that folder.
_, r, pipelineID := concurrentStore(t)
release := make(chan struct{})
defer close(release)
r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
select {
case <-release:
case <-ctx.Done():
}
return stage.Result{Outcome: "success"}, nil
}
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "notes", Workspace: notes, Input: map[string]any{"prompt": "task"}}); err != nil {
t.Fatal(err)
}
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "brief-scoped", Workspace: hub, WritePaths: []string{"notes"}, Input: map[string]any{"prompt": "task"}}); err == nil || !strings.Contains(err.Error(), "already active") {
t.Fatal("a hub run writing into the active folder was admitted:", err)
}
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "brief", Workspace: hub, Input: map[string]any{"prompt": "task"}}); err != nil {
t.Fatal("a hub run was refused for a sibling folder's run:", err)
}
}
+115
View File
@@ -0,0 +1,115 @@
package server
import (
"context"
"fmt"
"log"
"math"
"regexp"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// Run budgets and the error-loop policy.
//
// A run's whole-run USD cap is the run's own budget_usd, else the server
// default (run settings). Every model stage's budget also counts towards it:
// at 80% the operator is warned once, at 100% the visit stops and the run
// fails with failure class budget. The definition's per-stage budget_usd and
// budget_tokens still cap each stage on their own.
// budgetWarnRatio is the share of the run cap that sends the warning.
const budgetWarnRatio = 0.8
// errorLoopBackoff is the wait before the next visit of a stage whose
// transient harness failure routed back to itself: 15 s, 1 min, then 4 min
// for every further consecutive one. Tests shorten it.
var errorLoopBackoff = []time.Duration{15 * time.Second, time.Minute, 4 * time.Minute}
// sleepOrDone waits delay; false when ctx ends first.
func sleepOrDone(ctx context.Context, delay time.Duration) bool {
if delay <= 0 {
return ctx.Err() == nil
}
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return false
case <-timer.C:
return true
}
}
var harnessSignatureDigits = regexp.MustCompile(`[0-9]+`)
// harnessSignature is a failure's text with its numbers (ids, times,
// counts) removed, so the same failure on two visits compares equal.
func harnessSignature(err error) string {
if err == nil {
return ""
}
text := harnessSignatureDigits.ReplaceAllString(err.Error(), "#")
if len(text) > 400 {
text = text[:400]
}
return text
}
// resolveRunBudget is the cap a new run gets: its own request, else the
// server default. It returns the source recorded with it.
func (r *runner) resolveRunBudget(request protocol.Message) (float64, string, error) {
if request.BudgetUSD < 0 || math.IsNaN(request.BudgetUSD) || math.IsInf(request.BudgetUSD, 0) {
return 0, "", fmt.Errorf("budget_usd must be a positive USD amount")
}
if request.BudgetUSD > 0 {
return request.BudgetUSD, "run", nil
}
ctx, cancel := context.WithTimeout(r.ctx, 5*time.Second)
defer cancel()
settings, err := r.store.RunSettings(ctx)
if err != nil || settings.DefaultBudgetUSD <= 0 {
return 0, "", err
}
return settings.DefaultBudgetUSD, "server", nil
}
// runBudget loads a run's cap and what it already spent (a resumed run).
func (r *runner) runBudget(ctx context.Context, id int64) *stage.RunBudget {
read, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
detail, err := r.store.GetRun(read, id)
if err != nil || detail == nil || detail.Budget == nil {
return nil
}
spent := 0.0
if detail.Usage != nil {
spent = detail.Usage.CostUSD
}
return stage.NewRunBudget(detail.Budget.LimitUSD, spent)
}
// checkRunBudget sends the one 80% warning of a run's cap.
func (r *runner) checkRunBudget(id int64, name string, budget *stage.RunBudget) {
if !budget.Enabled() || budget.Spent() < budget.Limit()*budgetWarnRatio {
return
}
save, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
first, err := r.store.MarkRunBudgetWarned(save, id)
if err != nil || !first {
if err != nil {
log.Printf("run %d: record the budget warning: %v", id, err)
}
return
}
body := fmt.Sprintf("Run #%d · %s · spent $%.2f of its $%.2f budget; it stops at the cap", id, name, budget.Spent(), budget.Limit())
if err := r.store.EnqueueRunNotification(save, pipeline.RunNotification{RunID: id, Sequence: 0, Event: "budget_warning", Channel: "system", Title: "Run budget 80% used", Body: body, Click: runAttentionClick(id)}); err != nil {
log.Printf("run %d: queue the budget warning: %v", id, err)
return
}
r.deliverRunNotificationBatch(time.Now(), 1)
}
+411
View File
@@ -0,0 +1,411 @@
package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"strings"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/claude"
"git.a-wan.net/alan/pipelines/internal/claudeaccounts"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"git.a-wan.net/alan/pipelines/internal/turn"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
// Usage limits park runs instead of failing them.
//
// When a stage is refused for a provider usage limit the runner first tries
// the Claude account auto-switch chats use (the home's own setting decides);
// on a switch the same visit runs again at once on the new account. Otherwise
// the run is parked in waiting_quota with the reset time and resumes the same
// visit a minute after the reset (quotaResumeMargin). The parked state lives
// in the run row, so start-up re-arms the timers. Either way the visit that
// runs again is told, in a "# Previous attempt" note, that the limit
// interrupted it and partial edits may be in the worktree.
//
// A run or retry admitted while the account its Claude stages use is known
// to be out of usage is deferred the same way before its first stage (or
// refused, or started anyway: protocol.QuotaPolicy).
const (
// quotaResumeMargin is how long after the reset a parked run resumes.
quotaResumeMargin = time.Minute
// quotaFallbackHold is the wait when a refusal named no reset time.
quotaFallbackHold = time.Hour
// quotaBusyRetry is the wait before trying again when the run's
// workspace is held by another run at resume time.
quotaBusyRetry = time.Minute
)
// quotaState is the runner's usage-limit collaborators and timers.
type quotaState struct {
mu sync.Mutex
timers map[int64]*time.Timer
// switchAccount signs workspace's Claude home in to another saved
// account with usage left (the chats' auto-switch); nil means no switch
// is possible. It reports the accounts switched from and to.
switchAccount func(ctx context.Context, workspace string, resetsAt time.Time) (from, to string, err error)
// account names the Claude account a run in workspace uses; nil uses
// claudeAccountKey.
account func(ctx context.Context, workspace string) string
// now is the clock; nil is time.Now.
now func() time.Time
}
func (r *runner) quotaNow() time.Time {
if r.quota.now != nil {
return r.quota.now()
}
return time.Now()
}
// quotaAccount names the account a run in workspace uses for its Claude
// stages: its Claude home and the account signed in there.
func (r *runner) quotaAccount(ctx context.Context, workspace string) string {
if r.quota.account != nil {
return r.quota.account(ctx, workspace)
}
resolver := r.dirEnv
if resolver == nil {
resolver = workenv.Default
}
return claudeAccountKey(ctx, resolver, workspace)
}
// claudeAccountKey is "<home>|<email>": the CLAUDE_CONFIG_DIR a process in
// workspace runs with ("default" for the user's own ~/.claude) and the
// account signed in there when its files say.
func claudeAccountKey(ctx context.Context, resolver *workenv.Resolver, workspace string) string {
home, err := claude.AccountConfigDir(ctx, resolver, workspace, os.Environ())
if err != nil {
return "default|"
}
email, _, _, ok := claudeaccounts.Store{ConfigDir: home}.Identity()
if !ok {
email = ""
}
return home + "|" + strings.ToLower(strings.TrimSpace(email))
}
// quotaAccountLabel is the operator-facing name of an account key.
func quotaAccountLabel(account string) string {
home, email, _ := strings.Cut(account, "|")
switch {
case email != "":
return email
case home == "default" || home == "":
return "the server's Claude account"
}
return "the Claude account of " + home
}
// usesClaudeHarness reports whether any model stage of graph runs on the
// Claude harness (the only one whose usage windows reset on their own).
func usesClaudeHarness(graph protocol.Graph) bool {
for _, s := range graph.Stages {
if stage.EffectiveType(s.Type) == stage.ModelType && s.Configs["harness"] == stage.ClaudeBackend {
return true
}
}
return false
}
// quotaAdmission is what start does about a known usage limit.
type quotaAdmission struct {
account string
resetsAt time.Time
}
// knownQuotaLimit reports a known, unexpired usage limit of the account the
// graph's Claude stages would use in workspace.
func (r *runner) knownQuotaLimit(graph protocol.Graph, workspace string) (quotaAdmission, bool) {
if !usesClaudeHarness(graph) {
return quotaAdmission{}, false
}
ctx, cancel := context.WithTimeout(r.ctx, 10*time.Second)
defer cancel()
if any, err := r.store.AnyQuotaLimit(ctx, r.quotaNow()); err != nil || !any {
return quotaAdmission{}, false
}
account := r.quotaAccount(ctx, workspace)
resetsAt, ok, err := r.store.QuotaLimit(ctx, account, r.quotaNow())
if err != nil || !ok {
return quotaAdmission{}, false
}
return quotaAdmission{account: account, resetsAt: resetsAt}, true
}
// quotaRefusal is the error a refuse policy answers with.
func quotaRefusal(limit quotaAdmission) error {
return fmt.Errorf("the Claude usage limit of %s resets at %s; not starting into a known limit: queue the run to start at the reset (quota_policy=defer) or start it now anyway (quota_policy=now)", quotaAccountLabel(limit.account), limit.resetsAt.Local().Format("15:04 on 2 Jan"))
}
// deferredLaunch is the admitted request of a run deferred before its first
// stage, persisted so the start survives a restart.
type deferredLaunch struct {
Request protocol.Message `json:"request"`
RetrySource int64 `json:"retry_source,omitempty"`
}
// deferLaunch parks a just-created run before its first stage. Callers hold
// r.mu; the run is not in r.active.
func (r *runner) deferLaunch(id int64, workspace string, request protocol.Message, limit quotaAdmission) error {
data, err := json.Marshal(deferredLaunch{Request: request, RetrySource: request.RetrySource})
if err != nil {
return err
}
resumeAt := limit.resetsAt.Add(quotaResumeMargin)
diagnostic := fmt.Sprintf("Deferred: the Claude usage limit of %s resets at %s; the run starts at %s", quotaAccountLabel(limit.account), limit.resetsAt.Local().Format("15:04 on 2 Jan"), resumeAt.Local().Format("15:04"))
save, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := r.store.ParkRunForQuota(save, id, 0, "", quotaAccountLabel(limit.account), limit.resetsAt, resumeAt, diagnostic, string(data)); err != nil {
return err
}
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusWaitingQuota, QuotaWait: quotaWaitFrame(0, "", limit.account, limit.resetsAt, resumeAt)}, false)
r.armQuotaResume(id, resumeAt)
return nil
}
func quotaWaitFrame(sequence int, stageKey, account string, resetsAt, resumeAt time.Time) *protocol.RunQuotaWait {
return &protocol.RunQuotaWait{ResetsAt: resetsAt.UTC().Format(time.RFC3339), ResumeAt: resumeAt.UTC().Format(time.RFC3339), Sequence: sequence, Stage: stageKey, Account: quotaAccountLabel(account)}
}
// quotaDecision is what the loop does about a visit refused for usage.
type quotaDecision struct {
// rerun: the home switched accounts; run the visit again now.
rerun bool
// park: wait for the reset.
park bool
account string
resetsAt time.Time
note string
}
// decideQuota handles a visit refused for a usage limit: it records the
// account's limit, then switches accounts or parks. An exhausted paid
// balance (no reset of its own) still fails the run.
func (r *runner) decideQuota(ctx context.Context, workspace string, err error) quotaDecision {
if !stage.SubscriptionQuota(err) {
return quotaDecision{}
}
now := r.quotaNow()
resetsAt, known := stage.QuotaResetsAt(err)
if !known || !resetsAt.After(now) {
resetsAt = now.Add(quotaFallbackHold)
}
lookup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
account := r.quotaAccount(lookup, workspace)
if recordErr := r.store.RecordQuotaLimit(lookup, account, resetsAt); recordErr != nil {
log.Printf("record usage limit of %s: %v", quotaAccountLabel(account), recordErr)
}
if r.quota.switchAccount != nil {
switchCtx, switchCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Minute)
from, to, switchErr := r.quota.switchAccount(switchCtx, workspace, resetsAt)
switchCancel()
if switchErr == nil && to != "" {
if from == "" {
from = "the previous account"
}
return quotaDecision{rerun: true, account: account, resetsAt: resetsAt, note: fmt.Sprintf("The Claude usage limit of %s interrupted this visit; Pipelines switched the Claude home to %s and runs the visit again.", from, to)}
}
if switchErr != nil && !errors.Is(switchErr, claude.ErrAutoSwitchOff) && !errors.Is(switchErr, claude.ErrNoAccountLeft) && !errors.Is(switchErr, claude.ErrNoConfigDir) && !errors.Is(switchErr, errNotClaudeChat) {
log.Printf("run workspace %s: Claude account auto-switch: %v", workspace, switchErr)
}
}
return quotaDecision{park: true, account: account, resetsAt: resetsAt, note: fmt.Sprintf("The Claude usage limit of %s interrupted this visit; the run waited for the limit to reset at %s and resumed the visit.", quotaAccountLabel(account), resetsAt.Local().Format("15:04 on 2 Jan"))}
}
// quotaPreviousAttempt is the note the visit that runs again receives.
func quotaPreviousAttempt(stageKey, note string) string {
return turn.RenderPreviousAttempt(turn.PreviousAttempt{Attempt: 2, Stage: stageKey, Interruption: note})
}
// parkForQuota parks the run after its interrupted visit was recorded.
func (r *runner) parkForQuota(id int64, workspace string, sequence int, stageKey string, completed int, decision quotaDecision) {
resumeAt := decision.resetsAt.Add(quotaResumeMargin)
diagnostic := fmt.Sprintf("Waiting for the Claude usage limit of %s to reset at %s; stage %s resumes at %s", quotaAccountLabel(decision.account), decision.resetsAt.Local().Format("15:04 on 2 Jan"), stageKey, resumeAt.Local().Format("15:04"))
r.mu.Lock()
save, cancel := context.WithTimeout(context.Background(), 10*time.Second)
err := r.store.ParkRunForQuota(save, id, sequence, stageKey, quotaAccountLabel(decision.account), decision.resetsAt, resumeAt, diagnostic, "")
cancel()
if err != nil {
r.mu.Unlock()
log.Printf("run %d: park for the usage limit: %v; finishing it failed", id, err)
r.finishRunStateClass(id, "", workspace, "failed", "error", diagnostic, completed, sequence, stageKey, nil, protocol.FailureQuota)
return
}
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusWaitingQuota, CurrentStage: stageKey, CompletedSteps: completed, QuotaWait: quotaWaitFrame(sequence, stageKey, decision.account, decision.resetsAt, resumeAt)}, false)
// Like a human wait, a parked run holds no goroutine and no workspace
// reservation; the resume checks the workspace is free again.
delete(r.active, id)
r.mu.Unlock()
r.deliverRunNotificationBatch(time.Now(), 1)
r.armQuotaResume(id, resumeAt)
}
// armQuotaResume (re)schedules a parked run's resume.
func (r *runner) armQuotaResume(id int64, at time.Time) {
delay := max(at.Sub(r.quotaNow()), 0)
r.quota.mu.Lock()
defer r.quota.mu.Unlock()
if r.quota.timers == nil {
r.quota.timers = map[int64]*time.Timer{}
}
if old := r.quota.timers[id]; old != nil {
old.Stop()
}
r.quota.timers[id] = time.AfterFunc(delay, func() {
r.quota.mu.Lock()
delete(r.quota.timers, id)
r.quota.mu.Unlock()
if r.ctx.Err() != nil {
return
}
if _, err := r.resumeQuota(id); err != nil {
if errors.Is(err, errQuotaWorkspaceBusy) {
r.armQuotaResume(id, r.quotaNow().Add(quotaBusyRetry))
return
}
if !errors.Is(err, pipeline.ErrInvalidRunTransition) {
log.Printf("run %d: resume after the usage limit: %v", id, err)
}
}
})
}
// disarmQuotaResume drops a parked run's timer (canceled or deleted).
func (r *runner) disarmQuotaResume(id int64) {
r.quota.mu.Lock()
defer r.quota.mu.Unlock()
if timer := r.quota.timers[id]; timer != nil {
timer.Stop()
delete(r.quota.timers, id)
}
}
// stopQuotaTimers stops every pending resume (server shutdown).
func (r *runner) stopQuotaTimers() {
r.quota.mu.Lock()
defer r.quota.mu.Unlock()
for id, timer := range r.quota.timers {
timer.Stop()
delete(r.quota.timers, id)
}
}
// armParkedRuns re-arms the resume of every run a previous process parked.
func (r *runner) armParkedRuns() {
ctx, cancel := context.WithTimeout(r.ctx, 10*time.Second)
defer cancel()
parked, err := r.store.QuotaParkedRuns(ctx)
if err != nil {
log.Printf("list runs waiting for a usage limit: %v", err)
return
}
for _, p := range parked {
resumeAt := p.ResumeAt
if resumeAt.IsZero() {
resumeAt = r.quotaNow()
}
r.armQuotaResume(p.RunID, resumeAt)
}
}
var errQuotaWorkspaceBusy = errors.New("the run's workspace is held by another run")
// resumeQuota resumes a parked run now: the interrupted visit runs again, or
// a deferred run starts. Both the timer and the operator's "resume now" use
// it; the store's transition makes it happen at most once.
func (r *runner) resumeQuota(id int64) (*protocol.RunDetail, error) {
if id <= 0 {
return nil, fmt.Errorf("resume requires a positive run ID")
}
r.mu.Lock()
ctx, cancel := context.WithTimeout(r.ctx, 10*time.Second)
detail, err := r.store.GetRun(ctx, id)
if err != nil {
cancel()
r.mu.Unlock()
return nil, err
}
if detail.Status != protocol.RunStatusWaitingQuota {
cancel()
r.mu.Unlock()
return nil, fmt.Errorf("%w: run %d is not waiting for a usage limit (it is %s)", pipeline.ErrInvalidRunTransition, id, detail.Status)
}
if _, busy := r.active[id]; busy {
cancel()
r.mu.Unlock()
return nil, fmt.Errorf("run %d is still settling; try again in a moment", id)
}
if err := r.checkWorkspaceFree(detail.Workspace); err != nil {
cancel()
r.mu.Unlock()
return nil, fmt.Errorf("%w: %v", errQuotaWorkspaceBusy, err)
}
parking, err := r.store.UnparkQuotaRun(ctx, id)
cancel()
if err != nil {
r.mu.Unlock()
return nil, err
}
r.disarmQuotaResume(id)
r.rememberRunIdentity(id, identityOfRunSummary(detail.RunSummary))
workspace := detail.Workspace
if parking.Sequence == 0 {
var launch deferredLaunch
if err := json.Unmarshal([]byte(parking.Deferred), &launch); err != nil {
r.mu.Unlock()
r.finishRunStateClass(id, detail.Name, workspace, "failed", "error", "deferred launch request is unreadable: "+err.Error(), 0, 0, "", nil, protocol.FailureOther)
return r.getRun(id)
}
request := launch.Request
request.RetrySource = launch.RetrySource
d, err := r.store.Get(r.ctx, detail.PipelineID, detail.Version)
if err != nil {
r.mu.Unlock()
r.finishRunStateClass(id, detail.Name, workspace, "failed", "error", err.Error(), 0, 0, "", nil, protocol.FailureOther)
return r.getRun(id)
}
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusQueued}, false)
r.launch(id, workspace, func(ctx context.Context) {
r.run(ctx, id, d, workspace, request)
})
r.mu.Unlock()
return r.getRun(id)
}
var interrupted *protocol.RunStep
for i := range detail.Steps {
if detail.Steps[i].Sequence == parking.Sequence {
interrupted = &detail.Steps[i]
}
}
if interrupted == nil {
r.mu.Unlock()
r.finishRunStateClass(id, detail.Name, workspace, "failed", "error", fmt.Sprintf("the visit interrupted by the usage limit (#%d) is missing", parking.Sequence), completedSteps(detail.Steps), parking.Sequence, parking.Stage, nil, protocol.FailureQuota)
return r.getRun(id)
}
step := *interrupted
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusRunning, CurrentStage: step.Stage, CompletedSteps: completedSteps(detail.Steps)}, false)
note := fmt.Sprintf("The Claude usage limit of %s interrupted this visit; the run waited for the limit to reset at %s and resumed the visit.", parking.Account, parking.ResetsAt.Local().Format("15:04 on 2 Jan"))
r.launch(id, workspace, func(ctx context.Context) {
state := rebuildRunState(detail, protocol.RunStep{Target: step.Stage, Output: step.Input})
// The interrupted visit does not count against the stage's limits.
if state.visits[step.Stage] > 0 {
state.visits[step.Stage]--
}
state.previousAttempt = quotaPreviousAttempt(step.Stage, note)
r.runLoop(ctx, id, detail.Graph, detail.Name, workspace, protocol.Message{WritePaths: detail.WritePaths, AllowTools: detail.AllowTools, Model: detail.Model, StageModels: detail.StageModels}, state)
})
r.mu.Unlock()
return r.getRun(id)
}
+406
View File
@@ -0,0 +1,406 @@
package server
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// quotaSource is a two-stage Claude pipeline whose stages loop on error, so a
// test sees the runner (not the definition) decide what a failure does.
const quotaSource = "# stage work\n\n```prompt\nDo the work.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> review\nerror -> work\n```\n\n```limits\n{\"max_visits\":3,\"on\":[\"error\"]}\n```\n\n```configs\nharness=claude\nprovider=anthropic\nmodel=claude-haiku-5-5\nretries=0\n```\n\n" +
"# stage review\n\n```prompt\nReview the work.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> #success\nblocked -> #failure\nerror -> work\n```\n\n```configs\nharness=claude\nprovider=anthropic\nmodel=claude-haiku-5-5\nretries=0\n```\n\n"
// quotaRunner submits quotaSource and returns a runner whose Claude account
// is fixed (no real Claude home is read) and whose clock the test controls.
func quotaRunner(t *testing.T) (context.Context, *runner, *pipeline.Store, int64, *atomic.Int64) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
r, store, id := submitRunner(t, ctx, quotaSource)
t.Cleanup(func() {
cancel()
r.wg.Wait()
r.stopQuotaTimers()
store.Close()
})
clock := &atomic.Int64{}
clock.Store(time.Now().UnixNano())
r.quota.now = func() time.Time { return time.Unix(0, clock.Load()) }
r.quota.account = func(context.Context, string) string { return "/homes/a|a@example.com" }
return ctx, r, store, id, clock
}
func quotaLimited(resetsAt time.Time) error {
return fmt.Errorf("model stage work: HARNESS TRANSPORT: %w: %w", stage.ErrHarnessTransport, &stage.QuotaError{Subscription: true, ResetsAt: resetsAt})
}
func runStatus(t *testing.T, store *pipeline.Store, id int64) *protocol.RunDetail {
t.Helper()
detail, err := store.GetRun(context.Background(), id)
if err != nil {
t.Fatal(err)
}
return detail
}
func TestUsageLimitParksTheRunAndResumesTheSameVisit(t *testing.T) {
ctx, r, store, pipelineID, clock := quotaRunner(t)
reset := time.Unix(0, clock.Load()).Add(time.Hour).Truncate(time.Second)
var calls atomic.Int32
var resumedInput atomic.Value
r.execute = func(ctx context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == "work" && calls.Add(1) == 1 {
return stage.Result{}, quotaLimited(reset)
}
if def.Key == "work" {
data, _ := os.ReadFile(def.Turn.Input)
resumedInput.Store(string(data))
}
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
run := startRun(t, r, pipelineID, "quota-park")
parked := runStatus(t, store, run.ID)
if parked.Status != protocol.RunStatusWaitingQuota || parked.FinishedAt != "" || parked.QuotaWait == nil {
t.Fatalf("the run was not parked: %+v", parked.RunSummary)
}
wait := parked.QuotaWait
if wait.Sequence != 1 || wait.Stage != "work" || wait.ResetsAt != reset.UTC().Format(time.RFC3339) || wait.ResumeAt != reset.Add(time.Minute).UTC().Format(time.RFC3339) || wait.Account != "a@example.com" {
t.Fatalf("parking record %+v", wait)
}
if len(parked.Steps) != 1 || parked.Steps[0].Status != "failed" || parked.Steps[0].Target != "work" || strings.Contains(parked.Steps[0].Diagnostic, "top up") {
t.Fatalf("interrupted visit %+v", parked.Steps)
}
if parked.FailureClass != "" {
t.Fatalf("a parked run has no failure class: %q", parked.FailureClass)
}
r.quota.mu.Lock()
armed := r.quota.timers[run.ID] != nil
r.quota.mu.Unlock()
if !armed {
t.Fatal("no resume was scheduled")
}
// The account's limit is remembered for later admissions.
if at, ok, err := store.QuotaLimit(ctx, "/homes/a|a@example.com", time.Unix(0, clock.Load())); err != nil || !ok || !at.Equal(reset) {
t.Fatal("limit not recorded", at, ok, err)
}
// Resume now (the operator's action; the timer calls the same path).
if _, err := r.resumeQuota(run.ID); err != nil {
t.Fatal(err)
}
r.wg.Wait()
done := runStatus(t, store, run.ID)
if done.Status != "succeeded" || len(done.Steps) != 3 || done.QuotaWait != nil {
t.Fatalf("the resumed run did not finish: %+v %+v", done.RunSummary, done.Steps)
}
if done.Steps[1].Stage != "work" || done.Steps[1].Control == nil || done.Steps[1].Control.Visit != 1 {
t.Fatalf("the interrupted visit counted against the stage: %+v", done.Steps[1].Control)
}
input, _ := resumedInput.Load().(string)
if !strings.Contains(input, "# Previous attempt") || !strings.Contains(input, "interrupted") || !strings.Contains(input, "Partial edits") {
t.Fatalf("the resumed visit was not told about the interruption:\n%s", input)
}
if _, err := r.resumeQuota(run.ID); !errors.Is(err, pipeline.ErrInvalidRunTransition) {
t.Fatal("a second resume must be refused", err)
}
}
func TestUsageLimitSwitchesAccountAndRerunsAtOnce(t *testing.T) {
_, r, store, pipelineID, clock := quotaRunner(t)
var calls atomic.Int32
var switched atomic.Int32
r.quota.switchAccount = func(_ context.Context, workspace string, _ time.Time) (string, string, error) {
switched.Add(1)
return "a@example.com", "b@example.com", nil
}
r.execute = func(ctx context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == "work" && calls.Add(1) == 1 {
return stage.Result{}, quotaLimited(time.Unix(0, clock.Load()).Add(time.Hour))
}
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
run := startRun(t, r, pipelineID, "quota-switch")
done := runStatus(t, store, run.ID)
if done.Status != "succeeded" || len(done.Steps) != 3 || switched.Load() != 1 {
t.Fatalf("switch did not rerun the visit: %+v %+v", done.RunSummary, done.Steps)
}
if !strings.Contains(done.Steps[0].Diagnostic, "switched Claude account") || done.Steps[0].Target != "work" {
t.Fatalf("interrupted visit %+v", done.Steps[0])
}
}
func TestParkedRunSurvivesRestartAndCanBeCanceled(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "quota.db")
store, err := pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
ctx, shutdown := context.WithCancel(context.Background())
if _, err := store.Submit(ctx, "quota", quotaSource); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
r.quota.account = func(context.Context, string) string { return "default|" }
reset := time.Now().Add(time.Hour)
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{}, quotaLimited(reset)
}
parkedA := startRun(t, r, items[0].ID, "parked-a")
parkedB := startRun(t, r, items[0].ID, "parked-b")
shutdown()
r.wg.Wait()
r.stopQuotaTimers()
store.Close()
store, err = pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
defer store.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
r, err = newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
defer func() { r.wg.Wait(); r.stopQuotaTimers() }()
for _, id := range []int64{parkedA.ID, parkedB.ID} {
if status := runStatus(t, store, id).Status; status != protocol.RunStatusWaitingQuota {
t.Fatalf("run %d did not stay parked across the restart: %s", id, status)
}
}
// Cancel B while it waits: no goroutine holds it.
if err := r.cancel(parkedB.ID); err != nil {
t.Fatal(err)
}
canceled := runStatus(t, store, parkedB.ID)
if canceled.Status != protocol.RunStatusCanceled || canceled.FailureClass != protocol.FailureCanceled || canceled.FinishedAt == "" {
t.Fatalf("cancel of a parked run: %+v", canceled.RunSummary)
}
// The restarted server's clock is past A's resume time: it resumes.
r.quota.now = func() time.Time { return reset.Add(2 * time.Minute) }
r.quota.account = func(context.Context, string) string { return "default|" }
var mu sync.Mutex
var visits []string
r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
mu.Lock()
visits = append(visits, def.Key)
mu.Unlock()
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
r.armParkedRuns()
deadline := time.Now().Add(10 * time.Second)
for runStatus(t, store, parkedA.ID).Status != "succeeded" {
if time.Now().After(deadline) {
t.Fatalf("the parked run was not resumed after the restart: %+v", runStatus(t, store, parkedA.ID).RunSummary)
}
time.Sleep(20 * time.Millisecond)
}
r.wg.Wait()
mu.Lock()
defer mu.Unlock()
if strings.Join(visits, ",") != "work,review" {
t.Fatalf("resumed visits %v", visits)
}
if status := runStatus(t, store, parkedB.ID).Status; status != protocol.RunStatusCanceled {
t.Fatalf("the canceled run came back: %s", status)
}
}
func TestKnownUsageLimitDefersOrRefusesNewRunsAndRetries(t *testing.T) {
ctx, r, store, pipelineID, clock := quotaRunner(t)
reset := time.Unix(0, clock.Load()).Add(30 * time.Minute)
if err := store.RecordQuotaLimit(ctx, "/homes/a|a@example.com", reset); err != nil {
t.Fatal(err)
}
var calls atomic.Int32
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
calls.Add(1)
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
workspace := t.TempDir()
request := func(key, policy string) protocol.Message {
return protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: key, Workspace: workspace, Input: map[string]any{"prompt": "task"}, QuotaPolicy: policy}
}
if _, err := r.start(request("refused", protocol.QuotaRefuse)); err == nil || !strings.Contains(err.Error(), "resets at") {
t.Fatal("refuse policy did not refuse", err)
}
deferred, err := r.start(request("deferred", ""))
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
if deferred.Status != protocol.RunStatusWaitingQuota || deferred.QuotaWait == nil || deferred.QuotaWait.Sequence != 0 || calls.Load() != 0 {
t.Fatalf("the run was not deferred: %+v", deferred.RunSummary)
}
// A replay of the same request returns the deferred run, not a new one.
if replay, err := r.start(request("deferred", "")); err != nil || replay.ID != deferred.ID {
t.Fatal("replay", replay, err)
}
// The deferred run starts (here: resume now) and runs from its entry.
if _, err := r.resumeQuota(deferred.ID); err != nil {
t.Fatal(err)
}
r.wg.Wait()
if done := runStatus(t, store, deferred.ID); done.Status != "succeeded" || calls.Load() != 2 {
t.Fatalf("the deferred run did not run: %+v", done.RunSummary)
}
// quota_policy=now starts at once anyway.
now, err := r.start(request("now", protocol.QuotaNow))
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
if done := runStatus(t, store, now.ID); done.Status != "succeeded" {
t.Fatalf("quota_policy=now did not start: %+v", done.RunSummary)
}
// A retry is deferred the same way.
r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == "review" {
return stage.Result{Outcome: "blocked", Output: stage.Values{"summary": "no"}}, nil
}
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
failed, err := r.start(request("to-retry", protocol.QuotaNow))
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
if detail := runStatus(t, store, failed.ID); detail.Status != "failed" || detail.FailureClass != protocol.FailureBlocked {
t.Fatalf("blocked run: %+v", detail.RunSummary)
}
retried, err := r.retry(protocol.Message{RunID: failed.ID, RequestKey: "retry-1"})
if err != nil {
t.Fatal(err)
}
if retried.Status != protocol.RunStatusWaitingQuota {
t.Fatalf("the retry was not deferred: %+v", retried.RunSummary)
}
if _, err := r.retry(protocol.Message{RunID: failed.ID, RequestKey: "retry-2", QuotaPolicy: protocol.QuotaRefuse}); err == nil {
t.Fatal("a refuse-policy retry into a known limit was admitted")
}
stats, err := store.UsageStats(ctx)
if err != nil {
t.Fatal(err)
}
if stats.WaitingQuota != 1 || stats.FailureClasses[protocol.FailureBlocked] != 1 {
t.Fatalf("stats: waiting_quota %d, classes %v", stats.WaitingQuota, stats.FailureClasses)
}
}
func TestFailureClassesAndErrorLoopPolicy(t *testing.T) {
saved := errorLoopBackoff
errorLoopBackoff = []time.Duration{5 * time.Millisecond, 10 * time.Millisecond}
t.Cleanup(func() { errorLoopBackoff = saved })
for _, tc := range []struct {
name string
errs []error
status string
class string
visits int
reason string
}{
{name: "deterministic", errs: []error{fmt.Errorf("%w: invalid argument --tools", stage.ErrHarnessTransport)}, status: "failed", class: protocol.FailureHarnessError, visits: 1, reason: "repeats on every attempt"},
{name: "repeated-readback", errs: []error{fmt.Errorf("%w: final assistant readback contained no assistant message", stage.ErrHarnessTransport), fmt.Errorf("%w: final assistant readback contained no assistant message", stage.ErrHarnessTransport)}, status: "failed", class: protocol.FailureHarnessError, visits: 2, reason: "same harness failure repeated"},
{name: "transient", errs: []error{fmt.Errorf("%w: connection reset", stage.ErrHarnessTransport), fmt.Errorf("%w: 503 overloaded", stage.ErrHarnessTransport)}, status: "succeeded", visits: 3},
{name: "permission", errs: []error{fmt.Errorf("model stage work: %w", &stage.PermissionDeniedError{Denials: []string{"Bash(git push)"}})}, status: "failed", class: protocol.FailurePermissionDenied, visits: 1, reason: "Bash(git push)"},
{name: "loop", errs: []error{errors.New("a"), errors.New("b"), errors.New("c")}, status: "failed", class: protocol.FailureLoopExhausted, visits: 3},
{name: "timeout", errs: []error{fmt.Errorf("x: %w", context.DeadlineExceeded), fmt.Errorf("x: %w", context.DeadlineExceeded), fmt.Errorf("x: %w", context.DeadlineExceeded)}, status: "failed", class: protocol.FailureLoopExhausted, visits: 3},
} {
t.Run(tc.name, func(t *testing.T) {
_, r, store, pipelineID, _ := quotaRunner(t)
var calls atomic.Int32
r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == "work" {
if n := int(calls.Add(1)); n <= len(tc.errs) {
return stage.Result{}, tc.errs[n-1]
}
}
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
run := startRun(t, r, pipelineID, "class-"+tc.name)
detail := runStatus(t, store, run.ID)
if detail.Status != tc.status || detail.FailureClass != tc.class {
t.Fatalf("status %s class %q, want %s %q (%s)", detail.Status, detail.FailureClass, tc.status, tc.class, detail.Diagnostic)
}
if got := int(calls.Load()); got != tc.visits {
t.Fatalf("%d visits of work, want %d", got, tc.visits)
}
if tc.reason != "" && !strings.Contains(detail.Diagnostic, tc.reason) {
t.Fatalf("diagnostic %q does not say %q", detail.Diagnostic, tc.reason)
}
})
}
}
func TestRunBudgetWarnsAndStops(t *testing.T) {
ctx, r, store, pipelineID, _ := quotaRunner(t)
r.execute = func(ctx context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
cost := 0.85
if def.Key == "review" {
cost = 0.30
}
if err := stage.BudgetFrom(ctx).ObserveCost("session-"+def.Key, cost); err != nil {
return stage.Result{}, err
}
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
run, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "budget", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}, BudgetUSD: 1})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail := runStatus(t, store, run.ID)
if detail.Status != "failed" || detail.FailureClass != protocol.FailureBudget || len(detail.Steps) != 2 {
t.Fatalf("budget stop: %+v %+v", detail.RunSummary, detail.Steps)
}
// review's error edge leads back to work; a spent run budget does not.
if detail.Steps[1].Target != protocol.FailureEnd {
t.Fatalf("budget stop followed the error edge: %+v", detail.Steps[1])
}
if detail.Budget == nil || detail.Budget.LimitUSD != 1 || detail.Budget.Source != "run" || !detail.Budget.Warned {
t.Fatalf("budget record %+v", detail.Budget)
}
notes, err := store.RunNotifications(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
warned := false
for _, n := range notes {
warned = warned || n.Event == "budget_warning"
}
if !warned {
t.Fatalf("no 80%% warning was queued: %+v", notes)
}
}
func TestServerDefaultRunBudget(t *testing.T) {
ctx, r, store, pipelineID, _ := quotaRunner(t)
if _, err := store.SetRunSettings(ctx, protocol.RunSettings{DefaultBudgetUSD: -1}); err == nil {
t.Fatal("a negative default was accepted")
}
if _, err := store.SetRunSettings(ctx, protocol.RunSettings{DefaultBudgetUSD: 5}); err != nil {
t.Fatal(err)
}
r.execute = successExecute
run := startRun(t, r, pipelineID, "default-budget")
detail := runStatus(t, store, run.ID)
if detail.Budget == nil || detail.Budget.LimitUSD != 5 || detail.Budget.Source != "server" || detail.FailureClass != "" {
t.Fatalf("default budget %+v class %q", detail.Budget, detail.FailureClass)
}
}
+25 -6
View File
@@ -23,12 +23,19 @@ import (
// re-enters that visit, attaches to the session, waits for it to settle (or
// reads the result it reached while the server was down) and continues the
// graph as if it had watched it;
// - a running Claude Code visit is re-adopted the same way: its CLI runs in
// its own session writing stream-json to a file (see
// stage.ClaudeStageClient), so the next process keeps reading that file
// where the CLI is, waits for it to exit, or reads the result it left
// while the server was down (an interrupted outcome repair follow-up is
// asked again);
// - a visit begun but never handed to a harness is marked interrupted and the
// same stage starts again (nothing was admitted, so nothing replays);
// - a run between visits continues with its next stage;
// - a session whose harness process is gone, or that belongs to a harness the
// server owned as a child (Pi, OpenCode V1), falls back to the previous
// behaviour: the run is interrupted, with the reason in its diagnostic.
// - a session whose harness process is gone (a Claude Code CLI that ended
// without a result), or that belongs to a harness the server owned as a
// child (Pi, OpenCode V1), falls back to the previous behaviour: the run
// is interrupted, with the reason in its diagnostic.
//
// Only an operator cancel (cancel_run) stops a stage session.
@@ -61,6 +68,10 @@ var stageServiceAlive = func(ctx context.Context, owner pipeline.SessionOwner) e
return opencode.ReferenceAlive(ctx, owner.Reference)
}
// claudeStageReattachable reports why a retained Claude Code stage session
// cannot be re-adopted (nil when it can). It is a seam for tests.
var claudeStageReattachable = stage.ClaudeStageReattachable
// interruptRecoveredSession stops a previously active session that start-up
// recovery does not re-adopt. It is a seam for tests.
var interruptRecoveredSession = func(ctx context.Context, owner pipeline.SessionOwner) error {
@@ -126,14 +137,22 @@ func planReattach(ctx context.Context, s *pipeline.Store) ([]reattachPlan, map[i
return nil, nil, nil, err
}
owner.RunID = row.ID
if owner.Backend == stage.ClaudeBackend {
// Claude Code stage CLIs run detached from the server: re-adopt
// one still running, or one that left its result while the
// server was down.
if reason := claudeStageReattachable(owner.Reference, owner.ID); reason != nil {
reasons[row.ID] = fmt.Sprintf("the Claude Code session running stage %s could not be reattached: %v", last.Stage, reason)
continue
}
plans = append(plans, reattachPlan{runID: row.ID, kind: reattachAdopt, step: last, owner: owner})
continue
}
if owner.Backend != "v2" {
name := "OpenCode V1"
if owner.Backend == "pi" {
name = "Pi"
}
if owner.Backend == stage.ClaudeBackend {
name = "Claude Code"
}
reasons[row.ID] = fmt.Sprintf("%s stage sessions belong to the stopped server process, so stage %s could not be reattached", name, last.Stage)
continue
}
+91
View File
@@ -294,3 +294,94 @@ func TestOperatorCancelStillStopsDetachingRun(t *testing.T) {
t.Fatalf("operator cancel did not stop the run: detached=%v %+v", detached.Load(), final)
}
}
// ownedClaudeStage is a first-process stage one whose Claude Code CLI
// (session claude-live) is still running, detached, at shutdown.
func ownedClaudeStage(ctx context.Context, s *pipeline.Store, id int64) (stage.Result, error) {
if err := s.RunSession(context.Background(), id, 1, "claude-live", true, stage.ClaudeBackend, "ref-claude"); err != nil {
return stage.Result{}, err
}
<-ctx.Done()
if stage.Detached(ctx) {
return stage.Result{}, stage.ErrDetached
}
return stage.Result{}, ctx.Err()
}
func seamClaudeReattachable(t *testing.T, reason error) *atomic.Value {
t.Helper()
asked := &atomic.Value{}
previous := claudeStageReattachable
claudeStageReattachable = func(reference, session string) error {
asked.Store(reference + " " + session)
return reason
}
t.Cleanup(func() { claudeStageReattachable = previous })
return asked
}
// TestClaudeStageRunContinuesAfterRestart: a Claude Code stage in flight at a
// restart is re-adopted from its retained session (never re-prompted, never
// interrupted) and the run continues to the next stage.
func TestClaudeStageRunContinuesAfterRestart(t *testing.T) {
interrupts := seamRestartRecovery(t, fmt.Errorf("the OpenCode probe must not be used for Claude"))
asked := seamClaudeReattachable(t, nil)
f := stopMidStage(t, ownedClaudeStage)
var resumed atomic.Value
r, s := f.restart(t, func(ctx context.Context, s *pipeline.Store, def stage.Definition) (stage.Result, error) {
if def.Key == "one" {
resumed.Store(stage.TakeResumeSession(ctx))
if err := s.RunSession(context.Background(), f.runID, 1, "claude-live", false, stage.ClaudeBackend, "ref-claude"); err != nil {
return stage.Result{}, err
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "Claude finished"}}, nil
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "next"}}, nil
})
if interrupts.Load() != 0 {
t.Fatal("start-up recovery interrupted a Claude Code stage that survived the restart")
}
if got, _ := asked.Load().(string); got != "ref-claude claude-live" {
t.Fatalf("reattachability asked about %q", got)
}
r.reattachRuns()
r.wg.Wait()
d, err := s.GetRun(context.Background(), f.runID)
if err != nil {
t.Fatal(err)
}
if got, _ := resumed.Load().(string); got != "claude-live" {
t.Fatalf("stage one was not re-adopted from its Claude session: %q", got)
}
if d.Status != "succeeded" || len(d.Steps) != 2 || d.Steps[0].Output["markdown"] != "Claude finished" {
t.Fatalf("run did not continue after the re-adopted Claude stage: %+v", d)
}
}
// TestClaudeStageGoneWithoutResultIsInterruptedWithReason: a Claude Code CLI
// that ended without a result while the server was down is not replayed; the
// run is interrupted, saying why.
func TestClaudeStageGoneWithoutResultIsInterruptedWithReason(t *testing.T) {
interrupts := seamRestartRecovery(t, nil)
seamClaudeReattachable(t, fmt.Errorf("Claude Code stopped while the server was restarting, before it reported a final result"))
f := stopMidStage(t, ownedClaudeStage)
r, s := f.restart(t, func(context.Context, *pipeline.Store, stage.Definition) (stage.Result, error) {
t.Error("a Claude stage without a result executed again")
return stage.Result{}, nil
})
r.reattachRuns()
r.wg.Wait()
d, err := s.GetRun(context.Background(), f.runID)
if err != nil {
t.Fatal(err)
}
if d.Status != "interrupted" || !strings.Contains(d.Diagnostic, "Claude Code session running stage one could not be reattached") || !strings.Contains(d.Diagnostic, "before it reported a final result") {
t.Fatalf("lost Claude stage lacks a clear reason: status=%s run=%q", d.Status, d.Diagnostic)
}
if interrupts.Load() != 1 {
t.Fatalf("the leftover Claude group was not confirmed stopped: %d", interrupts.Load())
}
if owners, _ := s.ActiveSessionOwners(context.Background()); len(owners) != 0 {
t.Fatalf("the lost session still blocks recovery: %+v", owners)
}
}
+10
View File
@@ -537,6 +537,14 @@ func mergeRunEventFrame(into, in *protocol.RunEventFrame) {
if in.Status != "" {
into.Status = in.Status
into.ExportPendingSequence = in.ExportPendingSequence
// A status change carries its own usage-limit wait (or clears it).
into.QuotaWait = in.QuotaWait
}
if in.FailureClass != "" {
into.FailureClass = in.FailureClass
}
if in.FailureKind != "" {
into.FailureKind, into.FailureReason = in.FailureKind, in.FailureReason
}
if in.Outcome != "" {
into.Outcome = in.Outcome
@@ -617,6 +625,8 @@ func handleRunEvents(request protocol.Message, events *runEventHub, runs *runner
FinishedAt: summary.FinishedAt,
FailureKind: summary.FailureKind,
FailureReason: summary.FailureReason,
FailureClass: summary.FailureClass,
QuotaWait: summary.QuotaWait,
CancelRequested: summary.CancelRequested,
CleanupUnconfirmed: summary.CleanupUnconfirmed,
ExportPendingSequence: summary.ExportPendingSequence,
+289 -35
View File
@@ -100,6 +100,8 @@ type runner struct {
// holds the runs start-up recovery kept for reattachRuns to continue.
detach bool
reattach []reattachPlan
// quota parks runs refused for a usage limit (run_quota.go).
quota quotaState
}
func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
@@ -287,6 +289,32 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
}
}
}
budgetUSD, budgetSource, err := r.resolveRunBudget(request)
if err != nil {
return nil, err
}
// A known usage limit of the account the Claude stages would use: defer
// the start to the reset, refuse, or start anyway (protocol.QuotaPolicy).
// An idempotent replay returns its run as it is.
var quotaLimit quotaAdmission
quotaDeferred := false
switch request.QuotaPolicy {
case "", protocol.QuotaDefer, protocol.QuotaRefuse, protocol.QuotaNow:
default:
return nil, fmt.Errorf("quota_policy must be defer, refuse or now")
}
if request.QuotaPolicy != protocol.QuotaNow {
if limit, limited := r.knownQuotaLimit(d.Graph, workspace); limited {
if replay, err := r.store.RunByKey(r.ctx, request.RequestKey); err != nil {
return nil, err
} else if replay == 0 {
if request.QuotaPolicy == protocol.QuotaRefuse {
return nil, quotaRefusal(limit)
}
quotaLimit, quotaDeferred = limit, true
}
}
}
// Decide admission and idempotency under the lock, but generate the title
// only for a request that will actually start a run: a rejected or replayed
// request must not pay for a bounded model generation, and a live one must
@@ -319,7 +347,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
return nil, err
}
if existing == 0 {
if err := r.checkWorkspaceFree(workspace); err != nil {
if err := r.checkWorkspaceFree(workspace, request.WritePaths...); err != nil {
r.mu.Unlock()
return nil, err
}
@@ -343,7 +371,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
// Another run may have reserved this workspace while the title was
// generated, so re-check before reserving it; a race on the request key is
// handled by the store's idempotent insert.
if err := r.checkAdmissionWorkspace(workspace, existing); err != nil {
if err := r.checkAdmissionWorkspace(workspace, existing, request.WritePaths...); err != nil {
r.mu.Unlock()
return nil, err
}
@@ -380,7 +408,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
request.Input["pwd"] = workspace
recheck := r.ctx.Err()
if recheck == nil {
recheck = r.checkAdmissionWorkspace(workspace, existing)
recheck = r.checkAdmissionWorkspace(workspace, existing, request.WritePaths...)
}
if recheck != nil {
r.mu.Unlock()
@@ -414,6 +442,11 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
r.rememberRunIdentity(id, identityOfRunSummary(detail.RunSummary))
}
if created {
if budgetUSD > 0 {
if err := r.store.SetRunBudget(r.ctx, id, budgetUSD, budgetSource); err != nil {
return nil, err
}
}
if request.RetrySource > 0 && request.RetryMode != "restart" {
checkpoint, checkpointErr := r.retrySourceCheckpointSelected(request.RetrySource, d, request.RetryStage, request.RetryVisit, request.RetryInput)
if checkpointErr != nil {
@@ -432,9 +465,24 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
Status: protocol.RunStatusQueued,
CreatedAt: time.Now().UTC().Format(time.RFC3339),
}, false)
r.launch(id, workspace, func(ctx context.Context) {
r.run(ctx, id, d, workspace, request)
})
deferred := false
if quotaDeferred {
if err := r.deferLaunch(id, workspace, request, quotaLimit); err != nil {
log.Printf("run %d: defer to the usage-limit reset: %v; starting now", id, err)
} else {
deferred = true
}
}
if !deferred {
r.launch(id, workspace, func(ctx context.Context) {
r.run(ctx, id, d, workspace, request)
})
}
if budgetUSD > 0 || deferred {
if reread, err := r.store.GetRun(r.ctx, id); err == nil && reread != nil {
detail = reread
}
}
}
if detail != nil {
_, detail.Executing = r.active[id]
@@ -510,7 +558,7 @@ func (r *runner) settleLaunchOnce(id int64, generation *byte) (bool, error) {
}
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: detail.Workspace, Status: protocol.RunStatusCanceled, CancelRequested: true, CurrentStage: detail.CurrentStage, FinishedAt: time.Now().UTC().Format(time.RFC3339)}, true)
}
if detail.FinishedAt != "" || detail.Status == protocol.RunStatusWaiting {
if detail.FinishedAt != "" || detail.Status == protocol.RunStatusWaiting || detail.Status == protocol.RunStatusWaitingQuota {
delete(r.active, id)
}
// A landed (or change-free) successful run's own worktree is no longer
@@ -543,9 +591,9 @@ var runSettleRead = func(r *runner, ctx context.Context, id int64) (*protocol.Ru
// storage maintenance may have removed a clean inactive tree while an
// admission was generating its title, so it is checked under the same lock
// removal takes. Callers must hold r.mu.
func (r *runner) checkAdmissionWorkspace(workspace string, existing int64) error {
func (r *runner) checkAdmissionWorkspace(workspace string, existing int64, writePaths ...string) error {
if existing == 0 {
if err := r.checkWorkspaceFree(workspace); err != nil {
if err := r.checkWorkspaceFree(workspace, writePaths...); err != nil {
return err
}
}
@@ -557,14 +605,30 @@ func (r *runner) checkAdmissionWorkspace(workspace string, existing int64) error
// checkWorkspaceFree refuses a run when an active or cleanup-unconfirmed run
// reserves an overlapping resolved workspace. Callers must hold r.mu.
func (r *runner) checkWorkspaceFree(workspace string) error {
return r.checkWorkspaceFreeExcept(workspace, 0)
// writePaths are the new run's declared write paths (they decide an overlap
// only between nested folders outside any repository).
func (r *runner) checkWorkspaceFree(workspace string, writePaths ...string) error {
return r.checkWorkspaceFreeExcept(workspace, 0, writePaths...)
}
func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64) error {
func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64, writePaths ...string) error {
own := func() []string { return writePaths }
// pathsOf reads a reserving run's declared write paths only when needed.
pathsOf := func(id int64) func() []string {
return func() []string {
read, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 5*time.Second)
defer cancel()
paths, err := r.store.RunWritePaths(read, id)
if err != nil {
// Unknown scope: keep the whole folder reserved (fail closed).
return []string{"."}
}
return paths
}
}
for id, entry := range r.active {
if workspacesOverlap(entry.workspace, workspace) {
return fmt.Errorf("run %d is already active in %s, which overlaps this run's workspace %s; wait for run %d to finish or use a different workspace (for example another checkout of the repository)", id, entry.workspace, workspace, id)
if workspaceScopesOverlap(entry.workspace, workspace, pathsOf(id), own) {
return &workspaceBusyError{runID: id, message: fmt.Sprintf("run %d is already active in %s, which overlaps this run's workspace %s; wait for run %d to finish or use a different workspace (for example another checkout of the repository)", id, entry.workspace, workspace, id)}
}
}
check, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 5*time.Second)
@@ -574,35 +638,76 @@ func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64) error
return fmt.Errorf("read pending export workspace reservations: %w", err)
}
for id, reserved := range reservations {
if id != ownGate && workspacesOverlap(reserved, workspace) {
return fmt.Errorf("run %d is awaiting its session export; workspace %s remains reserved", id, reserved)
if id != ownGate && workspaceScopesOverlap(reserved, workspace, pathsOf(id), own) {
return &workspaceBusyError{runID: id, message: fmt.Sprintf("run %d is awaiting its session export; workspace %s remains reserved", id, reserved)}
}
}
return nil
}
// workspaceBusyError refuses an admission because another run (runID)
// reserves an overlapping workspace; waiting can clear it.
type workspaceBusyError struct {
runID int64
message string
}
func (e *workspaceBusyError) Error() string { return e.message }
// workspacesOverlap reports whether two resolved workspaces are the same
// tree or nested in one another within the same repository. A folder that
// merely holds separate repositories (a hub such as ~/project with clones
// under repos/) does not overlap a run inside one of those repositories, and
// neither do two different repositories nested in one another: each run
// works in its own repository.
// works in its own repository. Two folders outside any repository are not one
// shared tree either: nested, they overlap only where the outer run declared
// write paths reaching the inner folder (see workspaceScopesOverlap).
func workspacesOverlap(a, b string) bool {
within := func(parent, child string) bool {
rel, err := filepath.Rel(parent, child)
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator))
}
return workspaceScopesOverlap(a, b, nil, nil)
}
// workspaceScopesOverlap is workspacesOverlap with each workspace's declared
// write paths (relative to it). They matter only for two nested folders
// outside any repository; a nil lookup means "declared none".
func workspaceScopesOverlap(a, b string, aPaths, bPaths func() []string) bool {
switch {
case filepath.Clean(a) == filepath.Clean(b):
return true
case within(a, b):
return repositoryRoot(b) == repositoryRoot(a)
case within(b, a):
return repositoryRoot(a) == repositoryRoot(b)
case pathAtOrBelow(a, b):
return nestedWorkspacesOverlap(a, b, aPaths)
case pathAtOrBelow(b, a):
return nestedWorkspacesOverlap(b, a, bPaths)
}
return false
}
// nestedWorkspacesOverlap decides for an inner workspace below outer.
func nestedWorkspacesOverlap(outer, inner string, outerPaths func() []string) bool {
root := repositoryRoot(outer)
if repositoryRoot(inner) != root {
return false // Different repositories: each run works in its own.
}
if root != "" {
return true // The same repository is one shared tree.
}
if outerPaths == nil {
return false
}
for _, path := range outerPaths() {
target := filepath.Join(outer, path)
if pathAtOrBelow(target, inner) || pathAtOrBelow(inner, target) {
return true
}
}
return false
}
// pathAtOrBelow reports whether child is parent or below it.
func pathAtOrBelow(parent, child string) bool {
rel, err := filepath.Rel(parent, child)
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator))
}
// repositoryRoot is the nearest directory at or above dir holding a .git
// entry (a repository or a linked worktree), or "" outside any repository.
func repositoryRoot(dir string) string {
@@ -988,7 +1093,12 @@ 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)
// A retry keeps the source run's own budget unless it names one.
budgetUSD := request.BudgetUSD
if budgetUSD == 0 && original.Budget != nil && original.Budget.Source == "run" {
budgetUSD = original.Budget.LimitUSD
}
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, QuotaPolicy: request.QuotaPolicy, BudgetUSD: budgetUSD}, original.ID)
}
func (r *runner) cancel(id int64) error {
@@ -1001,10 +1111,12 @@ func (r *runner) cancel(id int64) error {
if ok {
entry.cancel()
} else {
// Only a parked human run is known to have no live executor.
// Only a parked run (a human decision or a usage limit) is known to
// have no live executor.
if err := r.store.CancelWaiting(r.ctx, id); err != nil {
return err
}
r.disarmQuotaResume(id)
}
r.forgetAttention(id)
if r.events != nil {
@@ -1020,6 +1132,7 @@ func (r *runner) cancel(id int64) error {
FinishedAt: detail.FinishedAt,
CancelRequested: detail.CancelRequested,
CleanupUnconfirmed: detail.CleanupUnconfirmed,
FailureClass: detail.FailureClass,
}, !ok)
}
}
@@ -1055,7 +1168,7 @@ func (r *runner) decide(request protocol.Message) (*protocol.RunDetail, error) {
return nil, fmt.Errorf("run %d is awaiting session export, not a human decision", detail.ID)
}
if detail.Status == protocol.RunStatusWaiting {
if err := r.checkWorkspaceFree(detail.Workspace); err != nil {
if err := r.checkWorkspaceFree(detail.Workspace, detail.WritePaths...); err != nil {
r.mu.Unlock()
return nil, err
}
@@ -1291,6 +1404,14 @@ 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
// failureClass is the class the run finishes with if it fails now: the
// latest visit's failure (protocol.Failure*), "" to let the store derive.
failureClass string
// errorLoops counts each stage's consecutive transient error self-loops
// (the backoff step); lastHarness is its latest repeatable harness
// failure, so the same one twice in a row stops the loop.
errorLoops map[string]int
lastHarness map[string]string
}
func newRunState(key string, input stage.Values) *runState {
@@ -1689,6 +1810,19 @@ func (r *runner) emitRun(frame protocol.RunEventFrame, terminal bool) {
}
func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diagnostic string, completed, sequence int, currentStage string, input stage.Values) {
r.finishRunStateClass(id, name, workspace, status, outcome, diagnostic, completed, sequence, currentStage, input, "")
}
// finishRunStateClass finishes a run recording the runner's failure class
// (empty lets the store derive one; a success records none).
func (r *runner) finishRunStateClass(id int64, name, workspace, status, outcome, diagnostic string, completed, sequence int, currentStage string, input stage.Values, class string) {
if class != "" && status != "succeeded" {
save, cancel := context.WithTimeout(context.Background(), 10*time.Second)
if err := r.store.SetRunFailureClass(save, id, class); err != nil {
log.Printf("run %d: record failure class: %v", id, err)
}
cancel()
}
// The deliverable and the size walk touch files only: they run without r.mu,
// so listings and details do not stall behind a large run finishing. The
// run stays in r.active (its workspace reserved) until the launch teardown.
@@ -1732,6 +1866,7 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag
FinishedAt: detail.FinishedAt,
FailureKind: detail.FailureKind,
FailureReason: detail.FailureReason,
FailureClass: detail.FailureClass,
SizeBytes: size,
}, true)
r.kickSizes()
@@ -1883,7 +2018,7 @@ func (r *runner) finishStage(id int64, name, workspace string, selected protocol
func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, name, workspace string, request protocol.Message, state *runState) {
finish := func(status, outcome, diagnostic string) {
r.finishRunState(id, name, workspace, status, outcome, diagnostic, state.completed, state.nextSequence-1, state.key, state.input)
r.finishRunStateClass(id, name, workspace, status, outcome, diagnostic, state.completed, state.nextSequence-1, state.key, state.input, state.failureClass)
}
// canceled settles an operator cancel. A server shutdown is not a cancel:
// the run is left exactly as persisted for the next process to continue.
@@ -1921,11 +2056,17 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
}
effectiveModels = resolved
}
runBudget := r.runBudget(ctx, id)
for sequence := state.nextSequence; sequence <= 30; sequence++ {
if ctx.Err() != nil {
canceled()
return
}
if budgetErr := runBudget.Check(); budgetErr != nil {
state.failureClass = protocol.FailureBudget
finish("failed", "error", budgetErr.Error())
return
}
key := state.key
var def stage.Definition
var selected protocol.Stage
@@ -1961,10 +2102,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
// stage must not begin work it can never execute.
if !isHuman {
if state.visits[key]+1 > 5 {
state.failureClass = protocol.FailureLoopExhausted
finish("failed", "error", "stage visit budget exceeded")
return
}
if state.visits[key]+1 > maxVisits {
state.failureClass = protocol.FailureLoopExhausted
finish("failed", "error", fmt.Sprintf("stage %s visit limit reached (%d)", key, maxVisits))
return
}
@@ -2190,9 +2333,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
// The budget is shared across every visit to this stage key, so capture
// its cumulative usage before the visit and record only this visit's
// increment on the step, never the cumulative total again.
budgets[key].SetRun(runBudget)
budgetBefore = budgets[key].Snapshot()
stageCtx = stage.WithBudget(stageCtx, budgets[key])
}
repairs := &stage.RepairCounter{}
stageCtx = stage.WithRepairCounter(stageCtx, repairs)
snapshotCtx, snapshotCancel := context.WithTimeout(ctx, 5*time.Second)
before := filediff.Capture(snapshotCtx, workspace)
snapshotCancel()
@@ -2209,7 +2355,11 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
err = ctx.Err()
return
}
if r.execute != nil {
if stage.EffectiveType(def.Type) == stage.CheckType {
// The server runs a check stage's commands itself, in the run
// workspace or, for delivery, in a fresh candidate worktree.
result, err = r.runCheckStage(stageCtx, def, workspace, delivery, landing, id)
} else if r.execute != nil {
timeout, _ := stage.StageTimeout(def)
executeCtx, cancel := context.WithTimeout(stageCtx, timeout)
defer cancel()
@@ -2237,6 +2387,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 adopted != nil {
// Follow the CLI the previous process left (see run_reattach.go).
claudeClient.Reference = adopted.owner.Reference
}
claudeClient.OnOwnership = func(session, reference string, active bool) error {
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
@@ -2360,6 +2514,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
step.Output["salvage"] = result.Output
}
}
checkFailed := false
if err == nil && result.Outcome == "success" {
target, targetErr := stage.VerificationTargetFor(def)
if targetErr != nil {
@@ -2376,6 +2531,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
}
}
}
checkFailed = err != nil
if err != nil {
step.Status = "failed"
step.Diagnostic = err.Error()
@@ -2383,7 +2539,26 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
step.Output = stage.Values{"error": err.Error(), "stage": key, "input": input}
}
}
if err == nil && delivery && result.Outcome == "success" {
if err == nil {
// A stage without edit must leave the run directory as it found it;
// a shell is not a licence to write (allow_workspace_changes opts out).
ignored := append([]string{artifactsDir, visitTurn.PublicDir}, stage.HarnessStateDirs(workspaceEnv(stageCtx, workspace))...)
if violation := readOnlyViolation(def, tools, explicitTools, changes, workspace, ignored); violation != "" {
err = errors.New(violation)
log.Printf("run %d stage %s #%d: %s", id, key, sequence, violation)
step.Status = "failed"
step.Diagnostic = violation
step.Outcome = "error"
step.Output = stage.Values{"error": violation, "stage": key, "input": input}
if len(result.Output) > 0 {
step.Output["salvage"] = result.Output
}
}
}
if err == nil && stage.EffectiveType(def.Type) == stage.CheckType {
step.Verdict = checkVerdict(result.Output)
}
if err == nil && delivery && stage.EffectiveType(def.Type) == stage.ModelType && result.Outcome == "success" {
checks, checksErr := stage.DeliveryChecks(def)
if checksErr != nil {
err = checksErr
@@ -2392,6 +2567,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
var catchUp string
catchUp, err = verifyDelivery(gateCtx, workspace, landing, checks, r.deliveryCommitMessage(id))
gateCancel()
checkFailed = err != nil
// A failed gate already carries the note in its diagnostic. A step
// diagnostic on success renders as a stop, so success is logged.
if catchUp != "" {
@@ -2411,10 +2587,45 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
step.Transcript = stage.RetainSession(step.Transcript, stageSession)
}
step.Target = def.Edges[step.Outcome]
var quota quotaDecision
if errors.Is(err, opencode.ErrProviderQuota) {
// Another visit would be refused the same way: stop the run on the
// provider's refusal instead of following the error edge again.
// Another visit would be refused the same way: never follow the
// error edge. A usage window that resets switches accounts or
// parks the run (run_quota.go); an empty balance stops it.
step.Target = protocol.FailureEnd
if !errors.Is(err, stage.ErrStageCleanup) {
quota = r.decideQuota(ctx, workspace, err)
}
if quota.rerun || quota.park {
step.Target = key
if quota.rerun {
step.Diagnostic += "; switched Claude account, running the visit again"
} else {
step.Diagnostic += fmt.Sprintf("; the run waits for the reset and resumes this stage at %s", quota.resetsAt.Add(quotaResumeMargin).Local().Format("15:04 on 2 Jan"))
}
}
}
harnessKind := stage.HarnessFailureKind(err)
if err != nil && !quota.rerun && !quota.park && step.Target != protocol.FailureEnd {
switch {
case errors.Is(err, stage.ErrPermissionDenied), errors.Is(err, stage.ErrRunBudgetExceeded):
// Another visit is refused the same way.
step.Target = protocol.FailureEnd
case step.Target == key && harnessKind == stage.HarnessDeterministic:
step.Target = protocol.FailureEnd
step.Diagnostic += "; this harness failure repeats on every attempt, so the error loop was not followed"
case step.Target == key && harnessKind == stage.HarnessRepeatable && state.lastHarness[key] == harnessSignature(err):
step.Target = protocol.FailureEnd
step.Diagnostic += "; the same harness failure repeated, so the error loop was not followed"
}
}
if state.lastHarness == nil {
state.lastHarness = map[string]string{}
}
if harnessKind == stage.HarnessRepeatable {
state.lastHarness[key] = harnessSignature(err)
} else {
delete(state.lastHarness, key)
}
if errors.Is(err, stage.ErrStageCleanup) {
// Retain the partial evidence without pretending that the agent stopped.
@@ -2427,7 +2638,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusRunning, CleanupUnconfirmed: true}, false)
return
}
step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads}
step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads, OutcomeRepairs: repairs.Count()}
if step.Control.OutcomeRepairs > 0 {
log.Printf("run %d stage %s #%d: outcome repair follow-up sent %d time(s)", id, key, sequence, step.Control.OutcomeRepairs)
}
if err == nil && selected.Limits != nil && state.visits[key] >= maxVisits {
for _, outcome := range selected.Limits.On {
if outcome == step.Outcome {
@@ -2441,6 +2655,19 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
if panicked {
step.Target = protocol.FailureEnd
}
switch {
case step.Control.LimitReached:
state.failureClass = protocol.FailureLoopExhausted
case checkFailed, stage.EffectiveType(def.Type) == stage.CheckType && step.Target == protocol.FailureEnd && !errors.Is(err, opencode.ErrProviderQuota):
// A delivery gate, verification target or check stage failed.
state.failureClass = protocol.FailureCheckFailed
case err != nil:
state.failureClass = stage.FailureClassOf(err)
case step.Target == protocol.FailureEnd:
state.failureClass = protocol.FailureBlocked
default:
state.failureClass = ""
}
_, _, _, failedTerminal := terminalFinish(step.Target, step.Stage, step.Outcome, step.Diagnostic)
if exportRequired && !completeSessionExport(sessionExport) && !(err != nil && failedTerminal && step.Target != protocol.SuccessEnd) {
// Preserve the real computation, files, outcome and target. In
@@ -2474,7 +2701,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
// markdown body, which the field-map summariser reads as untrusted data and
// answers with an invented rationale; those steps get the honest read-time
// fallback instead.
if r.verdict != nil && !turnOutputOnly(step.Output) {
if r.verdict != nil && !turnOutputOnly(step.Output) && step.Verdict == nil {
reasonCtx, reasonCancel := context.WithTimeout(context.Background(), summarise.DefaultTimeout)
if line := r.verdict(reasonCtx, step.Output); line != "" && line != summarise.NoSummary {
step.Verdict = &protocol.StageVerdict{Reason: line, ReasonSource: protocol.VerdictReasonModel}
@@ -2490,6 +2717,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
canceled()
return
}
if quota.park && !terminal {
r.parkForQuota(id, workspace, sequence, key, state.completed, quota)
return
}
// Advance the in-memory UI-surface evidence only after the step is
// persisted, so the skip guard agrees with what the store holds.
state.recordChanges(step.FileChanges, step.Artifacts)
@@ -2503,6 +2734,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
if artifactsDir != "" {
state.artifactDirs = append(state.artifactDirs, strconv.Itoa(sequence))
}
} else if quota.rerun {
// The visit runs again on the switched account with its own
// input, told that the limit interrupted it; it does not count.
state.input = input
state.visits[key]--
state.previousAttempt = quotaPreviousAttempt(key, quota.note)
} 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.
@@ -2535,8 +2772,25 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
finish(status, outcome, diagnostic)
return
}
r.checkRunBudget(id, name, runBudget)
if step.Status == "completed" {
delete(state.errorLoops, key)
} else if step.Status == "failed" && step.Target == key && !quota.rerun && (harnessKind == stage.HarnessTransient || harnessKind == stage.HarnessRepeatable) {
// A transient harness failure looping back to its own stage waits
// before the next visit, longer each time (errorLoopBackoff).
if state.errorLoops == nil {
state.errorLoops = map[string]int{}
}
delay := errorLoopBackoff[min(state.errorLoops[key], len(errorLoopBackoff)-1)]
state.errorLoops[key]++
if !sleepOrDone(ctx, delay) {
canceled()
return
}
}
state.key = step.Target
}
state.failureClass = protocol.FailureLoopExhausted
finish("failed", "error", "total stage budget exceeded")
}
+109 -8
View File
@@ -1,12 +1,16 @@
package server
import (
"context"
"errors"
"fmt"
"log"
"os"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
func (r *runner) scheduleLoop() {
@@ -89,6 +93,10 @@ func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recov
if err != nil {
return err
}
if claimed && status == "skipped_missed" {
name := scheduleLabel(item)
go r.scheduleNotice(item, due, "skipped", "Scheduled run skipped: "+name, fmt.Sprintf("%s was due at %s while the server was not running, so that run was skipped.", name, due.Local().Format("15:04 on 2 Jan")), "")
}
if !claimed || status != "claimed" {
return nil
}
@@ -100,21 +108,114 @@ func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recov
return nil
}
// admitScheduled starts one claimed schedule's run and records the outcome.
// scheduleBusyRetry is how often, and for how long after its due time, a
// scheduled admission whose workspace another run holds is tried again
// (the limit counts from the first attempt).
// PIPELINES_SCHEDULE_BUSY_RETRY_EVERY and PIPELINES_SCHEDULE_BUSY_RETRY_FOR
// (Go durations; FOR=0 disables waiting) override the defaults.
var scheduleBusyRetry = func() (every, limit time.Duration) {
every, limit = 5*time.Minute, 2*time.Hour
if value, err := time.ParseDuration(os.Getenv("PIPELINES_SCHEDULE_BUSY_RETRY_EVERY")); err == nil && value > 0 {
every = value
}
if value, err := time.ParseDuration(os.Getenv("PIPELINES_SCHEDULE_BUSY_RETRY_FOR")); err == nil && value >= 0 {
limit = value
}
return every, limit
}
// scheduleNoticePriority is ntfy's "low" priority.
const scheduleNoticePriority = 2
// admitScheduled starts one claimed schedule's run and records the outcome in
// the schedule's history. A workspace another run holds delays the admission
// instead of skipping it: it is tried again every few minutes for a bounded
// time, recorded as "delayed" meanwhile. The operator is told, at low
// priority, when a scheduled run is delayed and when one is skipped.
func (r *runner) admitScheduled(item protocol.SavedSchedule, due time.Time) {
request := protocol.Message{PipelineID: item.PipelineID, Version: item.Version, RequestKey: fmt.Sprintf("saved-schedule:%d:%d", item.ID, due.UnixNano()), Input: item.Input, Workspace: item.Workspace, WritePaths: item.WritePaths, AllowTools: item.AllowTools, Model: item.Model, StageModels: item.StageModels, NotifyMode: item.NotifyMode, Title: item.Title, OutputFormat: item.OutputFormat}
run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name})
every, limit := scheduleBusyRetry()
started := time.Now()
deadline := started.Add(limit)
name := scheduleLabel(item)
diagnostic := ""
status := "started"
var runID int64
if err != nil {
status = "skipped"
diagnostic = err.Error()
} else if run != nil {
runID = run.ID
for attempt := 1; ; attempt++ {
run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name})
if err == nil {
status, diagnostic = "started", ""
if run != nil {
runID = run.ID
}
if attempt > 1 {
diagnostic = fmt.Sprintf("started after waiting %s for a busy workspace", time.Since(started).Round(time.Second))
}
break
}
status, diagnostic = "skipped", err.Error()
var busy *workspaceBusyError
if !errors.As(err, &busy) {
break
}
if time.Now().Add(every).After(deadline) {
if attempt > 1 {
diagnostic = fmt.Sprintf("gave up after waiting %s for a busy workspace: %s", time.Since(started).Round(time.Second), diagnostic)
}
break
}
if attempt == 1 {
r.scheduleNotice(item, due, "delayed", "Scheduled run delayed: "+name,
fmt.Sprintf("%s is waiting for run #%d to free its workspace; it is tried again every %s until %s.", name, busy.runID, every, deadline.Local().Format("15:04")), runAttentionClick(busy.runID))
}
delayed := fmt.Sprintf("waiting for a busy workspace (attempt %d; retrying every %s until %s): %s", attempt, every, deadline.UTC().Format(time.RFC3339), err.Error())
if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, "delayed", delayed); err != nil {
log.Printf("schedule id=%d record delay: %v", item.ID, err)
}
log.Printf("schedule id=%d pipeline=%d due=%s delayed: %s", item.ID, item.PipelineID, due.Format(time.RFC3339), delayed)
timer := time.NewTimer(every)
select {
case <-timer.C:
continue
case <-r.ctx.Done():
timer.Stop()
diagnostic = "the server stopped while this run waited for a busy workspace: " + diagnostic
}
break
}
if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, status, diagnostic); err != nil {
save, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 10*time.Second)
if err := r.store.FinishSavedSchedule(save, item.ID, due, status, diagnostic); err != nil {
log.Printf("schedule id=%d record admission: %v", item.ID, err)
}
cancel()
if status == "skipped" {
r.scheduleNotice(item, due, "skipped", "Scheduled run skipped: "+name, name+" did not start: "+diagnostic, "")
}
log.Printf("schedule id=%d pipeline=%d version=%d due=%s status=%s run=%d %s", item.ID, item.PipelineID, item.Version, due.Format(time.RFC3339), status, runID, diagnostic)
}
// scheduleLabel names a schedule in a notice.
func scheduleLabel(item protocol.SavedSchedule) string {
if name := singleLine(item.Name); name != "" {
return truncateUTF8(name, 120)
}
return fmt.Sprintf("Schedule %d", item.ID)
}
// scheduleNotice tells the operator, at low priority, through the app
// notification stream and (when enabled) ntfy, that a scheduled run was
// delayed or skipped.
func (r *runner) scheduleNotice(item protocol.SavedSchedule, due time.Time, event, title, message, click string) {
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 30*time.Second)
defer cancel()
title, message = truncateUTF8(singleLine(title), 256), truncateUTF8(singleLine(message), 2000)
r.notes.record(ctx, pipeline.AppNotificationRecord{AppNotification: protocol.AppNotification{
ID: fmt.Sprintf("schedule:%d:%d:%s", item.ID, due.UnixNano(), event), Kind: protocol.NotificationSchedule,
Title: title, Message: message, Click: click, Priority: scheduleNoticePriority, Tags: []string{}, Group: fmt.Sprintf("schedule:%d", item.ID)}})
if !chatAttentionConfigured() || !ntfyEnabled(ctx, r.settingsStore()) {
return
}
if _, err := ntfyPublish(stage.WithNtfyPriority(ctx, scheduleNoticePriority), "system", title, message, "", nil, click); err != nil {
log.Printf("schedule id=%d %s notice: %v", item.ID, event, err)
}
}
+136
View File
@@ -0,0 +1,136 @@
package server
import (
"context"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
func scheduleNotices(t *testing.T, s *pipeline.Store) []protocol.AppNotification {
t.Helper()
active, _, err := s.ActiveAppNotifications(context.Background(), "", time.Now())
if err != nil {
t.Fatal(err)
}
var notices []protocol.AppNotification
for _, n := range active {
if n.Kind == protocol.NotificationSchedule {
notices = append(notices, n)
}
}
return notices
}
func waitOccurrence(t *testing.T, s *pipeline.Store, id int64, due time.Time, want string) (string, int64) {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for {
status, diagnostic, run, err := s.SavedScheduleOccurrence(context.Background(), id, due)
if err == nil && status == want {
return diagnostic, run
}
if time.Now().After(deadline) {
t.Fatalf("occurrence status %q (%q, %v), want %q", status, diagnostic, err, want)
}
time.Sleep(5 * time.Millisecond)
}
}
// A scheduled run whose workspace another run holds is delayed, not skipped:
// it is recorded as delayed, the operator is told at low priority, and it
// starts once the workspace is free.
func TestScheduledRunWaitsForABusyWorkspace(t *testing.T) {
seamScheduleBusyRetry(t, 20*time.Millisecond, time.Hour)
ctx, s, r, pid := scheduleFixture(t)
r.notes = newAppNotifier(s)
workspace := t.TempDir()
busy := saveTestSchedule(t, ctx, s, pid, "busy", workspace, "1h", time.Now())
brief := saveTestSchedule(t, ctx, s, pid, "Daily brief", workspace, "1h", time.Now())
release := make(chan struct{})
entered := make(chan struct{}, 2)
r.execute = func(ctx context.Context, _ stage.Definition, input stage.Values) (stage.Result, error) {
entered <- struct{}{}
if prompt, _ := input["prompt"].(string); prompt == "busy" {
<-release
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil
}
if err := r.scheduleTick(dueOf(t, busy), false); err != nil {
t.Fatal(err)
}
<-entered
due := dueOf(t, brief)
if err := r.scheduleTick(due, false); err != nil {
t.Fatal(err)
}
diagnostic, _ := waitOccurrence(t, s, brief.ID, due, "delayed")
if !strings.Contains(diagnostic, "busy workspace") || !strings.Contains(diagnostic, "already active") {
t.Fatalf("delay diagnostic %q", diagnostic)
}
notices := scheduleNotices(t, s)
if len(notices) != 1 || notices[0].Priority != 2 || !strings.Contains(notices[0].Title, "delayed") || !strings.Contains(notices[0].Title, "Daily brief") {
t.Fatalf("delay notices %+v", notices)
}
close(release)
diagnostic, run := waitOccurrence(t, s, brief.ID, due, "started")
r.scheduleAdmissions.Wait()
r.wg.Wait()
if run == 0 || !strings.Contains(diagnostic, "started after waiting") {
t.Fatalf("delayed run not admitted: run=%d %q", run, diagnostic)
}
runs, err := s.ListRuns(ctx)
if err != nil || len(runs) != 2 {
t.Fatalf("runs %+v %v", runs, err)
}
}
// Waiting is bounded: past the limit the occurrence is skipped, saying why,
// and the operator is told.
func TestScheduledRunGivesUpOnABusyWorkspace(t *testing.T) {
seamScheduleBusyRetry(t, 20*time.Millisecond, 150*time.Millisecond)
ctx, s, r, pid := scheduleFixture(t)
r.notes = newAppNotifier(s)
workspace := t.TempDir()
busy := saveTestSchedule(t, ctx, s, pid, "busy", workspace, "1h", time.Now())
brief := saveTestSchedule(t, ctx, s, pid, "Daily brief", workspace, "1h", time.Now())
release := make(chan struct{})
defer close(release)
entered := make(chan struct{}, 2)
r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
entered <- struct{}{}
select {
case <-release:
case <-ctx.Done():
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil
}
if err := r.scheduleTick(dueOf(t, busy), false); err != nil {
t.Fatal(err)
}
<-entered
due := dueOf(t, brief)
if claimed, err := s.ClaimSavedSchedule(ctx, *brief, due, due.Add(time.Hour), "claimed"); err != nil || !claimed {
t.Fatal(claimed, err)
}
r.admitScheduled(*brief, due)
diagnostic, run := waitOccurrence(t, s, brief.ID, due, "skipped")
if run != 0 || !strings.Contains(diagnostic, "gave up after waiting") {
t.Fatalf("skip diagnostic %q run=%d", diagnostic, run)
}
notices := scheduleNotices(t, s)
var titles []string
for _, n := range notices {
titles = append(titles, n.Title)
if n.Priority != 2 {
t.Fatalf("schedule notice is not low priority: %+v", n)
}
}
if len(notices) != 2 || !strings.Contains(strings.Join(titles, "|"), "skipped") {
t.Fatalf("notices %v", titles)
}
}
+10
View File
@@ -201,7 +201,17 @@ func TestScheduleDeletionDoesNotCancelAdmittedRun(t *testing.T) {
}
}
// seamScheduleBusyRetry sets how a scheduled admission waits for a busy
// workspace (limit 0: it is skipped at once, as before delays existed).
func seamScheduleBusyRetry(t *testing.T, every, limit time.Duration) {
t.Helper()
previous := scheduleBusyRetry
scheduleBusyRetry = func() (time.Duration, time.Duration) { return every, limit }
t.Cleanup(func() { scheduleBusyRetry = previous })
}
func TestSavedScheduleRecoveryAndOverlap(t *testing.T) {
seamScheduleBusyRetry(t, time.Minute, 0)
ctx, s, r, pid := scheduleFixture(t)
item := saveTestSchedule(t, ctx, s, pid, "task", t.TempDir(), "1m", time.Now())
due := dueOf(t, item)
+1 -1
View File
@@ -35,7 +35,7 @@ func (r *runner) resumeExportGates(ctx context.Context) error {
r.mu.Unlock()
return err
}
if err := r.checkWorkspaceFreeExcept(d.Workspace, id); err != nil {
if err := r.checkWorkspaceFreeExcept(d.Workspace, id, d.WritePaths...); err != nil {
r.mu.Unlock()
continue
}
+6 -3
View File
@@ -190,12 +190,15 @@ func TestUISkipRunsModelOnAnyRecordedChange(t *testing.T) {
}
}
// TestUISkipPartialCaptureNeverSkips proves a visit whose capture was partial
// (here a protected .env file forces skipped>0) blocks the fallback even when
// (here a protected secrets/ directory, which is never walked, forces skipped>0;
// an untouched .env no longer does) blocks the fallback even when
// it recorded no file changes, and that inspect carries a run-level warning.
func TestUISkipPartialCaptureNeverSkips(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, ".env"), []byte("A=1\n"), 0o600); err != nil {
if err := os.MkdirAll(filepath.Join(dir, "secrets"), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "secrets", "token"), []byte("A=1\n"), 0o600); err != nil {
t.Fatal(err)
}
detail, visited, verdictCalls := runUISkipIn(t, uiReviewerSource(true), nil, dir)
+34 -1
View File
@@ -14,6 +14,7 @@ import (
"git.a-wan.net/alan/pipelines/examples"
"git.a-wan.net/alan/pipelines/internal/buildinfo"
"git.a-wan.net/alan/pipelines/internal/claude"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/summarise"
@@ -554,7 +555,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
response.Error = err.Error()
}
}
} else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.DecideRun || request.Type == protocol.SetRunTitle || request.Type == protocol.GetRunEvidence || request.Type == protocol.RepairSessionExport || request.Type == protocol.DeleteRuns) {
} else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.DecideRun || request.Type == protocol.SetRunTitle || request.Type == protocol.GetRunEvidence || request.Type == protocol.RepairSessionExport || request.Type == protocol.DeleteRuns || request.Type == protocol.ResumeRun || request.Type == protocol.GetRunSettings || request.Type == protocol.SetRunSettings) {
var err error
switch request.Type {
case protocol.DeleteRuns:
@@ -598,6 +599,23 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
} else {
response.RunDetail, err = runs.getRun(request.RunID)
}
case protocol.ResumeRun:
response.Type = protocol.Run
response.RunDetail, err = runs.resumeQuota(request.RunID)
case protocol.GetRunSettings:
response.Type = protocol.RunSettingsReply
var settings protocol.RunSettings
settings, err = stores[0].RunSettings(connCtx)
response.RunSettings = &settings
case protocol.SetRunSettings:
response.Type = protocol.RunSettingsReply
if request.RunSettings == nil {
err = fmt.Errorf("set_run_settings requires run_settings")
} else {
var settings protocol.RunSettings
settings, err = stores[0].SetRunSettings(connCtx, *request.RunSettings)
response.RunSettings = &settings
}
case protocol.CancelRun:
response.Type = protocol.Run
err = runs.cancel(request.RunID)
@@ -657,9 +675,24 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
hub.watchUsageRefusals(options.Chat)
}
if runs != nil {
// A stage refused for a usage limit first tries the Claude account
// auto-switch chats use (the home's own setting decides).
if manager, ok := options.Chat.(*chatManager); ok {
runs.quota.switchAccount = func(ctx context.Context, workspace string, resetsAt time.Time) (string, string, error) {
switcher, ok := manager.harness(claude.Backend).(chatAutoSwitcher)
if !ok {
return "", "", errNotClaudeChat
}
result, err := switcher.AutoSwitchAccount(ctx, claude.UsageRefusal{Directory: workspace, ResetsAt: resetsAt})
return result.From, result.To, err
}
}
// Continue the runs a previous process left in flight, now that the
// runner's collaborators are wired and before any request is served.
runs.reattachRuns()
// Re-arm the resume of runs parked for a usage limit.
runs.armParkedRuns()
context.AfterFunc(ctx, runs.stopQuotaTimers)
}
return &runHandler{Handler: guardRequests(mux, options.AccessToken), runner: runs, hub: hub}
}
+101 -3
View File
@@ -90,6 +90,8 @@ type reportedUsage struct {
}
type Budget struct {
// run is the whole-run cap this stage budget also counts towards.
run *RunBudget
mu sync.Mutex
state BudgetSnapshot
records map[string]BudgetSnapshot
@@ -108,6 +110,22 @@ func (b *Budget) RestoreUsage(used BudgetSnapshot) {
used.LimitUSD, used.LimitTokens = b.state.LimitUSD, b.state.LimitTokens
b.state = used
}
// SetRun makes the stage budget count its cost towards the whole-run cap.
func (b *Budget) SetRun(run *RunBudget) { b.mu.Lock(); b.run = run; b.mu.Unlock() }
// watched reports whether a harness must poll usage: a stage limit or a
// whole-run cap is set.
func (b *Budget) watched() bool {
if b == nil {
return false
}
b.mu.Lock()
run := b.run
b.mu.Unlock()
return b.Enabled() || run.Enabled()
}
func (b *Budget) Enabled() bool { return b != nil && (b.state.LimitUSD > 0 || b.state.LimitTokens > 0) }
func (b *Budget) Snapshot() BudgetSnapshot { b.mu.Lock(); defer b.mu.Unlock(); return b.state }
@@ -154,13 +172,21 @@ func (b *Budget) checkLocked() error {
}
return nil
}
func (b *Budget) Check() error { b.mu.Lock(); defer b.mu.Unlock(); return b.checkLocked() }
func (b *Budget) Check() error {
b.mu.Lock()
defer b.mu.Unlock()
if err := b.checkLocked(); err != nil {
return err
}
return b.run.Check()
}
func (b *Budget) observe(key string, usage reportedUsage) error {
b.mu.Lock()
defer b.mu.Unlock()
old := b.records[key]
defer func() { b.records[key] = old }()
spentBefore := b.state.UsedUSD
if usage.USD != nil {
if *usage.USD < 0 || math.IsNaN(*usage.USD) || math.IsInf(*usage.USD, 0) {
return fmt.Errorf("%w: invalid cost", ErrBudgetAccounting)
@@ -231,7 +257,68 @@ func (b *Budget) observe(key string, usage reportedUsage) error {
case b.state.LimitTokens > 0:
return fmt.Errorf("%w: complete token usage was not reported", ErrBudgetAccounting)
}
return b.checkLocked()
if err := b.checkLocked(); err != nil {
return err
}
return b.run.add(b.state.UsedUSD - spentBefore)
}
// RunBudget is a run's whole-run USD cap, shared by every stage budget of
// the run. A nil or zero-limit RunBudget only counts.
type RunBudget struct {
mu sync.Mutex
limit float64
spent float64
}
// NewRunBudget starts a run cap of limit USD (0 = none) with spent already
// used by earlier visits.
func NewRunBudget(limit, spent float64) *RunBudget {
return &RunBudget{limit: limit, spent: spent}
}
func (r *RunBudget) Enabled() bool { return r != nil && r.limit > 0 }
// Spent and Limit report the cap's state.
func (r *RunBudget) Spent() float64 {
if r == nil {
return 0
}
r.mu.Lock()
defer r.mu.Unlock()
return r.spent
}
func (r *RunBudget) Limit() float64 {
if r == nil {
return 0
}
return r.limit
}
func (r *RunBudget) add(usd float64) error {
if r == nil {
return nil
}
r.mu.Lock()
if usd > 0 {
r.spent += usd
}
r.mu.Unlock()
return r.Check()
}
// Check fails with ErrRunBudgetExceeded once the run spent its cap.
func (r *RunBudget) Check() error {
if !r.Enabled() {
return nil
}
r.mu.Lock()
defer r.mu.Unlock()
if r.spent >= r.limit {
return fmt.Errorf("%w: %w: USD %.2f / %.2f", ErrBudgetExceeded, ErrRunBudgetExceeded, r.spent, r.limit)
}
return nil
}
type budgetContextKey struct{}
@@ -239,6 +326,17 @@ type budgetContextKey struct{}
func WithBudget(ctx context.Context, budget *Budget) context.Context {
return context.WithValue(ctx, budgetContextKey{}, budget)
}
// BudgetFrom is the stage budget a visit runs under (nil when none); an
// in-process executor reports its cost with ObserveCost.
func BudgetFrom(ctx context.Context) *Budget { return budgetFromContext(ctx) }
// ObserveCost reports a session's cumulative USD cost, as a harness usage
// report does, and fails once the stage or run cap is spent.
func (b *Budget) ObserveCost(session string, usd float64) error {
return b.observe(session, reportedUsage{USD: &usd})
}
func budgetFromContext(ctx context.Context) *Budget {
b, _ := ctx.Value(budgetContextKey{}).(*Budget)
return b
@@ -254,7 +352,7 @@ type budgetWatch struct {
func (c OpenCodeClient) BudgetCapable() bool { return true }
func (c OpenCodeClient) watchBudget(ctx context.Context, budget *Budget, id string) (context.Context, *budgetWatch, error) {
if !budget.Enabled() {
if !budget.watched() {
return ctx, nil, nil
}
if err := budget.Check(); err != nil {
+413
View File
@@ -0,0 +1,413 @@
package stage
import (
"bytes"
"context"
"errors"
"fmt"
"os/exec"
"strconv"
"strings"
"syscall"
"time"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
// CheckType is a stage the server runs itself: a list of shell commands in the
// run's workspace, no model. Its outcome is pass or fail, so a red tree can be
// routed back to the implementer (with the failing output as the handoff)
// before a reviewer or a landing stage ever sees it.
const CheckType = "check"
// Check outcomes. error stays the infrastructure-failure route, as for every
// stage type.
const (
CheckPass = "pass"
CheckFail = "fail"
)
// Per-command check statuses recorded on the step output.
const (
CheckStatusPassed = "passed"
CheckStatusFailed = "failed"
CheckStatusTimedOut = "timed_out"
CheckStatusNotRun = "not_run"
)
const (
maxCheckCommands = 20
maxCheckCommandBytes = 4096
defaultCommandTimeout = 30 * time.Minute
maxCheckOutputBytes = 64 << 10 // retained per failed command (head and tail)
maxPassedOutputBytes = 2 << 10 // retained per passing command (tail)
checkHandoffTailBytes = 1500 // per failed command in the handoff
checkOutputHeadBytes = 16 << 10
checkProcessWaitDelay = 5 * time.Second
checkFailureHandoffMax = 3
)
// CheckSpec is a validated check stage.
type CheckSpec struct {
Commands []string
CommandTimeout time.Duration
Timeout time.Duration
KeepGoing bool
Delivery bool
}
// CheckCommandResult is one command's recorded result (step output "checks").
type CheckCommandResult struct {
Command string `json:"command"`
Status string `json:"status"`
ExitCode int `json:"exit_code"`
DurationMS int64 `json:"duration_ms"`
Output string `json:"output,omitempty"`
Truncated bool `json:"truncated,omitempty"`
}
// CheckReport is the result of running a check stage's commands once.
type CheckReport struct {
Commands []CheckCommandResult
}
// Failed reports whether any command did not pass.
func (r CheckReport) Failed() bool {
for _, c := range r.Commands {
if c.Status != CheckStatusPassed {
return true
}
}
return false
}
type CheckStage struct{}
var _ Stage = CheckStage{}
func (CheckStage) Validate(def Definition) error {
_, err := CheckStageSpec(def)
return err
}
// CheckStageSpec validates a check stage definition and returns its settings.
func CheckStageSpec(def Definition) (CheckSpec, error) {
if EffectiveType(def.Type) != CheckType {
return CheckSpec{}, fmt.Errorf("expected check stage")
}
for name := range def.Blocks {
switch name {
case "configs", "edges", "output", "commands":
case "skills":
return CheckSpec{}, errSkillsModelOnly("check")
case "prompt", "tools", "permissions", "checks":
return CheckSpec{}, fmt.Errorf("check stages run their commands block on the server, without a model; remove the %s block", name)
default:
return CheckSpec{}, fmt.Errorf("unexpected block %q for check stage", name)
}
}
commands, err := CheckCommands(def.Blocks["commands"])
if err != nil {
return CheckSpec{}, err
}
spec := CheckSpec{Commands: commands, CommandTimeout: defaultCommandTimeout}
for key, value := range def.Configs {
switch key {
case "timeout":
case "command_timeout":
duration, err := time.ParseDuration(value)
if err != nil || duration <= 0 {
return CheckSpec{}, fmt.Errorf("command_timeout must be a positive duration, such as 10m")
}
spec.CommandTimeout = duration
case "keep_going":
if value != "true" && value != "false" {
return CheckSpec{}, fmt.Errorf("keep_going must be true or false")
}
spec.KeepGoing = value == "true"
case "delivery":
if value != "true" {
return CheckSpec{}, fmt.Errorf("delivery must be true when set")
}
spec.Delivery = true
default:
return CheckSpec{}, fmt.Errorf("unknown check config %q (use timeout, command_timeout, keep_going or delivery)", key)
}
}
if spec.Timeout, err = StageTimeout(def); err != nil {
return CheckSpec{}, err
}
for _, outcome := range []string{CheckPass, CheckFail} {
if def.Edges[outcome] == "" {
return CheckSpec{}, fmt.Errorf("check stage requires %s and %s edges", CheckPass, CheckFail)
}
}
for outcome := range def.Edges {
if outcome != CheckPass && outcome != CheckFail && outcome != "error" {
return CheckSpec{}, fmt.Errorf("check stage outcomes are %s, %s and error; remove the %s edge", CheckPass, CheckFail, outcome)
}
}
return spec, nil
}
// CheckCommands parses a commands block: one shell command per line; blank
// lines and lines starting with # are ignored.
func CheckCommands(text string) ([]string, error) {
var commands []string
for _, line := range strings.Split(text, "\n") {
command := strings.TrimSpace(line)
if command == "" || strings.HasPrefix(command, "#") {
continue
}
if len(command) > maxCheckCommandBytes {
return nil, fmt.Errorf("check command exceeds %d bytes", maxCheckCommandBytes)
}
if !utf8.ValidString(command) || strings.ContainsRune(command, 0) {
return nil, fmt.Errorf("check commands must be UTF-8 text")
}
commands = append(commands, command)
}
if len(commands) == 0 || len(commands) > maxCheckCommands {
return nil, fmt.Errorf("check stage requires a commands block with 1 to %d commands, one per line", maxCheckCommands)
}
return commands, nil
}
// Run executes the commands in place in def.Workspace. The runner calls
// RunCheckCommands directly for a delivery check (in a fresh candidate
// worktree); this is the in-place path.
func (CheckStage) Run(ctx context.Context, def Definition, _ Values) (Result, error) {
spec, err := CheckStageSpec(def)
if err != nil {
return Result{}, err
}
if strings.TrimSpace(def.Workspace) == "" {
return Result{}, fmt.Errorf("check stage has no workspace")
}
ctx, cancel := context.WithTimeout(ctx, spec.Timeout)
defer cancel()
report := RunCheckCommands(ctx, def.Workspace, spec)
if err := ctx.Err(); err != nil && !report.Failed() {
return Result{}, err
}
return CheckResult(def.Key, spec, report), nil
}
// RunCheckCommands runs every command with `sh -c` from directory, in order,
// with the directory's workspace environment. It stops at the first failure
// unless KeepGoing; later commands are recorded as not_run.
func RunCheckCommands(ctx context.Context, directory string, spec CheckSpec) CheckReport {
report := CheckReport{}
stop := false
for _, command := range spec.Commands {
if stop || ctx.Err() != nil {
report.Commands = append(report.Commands, CheckCommandResult{Command: command, Status: CheckStatusNotRun, ExitCode: -1})
continue
}
result := runCheckCommand(ctx, directory, command, spec.CommandTimeout)
report.Commands = append(report.Commands, result)
if result.Status != CheckStatusPassed && !spec.KeepGoing {
stop = true
}
}
return report
}
func runCheckCommand(ctx context.Context, directory, command string, timeout time.Duration) CheckCommandResult {
commandCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
cmd := exec.CommandContext(commandCtx, "sh", "-c", command)
cmd.Dir = directory
cmd.Env = workenv.CommandEnv(ctx, directory)
// A test suite starts children; a timeout kills the whole process group,
// and WaitDelay bounds a child that keeps the output pipes open.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
if cmd.Process != nil {
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
}
return nil
}
cmd.WaitDelay = checkProcessWaitDelay
output := &headTailBuffer{head: checkOutputHeadBytes, limit: maxCheckOutputBytes}
cmd.Stdout = output
cmd.Stderr = output
started := time.Now()
err := cmd.Run()
result := CheckCommandResult{Command: command, DurationMS: time.Since(started).Milliseconds()}
result.Output, result.Truncated = output.String()
var exit *exec.ExitError
switch {
case err == nil:
result.Status = CheckStatusPassed
case commandCtx.Err() != nil:
result.Status = CheckStatusTimedOut
result.ExitCode = -1
if ctx.Err() != nil {
result.Output = strings.TrimRight(result.Output+"\n[stopped: the stage timeout or cancellation ended the command]", "\n")
} else {
result.Output = strings.TrimRight(result.Output+"\n[stopped: command_timeout "+timeout.String()+" reached]", "\n")
}
case errors.As(err, &exit):
result.Status = CheckStatusFailed
result.ExitCode = exit.ExitCode()
default:
result.Status = CheckStatusFailed
result.ExitCode = -1
result.Output = strings.TrimSpace(result.Output + "\n" + err.Error())
}
if result.Status == CheckStatusPassed && len(result.Output) > maxPassedOutputBytes {
cut := len(result.Output) - maxPassedOutputBytes
for cut < len(result.Output) && !utf8.RuneStart(result.Output[cut]) {
cut++
}
result.Output = "[... earlier output omitted ...]\n" + result.Output[cut:]
result.Truncated = true
}
return result
}
// CheckResult renders a report as the stage result: outcome pass or fail, the
// output.md-style markdown later stages read (handoff first, then every
// command's output), a one-line summary and the structured per-command list.
func CheckResult(key string, spec CheckSpec, report CheckReport) Result {
outcome := CheckPass
if report.Failed() {
outcome = CheckFail
}
summary := CheckSummary(report)
var b strings.Builder
b.WriteString("# outcome\n\n" + outcome + "\n\n# handoff\n\n" + summary + "\n")
failures := 0
for _, c := range report.Commands {
if c.Status != CheckStatusFailed && c.Status != CheckStatusTimedOut {
continue
}
failures++
if failures > checkFailureHandoffMax {
b.WriteString("\nMore failures are listed below.\n")
break
}
fmt.Fprintf(&b, "\n`%s` %s:\n\n~~~\n%s\n~~~\n", c.Command, checkStatusPhrase(c), tailText(c.Output, checkHandoffTailBytes))
}
if outcome == CheckFail {
b.WriteString("\nFix the cause; the server reruns these checks.\n")
}
b.WriteString("\n## Commands\n")
for _, c := range report.Commands {
fmt.Fprintf(&b, "\n### `%s`: %s\n", c.Command, checkStatusPhrase(c))
if c.Status == CheckStatusNotRun {
continue
}
if strings.TrimSpace(c.Output) == "" {
b.WriteString("\n(no output)\n")
continue
}
fmt.Fprintf(&b, "\n~~~\n%s\n~~~\n", c.Output)
}
checks := make([]any, 0, len(report.Commands))
for _, c := range report.Commands {
checks = append(checks, map[string]any{
"command": c.Command, "status": c.Status, "exit_code": c.ExitCode,
"duration_ms": c.DurationMS, "output": c.Output, "truncated": c.Truncated,
})
}
output := Values{"markdown": b.String(), "summary": summary, "checks": checks}
if spec.Delivery {
output["delivery"] = true
}
return Result{Outcome: outcome, Output: output}
}
// CheckSummary is the one-line verdict for a report.
func CheckSummary(report CheckReport) string {
total := len(report.Commands)
var failed []string
for _, c := range report.Commands {
if c.Status == CheckStatusFailed || c.Status == CheckStatusTimedOut {
failed = append(failed, c.Command)
}
}
if len(failed) == 0 {
if total == 1 {
return "1 check passed."
}
return strconv.Itoa(total) + " checks passed."
}
line := fmt.Sprintf("%d of %d checks failed: %s", len(failed), total, strings.Join(failed, "; "))
if len(line) > 180 {
line = strings.ToValidUTF8(line[:180], "") + "…"
}
return line
}
func checkStatusPhrase(c CheckCommandResult) string {
duration := (time.Duration(c.DurationMS) * time.Millisecond).Round(100 * time.Millisecond)
switch c.Status {
case CheckStatusPassed:
return "passed (" + duration.String() + ")"
case CheckStatusTimedOut:
return "timed out (" + duration.String() + ")"
case CheckStatusNotRun:
return "not run (an earlier check failed)"
default:
return fmt.Sprintf("failed with exit code %d (%s)", c.ExitCode, duration)
}
}
func tailText(text string, limit int) string {
text = strings.TrimSpace(text)
if len(text) <= limit {
if text == "" {
return "(no output)"
}
return text
}
cut := len(text) - limit
for cut < len(text) && !utf8.RuneStart(text[cut]) {
cut++
}
return "[...]\n" + text[cut:]
}
// headTailBuffer keeps the first head bytes and the last limit-head bytes of a
// stream: compiler errors come first, test summaries last.
type headTailBuffer struct {
head, limit int
first bytes.Buffer
tail []byte
dropped int64
}
func (b *headTailBuffer) Write(p []byte) (int, error) {
n := len(p)
if room := b.head - b.first.Len(); room > 0 {
take := min(room, len(p))
b.first.Write(p[:take])
p = p[take:]
}
if len(p) == 0 {
return n, nil
}
keep := b.limit - b.head
b.tail = append(b.tail, p...)
if over := len(b.tail) - keep; over > 0 {
b.dropped += int64(over)
b.tail = append(b.tail[:0], b.tail[over:]...)
}
return n, nil
}
// String returns the retained text and whether anything was dropped.
func (b *headTailBuffer) String() (string, bool) {
if b.dropped == 0 {
return strings.ToValidUTF8(strings.TrimRight(b.first.String()+string(b.tail), "\n"), "\uFFFD"), false
}
tail := b.tail
for len(tail) > 0 && !utf8.RuneStart(tail[0]) {
tail = tail[1:]
}
text := b.first.String() + fmt.Sprintf("\n[... %d bytes omitted ...]\n", b.dropped) + string(tail)
return strings.ToValidUTF8(strings.TrimRight(text, "\n"), "\uFFFD"), true
}
+159
View File
@@ -0,0 +1,159 @@
package stage
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func checkDefinition(t *testing.T, commands string, configs map[string]string) Definition {
t.Helper()
if configs == nil {
configs = map[string]string{}
}
return Definition{Key: "verify", Type: CheckType, Workspace: t.TempDir(),
Blocks: map[string]string{"commands": commands, "configs": "type=check", "edges": "x"},
Configs: configs,
Edges: map[string]string{"pass": "review", "fail": "implement", "error": "#failure"}}
}
func TestCheckStageValidation(t *testing.T) {
def := checkDefinition(t, "# lint first\ngo vet ./...\n\ngo test ./...", map[string]string{"command_timeout": "5m", "keep_going": "true", "timeout": "20m", "delivery": "true"})
spec, err := CheckStageSpec(def)
if err != nil {
t.Fatal(err)
}
if len(spec.Commands) != 2 || spec.CommandTimeout != 5*time.Minute || spec.Timeout != 20*time.Minute || !spec.KeepGoing || !spec.Delivery {
t.Fatalf("spec %+v", spec)
}
if err := DefaultRegistry().Validate(def); err != nil {
t.Fatal("registry:", err)
}
if enabled, err := DeliveryEnabled(def); err != nil || !enabled {
t.Fatal("delivery check", enabled, err)
}
for name, change := range map[string]func(*Definition){
"no commands": func(d *Definition) { d.Blocks["commands"] = "# only a comment\n" },
"too many": func(d *Definition) { d.Blocks["commands"] = strings.Repeat("true\n", 21) },
"prompt block": func(d *Definition) { d.Blocks["prompt"] = "Run the tests." },
"tools block": func(d *Definition) { d.Blocks["tools"] = "shell" },
"skills block": func(d *Definition) { d.Blocks["skills"] = "x" },
"unknown config": func(d *Definition) { d.Configs["model"] = "x" },
"bad timeout": func(d *Definition) { d.Configs["command_timeout"] = "soon" },
"bad keep_going": func(d *Definition) { d.Configs["keep_going"] = "yes" },
"bad delivery": func(d *Definition) { d.Configs["delivery"] = "false" },
"missing fail": func(d *Definition) { delete(d.Edges, "fail") },
"missing pass": func(d *Definition) { delete(d.Edges, "pass") },
"success outcome": func(d *Definition) { d.Edges["success"] = "#success" },
} {
t.Run(name, func(t *testing.T) {
copy := def
copy.Blocks, copy.Configs, copy.Edges = map[string]string{}, map[string]string{}, map[string]string{}
for k, v := range def.Blocks {
copy.Blocks[k] = v
}
for k, v := range def.Configs {
copy.Configs[k] = v
}
for k, v := range def.Edges {
copy.Edges[k] = v
}
change(&copy)
if err := (CheckStage{}).Validate(copy); err == nil {
t.Fatal("accepted")
}
})
}
}
func TestCheckStageRunsCommandsInTheWorkspace(t *testing.T) {
def := checkDefinition(t, "pwd > where.txt\necho all good", nil)
result, err := DefaultRegistry().Run(context.Background(), def, Values{})
if err != nil {
t.Fatal(err)
}
if result.Outcome != CheckPass {
t.Fatalf("outcome %q: %v", result.Outcome, result.Output)
}
where, _ := os.ReadFile(filepath.Join(def.Workspace, "where.txt"))
real, _ := filepath.EvalSymlinks(def.Workspace)
if got := strings.TrimSpace(string(where)); got != def.Workspace && got != real {
t.Fatalf("ran in %q, want %q", got, def.Workspace)
}
if result.Output["summary"] != "2 checks passed." {
t.Fatal("summary", result.Output["summary"])
}
checks := result.Output["checks"].([]any)
if len(checks) != 2 || checks[1].(map[string]any)["output"] != "all good" {
t.Fatalf("checks %v", checks)
}
}
func TestCheckStageFailureIsTheHandoff(t *testing.T) {
def := checkDefinition(t, "echo compiling\necho 'FAIL: TestParse expected 2' >&2; exit 3\necho never", nil)
result, err := (CheckStage{}).Run(context.Background(), def, nil)
if err != nil {
t.Fatal(err)
}
if result.Outcome != CheckFail {
t.Fatalf("outcome %q", result.Outcome)
}
markdown := result.Output["markdown"].(string)
handoff := markdown[strings.Index(markdown, "# handoff"):strings.Index(markdown, "## Commands")]
for _, want := range []string{"1 of 3 checks failed", "exit code 3", "FAIL: TestParse expected 2"} {
if !strings.Contains(handoff, want) {
t.Fatalf("handoff lacks %q:\n%s", want, handoff)
}
}
if !strings.HasPrefix(markdown, "# outcome\n\nfail\n") {
t.Fatalf("markdown does not start with the outcome:\n%s", markdown)
}
checks := result.Output["checks"].([]any)
if checks[2].(map[string]any)["status"] != CheckStatusNotRun {
t.Fatal("a later check ran after a failure", checks[2])
}
// keep_going runs every command and reports each failure.
def.Configs["keep_going"] = "true"
def.Blocks["commands"] = "exit 1\nexit 2\ntrue"
result, _ = (CheckStage{}).Run(context.Background(), def, nil)
if result.Output["summary"] != "2 of 3 checks failed: exit 1; exit 2" {
t.Fatal(result.Output["summary"])
}
}
func TestCheckStageCommandTimeoutKillsTheProcessGroup(t *testing.T) {
def := checkDefinition(t, "sleep 30 & echo started; wait", map[string]string{"command_timeout": "300ms"})
started := time.Now()
result, err := (CheckStage{}).Run(context.Background(), def, nil)
if err != nil {
t.Fatal(err)
}
if time.Since(started) > 10*time.Second {
t.Fatal("timeout did not stop the command", time.Since(started))
}
check := result.Output["checks"].([]any)[0].(map[string]any)
if result.Outcome != CheckFail || check["status"] != CheckStatusTimedOut || !strings.Contains(check["output"].(string), "command_timeout") {
t.Fatalf("result %v", check)
}
}
func TestCheckOutputIsBoundedHeadAndTail(t *testing.T) {
buffer := &headTailBuffer{head: 10, limit: 30}
for i := 0; i < 100; i++ {
_, _ = buffer.Write([]byte("0123456789"))
}
_, _ = buffer.Write([]byte("THE-END"))
text, truncated := buffer.String()
if !truncated || !strings.HasPrefix(text, "0123456789") || !strings.HasSuffix(text, "THE-END") || len(text) > 80 {
t.Fatalf("%v %q", truncated, text)
}
def := checkDefinition(t, "head -c 300000 /dev/zero | tr '\\0' x; echo; echo TAIL; exit 1", nil)
result, _ := (CheckStage{}).Run(context.Background(), def, nil)
check := result.Output["checks"].([]any)[0].(map[string]any)
if output := check["output"].(string); len(output) > maxCheckOutputBytes+200 || !strings.HasSuffix(output, "TAIL") || check["truncated"] != true {
t.Fatalf("output %d bytes, truncated %v", len(output), check["truncated"])
}
}
+597 -141
View File
@@ -8,6 +8,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
@@ -16,7 +17,6 @@ import (
"time"
"git.a-wan.net/alan/pipelines/internal/claude"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
@@ -36,6 +36,9 @@ var (
errClaudeMissing = errors.New("Claude Code is not installed on the execution server; run pipelines harness setup claude there")
errClaudeSignedOut = errors.New("Claude Code is not signed in on the execution server; run pipelines harness setup claude there")
errClaudeNoResult = errors.New("Claude Code ended without a final result")
// errClaudeStoppedUnwatched: the CLI ended while no server was watching
// it (the server was restarting) and left no final result.
errClaudeStoppedUnwatched = errors.New("Claude Code stopped while the server was restarting, before it reported a final result")
)
// ClaudeStageClient runs one stage visit with the Claude Code CLI in print
@@ -64,6 +67,8 @@ type ClaudeStageClient struct {
operatorPlugins []string
budget *Budget
// denials are the tool uses the permission rules refused this visit.
denials []string
// Session totals across the visit's invocations (the prompt and one
// outcome follow-up share a session and report per invocation).
usd float64
@@ -131,7 +136,10 @@ func claudeMCPAllowRules(tools []string) ([]string, error) {
// approved only below the run directory and the stage's artifacts directory;
// everything else a declared tool does not need approval for stays denied by
// dontAsk.
func claudeAllowRules(tools []string, directory, artifactsDir string) []string {
//
// A non-nil shell allow-list replaces the bare Bash rule with one Bash(...)
// rule per permitted command, so any other command is refused.
func claudeAllowRules(tools []string, directory, artifactsDir string, shell []string) []string {
rules := []string{}
edit := false
for _, tool := range tools {
@@ -139,6 +147,12 @@ func claudeAllowRules(tools []string, directory, artifactsDir string) []string {
case "Edit":
edit = true
case "Write":
case "Bash":
if shell != nil {
rules = append(rules, claudeShellRules(shell)...)
} else {
rules = append(rules, tool)
}
default:
rules = append(rules, tool)
}
@@ -160,7 +174,7 @@ func (c *ClaudeStageClient) args(config ModelConfig, tools []string, effort stri
// skills block) may be loaded. A skill only adds instructions; the declared
// tools and their rules still bound what the session can do.
tools = append(append([]string(nil), tools...), "Skill")
rules := claudeAllowRules(tools, c.Directory, c.ArtifactsDir)
rules := claudeAllowRules(tools, c.Directory, c.ArtifactsDir, c.Policy.Shell)
args := []string{"-p", "--output-format", "stream-json", "--verbose",
"--model", config.Model,
"--permission-mode", "dontAsk",
@@ -196,7 +210,12 @@ func (c *ClaudeStageClient) args(config ModelConfig, tools []string, effort stri
}
func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, prompt string) (text string, err error) {
// A re-adopted visit was admitted by a previous server process (see
// WithResumeSession): follow its CLI or read what it left, never prompt
// again.
resume := TakeResumeSession(ctx)
c.WorkStarted = false
c.denials = nil
c.usd, c.input, c.output, c.reasoning, c.cacheRead, c.cacheW = 0, 0, 0, 0, 0, 0
c.budget = config.Budget
if c.budget == nil {
@@ -212,10 +231,11 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr
if effort == "none" || effort == "minimal" {
return "", fmt.Errorf("the claude harness supports reasoning_effort low, medium, high, xhigh or max")
}
if len(c.WritePaths) > 0 || c.Policy.Edit != nil || c.Policy.Shell != nil {
if len(c.WritePaths) > 0 || c.Policy.Edit != nil {
// The other harnesses enforce these narrower scopes themselves. Claude
// Code's rule syntax is not audited for them, so refuse, never widen.
return "", fmt.Errorf("the claude harness cannot enforce a permissions block or a narrowed write scope; use the opencode harness for this stage")
// Code's edit-path rules are not audited for them, so refuse, never
// widen. A shell allow-list is enforced with Bash(...) rules.
return "", fmt.Errorf("the claude harness cannot enforce permissions.edit or a narrowed write scope; use the opencode harness for this stage")
}
tools, err := claudeTools(c.Tools)
if err != nil {
@@ -230,34 +250,54 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr
if _, statErr := os.Stat(c.Executable); statErr != nil {
return "", fmt.Errorf("%w: %w", ErrHarnessUnreachable, errClaudeMissing)
}
cache, err := os.UserCacheDir()
if err != nil {
return "", err
}
root := filepath.Join(cache, "pipelines", claudeStageSessions)
if err = os.MkdirAll(root, 0700); err != nil {
return "", err
}
if c.Reference, err = os.MkdirTemp(root, "stage-*"); err != nil {
return "", err
}
if c.SessionID, err = newClaudeSessionID(); err != nil {
return "", err
var adopted *claudeStageOwner
if resume != "" {
owner, ownerErr := claudeStageOwnerAt(c.Reference)
if ownerErr != nil || owner.SessionID != resume || owner.Output == "" {
return "", fmt.Errorf("retained Claude Code stage session %.64s cannot be re-adopted: invalid retained evidence", RedactEvidence(resume))
}
adopted = &owner
c.SessionID = resume
} else {
cache, cacheErr := os.UserCacheDir()
if cacheErr != nil {
return "", cacheErr
}
root := filepath.Join(cache, "pipelines", claudeStageSessions)
if err = os.MkdirAll(root, 0700); err != nil {
return "", err
}
if c.Reference, err = os.MkdirTemp(root, "stage-*"); err != nil {
return "", err
}
if c.SessionID, err = newClaudeSessionID(); err != nil {
return "", err
}
}
env := claudeStageEnvironment(c.environment(ctx), c.ArtifactsDir)
// 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 {
// skills-only plugins generated for this visit, never their plugins. A
// re-adopted visit keeps the ones its first process generated.
if adopted != nil {
c.operatorPlugins = existingOperatorSkillPlugins(filepath.Join(c.Reference, "operator-skills"))
} else if c.operatorPlugins, err = writeOperatorSkillPlugins(filepath.Join(c.Reference, "operator-skills"), OperatorSkills(claudeConfigDir(env))); err != nil {
return "", err
}
owned := false
defer func() {
// Quiescence is proven per invocation (see run); only then is the
if errors.Is(err, ErrDetached) {
// The server is stopping: the CLI keeps running and its
// ownership stays recorded for the next process to re-adopt.
text = ""
return
}
// Quiescence is proven per invocation (see settle); only then is the
// evidence marked settled and ownership released.
if errors.Is(err, ErrStageCleanup) {
text = ""
return
}
c.removeRawOutput()
_ = os.WriteFile(filepath.Join(c.Reference, "quiescent"), []byte("quiescent"), 0600)
if owned {
if saveErr := c.OnOwnership(c.SessionID, c.Reference, false); saveErr != nil {
@@ -272,13 +312,26 @@ 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 c.Policy.Shell != nil {
// The allow-list is enforced by Bash(...) rules; say it up front so the
// session does not spend turns on refused commands.
prompt += "\nPermitted shell commands (a trailing * allows any arguments; anything else is refused): " + strings.Join(c.Policy.Shell, "; ")
}
if adopted != nil {
// The prompt was admitted by the previous process. The evidence stream
// is rebuilt from the CLI's own output, so nothing is listed twice.
c.WorkStarted = true
if err = os.WriteFile(filepath.Join(c.Reference, "stream.jsonl"), nil, 0600); err != nil {
return "", err
}
}
if text, err = c.invoke(ctx, env, c.args(config, tools, effort, false), 0, config.Model, prompt, adopted); err != nil {
return "", err
}
// One outcome repair follow-up in the same session.
repair := outputRepairFrom(ctx)
if message, ok := repair.followUp(text); ok {
reply, err := c.run(ctx, env, c.args(config, tools, effort, true), config.Model, message)
reply, err := c.invoke(ctx, env, c.args(config, tools, effort, true), 1, config.Model, message, adopted)
if err != nil {
return "", err
}
@@ -327,6 +380,17 @@ func claudeStageEnvironment(inherited []string, artifactsDir string) []string {
// claudeConfigDir is the Claude Code configuration directory the stage's CLI
// will use: the environment's CLAUDE_CONFIG_DIR, else $HOME/.claude.
// HarnessStateDirs are directories a harness itself writes during a visit
// (Claude Code's config directory: session state, caches) for the given
// environment. When one lives inside the run directory its changes are the
// harness's, not the stage's.
func HarnessStateDirs(env []string) []string {
if dir := claudeConfigDir(env); dir != "" {
return []string{filepath.Clean(dir)}
}
return nil
}
func claudeConfigDir(env []string) string {
lookup := func(name string) string {
for i := len(env) - 1; i >= 0; i-- {
@@ -380,149 +444,473 @@ type claudeStreamRecord struct {
ResetsAt int64 `json:"resetsAt"`
} `json:"rate_limit_info"`
Message *struct {
Error string `json:"error"`
Error string `json:"error"`
Content json.RawMessage `json:"content"`
} `json:"message"`
// PermissionDenials are the tool uses the permission rules refused
// during the invocation (on the result record).
PermissionDenials []claudePermissionDenial `json:"permission_denials"`
}
func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model, prompt string) (text string, err error) {
type claudePermissionDenial struct {
ToolName string `json:"tool_name"`
ToolInput map[string]any `json:"tool_input"`
}
// maxReportedDenials bounds the denials named in a diagnostic.
const maxReportedDenials = 5
// describe names a denied tool use for the operator: the tool and the path
// or the start of the command it was refused for (bounded, one line).
func (d claudePermissionDenial) describe() string {
name := sanitizedClaudeName(d.ToolName)
target := ""
for _, key := range []string{"file_path", "path", "notebook_path", "command", "url", "pattern"} {
if value, ok := d.ToolInput[key].(string); ok && strings.TrimSpace(value) != "" {
target = strings.Join(strings.Fields(value), " ")
break
}
}
if target == "" {
return name
}
if len([]rune(target)) > 80 {
target = string([]rune(target)[:80]) + "..."
}
return name + "(" + target + ")"
}
// PermissionDenials names the tool uses the visit's permission rules refused.
func (c *ClaudeStageClient) PermissionDenials() []string { return c.denials }
func (c *ClaudeStageClient) noteDenial(description string) {
for _, seen := range c.denials {
if seen == description {
return
}
}
if len(c.denials) < maxReportedDenials {
c.denials = append(c.denials, description)
}
}
// claudePermissionRefusal matches the tool_result text Claude Code returns for
// a tool use its permission mode refused.
func claudePermissionRefusal(text string) bool {
lower := strings.ToLower(text)
return strings.Contains(lower, "requested permissions to") || (strings.Contains(lower, "permission") && strings.Contains(lower, "denied"))
}
// toolResultDenials scans a user message's tool results for permission
// refusals of the tool uses named in uses (tool_use id -> description).
func toolResultDenials(content json.RawMessage, uses map[string]string) []string {
var blocks []struct {
Type string `json:"type"`
ToolUseID string `json:"tool_use_id"`
IsError bool `json:"is_error"`
Content json.RawMessage `json:"content"`
}
if json.Unmarshal(content, &blocks) != nil {
return nil
}
var denied []string
for _, block := range blocks {
if block.Type != "tool_result" || !block.IsError {
continue
}
var text string
if json.Unmarshal(block.Content, &text) != nil {
var parts []struct {
Text string `json:"text"`
}
_ = json.Unmarshal(block.Content, &parts)
for _, part := range parts {
text += part.Text
}
}
if claudePermissionRefusal(text) {
name := uses[block.ToolUseID]
if name == "" {
name = "a tool"
}
denied = append(denied, name)
}
}
return denied
}
// toolUses records the tool_use blocks of an assistant message.
func toolUses(content json.RawMessage, uses map[string]string) {
var blocks []struct {
Type string `json:"type"`
ID string `json:"id"`
Name string `json:"name"`
Input map[string]any `json:"input"`
}
if json.Unmarshal(content, &blocks) != nil {
return
}
for _, block := range blocks {
if block.Type == "tool_use" && block.ID != "" && len(uses) < 4096 {
uses[block.ID] = claudePermissionDenial{ToolName: block.Name, ToolInput: block.Input}.describe()
}
}
}
// claudeInvocation is what one CLI invocation's stream-json output reported.
type claudeInvocation struct {
final *claudeStreamRecord
refusal, limited bool
resetsAt int64
authFailed, sessionMismatch, modelMismatch bool
// uses names the invocation's tool_use blocks (id -> description) and
// denials the uses the permission rules refused.
uses map[string]string
denials []string
}
func (inv *claudeInvocation) observe(record claudeStreamRecord, session, model string) {
switch record.Type {
case "system":
if record.Subtype == "init" {
inv.sessionMismatch = record.SessionID != session
inv.modelMismatch = record.Model != model
}
case "rate_limit_event":
if record.RateLimit != nil && record.RateLimit.Status == "rejected" {
inv.limited = true
inv.resetsAt = record.RateLimit.ResetsAt
}
case "user":
if record.Message != nil {
inv.denials = append(inv.denials, toolResultDenials(record.Message.Content, inv.uses)...)
}
case "assistant":
if record.Message != nil {
if inv.uses == nil {
inv.uses = map[string]string{}
}
toolUses(record.Message.Content, inv.uses)
switch record.Message.Error {
case "billing_error":
inv.refusal = true
case "rate_limit":
inv.refusal, inv.limited = true, true
case "authentication_failed":
inv.authFailed = true
}
}
switch record.Error {
case "billing_error":
inv.refusal = true
case "rate_limit":
inv.refusal, inv.limited = true, true
case "authentication_failed":
inv.authFailed = true
}
case "result":
copied := record
inv.final = &copied
for _, denial := range record.PermissionDenials {
inv.denials = append(inv.denials, denial.describe())
}
}
}
// claudeProcess is one invocation's CLI: a child this process started, or one
// a previous server process left (adopted: it cannot be waited on and its exit
// status is unknown).
type claudeProcess struct {
pid int
adopted bool
done chan struct{} // closed once the CLI has exited
waitErr error // the child's exit error, read after done
stop chan struct{} // ends an adopted process's liveness poll
}
// exitedClaudeProcess is an invocation whose CLI already exited: its output
// is read to the end, nothing is waited for.
func exitedClaudeProcess(pid int) *claudeProcess {
p := &claudeProcess{pid: pid, adopted: true, done: make(chan struct{}), stop: make(chan struct{})}
close(p.done)
return p
}
// adoptClaudeProcess follows a CLI left running by a previous server process.
func adoptClaudeProcess(pid int, session string) *claudeProcess {
p := &claudeProcess{pid: pid, adopted: true, done: make(chan struct{}), stop: make(chan struct{})}
go func() {
ticker := time.NewTicker(claudeAdoptPoll)
defer ticker.Stop()
for claudeProcessAlive(pid, session) {
select {
case <-p.stop:
return
case <-ticker.C:
}
}
close(p.done)
}()
return p
}
func (p *claudeProcess) release() {
select {
case <-p.stop:
default:
close(p.stop)
}
}
// claudeAdoptPoll is how often an adopted CLI's liveness is checked, and how
// often its output file is read again when no new line has arrived.
var claudeAdoptPoll = 100 * time.Millisecond
// claudeOutputName is the raw stdout file of invocation n in the evidence
// directory. The CLI writes it directly, so it keeps writing whether or not a
// server is reading; it is removed once the visit settles.
func claudeOutputName(n int) string { return fmt.Sprintf("cli-%d.out", n) }
func claudePromptName(n int) string { return fmt.Sprintf("cli-%d.prompt", n) }
// removeRawOutput drops the unredacted CLI output and prompt files of a settled
// visit; the redacted stream.jsonl stays as its evidence.
func (c *ClaudeStageClient) removeRawOutput() {
for n := 0; n < 2; n++ {
_ = os.Remove(filepath.Join(c.Reference, claudeOutputName(n)))
_ = os.Remove(filepath.Join(c.Reference, claudePromptName(n)))
}
}
// invoke runs invocation n (0 is the prompt, 1 the outcome repair follow-up).
// For a re-adopted visit (adopted != nil), an invocation the previous process
// already started is followed instead: its CLI if it still runs, else the
// output it left. A prompt that ended without a result while no server was
// watching is never sent again; a lost repair follow-up is.
func (c *ClaudeStageClient) invoke(ctx context.Context, env, args []string, n int, model, prompt string, adopted *claudeStageOwner) (string, error) {
if adopted != nil && n <= adopted.Invocation {
var proc *claudeProcess
switch {
case n < adopted.Invocation:
// An earlier invocation settled before the next one started;
// the owner record names only the latest process.
proc = exitedClaudeProcess(0)
case claudeProcessAlive(adopted.PID, c.SessionID):
proc = adoptClaudeProcess(adopted.PID, c.SessionID)
default:
proc = exitedClaudeProcess(adopted.PID)
}
inv, waitErr, err := c.follow(ctx, proc, n, model)
if err != nil {
return "", err
}
if inv.final != nil || n == 0 || n < adopted.Invocation {
return c.settle(ctx, proc, inv, waitErr)
}
// The repair follow-up's CLI ended without a reply while the server
// was down; the follow-up only asks for the outcome, so ask again.
}
proc, err := c.start(env, args, n, prompt)
if err != nil {
return "", err
}
inv, waitErr, err := c.follow(ctx, proc, n, model)
if err != nil {
return "", err
}
return c.settle(ctx, proc, inv, waitErr)
}
// start launches one CLI invocation detached from the server process: in its
// own session, with the prompt read from a file and stdout written straight to
// a file, so a server restart neither signals it nor cuts its output. The owner
// record names the process and its output for a later server to re-adopt.
func (c *ClaudeStageClient) start(env, args []string, n int, prompt string) (*claudeProcess, error) {
promptPath := filepath.Join(c.Reference, claudePromptName(n))
if err := os.WriteFile(promptPath, []byte(prompt), 0600); err != nil {
return nil, err
}
stdin, err := os.Open(promptPath)
if err != nil {
return nil, err
}
defer stdin.Close()
stdout, err := os.OpenFile(filepath.Join(c.Reference, claudeOutputName(n)), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
if err != nil {
return nil, err
}
defer stdout.Close()
stderr, err := os.OpenFile(filepath.Join(c.Reference, "stderr.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
return nil, err
}
defer stderr.Close()
cmd := exec.Command(c.Executable, args...)
cmd.Dir = c.Directory
cmd.Env = env
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Stdin = strings.NewReader(prompt)
stderr, err := os.OpenFile(filepath.Join(c.Reference, "stderr.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
return "", err
}
defer stderr.Close()
cmd.Stderr = stderr
out, err := cmd.StdoutPipe()
if err != nil {
return "", err
}
stream, err := os.OpenFile(filepath.Join(c.Reference, "stream.jsonl"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
return "", err
}
defer stream.Close()
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr
if err = cmd.Start(); err != nil {
return "", fmt.Errorf("%w: %w", ErrHarnessUnreachable, errClaudeMissing)
return nil, fmt.Errorf("%w: %w", ErrHarnessUnreachable, errClaudeMissing)
}
owner, _ := json.Marshal(map[string]any{"pid": cmd.Process.Pid, "session_id": c.SessionID})
if err = os.WriteFile(filepath.Join(c.Reference, "owner.json"), owner, 0600); err != nil {
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
_ = cmd.Wait()
return "", err
proc := &claudeProcess{pid: cmd.Process.Pid, done: make(chan struct{}), stop: make(chan struct{})}
go func() {
// Reaps the child, also after this server detached from it.
proc.waitErr = cmd.Wait()
close(proc.done)
}()
owner := claudeStageOwner{PID: proc.pid, PGID: proc.pid, SessionID: c.SessionID, Invocation: n, Output: claudeOutputName(n)}
if err = writeClaudeStageOwner(c.Reference, owner); err != nil {
_ = syscall.Kill(-proc.pid, syscall.SIGKILL)
<-proc.done
return nil, err
}
// The prompt is admitted once the process has it: tool work may follow.
c.WorkStarted = true
var final *claudeStreamRecord
var refusal, limited bool
var resetsAt int64
var authFailed, sessionMismatch, modelMismatch bool
scanned := make(chan error, 1)
go func() {
scanner := bufio.NewScanner(out)
scanner.Buffer(make([]byte, 64<<10), 16<<20)
for scanner.Scan() {
line := scanner.Bytes()
var record claudeStreamRecord
if json.Unmarshal(line, &record) != nil {
continue
}
// One valid JSON record per line: the export parses this stream.
redacted := RedactEvidenceJSON(line)
_, _ = stream.WriteString(redacted + "\n")
if len(c.Transcript) < 32<<10 {
c.Transcript += redacted + "\n"
}
switch record.Type {
case "system":
if record.Subtype == "init" {
sessionMismatch = record.SessionID != c.SessionID
modelMismatch = record.Model != model
}
case "rate_limit_event":
if record.RateLimit != nil && record.RateLimit.Status == "rejected" {
limited = true
resetsAt = record.RateLimit.ResetsAt
}
case "assistant":
if record.Message != nil {
switch record.Message.Error {
case "billing_error", "rate_limit":
refusal = true
case "authentication_failed":
authFailed = true
}
}
switch record.Error {
case "billing_error", "rate_limit":
refusal = true
case "authentication_failed":
authFailed = true
}
case "result":
copied := record
final = &copied
}
}
scanned <- scanner.Err()
}()
waited := make(chan error, 1)
go func() {
scanErr := <-scanned
waitErr := cmd.Wait()
if scanErr != nil && waitErr == nil {
waitErr = scanErr
}
waited <- waitErr
}()
var waitErr error
select {
case waitErr = <-waited:
case <-ctx.Done():
// Timeout or cancellation: stop the whole process group, then prove it.
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)
select {
case <-waited:
case <-time.After(5 * time.Second):
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
<-waited
}
waitErr = ctx.Err()
return proc, nil
}
// follow reads invocation n's output file from its start until the CLI has
// exited and every line it wrote is read, keeping the redacted evidence
// stream. A server shutdown leaves the CLI running (ErrDetached); any other
// cancellation stops its process group first.
func (c *ClaudeStageClient) follow(ctx context.Context, proc *claudeProcess, n int, model string) (inv claudeInvocation, waitErr error, err error) {
defer proc.release()
out, err := os.Open(filepath.Join(c.Reference, claudeOutputName(n)))
if err != nil {
return inv, nil, err
}
defer out.Close()
stream, err := os.OpenFile(filepath.Join(c.Reference, "stream.jsonl"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
return inv, nil, err
}
defer stream.Close()
consume := func(line []byte) {
var record claudeStreamRecord
if json.Unmarshal(line, &record) != nil {
return
}
// One valid JSON record per line: the export parses this stream.
redacted := RedactEvidenceJSON(line)
_, _ = stream.WriteString(redacted + "\n")
if len(c.Transcript) < 32<<10 {
c.Transcript += redacted + "\n"
}
inv.observe(record, c.SessionID, model)
}
reader := bufio.NewReaderSize(out, 64<<10)
var partial []byte
exited := false
ticker := time.NewTicker(claudeAdoptPoll)
defer ticker.Stop()
for {
chunk, readErr := reader.ReadBytes('\n')
partial = append(partial, chunk...)
if readErr == nil {
consume(partial)
partial = partial[:0]
continue
}
if readErr != io.EOF {
return inv, nil, readErr
}
if exited {
if len(bytes.TrimSpace(partial)) > 0 {
consume(partial)
}
if !proc.adopted {
waitErr = proc.waitErr
}
return inv, waitErr, nil
}
select {
case <-proc.done:
exited = true // Read what it wrote before exiting.
case <-ticker.C:
case <-ctx.Done():
if Detached(ctx) {
return inv, nil, fmt.Errorf("%w: Claude Code stage session %s left running", ErrDetached, c.SessionID)
}
// Timeout or cancellation: stop the whole process group, then prove it.
if proc.pid > 1 {
_ = syscall.Kill(-proc.pid, syscall.SIGTERM)
}
select {
case <-proc.done:
case <-time.After(5 * time.Second):
_ = syscall.Kill(-proc.pid, syscall.SIGKILL) // done never stays open for pid 0.
select {
case <-proc.done:
case <-time.After(5 * time.Second):
}
}
if !claudeGroupStopped(proc.pid) {
return inv, nil, errors.Join(ctx.Err(), ErrStageCleanup)
}
return inv, nil, ctx.Err()
}
}
}
// claudeGroupStopped kills what is left of an exited CLI's process group and
// reports whether the group is proven gone.
func claudeGroupStopped(pid int) bool {
if pid <= 1 {
return true // No process of this server's to prove (see exitedClaudeProcess).
}
if claudeGroupGone(pid) {
return true
}
_ = syscall.Kill(-pid, syscall.SIGKILL)
deadline := time.Now().Add(5 * time.Second)
for !claudeGroupGone(pid) && time.Now().Before(deadline) {
time.Sleep(50 * time.Millisecond)
}
return claudeGroupGone(pid)
}
// settle proves the invocation's process group is gone and turns what its
// output reported into the invocation's result.
func (c *ClaudeStageClient) settle(ctx context.Context, proc *claudeProcess, inv claudeInvocation, waitErr error) (string, error) {
// The CLI's exit alone does not prove its shell descendants exited.
if !claudeGroupGone(cmd.Process.Pid) {
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
deadline := time.Now().Add(5 * time.Second)
for !claudeGroupGone(cmd.Process.Pid) && time.Now().Before(deadline) {
time.Sleep(50 * time.Millisecond)
}
if !claudeGroupGone(cmd.Process.Pid) {
return "", errors.Join(waitErr, ErrStageCleanup)
}
if !claudeGroupStopped(proc.pid) {
return "", errors.Join(waitErr, ErrStageCleanup)
}
if ctx.Err() != nil {
return "", ctx.Err()
}
for _, denial := range inv.denials {
c.noteDenial(denial)
}
final := inv.final
if final != nil {
if usageErr := c.observe(final); usageErr != nil {
return "", usageErr
}
}
switch {
case authFailed:
case inv.authFailed:
return "", fmt.Errorf("%w: %w", ErrHarnessTransport, errClaudeSignedOut)
case refusal || (limited && (final == nil || final.IsError)):
if resetsAt > 0 {
// A usage window, not an empty account: say when it reopens (a
// time only; no provider text is copied).
return "", fmt.Errorf("%w: %w; the Claude usage limit resets at %s", ErrHarnessTransport, opencode.ErrProviderQuota, time.Unix(resetsAt, 0).Format("15:04 on 2 Jan"))
case inv.refusal || (inv.limited && (final == nil || final.IsError)) || (final != nil && final.IsError && claudeUsageLimitText(final.Result)):
if inv.limited || !inv.refusal {
// A subscription usage window, not an empty account: say when it
// reopens (a time only; no provider text is copied).
quota := &QuotaError{Subscription: true}
if inv.resetsAt > 0 {
quota.ResetsAt = time.Unix(inv.resetsAt, 0)
} else if final != nil {
if at, ok := claude.UsageLimitResetIn(final.Result, time.Now()); ok {
quota.ResetsAt = at
}
}
return "", fmt.Errorf("%w: %w", ErrHarnessTransport, quota)
}
return "", fmt.Errorf("%w: %w", ErrHarnessTransport, opencode.ErrProviderQuota)
case sessionMismatch || modelMismatch:
return "", fmt.Errorf("%w: %w", ErrHarnessTransport, &QuotaError{})
case inv.sessionMismatch || inv.modelMismatch:
return "", fmt.Errorf("%w: Claude Code did not start the requested session and model", ErrHarnessTransport)
case final == nil && proc.adopted:
return "", fmt.Errorf("%w: %w", ErrHarnessTransport, errClaudeStoppedUnwatched)
case final == nil:
if waitErr != nil {
return "", fmt.Errorf("%w: Claude Code exited with an error before a result (see the retained stderr log)", ErrHarnessTransport)
@@ -536,6 +924,74 @@ func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model,
return final.Result, nil
}
// claudeUsageLimitText reports whether a result's text is Claude Code's
// usage-limit refusal (the text is only matched, never copied).
func claudeUsageLimitText(text string) bool {
return claude.IsUsageLimitText(text)
}
// claudeProcessAlive reports whether pid is a live (not zombie) process whose
// command line names the session, so a recorded pid the system reused is never
// mistaken for the stage's CLI.
func claudeProcessAlive(pid int, session string) bool {
if pid <= 1 || session == "" {
return false
}
if _, err := os.Stat("/proc/self/stat"); err != nil {
return syscall.Kill(pid, 0) == nil // No procfs: liveness only.
}
stat, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
if err != nil {
return false
}
if i := bytes.LastIndexByte(stat, ')'); i < 0 || i+2 >= len(stat) || stat[i+2] == 'Z' || stat[i+2] == 'X' {
return false
}
cmdline, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid))
return err == nil && bytes.Contains(cmdline, []byte(session))
}
// ClaudeStageReattachable reports whether a Claude Code stage session a
// stopped server left owned can be re-adopted: its CLI still runs, or it ended
// with a final result while no server was watching (or it was in the outcome
// repair follow-up, which follows a complete result). Otherwise the error says
// why.
func ClaudeStageReattachable(reference, sessionID string) error {
owner, err := claudeStageOwnerAt(reference)
if err != nil || owner.SessionID != sessionID {
return errors.New("its retained evidence is missing or invalid")
}
if owner.Output == "" {
return errors.New("it was started by a server version that ran Claude Code as its own child")
}
if claudeProcessAlive(owner.PID, sessionID) || owner.Invocation > 0 {
return nil
}
root, err := claudeStageRoot(reference)
if err != nil {
return errors.New("its retained evidence is missing or invalid")
}
defer root.Close()
f, err := piOpenEvidence(root, owner.Output)
if err != nil {
return errors.New("its Claude Code output is missing")
}
defer f.Close()
reader := bufio.NewReaderSize(f, 64<<10)
for {
line, readErr := reader.ReadBytes('\n')
var record struct {
Type string `json:"type"`
}
if json.Unmarshal(line, &record) == nil && record.Type == "result" {
return nil
}
if readErr != nil {
return errClaudeStoppedUnwatched
}
}
}
func claudeGroupGone(pid int) bool {
return errors.Is(syscall.Kill(-pid, 0), syscall.ESRCH)
}
+40 -2
View File
@@ -76,9 +76,47 @@ func claudeStageRead(root *os.Root, name string, limit int64) ([]byte, bool, err
return data, false, err
}
// claudeStageOwner is the retained owner record of a Claude stage visit's
// current CLI invocation. Output names the file the detached CLI writes its
// stream-json to; it is empty for a visit an older server ran as its own child
// (with piped output), which a restart cannot re-adopt.
type claudeStageOwner struct {
PID int `json:"pid"`
SessionID string `json:"session_id"`
PID int `json:"pid"`
PGID int `json:"pgid,omitempty"`
SessionID string `json:"session_id"`
Invocation int `json:"invocation,omitempty"`
Output string `json:"output,omitempty"`
}
// writeClaudeStageOwner replaces the owner record atomically, so a server
// stopped mid-write never leaves a torn record behind.
func writeClaudeStageOwner(reference string, owner claudeStageOwner) error {
data, err := json.Marshal(owner)
if err != nil {
return err
}
temp := filepath.Join(reference, "owner.json.tmp")
if err := os.WriteFile(temp, data, 0600); err != nil {
return err
}
return os.Rename(temp, filepath.Join(reference, "owner.json"))
}
// claudeStageOwnerAt reads the owner record of a validated evidence directory.
func claudeStageOwnerAt(reference string) (claudeStageOwner, error) {
root, err := claudeStageRoot(reference)
if err != nil {
return claudeStageOwner{}, err
}
defer root.Close()
owner, err := claudeStageOwnerOf(root)
if err != nil {
return owner, err
}
if owner.Output != "" && owner.Output != claudeOutputName(owner.Invocation) {
return owner, fmt.Errorf("invalid retained Claude stage owner")
}
return owner, nil
}
func claudeStageOwnerOf(root *os.Root) (claudeStageOwner, error) {
+268
View File
@@ -0,0 +1,268 @@
package stage
import (
"context"
"errors"
"os"
"path/filepath"
"slices"
"strings"
"syscall"
"testing"
"time"
)
// detachClaudeMidInvocation runs Generate until invocation n's CLI has started
// working, then stops the "server" (a shutdown-caused cancel). The CLI must be
// left running and owned.
func detachClaudeMidInvocation(t *testing.T, client *ClaudeStageClient, ctx context.Context, config ModelConfig, n int) claudeStageOwner {
t.Helper()
run, stop := context.WithCancelCause(ctx)
defer stop(nil)
done := make(chan error, 1)
go func() {
_, err := client.Generate(run, config, "the task")
done <- err
}()
waitForClaudeOutput(t, n, `"init"`)
stop(ErrServerShutdown)
if err := <-done; !errors.Is(err, ErrDetached) {
t.Fatalf("a server shutdown did not detach the stage: %v", err)
}
if _, err := os.Stat(filepath.Join(client.Reference, "quiescent")); err == nil {
t.Fatal("a detached stage was marked quiescent")
}
owner, err := claudeStageOwnerAt(client.Reference)
if err != nil || owner.Invocation != n || owner.SessionID != client.SessionID {
t.Fatalf("owner %+v %v", owner, err)
}
if !claudeProcessAlive(owner.PID, client.SessionID) {
t.Fatal("the server shutdown stopped the Claude Code CLI")
}
if err := ClaudeStageReattachable(client.Reference, client.SessionID); err != nil {
t.Fatalf("a running stage is not reattachable: %v", err)
}
return owner
}
// waitForClaudeOutput waits until the (only) stage evidence directory's
// invocation n output contains needle and returns that directory. It reads the
// file system, never the client a running Generate is writing.
func waitForClaudeOutput(t *testing.T, n int, needle string) string {
t.Helper()
cache, err := os.UserCacheDir()
if err != nil {
t.Fatal(err)
}
deadline := time.Now().Add(10 * time.Second)
for {
dirs, _ := filepath.Glob(filepath.Join(cache, "pipelines", claudeStageSessions, "stage-*"))
for _, dir := range dirs {
if data, err := os.ReadFile(filepath.Join(dir, claudeOutputName(n))); err == nil && strings.Contains(string(data), needle) {
return dir
}
}
if time.Now().After(deadline) {
t.Fatalf("invocation %d never started", n)
}
time.Sleep(10 * time.Millisecond)
}
}
// restartedClaudeClient is the next server process's client for the same visit.
func restartedClaudeClient(first *ClaudeStageClient) (*ClaudeStageClient, *[]bool) {
active := &[]bool{}
return &ClaudeStageClient{Executable: first.Executable, Directory: first.Directory, Tools: first.Tools, Reference: first.Reference, OnOwnership: func(_, _ string, value bool) error {
*active = append(*active, value)
return nil
}}, active
}
func release(t *testing.T, root string) {
t.Helper()
if err := os.WriteFile(filepath.Join(root, "release"), nil, 0600); err != nil {
t.Fatal(err)
}
}
func waitGone(t *testing.T, pid int) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for !claudeGroupGone(pid) {
if time.Now().After(deadline) {
t.Fatal("the CLI did not exit")
}
time.Sleep(10 * time.Millisecond)
}
}
// TestClaudeStageSurvivesServerRestart: a server restart mid-stage leaves the
// CLI running; the next process re-adopts it, keeps reading its output, waits
// for its result and settles the visit, without prompting again.
func TestClaudeStageSurvivesServerRestart(t *testing.T) {
first, root, firstActive := fakeClaudeClient(t, "slow")
owner := detachClaudeMidInvocation(t, first, context.Background(), claudeConfig(nil), 0)
if !slices.Equal(*firstActive, []bool{true}) {
t.Fatal("the detaching process released ownership", *firstActive)
}
second, active := restartedClaudeClient(first)
budget := NewBudget(10, 1000)
ctx, cancel := context.WithTimeout(WithResumeSession(context.Background(), first.SessionID), 10*time.Second)
defer cancel()
go func() { time.Sleep(200 * time.Millisecond); release(t, root) }()
text, err := second.Generate(ctx, claudeConfig(budget), "never sent")
if err != nil || text != "done" {
t.Fatal(text, err)
}
if calls := fakeClaudeArgs(t, root); len(calls) != 1 {
t.Fatalf("the restarted server prompted again: %v", calls)
}
if prompt, _ := os.ReadFile(filepath.Join(root, "prompt")); string(prompt) != "the task" {
t.Fatalf("prompt %q", prompt)
}
if !slices.Equal(*active, []bool{true, false}) || !second.WorkStarted || second.SessionID != first.SessionID {
t.Fatal("ownership", *active, second.WorkStarted)
}
if used := budget.Snapshot(); used.UsedUSD != 0.25 || used.UsedTokens != 17 {
t.Fatalf("usage %+v", used)
}
if !claudeGroupGone(owner.PID) {
t.Fatal("the adopted CLI's group is still running")
}
// The evidence lists each record once and the export reads it.
data, err := ClaudeStageEvidence(first.Reference)
if err != nil || strings.Count(data, `"working"`) != 1 || strings.Count(data, `"type":"result"`) != 1 {
t.Fatalf("evidence %q %v", data, err)
}
if _, err := os.Stat(filepath.Join(first.Reference, claudeOutputName(0))); !os.IsNotExist(err) {
t.Fatal("the raw CLI output outlived the settled visit")
}
session, err := exportClaudeStageSession(ctx, SessionExportRequest{Backend: ClaudeBackend, SessionID: first.SessionID, Reference: first.Reference})
if err != nil || len(session.Messages) == 0 {
t.Fatalf("export %+v %v", session, err)
}
}
// TestClaudeStageFinishedWhileServerWasDown: the CLI completed while no server
// ran; the next process reads the result it left.
func TestClaudeStageFinishedWhileServerWasDown(t *testing.T) {
first, root, _ := fakeClaudeClient(t, "slow")
owner := detachClaudeMidInvocation(t, first, context.Background(), claudeConfig(nil), 0)
release(t, root)
waitGone(t, owner.PID)
if err := ClaudeStageReattachable(first.Reference, first.SessionID); err != nil {
t.Fatalf("a completed stage is not reattachable: %v", err)
}
second, active := restartedClaudeClient(first)
text, err := second.Generate(WithResumeSession(context.Background(), first.SessionID), claudeConfig(nil), "never sent")
if err != nil || text != "done" || !slices.Equal(*active, []bool{true, false}) {
t.Fatal(text, err, *active)
}
if calls := fakeClaudeArgs(t, root); len(calls) != 1 {
t.Fatalf("the restarted server prompted again: %v", calls)
}
}
// TestClaudeStageDiedWithoutResultWhileServerWasDown: a CLI that ended
// without a result while no server watched is never prompted again; recovery
// says why.
func TestClaudeStageDiedWithoutResultWhileServerWasDown(t *testing.T) {
first, root, _ := fakeClaudeClient(t, "slow")
owner := detachClaudeMidInvocation(t, first, context.Background(), claudeConfig(nil), 0)
_ = syscall.Kill(-owner.PID, syscall.SIGKILL)
waitGone(t, owner.PID)
err := ClaudeStageReattachable(first.Reference, first.SessionID)
if !errors.Is(err, errClaudeStoppedUnwatched) {
t.Fatalf("a dead stage without a result was reattachable: %v", err)
}
// Adopting anyway (a death between the plan and the adoption) fails
// closed with the same diagnostic and settles ownership.
second, active := restartedClaudeClient(first)
_, err = second.Generate(WithResumeSession(context.Background(), first.SessionID), claudeConfig(nil), "never sent")
if !errors.Is(err, ErrHarnessTransport) || !errors.Is(err, errClaudeStoppedUnwatched) || !slices.Equal(*active, []bool{true, false}) {
t.Fatal(err, *active)
}
if calls := fakeClaudeArgs(t, root); len(calls) != 1 {
t.Fatalf("a lost prompt was sent again: %v", calls)
}
}
// TestClaudeStageRestartDuringOutcomeRepair: a restart during the outcome
// repair follow-up re-adopts that follow-up; the prompt's report is read back
// from its retained output and merged with the reply, and both invocations'
// usage counts.
func TestClaudeStageRestartDuringOutcomeRepair(t *testing.T) {
first, root, _ := fakeClaudeClient(t, "slowrepair")
repair := withOutputRepair(context.Background(), []string{"error", "success"})
detachClaudeMidInvocation(t, first, repair, claudeConfig(nil), 1)
second, active := restartedClaudeClient(first)
budget := NewBudget(0, 1000)
go func() { time.Sleep(200 * time.Millisecond); release(t, root) }()
text, err := second.Generate(WithResumeSession(repair, first.SessionID), claudeConfig(budget), "never sent")
if err != nil || !strings.HasPrefix(text, "# outcome\nsuccess\n") || !strings.Contains(text, "Report kept.") {
t.Fatalf("%q %v", text, err)
}
if calls := fakeClaudeArgs(t, root); len(calls) != 2 {
t.Fatalf("invocations %v", calls)
}
if budget.Snapshot().UsedTokens != 34 || !slices.Equal(*active, []bool{true, false}) {
t.Fatalf("usage %+v ownership %v", budget.Snapshot(), *active)
}
}
// TestClaudeStageLostRepairFollowUpIsSentAgain: the follow-up's CLI died
// without a reply while the server was down; it only asks for the outcome,
// so the next process asks again instead of failing the visit.
func TestClaudeStageLostRepairFollowUpIsSentAgain(t *testing.T) {
first, root, _ := fakeClaudeClient(t, "slowrepair")
repair := withOutputRepair(context.Background(), []string{"error", "success"})
owner := detachClaudeMidInvocation(t, first, repair, claudeConfig(nil), 1)
_ = syscall.Kill(-owner.PID, syscall.SIGKILL)
waitGone(t, owner.PID)
if err := ClaudeStageReattachable(first.Reference, first.SessionID); err != nil {
t.Fatalf("a visit with a complete prompt result is not reattachable: %v", err)
}
release(t, root)
second, _ := restartedClaudeClient(first)
text, err := second.Generate(WithResumeSession(repair, first.SessionID), claudeConfig(nil), "never sent")
if err != nil || !strings.HasPrefix(text, "# outcome\nsuccess\n") {
t.Fatalf("%q %v", text, err)
}
calls := fakeClaudeArgs(t, root)
if len(calls) != 3 || !slices.Contains(calls[2], "--resume") {
t.Fatalf("invocations %v", calls)
}
}
// TestClaudeStageOperatorCancelStillStopsTheCLI: only a server shutdown
// detaches; an ordinary cancel stops the detached process group.
func TestClaudeStageOperatorCancelStillStopsTheCLI(t *testing.T) {
client, _, active := fakeClaudeClient(t, "slow")
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() {
_, err := client.Generate(ctx, claudeConfig(nil), "task")
done <- err
}()
owner, _ := claudeStageOwnerAt(waitForClaudeOutput(t, 0, "working"))
cancel()
if err := <-done; !errors.Is(err, context.Canceled) || errors.Is(err, ErrDetached) {
t.Fatal(err)
}
if !claudeGroupGone(owner.PID) || !slices.Equal(*active, []bool{true, false}) {
t.Fatal("cancel left the CLI running", *active)
}
}
func TestClaudeStageLegacyOwnerIsNotReattachable(t *testing.T) {
client, _, _ := fakeClaudeClient(t, "success")
if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(client.Reference, "owner.json"), []byte(`{"pid":99999999,"session_id":"`+client.SessionID+`"}`), 0600); err != nil {
t.Fatal(err)
}
if err := ClaudeStageReattachable(client.Reference, client.SessionID); err == nil || !strings.Contains(err.Error(), "server version") {
t.Fatal(err)
}
}
+117 -9
View File
@@ -48,6 +48,24 @@ case "$FAKE_CLAUDE_CASE" in
if [ "$resumed" = 1 ]; then text='# outcome\nsuccess\n'; else text='Report kept.'; fi
printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"result":"'"$text"'","session_id":"'"$session"'",'"$usage"'}'
;;
slow)
# Works until the test releases it (a server restart happens meanwhile).
init "$session" "$model"
echo '{"type":"assistant","session_id":"'"$session"'","message":{"role":"assistant","content":[{"type":"text","text":"working"}]}}'
while [ ! -e "$FAKE_CLAUDE_OUT/release" ]; do sleep 0.02; done
echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"'"$session"'",'"$usage"'}'
;;
slowrepair)
# The prompt's report lacks an outcome; the follow-up waits for release.
init "$session" "$model"
if [ "$resumed" = 1 ]; then
while [ ! -e "$FAKE_CLAUDE_OUT/release" ]; do sleep 0.02; done
text='# outcome\nsuccess\n'
else
text='Report kept.'
fi
printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"result":"'"$text"'","session_id":"'"$session"'",'"$usage"'}'
;;
nousage)
init "$session" "$model"
echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"'"$session"'"}'
@@ -74,6 +92,18 @@ case "$FAKE_CLAUDE_CASE" in
echo '{"type":"result","subtype":"success","is_error":true,"result":"PROVIDER-BODY-SECRET","session_id":"'"$session"'",'"$usage"'}'
exit 1
;;
ratelimit)
init "$session" "$model"
echo '{"type":"assistant","session_id":"'"$session"'","error":"rate_limit","message":{"role":"assistant","error":"rate_limit","content":[{"type":"text","text":"Claude AI usage limit reached|1794409200"}]}}'
echo '{"type":"result","subtype":"success","is_error":true,"result":"Claude AI usage limit reached|1794409200","session_id":"'"$session"'",'"$usage"'}'
exit 1
;;
denied)
init "$session" "$model"
echo '{"type":"assistant","session_id":"'"$session"'","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Edit","input":{"file_path":"/etc/hosts"}}]}}'
echo '{"type":"user","session_id":"'"$session"'","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","is_error":true,"content":"Claude requested permissions to write to /etc/hosts, but you have not granted it yet."}]}}'
printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"result":"# outcome\nblocked\n","session_id":"'"$session"'","permission_denials":[{"tool_name":"Bash","tool_use_id":"t2","tool_input":{"command":"git push origin main"}}],'"$usage"'}'
;;
auth)
init "$session" "$model"
echo '{"type":"assistant","session_id":"'"$session"'","error":"authentication_failed","message":{"role":"assistant","content":[{"type":"text","text":"PROVIDER-BODY-SECRET"}]}}'
@@ -228,6 +258,74 @@ func TestClaudeStageDeclaredToolsAreTheOnlyTools(t *testing.T) {
}
}
// A shell allow-list replaces the bare Bash rule: only the listed commands
// (exact, or a prefix with any arguments) are approved under dontAsk.
func TestClaudeStageShellAllowListMapsToBashRules(t *testing.T) {
client, root, _ := fakeClaudeClient(t, "success")
client.Tools = []string{"read", "shell"}
client.Policy.Shell = []string{"go test ./...", "git diff *"}
if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil {
t.Fatal(err)
}
calls := fakeClaudeArgs(t, root)
if len(calls) != 1 {
t.Fatal(calls)
}
args := calls[0]
for _, want := range []string{"Read,Bash,Skill", "Bash(go test ./...)", "Bash(git diff:*)"} {
if !slices.Contains(args, want) {
t.Fatalf("missing %q in args %q", want, args)
}
}
if slices.Contains(args, "Bash") {
t.Fatalf("a bare Bash rule approves every command: %q", args)
}
prompt, _ := os.ReadFile(filepath.Join(root, "prompt"))
if !strings.Contains(string(prompt), "Permitted shell commands") || !strings.Contains(string(prompt), "git diff *") {
t.Fatalf("prompt does not name the allow-list: %q", prompt)
}
// An empty list approves no command at all.
client2, root2, _ := fakeClaudeClient(t, "success")
client2.Tools = []string{"shell"}
client2.Policy.Shell = []string{}
if _, err := client2.Generate(context.Background(), claudeConfig(nil), "task"); err != nil {
t.Fatal(err)
}
for _, arg := range fakeClaudeArgs(t, root2)[0] {
if strings.HasPrefix(arg, "Bash") && arg != "Bash,Skill" {
t.Fatalf("empty allow-list approved %q", arg)
}
}
}
func TestClaudeStagePermissionsValidation(t *testing.T) {
def := func(permissions string) Definition {
return Definition{Key: "review", Type: ModelType,
Blocks: map[string]string{"prompt": "Review.", "configs": "x", "tools": "read\nshell", "permissions": permissions},
Configs: map[string]string{"harness": "claude", "provider": "anthropic", "model": "claude-haiku-5-5"},
Edges: map[string]string{"success": "#success"}}
}
if _, err := (ModelStage{}).Spec(def(`{"shell":["git diff *","go test ./..."]}`)); err != nil {
t.Fatal("shell allow-list rejected:", err)
}
for name, permissions := range map[string]string{
"edit": `{"edit":["a.go"],"shell":[]}`,
"chaining": `{"shell":["go test && rm x"]}`,
"mid star": `{"shell":["git * diff"]}`,
"parentheses": `{"shell":["echo (x)"]}`,
} {
if _, err := (ModelStage{}).Spec(def(permissions)); err == nil {
t.Fatal(name, "accepted")
}
}
// Prefix entries are claude-only: other harnesses enforce exact commands.
opencode := def(`{"shell":["git diff *"]}`)
opencode.Configs = map[string]string{"provider": "opencode-go", "model": "deepseek-v4.1-flash"}
if _, err := (ModelStage{}).Spec(opencode); err == nil || !strings.Contains(err.Error(), "claude harness") {
t.Fatal("opencode prefix permission:", err)
}
}
func TestClaudeStageNamedMCPToolsAreAllowlistedSeparately(t *testing.T) {
client, root, _ := fakeClaudeClient(t, "success")
client.Tools = []string{"read", "mcp:ai-memory", "mcp:linear/list_issues"}
@@ -254,12 +352,11 @@ func TestClaudeStageNamedMCPToolsAreAllowlistedSeparately(t *testing.T) {
func TestClaudeStageRefusesWhatItCannotEnforce(t *testing.T) {
for name, change := range map[string]func(*ClaudeStageClient, *ModelConfig){
"write paths": func(c *ClaudeStageClient, _ *ModelConfig) { c.WritePaths = []string{"app"} },
"edit permissions": func(c *ClaudeStageClient, _ *ModelConfig) { c.Policy.Edit = []string{"app/**"} },
"shell permissions": func(c *ClaudeStageClient, _ *ModelConfig) { c.Policy.Shell = []string{"go test"} },
"unknown tool": func(c *ClaudeStageClient, _ *ModelConfig) { c.Tools = []string{"browser"} },
"other provider": func(_ *ClaudeStageClient, m *ModelConfig) { m.Provider = "opencode-go" },
"no reasoning": func(_ *ClaudeStageClient, m *ModelConfig) { m.ReasoningEffort = "none" },
"write paths": func(c *ClaudeStageClient, _ *ModelConfig) { c.WritePaths = []string{"app"} },
"edit permissions": func(c *ClaudeStageClient, _ *ModelConfig) { c.Policy.Edit = []string{"app/**"} },
"unknown tool": func(c *ClaudeStageClient, _ *ModelConfig) { c.Tools = []string{"browser"} },
"other provider": func(_ *ClaudeStageClient, m *ModelConfig) { m.Provider = "opencode-go" },
"no reasoning": func(_ *ClaudeStageClient, m *ModelConfig) { m.ReasoningEffort = "none" },
} {
t.Run(name, func(t *testing.T) {
client, root, active := fakeClaudeClient(t, "success")
@@ -290,7 +387,15 @@ func TestClaudeStageFailuresAreFixedText(t *testing.T) {
"quota": func(err error) bool { return errors.Is(err, opencode.ErrProviderQuota) },
// A usage window names when it reopens.
"limited": func(err error) bool {
return errors.Is(err, opencode.ErrProviderQuota) && strings.Contains(err.Error(), "usage limit resets at")
at, ok := QuotaResetsAt(err)
return errors.Is(err, opencode.ErrProviderQuota) && SubscriptionQuota(err) && ok && at.Unix() == 1794409200 &&
strings.Contains(err.Error(), "resets at") && !strings.Contains(err.Error(), "top up")
},
// A subscription refusal named only by the assistant's error and
// the CLI's own text still parks with the reset the text names.
"ratelimit": func(err error) bool {
at, ok := QuotaResetsAt(err)
return errors.Is(err, opencode.ErrProviderQuota) && SubscriptionQuota(err) && ok && at.Unix() == 1794409200 && !strings.Contains(err.Error(), "top up")
},
"auth": func(err error) bool { return errors.Is(err, errClaudeSignedOut) },
"maxturns": func(err error) bool { return strings.Contains(err.Error(), "(error_max_turns)") },
@@ -326,7 +431,8 @@ func TestClaudeStageBudgetAccounting(t *testing.T) {
func TestClaudeStageOutcomeRepairResumesTheSameSession(t *testing.T) {
client, root, _ := fakeClaudeClient(t, "repair")
budget := NewBudget(0, 1000)
ctx := withOutputRepair(context.Background(), []string{"error", "success"})
counter := &RepairCounter{}
ctx := withOutputRepair(WithRepairCounter(context.Background(), counter), []string{"error", "success"})
text, err := client.Generate(ctx, claudeConfig(budget), "task")
if err != nil || !strings.HasPrefix(text, "# outcome\nsuccess\n") || !strings.Contains(text, "Report kept.") {
t.Fatalf("%q %v", text, err)
@@ -339,6 +445,9 @@ func TestClaudeStageOutcomeRepairResumesTheSameSession(t *testing.T) {
if budget.Snapshot().UsedTokens != 34 {
t.Fatalf("usage %+v", budget.Snapshot())
}
if counter.Count() != 1 {
t.Fatalf("repair follow-ups counted %d, want 1", counter.Count())
}
}
func TestClaudeStageTimeoutStopsTheProcessGroup(t *testing.T) {
@@ -395,7 +504,6 @@ func TestClaudeHarnessValidation(t *testing.T) {
"unknown harness": definition(map[string]string{"harness": "codex", "provider": "anthropic", "model": "claude-haiku-5-5"}, nil),
"capitalised": definition(map[string]string{"harness": "Claude", "provider": "anthropic", "model": "claude-haiku-5-5"}, nil),
"other provider": definition(claude(map[string]string{"provider": "opencode-go"}), nil),
"delivery": definition(claude(map[string]string{"delivery": "true"}), nil),
"permissions block": definition(claude(nil), map[string]string{"permissions": `{"edit":["app/**"]}`}),
"no reasoning": definition(claude(map[string]string{"reasoning_effort": "none"}), nil),
} {
+139
View File
@@ -0,0 +1,139 @@
package stage
import (
"context"
"errors"
"fmt"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// QuotaError is a provider usage-limit refusal. It matches
// opencode.ErrProviderQuota with errors.Is. ResetsAt is when the limit resets
// (zero when the refusal did not say). A subscription window (Claude's 5-hour
// or weekly limit) is not an empty account, so its text never asks the
// operator to top anything up.
type QuotaError struct {
ResetsAt time.Time
Subscription bool
}
func (e *QuotaError) Error() string {
if !e.Subscription {
return opencode.ErrProviderQuota.Error()
}
if e.ResetsAt.IsZero() {
return "the Claude usage limit was reached; the run continues when it resets"
}
return "the Claude usage limit was reached; it resets at " + e.ResetsAt.Local().Format("15:04 on 2 Jan")
}
func (e *QuotaError) Unwrap() error { return opencode.ErrProviderQuota }
// QuotaResetsAt returns the reset time a usage-limit error carries.
func QuotaResetsAt(err error) (time.Time, bool) {
var quota *QuotaError
if errors.As(err, &quota) && !quota.ResetsAt.IsZero() {
return quota.ResetsAt, true
}
return time.Time{}, false
}
// SubscriptionQuota reports whether err is a subscription usage window (one
// that resets on its own), as opposed to an exhausted paid balance.
func SubscriptionQuota(err error) bool {
var quota *QuotaError
return errors.As(err, &quota) && quota.Subscription
}
// ErrPermissionDenied is a stage whose declared tool use was refused by the
// harness's permission rules and that then gave up (answered blocked or
// error) instead of finishing its work.
var ErrPermissionDenied = errors.New("tool permission denied")
// PermissionDeniedError names the refused tool uses (bounded).
type PermissionDeniedError struct{ Denials []string }
func (e *PermissionDeniedError) Error() string {
return fmt.Sprintf("%s: %s; widen the stage's tools or run write paths, or change the task", ErrPermissionDenied, strings.Join(e.Denials, ", "))
}
func (e *PermissionDeniedError) Unwrap() error { return ErrPermissionDenied }
// permissionDenier is a client that observed tool permission denials.
type permissionDenier interface{ PermissionDenials() []string }
// ErrRunBudgetExceeded is the whole-run USD cap; it also matches
// ErrBudgetExceeded.
var ErrRunBudgetExceeded = errors.New("run budget exceeded")
// Harness failure kinds (HarnessFailureKind).
const (
HarnessTransient = "transient"
HarnessDeterministic = "deterministic"
// HarnessRepeatable is a harness failure that is deterministic when it
// repeats on the next visit of the same stage (an empty readback).
HarnessRepeatable = "repeatable"
)
// HarnessFailureKind classifies a stage failure for the runner's error-loop
// policy: transient failures (network, 5xx, overloaded, timeouts) are worth
// another visit after a backoff; deterministic ones (authentication,
// invalid arguments, a configuration the harness refuses) fail the same way
// every time. "" means the error is not a harness failure.
func HarnessFailureKind(err error) string {
if err == nil || errors.Is(err, opencode.ErrProviderQuota) || errors.Is(err, ErrBudgetExceeded) || errors.Is(err, context.Canceled) {
return ""
}
if errors.Is(err, ErrPermissionDenied) || errors.Is(err, errClaudeSignedOut) || errors.Is(err, errClaudeMissing) {
return HarnessDeterministic
}
text := strings.ToLower(err.Error())
for _, marker := range []string{"authentication", "unauthorized", "invalid api key", "invalid argument", "invalid_request", "unknown option", "unknown model", "model not found", "not supported", "cannot enforce", "needs provider", "did not start the requested session and model"} {
if strings.Contains(text, marker) {
return HarnessDeterministic
}
}
if strings.Contains(text, "readback contained no assistant message") {
return HarnessRepeatable
}
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, ErrHarnessUnreachable) {
return HarnessTransient
}
for _, marker := range []string{"timeout", "timed out", "connection refused", "connection reset", "broken pipe", "eof", "no such host", "network", "overloaded", "529", "502", "503", "504", "500 internal", "temporarily", "try again"} {
if strings.Contains(text, marker) {
return HarnessTransient
}
}
if harnessTransportFailure(err) {
return HarnessTransient
}
return ""
}
// FailureClassOf maps a stage error to the run failure class it causes.
func FailureClassOf(err error) string {
var deadline *stageDeadlineError
switch {
case err == nil:
return ""
case errors.Is(err, opencode.ErrProviderQuota):
return protocol.FailureQuota
case errors.Is(err, ErrBudgetExceeded):
return protocol.FailureBudget
case errors.Is(err, ErrPermissionDenied):
return protocol.FailurePermissionDenied
case errors.Is(err, context.Canceled):
return protocol.FailureCanceled
case errors.Is(err, errClaudeSignedOut), errors.Is(err, errClaudeMissing), errors.Is(err, ErrHarnessUnreachable):
return protocol.FailureEnvironment
case errors.As(err, &deadline), errors.Is(err, context.DeadlineExceeded):
return protocol.FailureTimeout
case harnessTransportFailure(err), errors.Is(err, ErrStageCleanup), errors.Is(err, ErrBudgetAccounting):
return protocol.FailureHarnessError
}
return protocol.FailureOther
}
+84
View File
@@ -0,0 +1,84 @@
package stage
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func TestClaudeStagePermissionDenialFailsABlockedVisit(t *testing.T) {
client, _, _ := fakeClaudeClient(t, "denied")
def := modelDefinition()
def.Configs = map[string]string{"harness": ClaudeBackend, "provider": ClaudeProvider, "model": "claude-haiku-5-5", "retries": "0"}
def.Blocks["configs"] = "harness=claude\nprovider=anthropic\nmodel=claude-haiku-5-5\nretries=0"
def.Edges = map[string]string{"success": protocol.SuccessEnd, "blocked": protocol.FailureEnd, "error": protocol.FailureEnd}
_, err := (ModelStage{Client: client}).Run(context.Background(), def, nil)
if !errors.Is(err, ErrPermissionDenied) || FailureClassOf(err) != protocol.FailurePermissionDenied {
t.Fatal(err)
}
for _, want := range []string{"Edit(/etc/hosts)", "Bash(git push origin main)"} {
if !strings.Contains(err.Error(), want) {
t.Fatalf("diagnostic %q does not name %s", err, want)
}
}
if HarnessFailureKind(err) != HarnessDeterministic {
t.Fatal("a permission denial repeats on the next visit")
}
}
func TestQuotaErrorWording(t *testing.T) {
reset := time.Date(2026, 12, 3, 9, 0, 0, 0, time.UTC)
subscription := fmt.Errorf("%w: %w", ErrHarnessTransport, &QuotaError{Subscription: true, ResetsAt: reset})
if !errors.Is(subscription, opencode.ErrProviderQuota) || strings.Contains(subscription.Error(), "top up") {
t.Fatal(subscription)
}
if at, ok := QuotaResetsAt(subscription); !ok || !at.Equal(reset) {
t.Fatal(at, ok)
}
balance := &QuotaError{}
if !strings.Contains(balance.Error(), "top up") || SubscriptionQuota(balance) {
t.Fatal("an exhausted paid balance keeps the top-up advice")
}
if FailureClassOf(subscription) != protocol.FailureQuota || HarnessFailureKind(subscription) != "" {
t.Fatal("quota is its own class, never a harness retry")
}
}
func TestHarnessFailureKinds(t *testing.T) {
for _, tc := range []struct {
err error
kind string
}{
{fmt.Errorf("%w: connection refused", ErrHarnessUnreachable), HarnessTransient},
{&openCodeError{status: 503}, HarnessTransient},
{fmt.Errorf("%w: the provider is overloaded", ErrHarnessTransport), HarnessTransient},
{fmt.Errorf("x: %w", context.DeadlineExceeded), HarnessTransient},
{fmt.Errorf("%w: final assistant readback contained no assistant message", ErrHarnessTransport), HarnessRepeatable},
{fmt.Errorf("%w: %w", ErrHarnessTransport, errClaudeSignedOut), HarnessDeterministic},
{fmt.Errorf("%w: invalid argument --tools", ErrHarnessTransport), HarnessDeterministic},
{errors.New("plain stage error"), ""},
{fmt.Errorf("%w: USD 2 / 1", ErrBudgetExceeded), ""},
} {
if got := HarnessFailureKind(tc.err); got != tc.kind {
t.Errorf("%v: kind %q, want %q", tc.err, got, tc.kind)
}
}
for err, class := range map[error]string{
fmt.Errorf("%w: %w", ErrBudgetExceeded, ErrRunBudgetExceeded): protocol.FailureBudget,
&stageDeadlineError{timeout: time.Second}: protocol.FailureTimeout,
fmt.Errorf("%w: x", ErrHarnessTransport): protocol.FailureHarnessError,
fmt.Errorf("%w: x", ErrHarnessUnreachable): protocol.FailureEnvironment,
context.Canceled: protocol.FailureCanceled,
errors.New("anything else"): protocol.FailureOther,
} {
if got := FailureClassOf(err); got != class {
t.Errorf("%v: class %q, want %q", err, got, class)
}
}
}
+7 -5
View File
@@ -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", "allow_workspace_changes":
default:
return ModelSpec{}, fmt.Errorf("unknown config %q", key)
}
@@ -111,8 +111,10 @@ 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")
}
if def.Configs["delivery"] == "true" && backend != "opencode" {
return ModelSpec{}, fmt.Errorf("delivery is supported only by the opencode harness")
// allow_workspace_changes=true lets a stage with shell but no edit leave file changes
// in the run directory; by default the runner fails such a visit.
if value := def.Configs["allow_workspace_changes"]; value != "" && value != "true" && value != "false" {
return ModelSpec{}, fmt.Errorf("allow_workspace_changes must be true or false")
}
if err := ValidateChecksBlock(def); err != nil {
return ModelSpec{}, err
@@ -143,8 +145,8 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
if _, err := claudeTools(tools); err != nil {
return ModelSpec{}, err
}
if _, present := def.Blocks["permissions"]; present {
return ModelSpec{}, fmt.Errorf("the claude harness cannot enforce a permissions block; use the opencode harness for this stage")
if err := claudePermissionsSupported(def); err != nil {
return ModelSpec{}, err
}
if effort == "none" || effort == "minimal" {
return ModelSpec{}, fmt.Errorf("the claude harness supports reasoning_effort low, medium, high, xhigh or max")
+30 -2
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"strings"
"sync/atomic"
"git.a-wan.net/alan/pipelines/internal/turn"
)
@@ -13,14 +14,38 @@ import (
// message in the same session asking only for the outcome, instead of failing
// a stage whose admitted work a full retry would repeat. The outcome is always
// stated by the model; the server never infers one from prose.
type outputRepair struct{ outcomes []string }
type outputRepair struct {
outcomes []string
counter *RepairCounter
}
type outputRepairKey struct{}
type repairCounterKey struct{}
// RepairCounter counts the outcome repair follow-ups sent during one visit
// (across its attempts). The runner records the count on the step.
type RepairCounter struct{ n atomic.Int32 }
// Count is the number of follow-ups sent so far.
func (c *RepairCounter) Count() int {
if c == nil {
return 0
}
return int(c.n.Load())
}
// WithRepairCounter makes every outcome repair follow-up under ctx increment
// counter.
func WithRepairCounter(ctx context.Context, counter *RepairCounter) context.Context {
return context.WithValue(ctx, repairCounterKey{}, counter)
}
// withOutputRepair lets a model client repair a missing or invalid outcome
// for the given declared outcomes while its session is still open.
func withOutputRepair(ctx context.Context, outcomes []string) context.Context {
return context.WithValue(ctx, outputRepairKey{}, &outputRepair{outcomes: outcomes})
counter, _ := ctx.Value(repairCounterKey{}).(*RepairCounter)
return context.WithValue(ctx, outputRepairKey{}, &outputRepair{outcomes: outcomes, counter: counter})
}
// outputRepairFrom returns the attempt's repair, or nil when none applies.
@@ -40,6 +65,9 @@ func (r *outputRepair) followUp(text string) (string, bool) {
if !errors.Is(err, turn.ErrMissingOutcome) && !errors.Is(err, turn.ErrOutcomeNotAllowed) && !errors.Is(err, turn.ErrDuplicateOutcome) {
return "", false
}
if r.counter != nil {
r.counter.n.Add(1)
}
allowed := strings.Join(r.outcomes, ", ")
return "Your final message has no valid `# outcome` section. Do not redo any work or repeat your report; the server keeps it. " +
outputShape(r.outcomes) + " Reply with only these two lines:\n\n# outcome\n<one of: " + allowed + ">\n", true
+7
View File
@@ -90,6 +90,13 @@ func (m ModelStage) Run(ctx context.Context, def Definition, input Values) (Resu
}
cancel()
if resultErr == nil {
// A stage that gave up after its tool use was refused failed on
// the permission rules, not on the task: say which use.
if denier, ok := client.(permissionDenier); ok && (result.Outcome == "blocked" || result.Outcome == "error") {
if denials := denier.PermissionDenials(); len(denials) > 0 {
return result, wrapModelStageFailure(def.Key, &PermissionDeniedError{Denials: denials})
}
}
return result, nil
}
// A malformed final result mutates nothing on an explicit read-only
+17
View File
@@ -249,3 +249,20 @@ func writeOperatorSkillPlugins(dir string, groups []OperatorSkillGroup) ([]strin
}
return roots, nil
}
// existingOperatorSkillPlugins lists the skills-only plugin roots an earlier
// process generated in dir (see writeOperatorSkillPlugins), for a re-adopted
// visit whose follow-up must offer the same skills.
func existingOperatorSkillPlugins(dir string) []string {
entries, err := os.ReadDir(dir)
if err != nil {
return nil
}
var roots []string
for _, entry := range entries {
if entry.IsDir() {
roots = append(roots, filepath.Join(dir, entry.Name()))
}
}
return roots
}
+52 -2
View File
@@ -77,9 +77,17 @@ func StagePermissions(def Definition) (ToolPolicy, error) {
seen[pattern] = true
}
seen = map[string]bool{}
claude := def.Configs["harness"] == ClaudeBackend
for _, command := range policy.Shell {
if command == "" || strings.TrimSpace(command) != command || strings.ContainsAny(command, "*?;|&<>`$\r\n\\") {
return ToolPolicy{}, fmt.Errorf("shell permissions must be exact commands without wildcards, chaining, redirects, or expansion")
exact, prefix := ShellPermissionPrefix(command)
if prefix && !claude {
return ToolPolicy{}, fmt.Errorf("shell prefix permissions (%q) are supported only by the claude harness; list exact commands", command)
}
if exact == "" || strings.TrimSpace(exact) != exact || strings.ContainsAny(exact, "*?;|&<>`$\r\n\\") {
return ToolPolicy{}, fmt.Errorf("shell permissions must be exact commands (or, on the claude harness, a command prefix ending in \" *\") without other wildcards, chaining, redirects, or expansion")
}
if claude && strings.ContainsAny(exact, "()") {
return ToolPolicy{}, fmt.Errorf("claude shell permissions cannot contain parentheses")
}
if seen[command] {
return ToolPolicy{}, fmt.Errorf("duplicate shell permission")
@@ -92,3 +100,45 @@ func StagePermissions(def Definition) (ToolPolicy, error) {
}
return *policy, nil
}
// ShellPermissionPrefix splits a permissions.shell entry. "go test *" is a
// prefix entry (the command with any arguments; claude harness only) and
// returns ("go test", true); any other entry is an exact command.
func ShellPermissionPrefix(entry string) (string, bool) {
if base, ok := strings.CutSuffix(entry, " *"); ok {
return base, true
}
return entry, false
}
// claudePermissionsSupported limits a claude stage's permissions block to a
// shell allow-list (mapped to Bash(...) rules). Claude Code's edit-path rules
// are not audited, so restricted edits stay with the other harnesses.
func claudePermissionsSupported(def Definition) error {
if _, present := def.Blocks["permissions"]; !present {
return nil
}
policy, err := StagePermissions(def)
if err != nil {
return err
}
if policy.Edit != nil {
return fmt.Errorf("the claude harness enforces only permissions.shell; remove permissions.edit or use the opencode harness for this stage")
}
return nil
}
// claudeShellRules maps a shell allow-list to Claude Code permission rules:
// an exact command to Bash(command) and a prefix entry to Bash(prefix:*).
// Claude Code checks each part of a chained command against the rules.
func claudeShellRules(shell []string) []string {
rules := make([]string, 0, len(shell))
for _, entry := range shell {
if base, prefix := ShellPermissionPrefix(entry); prefix {
rules = append(rules, "Bash("+base+":*)")
} else {
rules = append(rules, "Bash("+base+")")
}
}
return rules
}
+5 -2
View File
@@ -33,7 +33,10 @@ type Definition struct {
// ArtifactsDir is the per-run/step directory the runtime created for this
// visit; empty when the runner did not provide one (for example in tests).
ArtifactsDir string
Turn TurnPaths
// Workspace is the run directory (runtime-provided); a check stage runs
// its commands there.
Workspace string
Turn TurnPaths
// Skills is the visit's materialised skills block (runtime-provided, like
// ArtifactsDir); nil when the stage configures none or in tests.
Skills *SkillSet
@@ -72,7 +75,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{}, CheckType: CheckStage{}})
}
func EffectiveType(name string) string {
+10 -3
View File
@@ -40,8 +40,9 @@ func (a LandingAccess) valid() bool {
}
// DeliveryEnabled is the narrow, declarative capability check used before the
// runner supplies any landing paths. Only a validated model definition can ask
// for it; runtime paths are still derived by the server.
// runner supplies any landing paths. Only a validated model or check
// definition can ask for it, whatever its harness; runtime paths are still
// derived by the server.
func DeliveryEnabled(def Definition) (bool, error) {
delivery := def.Configs["delivery"]
if delivery == "" {
@@ -50,8 +51,14 @@ func DeliveryEnabled(def Definition) (bool, error) {
if delivery != "true" {
return false, fmt.Errorf("delivery must be true when set")
}
if EffectiveType(def.Type) == CheckType {
if _, err := CheckStageSpec(def); err != nil {
return false, fmt.Errorf("invalid delivery check stage: %w", err)
}
return true, nil
}
if EffectiveType(def.Type) != ModelType {
return false, fmt.Errorf("delivery is supported only by model stages")
return false, fmt.Errorf("delivery is supported only by model and check stages")
}
if _, err := (ModelStage{}).Spec(def); err != nil {
return false, fmt.Errorf("invalid delivery model stage: %w", err)
+19 -10
View File
@@ -246,18 +246,27 @@ func TestDeliveryEnabledRequiresValidatedModelStage(t *testing.T) {
}
}
func TestDeliveryRejectsPiBeforeAgentExecution(t *testing.T) {
func TestDeliveryIsHarnessAgnostic(t *testing.T) {
for _, harness := range []string{"opencode", "pi"} {
def := modelDefinition()
def.Configs["delivery"] = "true"
def.Configs["harness"] = harness
def.Blocks["checks"] = "go test ./..."
if err := (ModelStage{}).Validate(def); err != nil {
t.Fatalf("%s delivery was rejected: %v", harness, err)
}
if enabled, err := DeliveryEnabled(def); err != nil || !enabled {
t.Fatalf("%s delivery = %v, %v", harness, enabled, err)
}
}
def := modelDefinition()
def.Configs["delivery"] = "true"
def.Configs["harness"] = "pi"
def.Blocks["checks"] = "true"
if err := (ModelStage{}).Validate(def); err == nil || !strings.Contains(err.Error(), "opencode harness") {
t.Fatal("Pi delivery was accepted", err)
}
delete(def.Configs, "delivery")
delete(def.Blocks, "checks")
if err := (ModelStage{}).Validate(def); err != nil {
t.Fatal("Pi non-delivery was changed", err)
def.Configs["harness"] = ClaudeBackend
def.Configs["provider"] = ClaudeProvider
def.Configs["model"] = "claude-sonnet-4-5"
def.Blocks["checks"] = "go test ./..."
if enabled, err := DeliveryEnabled(def); err != nil || !enabled {
t.Fatalf("claude delivery = %v, %v", enabled, err)
}
}
+3
View File
@@ -19,6 +19,9 @@ type RunOptions struct {
Model string
StageModels map[string]string
NotifyMode string
// QuotaPolicy and BudgetUSD pass the CLI's --now/--defer and --budget.
QuotaPolicy string
BudgetUSD float64
}
func NewRun(ctx context.Context, url string, options RunOptions) Model {
+3
View File
@@ -107,6 +107,9 @@ func (m Model) homeLines() []string {
if r.Status == protocol.RunStatusWaiting {
runs = append(runs, "Waiting on a person · stage "+r.CurrentStage)
}
if r.Status == protocol.RunStatusWaitingQuota && r.QuotaWait != nil {
runs = append(runs, "Waiting for the usage limit · resumes "+quotaResumeClock(r.QuotaWait.ResumeAt))
}
runs = append(runs, "")
}
if len(m.runs) > limit {
+1 -1
View File
@@ -269,7 +269,7 @@ func runStatus(status string) string {
color = themeError
case "running", "queued":
color = themeAccent
case protocol.RunStatusWaiting:
case protocol.RunStatusWaiting, protocol.RunStatusWaitingQuota:
color = themeAccent
}
return lipgloss.NewStyle().Foreground(color).Render(status)
+14
View File
@@ -1,6 +1,8 @@
package tui
import (
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/charmbracelet/lipgloss"
)
@@ -30,6 +32,9 @@ func (m Model) progress(status string) string {
case protocol.RunStatusWaiting:
marker = "⏸"
color = themeAccent
case protocol.RunStatusWaitingQuota:
marker = "⧗"
color = themeAccent
}
return lipgloss.NewStyle().Foreground(color).Render(marker + " " + status)
}
@@ -51,3 +56,12 @@ func (m Model) stepProgressStatus(step protocol.RunStep) string {
}
return status
}
// quotaResumeClock is a parked run's resume time in local wall-clock time.
func quotaResumeClock(value string) string {
at, err := time.Parse(time.RFC3339, value)
if err != nil {
return value
}
return at.Local().Format("15:04 Mon")
}
+1 -1
View File
@@ -147,7 +147,7 @@ func (m *Model) startSelectedRun() tea.Cmd {
m.runCollapsed = nil
m.runDetail = nil
m.runTop = 0
request := protocol.Message{Type: protocol.RunPipeline, PipelineID: m.detail.ID, Version: m.detail.Version, RequestKey: fmt.Sprintf("tui-%d", time.Now().UnixNano()), Title: m.cliOptions.Title, Input: initialRunInput(m.runTask), AllowTools: m.runHasMutationTools(), WritePaths: m.runPaths, Workspace: m.runWorkspace, Model: m.cliOptions.Model, StageModels: m.cliOptions.StageModels, NotifyMode: m.cliOptions.NotifyMode, OutputFormat: m.cliOptions.OutputFormat}
request := protocol.Message{Type: protocol.RunPipeline, PipelineID: m.detail.ID, Version: m.detail.Version, RequestKey: fmt.Sprintf("tui-%d", time.Now().UnixNano()), Title: m.cliOptions.Title, Input: initialRunInput(m.runTask), AllowTools: m.runHasMutationTools(), WritePaths: m.runPaths, Workspace: m.runWorkspace, Model: m.cliOptions.Model, StageModels: m.cliOptions.StageModels, NotifyMode: m.cliOptions.NotifyMode, OutputFormat: m.cliOptions.OutputFormat, QuotaPolicy: m.cliOptions.QuotaPolicy, BudgetUSD: m.cliOptions.BudgetUSD}
updated, cmd := m.runRequest(request)
*m = updated.(Model)
return cmd
+11
View File
@@ -20,6 +20,10 @@ type PreviousAttempt struct {
Diagnostic string
// Run is the failed source run for a run retry; 0 for an in-stage retry.
Run int64
// Interruption, when set, says the previous attempt did not fail on its
// own but was stopped from outside (a provider usage limit); it replaces
// the failure wording and the diagnostic.
Interruption string
}
// RenderPreviousAttempt renders a bounded "# Previous attempt" section that
@@ -36,6 +40,13 @@ func RenderPreviousAttempt(p PreviousAttempt) string {
if stageName == "" {
stageName = "unknown"
}
if interruption := strings.TrimSpace(p.Interruption); interruption != "" {
fmt.Fprintf(&b, "This is attempt %d of stage %s. The previous attempt did not fail on its own: it was interrupted.", attempt, capLine(stageName, essentialLineCap))
b.WriteString(" Partial edits from it may still be in the worktree; check them (for example with git status and git diff) and continue from them instead of redoing work.\n\n")
b.WriteString(capLine(oneLine(interruption), PreviousAttemptCap))
b.WriteString("\n")
return b.String()
}
if p.Run > 0 {
fmt.Fprintf(&b, "This is attempt %d. The previous attempt (run %d) failed in stage %s.", attempt, p.Run, capLine(stageName, essentialLineCap))
} else {