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
+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)
}
}