package headless import ( "os" "os/exec" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/thintest" "amadan.net/oficina/equipo/internal/wire" ) // taskOf waits for the task a turn recorded (its task card) and returns // its id. func (s *session) taskOf(t *testing.T, turn string) string { t.Helper() var id string s.wait(t, "task card", 3*time.Minute, func(c *thintest.Conversation) bool { for _, k := range cards(c, turn, wire.CardTask) { if _, ok := c.Tasks[k.TaskID]; ok { id = k.TaskID return true } } return wire.Terminal(c.Turns[turn].State) && c.Turns[turn].State != wire.TurnReplied }) if id == "" { t.Fatalf("turn %s recorded no task", turn) } return id } // step waits for the task's step to reach one of states and returns it. func (s *session) step(t *testing.T, task string, timeout time.Duration, states ...string) wire.Step { t.Helper() var out wire.Step s.wait(t, "step "+strings.Join(states, "|"), timeout, func(c *thintest.Conversation) bool { // The newest Engineering step (checks and review follow it). var last *wire.Step for i := range c.Tasks[task].Steps { if s := c.Tasks[task].Steps[i]; s.Specialist == wire.SpecialistEngineering { last = &c.Tasks[task].Steps[i] } } if last == nil { return false } out = c.Steps[last.ID] if out.ID == "" || out.Revision < last.Revision { out = *last } return slices.Contains(states, out.State) }) return out } // forgeHead reads a branch tip in the local forge. func forgeHead(t *testing.T, bare, branch string) string { out, err := exec.Command("git", "--git-dir="+bare, "rev-parse", "--verify", "-q", "refs/heads/"+branch).Output() if err != nil { return "" } return strings.TrimSpace(string(out)) } func forgeShow(t *testing.T, bare string, args ...string) string { t.Helper() out, err := exec.Command("git", append([]string{"--git-dir=" + bare, "show"}, args...)...).Output() if err != nil { t.Fatalf("git show %v: %v", args, err) } return string(out) } // pushedTask is the task a live 3_engineering pushed in this run, for the // scenarios that judge and ask about it without a new message. var pushedTask string // Scenario 2, to the branch: the person reports a bug; the task is noted // at once, investigated with a finding, and Engineering's step commits in // a task tree, records the candidate SHA and pushes the task's own branch // through forge. Nothing merges. func scenarioEngineering(t *testing.T, env *Env) { s := open(t, env) s.keep() s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) // Review is held (reviewsleep) so the branch and main are read before // Equipo merges the task (slice 4c). text := "think Fix the README typo in sample.\ntool:record_task:oficina/sample|Fix the README typo|The README says teh panes.\ntool:read_file:oficina/sample|README.md\ntool:add_finding:$task|The README has teh for the.|oficina/sample|README.md|5|Found it: a typo in the README.\ntool:start_task:$task|Fix the typo. reviewsleep:20000 edit:README.md|teh panes|the panes" if env.Live { text = env.Witness } sent := s.send(t, text) start := time.Now() id := s.taskOf(t, sent.Turn.ID) noted := time.Since(start) step := s.step(t, id, 25*time.Minute, wire.StepDone, wire.StepFailed, wire.StepCancelled) // The task's own event (with its link) may follow the step's. if step.Pushed { s.wait(t, "the task's link", 30*time.Second, func(c *thintest.Conversation) bool { return c.Tasks[id].URL != "" }) } var task wire.Task var stages []string s.conv.Locked(func(c *thintest.Conversation) { task, stages = c.Tasks[id], c.Stages[id] }) t.Logf("task %s noted after %s; stages %v; step %s %s %s pushed=%v after %s; branch %s", id, noted.Round(time.Millisecond), stages, step.State, step.Reason, step.CandidateSHA, step.Pushed, time.Since(start).Round(time.Second), task.Branch) Witness[t.Name()] = map[string]any{"task": id, "stages": stages, "branch": task.Branch, "candidate_sha": step.CandidateSHA, "base_sha": step.BaseSHA, "pushed": step.Pushed, "state": step.State, "reason": step.Reason, "noted_ms": noted.Milliseconds(), "pushed_s": time.Since(start).Seconds(), "url": task.URL, "summary": step.Summary, "findings": task.Findings} if step.State != wire.StepDone || !step.Pushed || !step.Terminated || len(step.CandidateSHA) != 40 { t.Fatalf("step %+v", step) } // The client records the stages its events show. A live model can // investigate before the first event arrives, so live runs may first // see investigated; work must never be the first thing seen. first := []string{wire.StageNoted} if env.Live { first = append(first, wire.StageInvestigated) } if !slices.Contains(first, stages[0]) || !slices.Contains(stages, wire.StageInProgress) { t.Fatalf("stages %v", stages) } if !wire.ValidTaskBranch(task.Branch) || !strings.HasPrefix(task.Branch, "equipo/"+id) || task.URL == "" || len(task.Findings) == 0 { t.Fatalf("task %+v", task) } noRepoQuestion(t, s, sent.Turn.ID) if env.Live { pushedTask = id return } if !slices.Contains(stages, wire.StageInvestigated) || task.Findings[0].Path != "README.md" || task.Findings[0].Line != 5 { t.Fatalf("finding %+v stages %v", task.Findings, stages) } bare := env.ForgePath("amadan.net/oficina/sample") if got := forgeHead(t, bare, task.Branch); got != step.CandidateSHA { t.Fatalf("forge branch at %q, want %s", got, step.CandidateSHA) } if forgeHead(t, bare, "main") != step.BaseSHA { t.Fatal("main moved") } if parent := strings.TrimSpace(forgeShow(t, bare, "--no-patch", "--format=%P", step.CandidateSHA)); parent != step.BaseSHA { t.Fatalf("parent %s, base %s", parent, step.BaseSHA) } if readme := forgeShow(t, bare, step.CandidateSHA+":README.md"); !strings.Contains(readme, "the panes") || strings.Contains(readme, "teh panes") { t.Fatalf("README at the candidate: %s", readme) } log, err := env.Client.StepLog(s.ctx, step.ID) if err != nil || !strings.Contains(log.Tail, "Edit README.md") || !strings.Contains(log.Tail, "Changed: README.md") { t.Fatalf("log %+v %v", log, err) } // The headlines: the coordinator's on the finding, Engineering's // split off its reply (and out of the summary). if !env.Live && (task.Findings[0].Headline != "Found it: a typo in the README." || step.Headline != "Made the change the task asks for." || strings.Contains(step.Summary, "Headline:")) { t.Fatalf("headlines: finding %q, step %q, summary %q", task.Findings[0].Headline, step.Headline, step.Summary) } if !strings.Contains(step.Summary, "Replaced") { t.Fatalf("summary %q", step.Summary) } } // Scenario 4: the runner is killed mid-step. Retry is refused while the // attempt's end is unknown; the restarted runner proves it (its // namespaces died with it, verified at start) and reports the step // failed with termination; Equipo then retries it on its own (needs-you // triage), and attempt 2 runs to a pushed branch. func scenarioStepCrash(t *testing.T, env *Env) { s := open(t, env) s.keep() s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Slowly. stepsleep:4000 edit:README.md|teh panes|the panes" if env.Live { if env.CrashWitness == "" { t.Fatal("EQUIPO_STAGING_CRASH_WITNESS is not set") } text = env.CrashWitness } sent := s.send(t, text) id := s.taskOf(t, sent.Turn.ID) // Live, the step may queue behind the earlier tasks' checks and review. running := s.step(t, id, 10*time.Minute, wire.StepRunning) if !env.Live { // What Engineering started shows while it runs: the fake reads the // file it will edit before it sleeps. s.wait(t, "step activity while running", time.Minute, func(c *thintest.Conversation) bool { for _, a := range c.StepActivity[running.ID] { if n := len(a.Activity); n > 0 && a.Activity[n-1].Kind == wire.ActivityRead && a.Activity[n-1].Subject == "README.md" { return c.Steps[running.ID].State == wire.StepRunning } } return false }) } // Let the step's process start before the kill. time.Sleep(1500 * time.Millisecond) env.KillRunner(t) if _, err := env.Client.RetryTask(s.ctx, id); thintest.Status(err) != 409 { t.Fatalf("retry while the runner is down: %v", err) } env.StartRunner(t) // The restarted runner proves the attempt ended (runner_restarted): a // passing stop, so Equipo retries it once on its own (needs-you // triage), with a receipt, and nothing waits on the person. s.wait(t, "attempt 2", 2*time.Minute, func(c *thintest.Conversation) bool { return c.Steps[running.ID].Attempt == 2 }) h, err := env.Client.Housekeeping(s.ctx) if err != nil { t.Fatal(err) } retried := 0 for _, a := range h.Actions { if a.Detector == "triage_retry" && a.Subject.ID == id && a.State == wire.ActionDone { retried++ } } if retried != 1 { t.Fatalf("automatic retries %+v", h.Actions) } done := s.step(t, id, 25*time.Minute, wire.StepDone, wire.StepFailed) if done.State != wire.StepDone || done.Attempt != 2 || !done.Pushed { t.Fatalf("attempt 2: %+v", done) } if !env.Live { // The step keeps its last lines: attempt 2's read and edit. k, err := env.Client.Task(s.ctx, id) if err != nil { t.Fatal(err) } lines := k.Steps[0].Activity if len(lines) != 2 || lines[0].Kind != wire.ActivityRead || lines[1].Kind != wire.ActivityEdit || lines[1].Subject != "README.md" { t.Fatalf("kept activity %+v", lines) } if got := forgeHead(t, env.ForgePath("amadan.net/oficina/sample"), wire.TaskBranch(id, "Fix the README typo")); got != done.CandidateSHA { t.Fatalf("branch at %q, want %s", got, done.CandidateSHA) } } } // Cancel during a step: the task ends only when the runner reports the // attempt's termination; nothing is pushed. Live, the person asks for a // real change (EQUIPO_STAGING_CANCEL_WITNESS) and cancels it a second // after the real Engineering step starts, long before it could push. func scenarioStepCancel(t *testing.T, env *Env) { s := open(t, env) s.keep() text, running, ended := "tool:record_task:oficina/sample|Slow change|x\ntool:start_task:$task|stepsleep:20000 edit:README.md|teh|the", time.Minute, time.Minute if env.Live { if env.CancelWitness == "" { t.Fatal("EQUIPO_STAGING_CANCEL_WITNESS is not set") } // The live step may queue behind the earlier task's checks and // review, and ends only when the runner has stopped a real // process tree. text, running, ended = env.CancelWitness, 10*time.Minute, 3*time.Minute } sent := s.send(t, text) id := s.taskOf(t, sent.Turn.ID) s.step(t, id, running, wire.StepRunning) time.Sleep(time.Second) acc, err := env.Client.CancelTask(s.ctx, id) if err != nil || acc.Attempt != 1 { t.Fatalf("cancel: %+v %v", acc, err) } st := s.step(t, id, ended, wire.StepCancelled, wire.StepFailed, wire.StepDone) if st.State != wire.StepCancelled || !st.Terminated || st.Pushed { t.Fatalf("cancelled step %+v", st) } s.wait(t, "task cancelled", 30*time.Second, func(c *thintest.Conversation) bool { return c.Tasks[id].Stage == wire.StageCancelled }) if env.Live { return } if forgeHead(t, env.ForgePath("amadan.net/oficina/sample"), wire.TaskBranch(id, "Slow change")) != "" { t.Fatal("a cancelled step pushed") } } // A step that asks to write outside /workspace is denied by the // permission callback, and the tree commits only what it changed inside. func scenarioStepContained(t *testing.T, env *Env) { if env.Live { t.Skip("local only: the fake CLI asks to write outside /workspace; a live model is never steered to") } s := open(t, env) s.keep() sent := s.send(t, "tool:record_task:oficina/sample|Contained|x\ntool:start_task:$task|escape:/etc/hostname escape:/home/runner/.claude/x edit:README.md|teh|the") id := s.taskOf(t, sent.Turn.ID) st := s.step(t, id, 2*time.Minute, wire.StepDone, wire.StepFailed) if st.State != wire.StepDone || !strings.Contains(st.Summary, "Write to /etc/hostname was denied.") || !strings.Contains(st.Summary, "Write to /home/runner/.claude/x was denied.") { t.Fatalf("step %+v", st) } if _, err := os.Stat("/etc/hostname.equipo"); err == nil { t.Fatal("wrote outside") } } // A step whose only requests the permission callback denied commits // nothing and stops tools_refused, not no_changes: the person reads that // Equipo refused the commands it needed, not that nothing needed changing. func scenarioStepRefused(t *testing.T, env *Env) { if env.Live { t.Skip("local only: the fake CLI asks to write outside /workspace; a live model is never steered to") } s := open(t, env) s.keep() sent := s.send(t, "tool:record_task:oficina/sample|Refused|x\ntool:start_task:$task|escape:/etc/hostname") id := s.taskOf(t, sent.Turn.ID) st := s.step(t, id, 2*time.Minute, wire.StepDone, wire.StepFailed) if st.State != wire.StepFailed || st.Reason != "tools_refused" || st.Pushed { t.Fatalf("step %+v", st) } } // A grant shows up at once when the person acts on the grant card: the // card names the namespace, the runner checks its reach, indexes only // the new repository, and the card resolves itself. func scenarioGrant(t *testing.T, env *Env) { if env.Live { t.Skip("no live grant on staging") } s := open(t, env) s.keep() // The person names the repository: in a namespace Equipo knows // nothing of, that is what raises the card (#48, review R1). sent := s.send(t, "Fix the index in recipes/book. tool:find:recipes/book") var card wire.Card s.wait(t, "access card", time.Minute, func(c *thintest.Conversation) bool { if k := cards(c, sent.Turn.ID, wire.CardAccess); len(k) == 1 { card = k[0] } return card.ID != "" }) if card.Name != "recipes/book" || card.Choice != "equipo-test" { t.Fatalf("card %+v", card) } s.waitTurn(t, sent.Turn.ID, wire.TurnReplied) if reply := s.reply(t, sent.Turn.ID).Text; strings.Contains(reply, "amadan agent grant") { t.Fatalf("the reply repeats the card: %s", reply) } env.GrantNow(t, "amadan.net/recipes/book") start := time.Now() if _, err := env.Client.Answer(s.ctx, card.ID, wire.ChoiceCheck, card.Revision); err != nil { t.Fatal(err) } s.wait(t, "card resolved", 45*time.Second, func(c *thintest.Conversation) bool { return c.Cards[card.ID].State == wire.CardResolved }) t.Logf("grant seen %s after the check", time.Since(start).Round(time.Millisecond)) list, err := env.Client.Projects(s.ctx) if err != nil || !slices.Contains(list.Allowed, "amadan.net/recipes/book") { t.Fatalf("allowlist %+v %v", list.Allowed, err) } } // A repository the agent reaches but nobody has pushed to yet, through // the coordinator's own tools on the real runner: status offers it, // add_project adds it, find names it and the read tools say it has no // commits yet. Nothing calls it unreachable or puts up an access card. func scenarioEmptyRepo(t *testing.T, env *Env) { if env.Live || env.GrantEmpty == nil { t.Skip("local forge only") } const repo = "amadan.net/paulca/threatmin" env.GrantEmpty(t, repo) s := open(t, env) s.keep() s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) deadline := time.Now().Add(45 * time.Second) for found, empty := env.Indexed(t, repo); !found || !empty; found, empty = env.Indexed(t, repo) { if time.Now().After(deadline) { t.Fatalf("not catalogued as empty: found %v", found) } time.Sleep(200 * time.Millisecond) } sent := s.send(t, "Look at threatmin. tool:status\ntool:add_project:paulca/threatmin\ntool:find:threatmin\ntool:read_file:paulca/threatmin|README.md\ntool:search_code:paulca/threatmin|main") s.waitTurn(t, sent.Turn.ID, wire.TurnReplied) r := s.reply(t, sent.Turn.ID).Text if !strings.Contains(r, `"paulca/threatmin"`) || !strings.Contains(r, "[add_project: Added paulca/threatmin.") || strings.Count(r, "no commits yet") < 3 { t.Fatalf("reply %s", r) } for _, bad := range []string{"Could not read that", "not one Equipo's agent can reach", "amadan agent grant"} { if strings.Contains(r, bad) { t.Fatalf("reply says %q: %s", bad, r) } } if _, ok := s.project("paulca/threatmin"); !ok { t.Fatal("no project") } s.conv.Locked(func(c *thintest.Conversation) { if k := cards(c, sent.Turn.ID, wire.CardAccess); len(k) != 0 { t.Fatalf("access card %+v", k) } }) } // Engineering in a repository with no commits (Paul's barber mockups in // an empty paulca repository): the step starts from an empty tree, its // commit is the repository's initial commit, and the push creates the // task branch only; the default branch stays unborn until a merge. // Review reads that commit and approves it. With no trusted base, checks // are unavailable and the task waits for the person. Reads of the // repository still say it has no commits yet. func scenarioEmptyEngineering(t *testing.T, env *Env) { if env.Live || env.GrantEmpty == nil { t.Skip("local forge only") } const repo = "amadan.net/paulca/barber" env.GrantEmpty(t, repo) s := open(t, env) s.keep() s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) deadline := time.Now().Add(45 * time.Second) for found, empty := env.Indexed(t, repo); !found || !empty; found, empty = env.Indexed(t, repo) { if time.Now().After(deadline) { t.Fatalf("not catalogued as empty: found %v", found) } time.Sleep(200 * time.Millisecond) } sent := s.send(t, "tool:record_task:paulca/barber|Create two clickable barber app mockups|Two screens that link to each other.\ntool:start_task:$task|Make them. create:index.html|Book a cut; create:book.html|Back") id := s.taskOf(t, sent.Turn.ID) k := s.settled(t, id, 10*time.Minute) checks, review := oneSHA(t, k) var eng wire.Step for _, st := range k.Steps { if st.Specialist == wire.SpecialistEngineering && st.Pushed { eng = st } } t.Logf("task %s: %s needs_you=%q checks %s verdict %s on %s", id, k.Stage, k.NeedsYou, k.Checks, k.Verdict, k.CandidateSHA) if eng.State != wire.StepDone || eng.BaseSHA != "" || len(eng.CandidateSHA) != 40 || eng.CandidateSHA != k.CandidateSHA { t.Fatalf("engineering %+v", eng) } bare := env.ForgePath(repo) if got := forgeHead(t, bare, k.Branch); got != eng.CandidateSHA { t.Fatalf("forge branch at %q, want %s", got, eng.CandidateSHA) } if got := forgeHead(t, bare, "main"); got != "" { t.Fatalf("main was created at %s", got) } if parents := strings.TrimSpace(forgeShow(t, bare, "--no-patch", "--format=%P", eng.CandidateSHA)); parents != "" { t.Fatalf("the first commit has parents %q", parents) } if page := forgeShow(t, bare, eng.CandidateSHA+":book.html"); !strings.Contains(page, "Back") { t.Fatalf("book.html %q", page) } if review.State != wire.StepDone || review.Verdict != wire.VerdictApprove || checks.State != wire.StepDone || checks.Checks != wire.ChecksNone || checks.Reason != "" || checks.Gate != "" || checks.ExitCode != nil { t.Fatalf("review %+v checks %+v", review, checks) } if k.Stage != wire.StageReadyToMerge || k.NeedsYou != wire.NeedsMerge || k.Merged != nil { t.Fatalf("task ended %s", k.Stage) } read := s.send(t, "tool:read_file:paulca/barber|index.html") s.waitTurn(t, read.Turn.ID, wire.TurnReplied) if r := s.reply(t, read.Turn.ID).Text; !strings.Contains(r, "no commits yet") { t.Fatalf("read after the task branch: %s", r) } } // A fix round in a repository with no commits (threatmin's round 2 on // staging, which stopped with push_failed): the first round pushes the // task branch's initial commit; review asks for one more file and the fix // round, its base the task branch's tip, pushes again as a fast-forward // of that tip (the forge refuses any other). Both rounds pushed, nothing // stopped, and the default branch stays unborn. func scenarioEmptyFixRound(t *testing.T, env *Env) { if env.Live || env.GrantEmpty == nil { t.Skip("local forge only") } const repo = "amadan.net/paulca/parlour" env.GrantEmpty(t, repo) bare := env.ForgePath(repo) if out, err := exec.Command("git", "--git-dir="+bare, "config", "receive.denyNonFastForwards", "true").CombinedOutput(); err != nil { t.Fatalf("git config: %v %s", err, out) } s := open(t, env) s.keep() s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) deadline := time.Now().Add(45 * time.Second) for found, empty := env.Indexed(t, repo); !found || !empty; found, empty = env.Indexed(t, repo) { if time.Now().After(deadline) { t.Fatalf("not catalogued as empty: found %v", found) } time.Sleep(200 * time.Millisecond) } sent := s.send(t, "tool:record_task:paulca/parlour|Create the parlour mockup|One page and its hours.\ntool:start_task:$task|review:need:hours.txt|open late|create=hours.txt~open late; create:index.html|