From 86933e34c92394d9377d433512e3338fbab837e0 Mon Sep 17 00:00:00 2001 From: Brixton Pham <117471232+brixtonpham@users.noreply.github.com> Date: Mon, 30 Nov 2026 23:25:41 +0700 Subject: [PATCH] fix(server,agent): enforce planner run budgets and stop revive loops (#705) --- CHANGELOG.md | 1 + agent/budget.go | 262 ++++++++++++++++++++++++++++++++--- agent/budget_test.go | 177 +++++++++++++++++++++++ agent/planner.go | 11 +- agent/planner_progress.go | 21 ++- server/engine.go | 2 +- server/engine_budget.go | 35 +++-- server/engine_budget_test.go | 144 +++++++++++++++++++ server/engine_timeout.go | 31 ++++- server/goals.go | 28 +++- server/orchestration.go | 8 +- server/server.go | 2 +- 12 files changed, 678 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e7cfbb04f..6d15e8318 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ All notable changes to this project are documented in this file. The format is b - **Go vulnerability scanning in CI**: every push and pull request runs the official `govulncheck` action against packages reachable from `./...`, using the Go version declared by `go.mod`. Run the same check locally with `./scripts/verify.sh --security`. ### Fixed +- **Task run budgets now bound planner rounds and stop unbounded settle/revive loops** (#705): `budgetStop` now accounts for the planner round's own cost alongside the next worker's estimate, `Planner.Plan` enforces a per-round `PlannerMeter` (clamping `MaxTurns`, blocking intent/goal mutations and active probes on forced wrap-up or exhaustion, skipping `checkPlanningProgress` retries on budget wrap-up rounds, and failing closed at a hard `task + margin` lifetime ceiling), `settleTask` skips the final planner round when lifetime spend has already exceeded that hard ceiling, and `set_goals`/`add_intent` automatic agent revival no longer revives timed-out, settling, or budget-exhausted tasks. - **Attached curl body flags no longer bypass the stateful target guard**: `ClassifyHTTPAction` required a separator after `-d`, `-F` and `-T`, but curl takes the value fully attached, so `curl -dfoo=1`, `-Tshell.php` and `-Ffile=@payload` were classified read-only. That skipped the pre-mutation baseline gate and let `RecordStatefulReadOnly` store the mutation itself as the host's read-only baseline, a fail-open on a safety invariant. The attached forms are now mutating, including a spaced value (`-T shell.php`), while `-D` (dump headers), `-f`, `-o` and wget's `-T` timeout stay read-only. A body flag inside a multi-letter cluster (`-sSd...`) is still not detected. - **The chat agent filter no longer keeps a thread from another agent open**: switching the filter left the previously selected conversation in place, so a thread started with one agent could still be read while the filter showed another, and the draft could pick the wrong agent. The selection is now cleared when it does not belong to the new filter, and the draft uses the filtered agent. `npm run test:chat-filter` covers both helpers and now runs in CI. - **Session tokens are no longer accepted from a URL query string**: the SSE, log and browser endpoints accepted `?token=`, which put a console JWT into browser history, proxy logs and `Referer` headers. Those endpoints now require the same Bearer header as the rest of the API; the console uses a `fetch` based SSE reader, the client-written auth cookie is gone, and the same-origin CORS preflight allows `Authorization` and `Last-Event-ID`. Login and uploads no longer carry a token in the URL either (#660). diff --git a/agent/budget.go b/agent/budget.go index 4eb2925c0..2d6dec7ca 100644 --- a/agent/budget.go +++ b/agent/budget.go @@ -2,6 +2,7 @@ package agent import ( "context" + "errors" "fmt" "math" "os" @@ -9,6 +10,7 @@ import ( "strings" "sync" + "github.com/Autumn-27/norma/harness" "github.com/Autumn-27/norma/llm" ) @@ -25,13 +27,20 @@ import ( const Unlimited int64 = math.MaxInt64 const ( - BudgetMarginPercent = 5 // wrap-up reserve = max(5% of the task budget, floor) - BudgetMarginMinTokens = 20_000 // token floor of the reserve - BudgetMarginMinTurns = 2 // turn floor of the reserve - DefaultWorkerEstimateTokens = 50_000 // one worker run, until a worker of this task finished - DefaultWorkerEstimateTurns = 10 + BudgetMarginPercent = 5 // wrap-up reserve = max(5% of the task budget, floor) + BudgetMarginMinTokens = 20_000 // token floor of the reserve + BudgetMarginMinTurns = 2 // turn floor of the reserve + DefaultWorkerEstimateTokens = 50_000 // one worker run, until a worker of this task finished + DefaultWorkerEstimateTurns = 10 + DefaultPlannerEstimateTokens = 10_000 // one planner round, until a normal planner round finishes + DefaultPlannerEstimateTurns = 2 + BudgetWrapupMaxTurns = 4 // upper bound on turns in a forced budget wrap-up planner round ) +// ErrTaskBudgetExhausted is returned by a planner provider when the task's +// lifetime spend has exceeded its configured budget plus wrap-up reserve. +var ErrTaskBudgetExhausted = errors.New("task run budget exhausted") + // Budget caps tokens and turns; a dimension equal to Unlimited has no cap. type Budget struct{ Tokens, Turns int64 } @@ -100,6 +109,8 @@ type BudgetLedger struct { spent Spend // planner rounds + worker runs workerRuns int64 workerSpent Spend + plannerRuns int64 + plannerSpent Spend wrapup bool // the forced wrap-up has started } @@ -137,14 +148,19 @@ func (l *BudgetLedger) Record(u llm.Usage) { type BudgetState struct { Task, Remaining, Margin Budget Spent, Estimate Spend - AtMargin bool // remaining is at or under the wrap-up reserve - Dispatch bool // a new worker may start + PlannerEstimate Spend // estimated cost of one normal planner round + AtMargin bool // remaining is at or under the wrap-up reserve + Dispatch bool // a new worker may start + Plan bool // a new normal planner round may start + HardExhausted bool // lifetime spend exceeded task budget + wrap-up reserve } -// State reports the remaining budget and whether a worker may be dispatched: -// not once the wrap-up started or the reserve is reached, and not when the -// remaining budget is below one worker's estimated cost (the average of this -// task's finished worker runs, else the defaults; never above the intent cap). +// State reports the remaining budget and whether a worker or planner round may +// start: not once the wrap-up started or the reserve is reached, and not when +// the remaining budget is below the estimated cost (the average of this task's +// finished worker/planner runs, else the defaults; worker estimate never above +// the intent cap). HardExhausted is the lifetime circuit breaker once total +// spend has consumed both the task budget and the wrap-up reserve. func (l *BudgetLedger) State() BudgetState { l.mu.Lock() defer l.mu.Unlock() @@ -154,9 +170,32 @@ func (l *BudgetLedger) State() BudgetState { est = Spend{l.workerSpent.Tokens / l.workerRuns, l.workerSpent.Turns / l.workerRuns} } est = Spend{min(est.Tokens, l.intent.Tokens), min(est.Turns, l.intent.Turns)} + pEst := Spend{DefaultPlannerEstimateTokens, DefaultPlannerEstimateTurns} + if l.plannerRuns > 0 { + pEst = Spend{l.plannerSpent.Tokens / l.plannerRuns, l.plannerSpent.Turns / l.plannerRuns} + } at := (rem.Tokens != Unlimited && rem.Tokens <= m.Tokens) || (rem.Turns != Unlimited && rem.Turns <= m.Turns) - return BudgetState{Task: l.task, Remaining: rem, Margin: m, Spent: l.spent, Estimate: est, AtMargin: at, - Dispatch: !l.wrapup && !at && rem.Tokens >= est.Tokens && rem.Turns >= est.Turns} + dispatch := !l.wrapup && !at && rem.Tokens >= est.Tokens && rem.Turns >= est.Turns + avail := Budget{left(rem.Tokens, m.Tokens), left(rem.Turns, m.Turns)} + canPlan := dispatch && avail.Tokens >= pEst.Tokens && avail.Turns >= pEst.Turns + if canPlan && (l.plannerRuns > 0 || l.spent.Tokens > 0 || l.spent.Turns > 0) { + canPlan = (rem.Tokens == Unlimited || (rem.Tokens >= est.Tokens && rem.Tokens-est.Tokens >= pEst.Tokens)) && + (rem.Turns == Unlimited || (rem.Turns >= est.Turns && rem.Turns-est.Turns >= pEst.Turns)) + } + hardExhausted := (l.task.Tokens != Unlimited && l.spent.Tokens >= l.task.Tokens && l.spent.Tokens-l.task.Tokens >= m.Tokens) || + (l.task.Turns != Unlimited && l.spent.Turns >= l.task.Turns && l.spent.Turns-l.task.Turns >= m.Turns) + return BudgetState{ + Task: l.task, + Remaining: rem, + Margin: m, + Spent: l.spent, + Estimate: est, + PlannerEstimate: pEst, + AtMargin: at, + Dispatch: dispatch, + Plan: canPlan, + HardExhausted: hardExhausted, + } } // BeginWrapup marks the forced wrap-up; true only for the first caller, so the @@ -225,21 +264,136 @@ func (m *IntentMeter) Finish() { m.l.workerSpent = Spend{m.l.workerSpent.Tokens + m.spent.Tokens, m.l.workerSpent.Turns + m.spent.Turns} } +// PlannerMeter meters one planner round against the task's remaining budget. +// Normal rounds spend only above the wrap-up reserve; forced wrap-up rounds +// spend only within the wrap-up reserve. +type PlannerMeter struct { + l *BudgetLedger + wrapup bool + spent Spend // guarded by l.mu + finished bool // guarded by l.mu +} + +// StartPlannerRound opens the meter for one planner round. +func (l *BudgetLedger) StartPlannerRound(wrapup bool) *PlannerMeter { + return &PlannerMeter{l: l, wrapup: wrapup} +} + +// Record meters one planner LLM call into this round and the task ledger. +func (m *PlannerMeter) Record(u llm.Usage) { + if m == nil || m.l == nil { + return + } + m.l.mu.Lock() + defer m.l.mu.Unlock() + m.spent, m.l.spent = addUsage(m.spent, u), addUsage(m.l.spent, u) +} + +// Remaining is this planner round's effective remaining budget. Normal rounds +// drop to zero once the wrap-up reserve is reached or forced wrap-up begins. +func (m *PlannerMeter) Remaining() Budget { + if m == nil || m.l == nil { + return NewBudget(0, 0) + } + l := m.l + l.mu.Lock() + defer l.mu.Unlock() + rem, res := l.task.Remaining(l.spent), WrapupMargin(l.task) + if m.wrapup { + tokens := rem.Tokens + if res.Tokens > 0 && tokens != Unlimited { + tokens = min(tokens, res.Tokens) + } + turns := rem.Turns + if res.Turns > 0 && turns != Unlimited { + turns = min(turns, res.Turns) + } + return Budget{tokens, turns} + } + if l.wrapup { + return Budget{} + } + return Budget{left(rem.Tokens, res.Tokens), left(rem.Turns, res.Turns)} +} + +// Exhausted reports whether this planner round has no budget left in some dimension. +func (m *PlannerMeter) Exhausted() bool { + if m == nil || m.l == nil { + return false + } + r := m.Remaining() + return r.Tokens == 0 || r.Turns == 0 +} + +// HardExhausted reports whether lifetime task spend has exceeded the configured +// task budget plus its wrap-up reserve (circuit breaker). +func (m *PlannerMeter) HardExhausted() bool { + if m == nil || m.l == nil { + return false + } + return m.l.State().HardExhausted +} + +// Finish folds a normal planner round into the task's per-round average. +// Idempotent; wrap-up rounds are excluded so they do not skew normal estimates. +func (m *PlannerMeter) Finish() { + if m == nil || m.l == nil { + return + } + m.l.mu.Lock() + defer m.l.mu.Unlock() + if m.finished || m.wrapup || (m.spent.Tokens == 0 && m.spent.Turns == 0) { + m.finished = true + return + } + m.finished = true + m.l.plannerRuns++ + m.l.plannerSpent = Spend{m.l.plannerSpent.Tokens + m.spent.Tokens, m.l.plannerSpent.Turns + m.spent.Turns} +} + // BudgetWrapupBlocks reports whether a worker tool is refused once its budget is // exhausted: all but the write-back tools, so the run records facts and stops. func BudgetWrapupBlocks(tool string) bool { return tool != "record_fact" && tool != "insert_assets" && tool != "report_finding" && tool != "update_finding_report" && tool != "record_coverage" } +// PlannerWrapupBlocks reports whether a tool is forbidden during a forced budget +// wrap-up planner round: no new intents, no goal/constraint mutations (which +// could revive the task), no scope changes, and no active probing or editing. +func PlannerWrapupBlocks(tool string) bool { + switch tool { + case "add_intent", "set_goals", "set_constraints", + "add_task_scope", "add_company_scope", + "Bash", "WebFetch", "web_search", + "Write", "Edit", "MultiEdit", + "shell_open", "shell_exec", "shell_write", "shell_read", "shell_close": + return true + default: + return false + } +} + +// PlannerBudgetExhaustedBlocks reports whether a planner tool is refused once +// the round's budget is exhausted: only final goal judgment and finding +// write-back remain allowed. +func PlannerBudgetExhaustedBlocks(tool string) bool { + return tool != "prove_goal" && tool != "goal_met" && tool != "report_finding" && tool != "update_finding_report" +} + // WorkerBudgetWrapup is returned in place of a refused tool call. const WorkerBudgetWrapup = "[Budget reached] This intent's token/turn budget is used up; the tool call was not executed. Do not run any more commands or probes. Write back what you identified but have not persisted yet (insert_assets, record_fact, report_finding), then, in a single standalone sentence of plain text, summarize what you did and your key conclusions." +// PlannerBudgetWrapup is returned in place of a refused planner tool call when +// the task budget is exhausted or the forced wrap-up round forbids the tool. +const PlannerBudgetWrapup = "[Budget reached] This task's token/turn budget is used up; the tool call was not executed. Do not dispatch new intents, add goals, or run probes. Only call prove_goal or report_finding/update_finding_report if already proven by existing evidence, then finish with a single standalone sentence summarizing where the task stands." + const plannerBudgetWrapup = "**The task's token/turn budget is exhausted and the task is about to end** (a normal end, not an error). Based on the current facts and findings, make the final goal judgment: call prove_goal for goals proven met by evidence. **Do not generate any new intents** (they will not be executed). Then, in a single standalone sentence of plain text, summarize where the task stands." // BudgetRound carries one planner round's budget on ctx (zero = no budget). type BudgetRound struct { - Line string // one-line remaining budget for the planner context - WrapUp bool // the forced wrap-up round + Line string // one-line remaining budget for the planner context + WrapUp bool // the forced wrap-up round + Meter *PlannerMeter // live per-round meter (nil when no budget is configured) } type budgetRoundKey struct{} @@ -250,6 +404,11 @@ func WithBudgetRound(ctx context.Context, r BudgetRound) context.Context { return context.WithValue(ctx, budgetRoundKey{}, r) } +func budgetRoundFrom(ctx context.Context) BudgetRound { + r, _ := ctx.Value(budgetRoundKey{}).(BudgetRound) + return r +} + // WithIntentMeter attaches a worker run's meter to ctx (turn clamp). func WithIntentMeter(ctx context.Context, m *IntentMeter) context.Context { return context.WithValue(ctx, intentMeterKey{}, m) @@ -258,7 +417,7 @@ func WithIntentMeter(ctx context.Context, m *IntentMeter) context.Context { // plannerBudgetBlock is the code-owned budget text appended to the planner's // situational block (same pattern as the endgame words); empty without a budget. func plannerBudgetBlock(ctx context.Context) string { - r, _ := ctx.Value(budgetRoundKey{}).(BudgetRound) + r := budgetRoundFrom(ctx) s := "" if r.Line != "" { s += "\n\n" + r.Line @@ -269,6 +428,77 @@ func plannerBudgetBlock(ctx context.Context) string { return s } +// plannerBudgetHooks enforces planner round budget rules in PreToolUse. +type plannerBudgetHooks struct { + inner harness.HookRunner + meter *PlannerMeter + wrapup bool +} + +func wrapPlannerBudgetHooks(hooks harness.HookRunner, r BudgetRound) harness.HookRunner { + if r.Meter == nil && !r.WrapUp { + return hooks + } + return plannerBudgetHooks{inner: hooks, meter: r.Meter, wrapup: r.WrapUp} +} + +func (h plannerBudgetHooks) PreToolUse(ctx context.Context, name string, input []byte) (bool, string, []byte) { + if h.wrapup && PlannerWrapupBlocks(name) { + return true, PlannerBudgetWrapup, nil + } + if h.meter != nil && PlannerBudgetExhaustedBlocks(name) && h.meter.Exhausted() { + return true, PlannerBudgetWrapup, nil + } + if h.inner != nil { + return h.inner.PreToolUse(ctx, name, input) + } + return false, "", nil +} + +func (h plannerBudgetHooks) PostToolUse(ctx context.Context, name string, input, result []byte, isErr bool) { + if h.inner != nil { + h.inner.PostToolUse(ctx, name, input, result, isErr) + } +} + +func (h plannerBudgetHooks) Stop(ctx context.Context, messages []llm.Message) (bool, []string, string) { + if h.inner != nil { + return h.inner.Stop(ctx, messages) + } + return false, nil, "" +} + +// turnCap is the planner's MaxTurns for this round: its own, clamped by the +// round's remaining turn budget (and tightly bounded on forced budget wrap-up). +func (p *Planner) turnCap(ctx context.Context) int { + r := budgetRoundFrom(ctx) + if r.Meter == nil { + if r.WrapUp && (p.maxTurns <= 0 || BudgetWrapupMaxTurns < p.maxTurns) { + return BudgetWrapupMaxTurns + } + return p.maxTurns + } + rem := r.Meter.Remaining() + capTurns := rem.Turns + if r.WrapUp { + if capTurns == Unlimited { + capTurns = BudgetWrapupMaxTurns + } else { + capTurns = min(capTurns, BudgetWrapupMaxTurns) + } + if rem.Tokens == 0 { + capTurns = min(capTurns, BudgetMarginMinTurns) + } + } + if capTurns == Unlimited { + return p.maxTurns + } + if c := int(max(capTurns, 1)); p.maxTurns <= 0 || c < p.maxTurns { + return c + } + return p.maxTurns +} + // turnCap is the worker's MaxTurns for this run: its own, clamped by the // intent's effective remaining turns (never 0, which harness reads as unlimited). func (w *Worker) turnCap(ctx context.Context) int { diff --git a/agent/budget_test.go b/agent/budget_test.go index 2c4c10a18..98e64710a 100644 --- a/agent/budget_test.go +++ b/agent/budget_test.go @@ -2,6 +2,8 @@ package agent import ( "context" + "errors" + "iter" "strings" "testing" @@ -155,3 +157,178 @@ func TestRestoreSpendCountsTowardCap(t *testing.T) { var none *BudgetLedger none.RestoreSpend(Spend{Tokens: 1, Turns: 1}) } + +func TestPlannerRoundReservationAndMetering(t *testing.T) { + // Exact config from #705: task 250k / 150 turns, intent 30k / 10 turns. + // Wrap-up reserve is max(5% = 12.5k, 20k) = 20k tokens, max(5% = 7, 2) = 7 turns. + l := NewBudgetLedger(NewBudget(250_000, 150), NewBudget(30_000, 10)) + if st := l.State(); !st.Dispatch || !st.Plan || st.HardExhausted { + t.Fatalf("fresh state = %+v, want Dispatch=true Plan=true HardExhausted=false", st) + } + + // Finish one normal planner round costing 35k tokens / 3 turns. + pm := l.StartPlannerRound(false) + pm.Record(llm.Usage{InputTokens: 10_000, OutputTokens: 2_000}) + pm.Record(llm.Usage{InputTokens: 12_000, OutputTokens: 1_000}) + pm.Record(llm.Usage{InputTokens: 9_000, OutputTokens: 1_000}) + pm.Finish() + pm.Finish() // idempotent + + st := l.State() + if st.PlannerEstimate != (Spend{35_000, 3}) { + t.Fatalf("PlannerEstimate = %+v, want {35000 3}", st.PlannerEstimate) + } + + // Spend up to 195k total (55k remaining): still enough for one 30k worker + // (Dispatch=true), but not enough for a 35k planner round + 30k worker (Plan=false). + spend(l, 160_000) + st = l.State() + if !st.Dispatch || st.AtMargin || st.Plan { + t.Fatalf("at 55k remaining: Dispatch=%v AtMargin=%v Plan=%v, want Dispatch=true AtMargin=false Plan=false", + st.Dispatch, st.AtMargin, st.Plan) + } + + // Normal planner round meter stops at the 20k wrap-up reserve (35k available above reserve). + pm2 := l.StartPlannerRound(false) + if got := pm2.Remaining(); got.Tokens != 35_000 || pm2.Exhausted() { + t.Fatalf("normal planner remaining = %+v exhausted=%v, want 35000 tokens", got, pm2.Exhausted()) + } + pm2.Record(llm.Usage{InputTokens: 35_000}) // total spent 230k (remaining == 20k reserve) + if !pm2.Exhausted() || pm2.HardExhausted() { + t.Fatalf("at reserve: exhausted=%v hard=%v, want exhausted=true hard=false", pm2.Exhausted(), pm2.HardExhausted()) + } + + // Concurrent BeginWrapup exhausts any in-flight normal planner meter immediately. + l2 := NewBudgetLedger(NewBudget(250_000, 150), NewBudget(30_000, 10)) + inFlight := l2.StartPlannerRound(false) + if inFlight.Exhausted() { + t.Fatal("fresh in-flight planner meter must not be exhausted") + } + l2.BeginWrapup() + if !inFlight.Exhausted() { + t.Fatal("BeginWrapup must exhaust in-flight normal planner meter") + } + + // Wrap-up round meter does not alter PlannerEstimate, and HardExhausted flips + // once lifetime spend crosses task + wrap-up reserve (250k + 20k = 270k). + wm := l.StartPlannerRound(true) + if got := wm.Remaining(); got.Tokens != 20_000 || wm.Exhausted() { + t.Fatalf("wrap-up remaining = %+v exhausted=%v, want 20000 tokens", got, wm.Exhausted()) + } + wm.Record(llm.Usage{InputTokens: 20_000}) // total spent 250k (remaining == 0, not yet hard ceiling) + if !wm.Exhausted() || wm.HardExhausted() { + t.Fatalf("at 100%% cap: exhausted=%v hard=%v, want exhausted=true hard=false", wm.Exhausted(), wm.HardExhausted()) + } + wm.Record(llm.Usage{InputTokens: 20_000}) // total spent 270k == task + margin + if !wm.HardExhausted() || !l.State().HardExhausted { + t.Fatalf("at 270k (task+margin): HardExhausted=false, want true") + } + wm.Finish() + if got := l.State().PlannerEstimate; got != (Spend{35_000, 3}) { + t.Fatalf("wrap-up Finish modified PlannerEstimate to %+v, want {35000 3}", got) + } +} + +func TestPlannerBudgetHooksAndTurnCap(t *testing.T) { + // Without a budget on ctx, turnCap and hooks are passthrough. + p := &Planner{maxTurns: 25} + if got := p.turnCap(context.Background()); got != 25 { + t.Fatalf("turnCap without budget = %d, want 25", got) + } + if got := wrapPlannerBudgetHooks(nil, BudgetRound{}); got != nil { + t.Fatalf("wrapPlannerBudgetHooks without budget = %#v, want nil", got) + } + + // Normal round with turn budget clamps even unlimited planner maxTurns (0). + l := NewBudgetLedger(NewBudget(250_000, 10), NewBudget(30_000, 5)) // margin = 2 turns, 8 normal turns + pm := l.StartPlannerRound(false) + normalCtx := WithBudgetRound(context.Background(), BudgetRound{Meter: pm}) + if got := (&Planner{maxTurns: 0}).turnCap(normalCtx); got != 8 { + t.Fatalf("normal turnCap with unlimited maxTurns = %d, want 8", got) + } + + // Wrap-up round clamps unlimited turns to BudgetWrapupMaxTurns, and to + // BudgetMarginMinTurns when token budget is already at zero. + lTokOnly := NewBudgetLedger(NewBudget(100_000, 0), NewBudget(0, 0)) + spend(lTokOnly, 80_000) // 20k reserve left + wm := lTokOnly.StartPlannerRound(true) + wrapCtx := WithBudgetRound(context.Background(), BudgetRound{WrapUp: true, Meter: wm}) + if got := (&Planner{maxTurns: 0}).turnCap(wrapCtx); got != BudgetWrapupMaxTurns { + t.Fatalf("wrap-up turnCap with reserve remaining = %d, want %d", got, BudgetWrapupMaxTurns) + } + wm.Record(llm.Usage{InputTokens: 20_000}) // tokens now 0 + if got := (&Planner{maxTurns: 0}).turnCap(wrapCtx); got != BudgetMarginMinTurns { + t.Fatalf("wrap-up turnCap at 0 tokens = %d, want %d", got, BudgetMarginMinTurns) + } + + // Wrap-up hook blocks add_intent/set_goals/Bash even while reserve remains, + // allows read/judgment tools, and once exhausted allows only final judgment tools. + lWrap := NewBudgetLedger(NewBudget(100_000, 0), NewBudget(0, 0)) + spend(lWrap, 80_000) + wm2 := lWrap.StartPlannerRound(true) + h := wrapPlannerBudgetHooks(nil, BudgetRound{WrapUp: true, Meter: wm2}) + for _, blocked := range []string{"add_intent", "set_goals", "Bash", "WebFetch"} { + if ok, msg, _ := h.PreToolUse(context.Background(), blocked, nil); !ok || msg != PlannerBudgetWrapup { + t.Fatalf("wrap-up PreToolUse(%q) = (%v, %q), want blocked with PlannerBudgetWrapup", blocked, ok, msg) + } + } + for _, allowed := range []string{"node_detail", "prove_goal", "report_finding"} { + if ok, _, _ := h.PreToolUse(context.Background(), allowed, nil); ok { + t.Fatalf("wrap-up PreToolUse(%q) blocked while reserve remains", allowed) + } + } + wm2.Record(llm.Usage{InputTokens: 20_000}) // reserve exhausted + if ok, msg, _ := h.PreToolUse(context.Background(), "node_detail", nil); !ok || msg != PlannerBudgetWrapup { + t.Fatalf("exhausted wrap-up PreToolUse(node_detail) = (%v, %q), want blocked", ok, msg) + } + for _, allowed := range []string{"prove_goal", "goal_met", "report_finding", "update_finding_report"} { + if ok, _, _ := h.PreToolUse(context.Background(), allowed, nil); ok { + t.Fatalf("exhausted PreToolUse(%q) blocked final judgment tool", allowed) + } + } +} + +type budgetCountingProvider struct{ calls int } + +func (p *budgetCountingProvider) Complete(context.Context, llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + p.calls++ + return llm.Message{Role: llm.RoleAssistant}, "end_turn", llm.Usage{}, nil +} + +func (p *budgetCountingProvider) Stream(context.Context, llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { + return func(yield func(llm.StreamEvent, error) bool) { + p.calls++ + yield(llm.StreamEvent{Type: llm.SEMessageStop, StopReason: "end_turn"}, nil) + } +} + +func TestPlanningProviderHardExhaustedRefusesBeforeTransport(t *testing.T) { + l := NewBudgetLedger(NewBudget(100_000, 0), NewBudget(0, 0)) + pm := l.StartPlannerRound(false) + inner := &budgetCountingProvider{} + prov := &planningProvider{Provider: inner, budget: pm} + + // Below hard ceiling (100k + 20k = 120k): request reaches inner provider. + if _, _, _, err := prov.Complete(context.Background(), llm.CompletionRequest{}); err != nil { + t.Fatalf("below ceiling Complete err = %v", err) + } + if inner.calls != 1 { + t.Fatalf("below ceiling calls = %d, want 1", inner.calls) + } + + // Exceed hard ceiling: both Complete and Stream fail closed with 0 transport calls. + pm.Record(llm.Usage{InputTokens: 120_000}) + if _, _, _, err := prov.Complete(context.Background(), llm.CompletionRequest{}); !errors.Is(err, ErrTaskBudgetExhausted) { + t.Fatalf("hard-exhausted Complete err = %v, want ErrTaskBudgetExhausted", err) + } + var streamErr error + for _, err := range prov.Stream(context.Background(), llm.CompletionRequest{}) { + streamErr = err + } + if !errors.Is(streamErr, ErrTaskBudgetExhausted) { + t.Fatalf("hard-exhausted Stream err = %v, want ErrTaskBudgetExhausted", streamErr) + } + if inner.calls != 1 { + t.Fatalf("hard-exhausted provider still invoked inner transport: calls=%d, want 1", inner.calls) + } +} diff --git a/agent/planner.go b/agent/planner.go index d7283b254..692f248bd 100644 --- a/agent/planner.go +++ b/agent/planner.go @@ -640,7 +640,7 @@ func (p *Planner) planOnce(ctx context.Context, taskID int64, as *db.AssetStore, situational += plannerBudgetBlock(ctx) // Coverage ledger (coverage-only): compact line each round; capped gap list on a // wrap-up round. Its agent-reported gap lines are framed with this message's env. - budgetRound, _ := ctx.Value(budgetRoundKey{}).(BudgetRound) + budgetRound := budgetRoundFrom(ctx) situational += tsx.coverageLedgerBlock(tc.Final || budgetRound.WrapUp, env) // The main run directory /tasks//main; create it first. taskDir := ensureRunDir(p.workDir, taskID, 0) @@ -660,7 +660,7 @@ func (p *Planner) planOnce(ctx context.Context, taskID int64, as *db.AssetStore, if tc.DeadlineUnix > 0 { settle = wrapupSettlementForTask("planner", nil, clamped) } - observedProvider := &planningProvider{Provider: p.prov} + observedProvider := &planningProvider{Provider: p.prov, budget: budgetRound.Meter} opts := agentcore.Options{ Provider: observedProvider, SystemPrompt: system, @@ -684,8 +684,8 @@ func (p *Planner) planOnce(ctx context.Context, taskID int64, as *db.AssetStore, BashEnv: proxyEnv(p.proxyAddr, p.proxyCACert), // Bash subcommands go through the proxy + trust its CA by default WorkingDir: taskDir, // the main run directory /tasks//main ToolOutputDir: TaskToolOutputDir(p.workDir, taskID, taskDir), - MaxTurns: p.maxTurns, // 0 = unlimited (configurable in agent management) - MaxDuration: maxDur, // 0=unlimited; with a deadline = time remaining until it + MaxTurns: p.turnCap(ctx), // 0 = unlimited; clamped by task turn budget and forced wrap-up cap + MaxDuration: maxDur, // 0=unlimited; with a deadline = time remaining until it Compaction: compactionConfig(p.compactionWindow()), // Planning todos shared across wake-ups: keep the serial chain across rounds (the session is new; the store isn't). Todos: p.todoFor(ts.ID()), @@ -704,6 +704,7 @@ func (p *Planner) planOnce(ctx context.Context, taskID int64, as *db.AssetStore, if hooks != nil { // typed-nil guard: only set when concrete (avoids harness panic) opts.Hooks = hooks } + opts.Hooks = wrapPlannerBudgetHooks(opts.Hooks, budgetRound) opts.Hooks = SpillHooks(opts.Hooks, opts.ToolOutputDir) // The session id is the provider-side identity (session header, usage metering) // with or without persistence; Norma only puts it on ctx when it writes a transcript. @@ -755,7 +756,7 @@ func (p *Planner) planOnce(ctx context.Context, taskID int64, as *db.AssetStore, emit(r) } }) - if err == nil && !tsx.GoalMet && !tc.Final { + if err == nil && !tsx.GoalMet && !tc.Final && !budgetRound.WrapUp && (budgetRound.Meter == nil || !budgetRound.Meter.Exhausted()) { err = p.checkPlanningProgress(ctx, ts, tsx, before, terminal, observedProvider.refused.Load(), toolErrors) } return tsx.GoalMet, tsx.Reason, err diff --git a/agent/planner_progress.go b/agent/planner_progress.go index e9ed8e787..8cce1995f 100644 --- a/agent/planner_progress.go +++ b/agent/planner_progress.go @@ -39,10 +39,13 @@ func (e *PlanningNoProgressError) Error() string { } // The wrapper observes explicit provider refusal flags, without interpreting -// natural-language refusal text or retrying it on a different provider. +// natural-language refusal text or retrying it on a different provider. When a +// planner budget meter is attached, it also enforces the lifetime hard ceiling +// before sending any further LLM requests. type planningProvider struct { llm.Provider refused atomic.Bool + budget *PlannerMeter } func (p *planningProvider) observe(stop string) { @@ -51,12 +54,19 @@ func (p *planningProvider) observe(stop string) { } } func (p *planningProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + if p.budget != nil && p.budget.HardExhausted() { + return llm.Message{}, "", llm.Usage{}, ErrTaskBudgetExhausted + } m, s, u, e := p.Provider.Complete(ctx, req) p.observe(s) return m, s, u, e } func (p *planningProvider) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { return func(yield func(llm.StreamEvent, error) bool) { + if p.budget != nil && p.budget.HardExhausted() { + yield(llm.StreamEvent{}, ErrTaskBudgetExhausted) + return + } for ev, err := range p.Provider.Stream(ctx, req) { p.observe(ev.StopReason) if !yield(ev, err) { @@ -92,8 +102,12 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts if err := ctx.Err(); err != nil { return false, "", err } + budgetRound := budgetRoundFrom(ctx) + if budgetRound.Meter != nil { + defer budgetRound.Meter.Finish() + } p.compactor.OnPlannerRound(ctx, ts) - if taskClockFrom(ctx).Final { + if taskClockFrom(ctx).Final || budgetRound.WrapUp { return p.planOnce(ctx, taskID, as, ts, goal, triggers, hooks, emit) } parentCtx := ctx @@ -124,6 +138,9 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts if err == nil || met { return met, reason, err } + if errors.Is(err, ErrTaskBudgetExhausted) || (budgetRound.Meter != nil && budgetRound.Meter.Exhausted()) { + return false, reason, err + } if ctx.Err() != nil { err = ctx.Err() break diff --git a/server/engine.go b/server/engine.go index d5241ce50..5c30e972c 100644 --- a/server/engine.go +++ b/server/engine.go @@ -1129,7 +1129,7 @@ func (e *Engine) plannerLoop(ctx context.Context, t *Task) { if fp, err := t.Store.OpenGoalFingerprint(); err == nil { e.goalFP.Store(t.ID, fp) } - if e.budgetBlocksClaim(t.ID) { + if e.budgetBlocksPlan(t.ID) { t.Notify() // this round crossed the budget: settle on the next round, not at the next heartbeat } e.touch(t.ID) diff --git a/server/engine_budget.go b/server/engine_budget.go index fc6d45af3..dbd6dace0 100644 --- a/server/engine_budget.go +++ b/server/engine_budget.go @@ -50,9 +50,9 @@ func (e *Engine) seedBudget(taskID string, ledger *agent.BudgetLedger) { } // budgetStop is the enforcement point of a planner round: it logs the remaining -// budget and, once no worker can be dispatched any more, starts the forced -// wrap-up (exactly once: the settle sequence with the budget words) and reports -// that the normal round must not run. ctx is the planner loop's context. +// budget and, once no planner+worker cycle can be afforded any more, starts the +// forced wrap-up (exactly once: the settle sequence with the budget words) and +// reports that the normal round must not run. ctx is the planner loop's context. func (e *Engine) budgetStop(ctx context.Context, t *Task) bool { l := e.budgetFor(t.ID) if l == nil { @@ -60,26 +60,28 @@ func (e *Engine) budgetStop(ctx context.Context, t *Task) bool { } st := l.State() log.Printf("[budget] task %s planner round: %s", t.ID, st.Line()) - if st.Dispatch { + if st.Plan { return false } if l.BeginWrapup() { - log.Printf("[budget] task %s cannot afford another worker (estimate %d tokens / %d turns), forced wrap-up", - t.ID, st.Estimate.Tokens, st.Estimate.Turns) + log.Printf("[budget] task %s cannot afford another planner+worker cycle (planner estimate %d tokens / %d turns, worker estimate %d tokens / %d turns), forced wrap-up", + t.ID, st.PlannerEstimate.Tokens, st.PlannerEstimate.Turns, st.Estimate.Tokens, st.Estimate.Turns) e.settleTask(ctx, t, true) } return true } // budgetRoundCtx attaches a planner round's budget (the one-line remaining -// budget, the wrap-up flag) and meters the round's own calls into the task. +// budget, the wrap-up flag, and its per-round meter) and meters the round's +// own calls into both the round meter and the task ledger. func (e *Engine) budgetRoundCtx(ctx context.Context, t *Task, wrapup bool) context.Context { l := e.budgetFor(t.ID) if l == nil { return ctx } - ctx = agent.WithBudgetRound(ctx, agent.BudgetRound{Line: l.State().Line(), WrapUp: wrapup}) - return llmrec.WithUsageSink(ctx, l.Record) + m := l.StartPlannerRound(wrapup) + ctx = agent.WithBudgetRound(ctx, agent.BudgetRound{Line: l.State().Line(), WrapUp: wrapup, Meter: m}) + return llmrec.WithUsageSink(ctx, m.Record) } // budgetBlocksClaim reports whether a worker must not claim a new intent: the @@ -89,6 +91,21 @@ func (e *Engine) budgetBlocksClaim(taskID string) bool { return l != nil && !l.State().Dispatch } +// budgetBlocksPlan reports whether a normal planner round (or terminal revival) +// must not start: the remaining task budget cannot cover a planner+worker cycle, +// or the wrap-up has already started. +func (e *Engine) budgetBlocksPlan(taskID string) bool { + l := e.budgetFor(taskID) + return l != nil && !l.State().Plan +} + +// budgetHardExhausted reports whether lifetime task spend has exceeded the +// configured task budget plus its wrap-up reserve (circuit breaker). +func (e *Engine) budgetHardExhausted(taskID string) bool { + l := e.budgetFor(taskID) + return l != nil && l.State().HardExhausted +} + // budgetIntent opens the meter of one worker run: ctx meters its calls and // clamps its turns; the returned meter feeds the tool hook. nil = no budget. func (e *Engine) budgetIntent(ctx context.Context, taskID string) (context.Context, *agent.IntentMeter) { diff --git a/server/engine_budget_test.go b/server/engine_budget_test.go index bd986cbec..1d67ead0a 100644 --- a/server/engine_budget_test.go +++ b/server/engine_budget_test.go @@ -2,12 +2,15 @@ package server import ( "context" + "errors" "strconv" + "strings" "testing" "time" "github.com/Autumn-27/artex/agent" pgdb "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/artex/llmrec" "github.com/Autumn-27/norma/llm" ) @@ -131,3 +134,144 @@ func TestResetSettledRunReseedsBudgetFromUsage(t *testing.T) { got.Remaining.Tokens, got.Margin.Tokens, got.Dispatch) } } + +// Repro for #705: a task whose lifetime spend has already exceeded its budget +// plus wrap-up reserve must cancel any in-flight exec and skip the final +// planner round during settleTask (0 additional LLM calls). +func TestHardExhaustedBudgetSkipsFinalPlannerRound(t *testing.T) { + for _, k := range []string{"ARTEX_TASK_BUDGET_TURNS", "ARTEX_INTENT_BUDGET_TOKENS", "ARTEX_INTENT_BUDGET_TURNS"} { + t.Setenv(k, "") + } + t.Setenv("ARTEX_TASK_BUDGET_TOKENS", "250000") + e := NewEngine(nil) + plannerCalls := 0 + e.SetAuthoritativeAgentResolver(func(*Task) (*agent.Planner, *agent.Worker) { + plannerCalls++ + return nil, nil + }) + task := &Task{ID: "705"} + execCtx := e.execContextFor(context.Background(), task.ID) + l := e.budgetFor(task.ID) + // Exact scale from #705: 347,003 tokens spent against a 250,000 token cap. + l.RestoreSpend(agent.Spend{Tokens: 347_003, Turns: 12}) + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + if !e.budgetStop(ctx, task) { + t.Fatal("budgetStop did not stop a hard-exhausted task") + } + if plannerCalls != 0 { + t.Fatalf("hard-exhausted budgetStop attempted final planner round (resolver called %d times)", plannerCalls) + } + if !errors.Is(context.Cause(execCtx), agent.AbortSettleDrainTimeout) { + t.Fatalf("hard-exhausted settle did not cancel in-flight exec context: cause=%v", context.Cause(execCtx)) + } +} + +// budgetStop must account for the planner round's own estimated cost, not just +// the next worker's estimate, so it stops before starting a planner round whose +// cost would leave too little budget to dispatch any worker. +func TestBudgetStopReservesPlannerRoundCost(t *testing.T) { + t.Setenv("ARTEX_TASK_BUDGET_TOKENS", "250000") + t.Setenv("ARTEX_TASK_BUDGET_TURNS", "150") + t.Setenv("ARTEX_INTENT_BUDGET_TOKENS", "30000") + t.Setenv("ARTEX_INTENT_BUDGET_TURNS", "10") + + e := NewEngine(nil) + task := &Task{ID: "706"} + // Run one metered planner round via budgetRoundCtx + llmrec.Wrap (40k tokens). + rctx := e.budgetRoundCtx(context.Background(), task, false) + rec := llmrec.Wrap(stopReasonProvider{stop: "end_turn"}, nil, "model", "profile", "", "", func() bool { return false }) + for _, err := range rec.Stream(rctx, llm.CompletionRequest{}) { + if err != nil { + t.Fatal(err) + } + } + // Simulate a 40k-token planner round and finish its meter. + l := e.budgetFor(task.ID) + pm := l.StartPlannerRound(false) + pm.Record(llm.Usage{InputTokens: 39_959}) // +41 from stream = 40,000 total + pm.Finish() + + // Add 155k worker/other spend -> 195k spent, 55k remaining: + // Worker estimate (30k) still fits (budgetBlocksClaim == false), + // but planner (40k) + worker (30k) = 70k > 55k (budgetBlocksPlan == true). + l.Record(llm.Usage{InputTokens: 155_000}) + if e.budgetBlocksClaim(task.ID) { + t.Fatal("worker claim should still fit at 55k remaining vs 30k intent cap") + } + if !e.budgetBlocksPlan(task.ID) { + t.Fatal("budgetBlocksPlan must stop new planner round when planner+worker estimate exceeds remaining") + } + // Pre-mark wrap-up so budgetStop exercises its gate without entering settleTask. + l.BeginWrapup() + if !e.budgetStop(context.Background(), task) { + t.Fatal("budgetStop did not stop planner round") + } +} + +// Repro for #705: agent-triggered revival (set_goals / add_intent via +// reviveTaskFromAgent) must not revive timed-out, settling, or budget-exhausted +// tasks, and admitTask must refuse reviving any terminal task whose configured +// run budget is already exhausted. +func TestReviveGuardsPreventTimeoutSettlingAndBudgetLoops(t *testing.T) { + newTestServer := func(task *Task) *Server { + e := NewEngine(nil) + m := &Manager{tasks: map[string]*Task{task.ID: task}} + return &Server{m: m, engine: e, ctx: context.Background()} + } + + t.Run("agent revival refuses timed-out task even without token budget", func(t *testing.T) { + for _, k := range []string{"ARTEX_TASK_BUDGET_TOKENS", "ARTEX_TASK_BUDGET_TURNS", "ARTEX_INTENT_BUDGET_TOKENS", "ARTEX_INTENT_BUDGET_TURNS"} { + t.Setenv(k, "") + } + task := &Task{ID: "101", Status: "timeout"} + s := newTestServer(task) + if _, err := s.admitTaskWhen(task, "resume", false, true); err == nil || !strings.Contains(err.Error(), "timed out") { + t.Fatalf("agent revival of timed-out task = %v, want timed-out refusal", err) + } + s.reviveTaskFromAgent(task) + if got := task.lifecycleSnapshot().Status; got != "timeout" { + t.Fatalf("status after reviveTaskFromAgent = %q, want timeout", got) + } + }) + + t.Run("admission refuses while in-flight settlement is active", func(t *testing.T) { + for _, k := range []string{"ARTEX_TASK_BUDGET_TOKENS", "ARTEX_TASK_BUDGET_TURNS", "ARTEX_INTENT_BUDGET_TOKENS", "ARTEX_INTENT_BUDGET_TURNS"} { + t.Setenv(k, "") + } + task := &Task{ID: "102", Status: "running"} + s := newTestServer(task) + s.engine.settling.Store(task.ID, true) + if _, err := s.admitTask(task, "resume"); err == nil || !strings.Contains(err.Error(), "settling") { + t.Fatalf("admitTask during in-flight settle = %v, want settling refusal", err) + } + if _, err := s.admitTaskWhen(task, "resume", false, true); err == nil || !strings.Contains(err.Error(), "settling") { + t.Fatalf("agent revival during in-flight settle = %v, want settling refusal", err) + } + if !s.engine.isSettling(task.ID) { + t.Fatal("refused revival cleared settling barrier") + } + }) + + t.Run("terminal task with exhausted budget cannot be revived", func(t *testing.T) { + t.Setenv("ARTEX_TASK_BUDGET_TOKENS", "250000") + t.Setenv("ARTEX_TASK_BUDGET_TURNS", "") + t.Setenv("ARTEX_INTENT_BUDGET_TOKENS", "30000") + t.Setenv("ARTEX_INTENT_BUDGET_TURNS", "") + for _, status := range []string{"timeout", "done"} { + task := &Task{ID: "103", Status: status} + s := newTestServer(task) + l := s.engine.budgetFor(task.ID) + l.RestoreSpend(agent.Spend{Tokens: 250_000, Turns: 20}) + if _, err := s.admitTask(task, "resume"); err == nil || !strings.Contains(err.Error(), "budget is exhausted") { + t.Fatalf("admitTask on budget-exhausted %s task = %v, want budget exhaustion refusal", status, err) + } + if _, err := s.admitTaskWhen(task, "resume", false, true); err == nil { + t.Fatalf("agent revival on budget-exhausted %s task succeeded, want refusal", status) + } + if got := s.engine.budgetFor(task.ID); got != l { + t.Fatal("refused revival dropped or replaced the budget ledger") + } + } + }) +} diff --git a/server/engine_timeout.go b/server/engine_timeout.go index 430bac93c..2f1c573e2 100644 --- a/server/engine_timeout.go +++ b/server/engine_timeout.go @@ -233,6 +233,14 @@ func (e *Engine) settleTask(ctx context.Context, t *Task, budget bool) { log.Printf("[deadline] task %s reached the timeout limit, entering the settle sequence", t.ID) } + hardBudget := budget && e.budgetHardExhausted(t.ID) + if hardBudget { + // Lifetime spend already exceeded budget + wrap-up reserve: cancel any + // in-flight planner/worker calls immediately instead of letting them burn + // through the full drain grace window. + e.cancelExec(t.ID, agent.AbortSettleDrainTimeout) + } + // ④ wait for running workers/planners to drain (running runs enter wrap-up on their own // via the clamped MaxDuration); if not drained within the grace period, hard-cancel the // task's exec ctx (the settling-aware branches classify it correctly). @@ -250,7 +258,16 @@ func (e *Engine) settleTask(ctx context.Context, t *Task, budget bool) { } // ⑤ one final planner round (task-timeout words, final goal judgment, no new intents). - met := e.runFinalPlannerRound(ctx, t, budget) + // Circuit breaker: once lifetime spend has already exceeded the task budget plus + // its wrap-up reserve, skip the final planner round so an over-budget task never + // burns extra LLM calls while settling. + var met bool + if hardBudget || (budget && e.budgetHardExhausted(t.ID)) { + hardBudget = true + log.Printf("[budget] task %s lifetime spend exceeded hard ceiling, skipping final planner round", t.ID) + } else { + met = e.runFinalPlannerRound(ctx, t, budget) + } if !e.beginTaskOperation(t.ID) { return } @@ -269,8 +286,16 @@ func (e *Engine) settleTask(ctx context.Context, t *Task, budget bool) { endReason := "" if budget { endReason = db.EndReasonBudget - e.emitActivity(t, db.Activity{Worker: "system", Kind: "text", - Summary: "Task run budget exhausted: forced wrap-up done, task stopped (final state " + status + ")"}) + if t.Store != nil { + summary := "Task run budget exhausted: forced wrap-up done, task stopped (final state " + status + ")" + if hardBudget { + summary = "Task run budget exhausted beyond wrap-up reserve: skipped final planner round, task stopped (final state " + status + ")" + } + e.emitActivity(t, db.Activity{Worker: "system", Kind: "text", Summary: summary}) + } + } + if e.m == nil { + return } won, err := e.m.SetTaskStatusGuarded(t.ID, status, endReason) switch { diff --git a/server/goals.go b/server/goals.go index e732f6f65..04e1d02b8 100644 --- a/server/goals.go +++ b/server/goals.go @@ -115,17 +115,17 @@ func (s *Server) runningTaskCount(excludeID string) int { // work. It atomically either starts the task or appends it to the persistent FIFO // queue. mode is bootstrap for a freshly-created task and resume otherwise. func (s *Server) admitTask(t *Task, mode string) (queued bool, err error) { - return s.admitTaskWhen(t, mode, false) + return s.admitTaskWhen(t, mode, false, false) } // admitPausedTask is the task-control resume path. The paused precondition is // checked under the same scheduler lock as admission so a concurrent pause, // dequeue or FIFO promotion cannot leave database and Engine state divergent. func (s *Server) admitPausedTask(t *Task) (queued bool, err error) { - return s.admitTaskWhen(t, "resume", true) + return s.admitTaskWhen(t, "resume", true, false) } -func (s *Server) admitTaskWhen(t *Task, mode string, requirePaused bool) (queued bool, err error) { +func (s *Server) admitTaskWhen(t *Task, mode string, requirePaused, blockTimeoutRevive bool) (queued bool, err error) { if t == nil { return false, fmt.Errorf("task not found") } @@ -156,6 +156,15 @@ func (s *Server) admitTaskWhen(t *Task, mode string, requirePaused bool) (queued mode = s.resumeAdmissionMode(t) } wasTerminal := isTerminalStatus(lifecycle.Status) + if !wasTerminal && s.engine.isSettling(t.ID) { + return false, fmt.Errorf("task %s is settling and cannot be admitted", t.ID) + } + if blockTimeoutRevive && lifecycle.Status == "timeout" { + return false, fmt.Errorf("task %s is timed out and cannot be revived automatically", t.ID) + } + if wasTerminal && s.engine.budgetBlocksPlan(t.ID) { + return false, fmt.Errorf("task %s run budget is exhausted", t.ID) + } wasPaused := lifecycle.Paused || s.engine.IsPaused(t.ID) wasQueued := lifecycle.Queued engineWasPaused := s.engine.IsPaused(t.ID) @@ -383,6 +392,19 @@ func (s *Server) reviveTask(t *Task) { } } +// reviveTaskFromAgent is the automatic revival callback for agent tools +// (set_goals / add_intent via orchestration or mainagent). Unlike explicit UI +// actions, it refuses to pull a timed-out task back to running, and shares the +// in-flight settlement and run-budget exhaustion guards inside admitTaskWhen. +func (s *Server) reviveTaskFromAgent(t *Task) { + if t == nil { + return + } + if _, err := s.admitTaskWhen(t, "resume", false, true); err != nil { + log.Printf("[revive] task %s skipped automatic agent revival: %v", t.ID, err) + } +} + // createGoals materializes the goal node(s) under the task root (rel objective) // through the LLM Goal Decomposer's structured set_goals tool call. It returns an // explicit error if the task has no goal or if the decomposer fails to submit at diff --git a/server/orchestration.go b/server/orchestration.go index 72e22968e..0597d6ee7 100644 --- a/server/orchestration.go +++ b/server/orchestration.go @@ -169,10 +169,10 @@ func (s *Server) delegateToTask(ctx context.Context, in json.RawMessage, pick fu if s.m.Assets() != nil { tsx.SetAssetStore(s.m.Assets(), s.m.Assets().Companies()) } - tsx.SetNotify(t.Notify) // generic wake-up (write ops without a dedicated callback go through it; no-op for read tools) - tsx.SetResumeTask(func() { s.reviveTask(t) }) // set_goals → pulls a completed/paused task back to running - tsx.SetNotifyGoal(t.NotifyGoal) // set_goals → records a goal-added trigger and wakes the planner - tsx.SetNotifyHint(t.NotifyHint) // add_hint → records an "orchestrator added N strategic hints: ..." entry and wakes the planner + tsx.SetNotify(t.Notify) // generic wake-up (write ops without a dedicated callback go through it; no-op for read tools) + tsx.SetResumeTask(func() { s.reviveTaskFromAgent(t) }) // set_goals → pulls a completed/paused task back to running (never timed-out/settling/budget-exhausted) + tsx.SetNotifyGoal(t.NotifyGoal) // set_goals → records a goal-added trigger and wakes the planner + tsx.SetNotifyHint(t.NotifyHint) // add_hint → records an "orchestrator added N strategic hints: ..." entry and wakes the planner return pick(tsx).Call(ctx, inner, nil) } diff --git a/server/server.go b/server/server.go index 17e04bde0..3d25c2215 100644 --- a/server/server.go +++ b/server/server.go @@ -4582,7 +4582,7 @@ func (s *Server) startTaskChat(t *Task, turn taskChatTurn) (mode, reply string, s.engine.emitActivity(t, rec) } maTaskID, _ := strconv.ParseInt(t.ID, 10, 64) - resume := func() { s.reviveTask(t) } // set_goals added a goal → pulls the task back to running + resume := func() { s.reviveTaskFromAgent(t) } // set_goals added a goal → pulls a completed/paused task back to running (never timed-out/settling/budget-exhausted) // Splice the list of [absolute paths] of uploaded attachments into the message sent to the agent; it uses them to open files via Read/Bash. // mainDir = the main agent's run directory (its CWD, tasks//main), the same call as chatUpload's target dir and the agent itself. mainDir := agent.EnsureRunDir(s.m.dir, maTaskID, 0)