Files
archie/internal/domain/workflow/agent_budget_continue_test.go

161 lines
6.3 KiB
Go

package workflow
import (
"context"
"fmt"
"log/slog"
"strings"
"sync"
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/agentrun"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// sequenceRunner answers each agent run with the next result queued for its
// mission, after the conversation entries it reports, and keeps the requests
// it was given. Parallel branches run concurrently, so the queue is by mission.
type sequenceRunner struct {
mu sync.Mutex
results map[string][]agentrun.Result
requests []agentrun.Request
}
func (s *sequenceRunner) Run(_ context.Context, _ string, req agentrun.Request, report agentrun.Reporter) (agentrun.Result, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.requests = append(s.requests, req)
var key string
for mission := range s.results {
if strings.Contains(req.Mission, mission) {
key = mission
}
}
report.ReportTranscript(agentrun.TranscriptEntry{Kind: agentrun.TranscriptUser, Text: "the mission"})
report.ReportTranscript(agentrun.TranscriptEntry{Kind: agentrun.TranscriptTool, Tool: "read", Output: fmt.Sprintf("%s run %d output", key, len(s.requests))})
res := s.results[key][0]
res.Stage = req.Stage
s.results[key] = s.results[key][1:]
return res, nil
}
// A stage that opts in asks for approval when it reaches its step budget and
// keeps its worktree for the continuation; approval runs it again from there
// to completion. Any other stop parks as before.
func TestBudgetStopAsksToContinue(t *testing.T) {
stopped := func(reason string) agentrun.Result {
return agentrun.Result{
Version: agentrun.ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "build",
Status: "parked", StopReason: reason, Detail: "stopped after 60/60 steps",
Summary: "halfway through the migration", Changes: []string{"internal/auth/token.go"},
}
}
passed := agentrun.Result{Version: agentrun.ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "build", Status: agentrun.StatusPassed}
tests := []struct {
name string
approve bool
parallel bool
reason string
wantStatus string
wantKeep bool
}{
{name: "step budget asks", approve: true, reason: "budget_exhausted", wantStatus: StatusWaitingApproval, wantKeep: true},
{name: "step budget in a parallel branch asks", approve: true, parallel: true, reason: "budget_exhausted", wantStatus: StatusWaitingApproval, wantKeep: true},
{name: "not opted in parks", reason: "budget_exhausted", wantStatus: StatusParked},
{name: "wall clock parks", approve: true, reason: "timed_out", wantStatus: StatusParked},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
runner := &sequenceRunner{results: map[string][]agentrun.Result{"do it": {stopped(tt.reason), passed}}}
if tt.parallel {
runner.results = map[string][]agentrun.Result{"left": {passed}, "right": {stopped(tt.reason), passed}}
}
tk := &task.Task{ID: 1, Attempt: 1}
newContext := func() *TaskContext {
return &TaskContext{
Dir: "/work", Task: tk, Store: &lockedStepStore{}, Log: slog.Default(), Agent: runner,
Cfg: config.Config{Models: map[string]string{"default": "test/model"}},
}
}
setups := 0
wf := Workflow{Name: "implement", Stages: []Stage{
{Name: "setup", Run: func(context.Context, *TaskContext) error { setups++; return nil }},
AgentStage{Name: "build", ApproveBudget: tt.approve, Mission: func(*TaskContext) string { return "do it" }}.Stage(),
}}
if tt.parallel {
registry := StepRegistry{AgentRunStepName: newAgentRunStage}
definition, err := ParseDefinition("id: fan\nrepository: none\nsteps:\n - parallel:\n a: [{type: agent.run, settings: {mission: left, read_only: true}}]\n b: [{type: agent.run, settings: {mission: right, read_only: true}}]\n", registry)
if err != nil {
t.Fatal(err)
}
compiled, err := Compile(definition, registry)
if err != nil {
t.Fatal(err)
}
wf.Stages = append(wf.Stages[:1], compiled.Stages...)
}
tc := newContext()
Run(context.Background(), wf, tc)
if tc.Outcome.Status != tt.wantStatus {
t.Fatalf("outcome = %q, want %q", tc.Outcome.Status, tt.wantStatus)
}
if keeps := tk.RetryMode == string(taskstate.RetryKeepWorktree); keeps != tt.wantKeep {
t.Fatalf("keeps worktree = %v, want %v", keeps, tt.wantKeep)
}
if !tt.wantKeep {
return
}
wantFrom, stoppedMission, wantRuns := "build", "do it", 2
if tt.parallel {
wantFrom, stoppedMission, wantRuns = "parallel", "right", 3
}
if tk.ResumeFrom != wantFrom {
t.Errorf("resume point = %q, want %q", tk.ResumeFrom, wantFrom)
}
if kind := taskstate.ApprovalKind(StatusWaitingApproval, "", tk.RetryMode); kind != taskstate.ApprovalBudget {
t.Errorf("approval kind = %q, want %q", kind, taskstate.ApprovalBudget)
}
for _, want := range []string{"halfway through the migration", "internal/auth/token.go"} {
if !strings.Contains(tk.Notes, want) {
t.Errorf("notes %q lack %q for the continuation", tk.Notes, want)
}
}
tc = newContext()
Run(context.Background(), wf, tc)
if tc.Outcome.Status != StatusCompleted {
t.Errorf("continued outcome = %q, want %q", tc.Outcome.Status, StatusCompleted)
}
if setups != 1 {
t.Errorf("setup ran %d times, want once: the continuation skips completed steps", setups)
}
if tk.ResumeFrom != "" || len(tk.ResumeHistory) != 0 {
t.Errorf("resume point %q and history survive the continuation", tk.ResumeFrom)
}
if len(runner.requests) != wantRuns {
t.Fatalf("agent ran %d times, want %d: a continuation does not run finished branches again", len(runner.requests), wantRuns)
}
var stoppedRuns []agentrun.Request
for _, req := range runner.requests {
if strings.Contains(req.Mission, stoppedMission) {
stoppedRuns = append(stoppedRuns, req)
}
}
if len(stoppedRuns) != 2 {
t.Fatalf("stopped step ran %d times, want 2", len(stoppedRuns))
}
if first := stoppedRuns[0].History; len(first) != 0 {
t.Errorf("first run got history %v", first)
}
history := stoppedRuns[1].History
if len(history) != 1 || !strings.HasPrefix(history[0].Output, stoppedMission+" run ") {
t.Errorf("continued run history = %+v, want the stopped run's tool output without its mission", history)
}
})
}
}