Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
262 changes: 246 additions & 16 deletions agent/budget.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ package agent

import (
"context"
"errors"
"fmt"
"math"
"os"
"strconv"
"strings"
"sync"

"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
)

Expand All @@ -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 }

Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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()
Expand All @@ -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
Expand Down Expand Up @@ -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{}
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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 {
Expand Down
Loading
Loading