mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-06 12:24:44 +00:00
Mechanical modernization of the agent package with the gopls/go fix modernizers: range over int, strings.SplitSeq / FieldsSeq, strings.Cut / CutPrefix, slices.Contains / Sort / Backward, maps.Copy, min / max, sync.WaitGroup.Go and t.Context in tests. No behaviour change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
335 lines
14 KiB
Go
335 lines
14 KiB
Go
package agent
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"iter"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/Autumn-27/norma/llm"
|
|
)
|
|
|
|
// spend records n tokens as one task-level call; finishWorker records one
|
|
// finished worker run of n tokens (it feeds the per-worker estimate).
|
|
func spend(l *BudgetLedger, n int) { l.Record(llm.Usage{InputTokens: n}) }
|
|
|
|
func finishWorker(l *BudgetLedger, n int) {
|
|
m := l.StartIntent()
|
|
m.Record(llm.Usage{OutputTokens: n})
|
|
m.Finish()
|
|
}
|
|
|
|
func TestEffectiveBudgetNeverExceedsParent(t *testing.T) {
|
|
for _, c := range []struct{ own, parent, want Budget }{
|
|
{NewBudget(50, 5), NewBudget(100, 10), Budget{50, 5}},
|
|
{NewBudget(200, 20), NewBudget(100, 10), Budget{100, 10}},
|
|
{NewBudget(0, 0), NewBudget(100, 10), Budget{100, 10}}, // own unlimited
|
|
{NewBudget(70, 7), NewBudget(0, 0), Budget{70, 7}}, // parent unlimited
|
|
{NewBudget(0, 0), NewBudget(0, 0), Budget{Unlimited, Unlimited}},
|
|
{NewBudget(70, 7), Budget{0, 0}, Budget{0, 0}}, // parent exhausted
|
|
} {
|
|
if got := EffectiveBudget(c.own, c.parent); got != c.want || got.Tokens > c.parent.Tokens || got.Turns > c.parent.Turns {
|
|
t.Fatalf("EffectiveBudget(%+v, %+v) = %+v, want %+v", c.own, c.parent, got, c.want)
|
|
}
|
|
}
|
|
// Through the meter: intent 100k is cut to the task's remaining above the
|
|
// reserve (task 100k, reserve 20k, 70k spent → 10k); intent turns clamp MaxTurns.
|
|
l := NewBudgetLedger(NewBudget(100_000, 0), NewBudget(100_000, 5))
|
|
spend(l, 70_000)
|
|
m := l.StartIntent()
|
|
if got := m.Remaining(); got != (Budget{10_000, 5}) {
|
|
t.Fatalf("intent remaining = %+v, want {10000 5}", got)
|
|
}
|
|
if got := (&Worker{maxTurns: 40}).turnCap(WithIntentMeter(context.Background(), m)); got != 5 {
|
|
t.Fatalf("worker MaxTurns = %d, want the intent's 5", got)
|
|
}
|
|
if m.Record(llm.Usage{InputTokens: 10_000}); !m.Exhausted() {
|
|
t.Fatal("intent not exhausted once the task's remaining above the reserve is spent")
|
|
}
|
|
}
|
|
|
|
func TestWrapupMarginTriggersOnceAndStopsDispatch(t *testing.T) {
|
|
if a, b := WrapupMargin(NewBudget(1_000_000, 100)), WrapupMargin(NewBudget(100_000, 10)); a != (Budget{50_000, 5}) || b != (Budget{20_000, 2}) {
|
|
t.Fatalf("margins %+v %+v, want 5%% then the floors", a, b)
|
|
}
|
|
l := NewBudgetLedger(NewBudget(100_000, 0), NewBudget(0, 0))
|
|
finishWorker(l, 10) // tiny estimate: only the reserve can stop dispatch here
|
|
spend(l, 100_000-10-20_001)
|
|
if st := l.State(); st.AtMargin || !st.Dispatch {
|
|
t.Fatalf("one token above the reserve: %+v, want dispatch", st)
|
|
}
|
|
spend(l, 1) // remaining == reserve
|
|
st := l.State()
|
|
if !st.AtMargin || st.Dispatch {
|
|
t.Fatalf("at the reserve: %+v, want AtMargin and no dispatch", st)
|
|
}
|
|
running, wrapups := l.StartIntent(), 0
|
|
for range 3 { // several planner wake-ups at the reserve
|
|
if l.BeginWrapup() {
|
|
wrapups++
|
|
}
|
|
}
|
|
if wrapups != 1 || l.State().Dispatch {
|
|
t.Fatalf("wrap-up started %d times (want 1), dispatch=%v", wrapups, l.State().Dispatch)
|
|
}
|
|
if !running.Exhausted() || !BudgetWrapupBlocks("Bash") || BudgetWrapupBlocks("record_fact") {
|
|
t.Fatal("after the wrap-up a running worker must be held to its write-back tools")
|
|
}
|
|
block := plannerBudgetBlock(WithBudgetRound(context.Background(), BudgetRound{Line: st.Line(), WrapUp: true}))
|
|
if strings.Count(block, plannerBudgetWrapup) != 1 || !strings.Contains(block, "[Task budget] remaining: tokens 20000 of 100000") {
|
|
t.Fatalf("wrap-up block:\n%s", block)
|
|
}
|
|
}
|
|
|
|
func TestDispatchStopsUnderOneWorkerEstimate(t *testing.T) {
|
|
// No worker finished yet: the default estimate applies.
|
|
l := NewBudgetLedger(NewBudget(200_000, 0), NewBudget(0, 0))
|
|
spend(l, 200_000-DefaultWorkerEstimateTokens)
|
|
if st := l.State(); !st.Dispatch {
|
|
t.Fatalf("remaining == default estimate: %+v, want dispatch", st)
|
|
}
|
|
if spend(l, 1); l.State().Dispatch || l.State().AtMargin {
|
|
t.Fatalf("below the default estimate, above the reserve: %+v, want no dispatch", l.State())
|
|
}
|
|
// Finished workers: their average spend is the estimate (90k, 30k → 60k).
|
|
l = NewBudgetLedger(NewBudget(300_000, 0), NewBudget(0, 0))
|
|
finishWorker(l, 90_000)
|
|
finishWorker(l, 30_000)
|
|
spend(l, 120_000) // remaining 60k
|
|
if st := l.State(); st.Estimate.Tokens != 60_000 || !st.Dispatch {
|
|
t.Fatalf("average estimate: %+v, want 60000 and dispatch", st)
|
|
}
|
|
if spend(l, 1); l.State().Dispatch || l.State().AtMargin {
|
|
t.Fatalf("below the 60000 estimate, above the reserve: %+v, want no dispatch", l.State())
|
|
}
|
|
}
|
|
|
|
func TestBudgetUnsetIsPassthrough(t *testing.T) {
|
|
for _, v := range []string{"", "0", "abc"} {
|
|
for _, k := range []string{"ARTEX_TASK_BUDGET_TOKENS", "ARTEX_TASK_BUDGET_TURNS", "ARTEX_INTENT_BUDGET_TOKENS", "ARTEX_INTENT_BUDGET_TURNS"} {
|
|
t.Setenv(k, v)
|
|
}
|
|
if NewBudgetLedger(BudgetsFromEnv()) != nil {
|
|
t.Fatalf("env %q: got a ledger, want nil (no budget)", v)
|
|
}
|
|
}
|
|
// Without a budget on ctx the planner input and the worker turns are unchanged.
|
|
ctx := context.Background()
|
|
situational := plannerSituational(nil, triggerLookup{}, nil, newDataEnvelope())
|
|
if plannerRoundInput("l", situational, "", "g", "") != plannerRoundInput("l", situational+plannerBudgetBlock(ctx), "", "g", "") {
|
|
t.Fatal("planner input changed without a budget")
|
|
}
|
|
if got := (&Worker{maxTurns: 40}).turnCap(ctx); got != 40 {
|
|
t.Fatalf("worker turns without budget = %d, want 40", got)
|
|
}
|
|
}
|
|
|
|
func TestBudgetCountsMatchUsageFixture(t *testing.T) {
|
|
// One entry per llm_usage row; InputTokens already includes the cache buckets.
|
|
planner := []llm.Usage{
|
|
{InputTokens: 12_000, OutputTokens: 800, CacheReadTokens: 9_000},
|
|
{InputTokens: 15_500, OutputTokens: 1_200, CacheReadTokens: 12_000, CacheWriteTokens: 3_000},
|
|
}
|
|
worker := []llm.Usage{{InputTokens: 4_000, OutputTokens: 300}, {InputTokens: 6_100, CacheWriteTokens: 6_000}, {}} // {} = an errored call's row
|
|
l := NewBudgetLedger(NewBudget(1_000_000, 1_000), NewBudget(0, 0))
|
|
for _, u := range planner {
|
|
l.Record(u)
|
|
}
|
|
m := l.StartIntent()
|
|
for _, u := range worker {
|
|
m.Record(u)
|
|
}
|
|
m.Finish()
|
|
const want = 12_000 + 800 + 15_500 + 1_200 + 4_000 + 300 + 6_100
|
|
if st := l.State(); st.Spent != (Spend{want, 5}) || st.Remaining != (Budget{1_000_000 - want, 995}) || st.Estimate != (Spend{10_400, 3}) {
|
|
t.Fatalf("spent %+v remaining %+v estimate %+v, want {%d 5}, remaining, {10400 3}", st.Spent, st.Remaining, st.Estimate, want)
|
|
}
|
|
}
|
|
|
|
func TestRestoreSpendCountsTowardCap(t *testing.T) {
|
|
l := NewBudgetLedger(NewBudget(100, 10), NewBudget(0, 0))
|
|
l.RestoreSpend(Spend{Tokens: 40, Turns: 4})
|
|
st := l.State()
|
|
if st.Spent != (Spend{40, 4}) || st.Remaining != (Budget{60, 6}) {
|
|
t.Fatalf("spent=%+v remaining=%+v", st.Spent, st.Remaining)
|
|
}
|
|
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)
|
|
}
|
|
}
|