package thintest import ( "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/wire" ) // Exploration tasks (spec 2026-11-12-equipo-exploration-tasks.md): // mockups, prototypes and spikes end at a preview and the person's // choice of direction, never a merge. var baseX, candX = strings.Repeat("1", 40), strings.Repeat("2", 40) // previewsOn sends the primary's hello again saying it can publish // previews (the first hello never says so). func (r *toolRig) previewsOn() { r.t.Helper() h := primaryAt(toolHello(r.runner.Welcome.Generation), wire.ProtocolCurrent) h.Capabilities.Previews = true h.Capabilities.PreviewHost = &wire.PreviewHost{Kind: wire.PreviewHostDevbox, Domain: "docs-t1.example.ts.net"} if err := r.runner.Send(r.ctx, "h-previews", wire.FrameHello, h); err != nil { r.t.Fatal(err) } r.client.Snapshot(r.ctx) } // explored records an exploration, starts it, and reports its // Engineering step pushed on cand; it returns the task and the step's // dispatch. func (r *toolRig) explored(key, title, cand string) (string, *wire.DispatchCommand) { r.t.Helper() id := taskID(r.t, r.call(key+"-rec", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": title, "brief": "Two clickable mockups.", "separate": true, "kind": wire.KindExplore})) if res := r.call(key+"-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Make them."}); res.IsError { r.t.Fatalf("start: %+v", res) } d := r.nextDispatch() r.step(key+"-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: baseX}) r.step(key+"-done", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: baseX, CandidateSHA: cand, Pushed: true, Termination: true}) r.expect(wire.FrameWatchMerge) return id, d } // approved has Review approve cand, saying whether it has a preview // config; it returns Review's dispatch. func (r *toolRig) approved(key, cand string, has bool) *wire.DispatchCommand { r.t.Helper() rv := r.dispatched(wire.SpecialistReview, baseX, cand, 0) r.step(key+"-r", wire.StepReport{TaskID: rv.TaskID, StepID: rv.StepID, Attempt: rv.Attempt, State: wire.StepDone, BaseSHA: baseX, CandidateSHA: cand, Termination: true, Family: "codex", Account: "codex-a", Verdict: wire.VerdictApprove, ReviewLabel: wire.ReviewOtherFamily, Findings: []wire.Finding{}, Summary: "Read it.", HasPreview: has}) return rv } // directionCard waits for the task's open direction card. func (r *toolRig) directionCard(id string) wire.Card { r.t.Helper() var card wire.Card r.wait("direction card", func(c *Conversation) bool { for _, k := range c.Cards { if k.Kind == wire.CardDirection && k.TaskID == id && k.State == wire.CardOpen { card = k return true } } return false }) return card } func (r *toolRig) noMerge() { r.t.Helper() if n := r.commandsLike(wire.FrameDispatch, `"specialist":"merge"`); n != 0 { r.t.Fatalf("%d merge dispatches", n) } } func (r *toolRig) commandsLike(kind, like string) int { r.t.Helper() var n int if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", kind, "%"+like+"%").Scan(&n); err != nil { r.t.Fatal(err) } return n } // TestExploreFlow: the coordinator records an exploration; Engineering's // brief asks for the preview config; Review comes next, no checks, told // it reads an exploration; its approval schedules the preview and, at // once, the direction card; the deployed preview fills the card's line // in; nothing is ever merged. func TestExploreFlow(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) r.previewsOn() id, d := r.explored("x", "Barber app mockups", candX) if !strings.Contains(d.Brief, "release/preview.json") || !strings.Contains(d.Brief, "never merged") { t.Fatalf("Engineering's brief: %q", d.Brief) } if k := r.task(id); k.Kind != wire.KindExplore { t.Fatalf("kind %q", k.Kind) } rv := r.approved("x", candX, true) if !strings.Contains(rv.Brief, "exploration, never merged") { t.Fatalf("Review's brief: %q", rv.Brief) } pv := r.previewDispatch(candX) if pv == nil { t.Fatal("no preview") } card := r.directionCard(id) if !strings.Contains(card.Question, "Barber app mockups") || strings.Join(card.Options, ",") != "build,again,drop" { t.Fatalf("card %+v", card) } k := r.task(id) if k.NeedsYou != wire.NeedsDirection || k.Stage != wire.StageInReview || k.Direction == nil || k.Direction.PreviewURL != "" || k.Direction.PreviewsOff { t.Fatalf("waiting %+v %+v", k.NeedsYou, k.Direction) } if r.commandsLike(wire.FrameDispatch, `"specialist":"checks"`) != 0 { t.Fatal("an exploration got checks") } // The preview deploys: its link is the card's line. if refused := r.lease(r.runner, "x-pv-start", wire.LeaseCheck{StepID: pv.StepID, Attempt: pv.Attempt}); refused != "" { t.Fatalf("start refused %q", refused) } r.built("x-pv-built", pv, digestA) if refused := r.lease(r.runner, "x-pv-pub", wire.LeaseCheck{StepID: pv.StepID, Attempt: pv.Attempt, Purpose: wire.LeasePurposePreview, Digest: digestA}); refused != "" { t.Fatalf("publish refused %q", refused) } expires := time.Now().Add(7 * 24 * time.Hour) link := "https://tmp-" + id + ".bds.oncarlos.com/" r.previewDone("x-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "tmp-" + id, URL: link, Version: "p-" + pv.StepID + "-1", Digest: digestA, ExpiresAt: &expires, Outcome: wire.PreviewDeployed}) if k := r.task(id); k.Direction == nil || k.Direction.PreviewURL != link || k.NeedsYou != wire.NeedsDirection { t.Fatalf("after the preview %+v", k.Direction) } page := r.get(r.inst.Cookie(), "/tasks/"+id, 200) if list := r.get(r.inst.Cookie(), "/tasks", 200); !strings.Contains(list, "Exploration") { t.Fatal("no Exploration badge on the task list") } for _, want := range []string{"Preview: tmp-" + id + ".bds.oncarlos.com", `href="/tasks/` + id + `/preview"`, "data-direction-choice", "data-direction-note"} { if !strings.Contains(page, want) && !strings.Contains(r.get(r.inst.Cookie(), "/conversation", 200), want) { t.Fatalf("pages lack %q", want) } } r.syncNow("x-sync") r.noMerge() } // toDirection takes an exploration to its direction card (previews off: // a primary at 10 without the capability). func (r *toolRig) toDirection(key, title string) (string, wire.Card) { r.t.Helper() id, _ := r.explored(key, title, candX) r.approved(key, candX, true) return id, r.directionCard(id) } // TestExploreBuildThisOne: one transaction makes a linked change task, // from the default branch, its brief naming the explored branch and // commit, started at once; the exploration is done; a replayed answer // changes nothing. func TestExploreBuildThisOne(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id, card := r.toDirection("b", "Barber app mockups") explore := r.task(id) if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceBuild, card.Revision); err != nil { t.Fatal(err) } d := r.nextDispatch() k := r.task(id) if k.Stage != wire.StageDone || k.BuiltAs == nil || k.BuiltAs.ID != d.TaskID { t.Fatalf("exploration after Build %+v %+v", k.Stage, k.BuiltAs) } built := r.task(d.TaskID) if built.Kind != "" || built.ExploredFrom == nil || built.ExploredFrom.ID != id || built.Title != "Build: Barber app mockups" || built.Stage != wire.StageInProgress { t.Fatalf("built %+v", built) } if d.Specialist != wire.SpecialistEngineering || d.BaseSHA != "" || !strings.Contains(d.Brief, explore.Branch) || !strings.Contains(d.Brief, candX[:7]) || strings.Contains(d.Brief, "release/preview.json") { t.Fatalf("its Engineering: base %q brief %q", d.BaseSHA, d.Brief) } if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceBuild, card.Revision); Status(err) != 409 { t.Fatalf("a replayed answer: %v", err) } if n := r.commandsLike(wire.FrameDispatch, `"title":"Build: Barber app mockups"`); n != 1 { t.Fatalf("%d builds", n) } } // TestExploreBuildNote: Build this may carry the person's note (protocol // 36: the option they want), bounded as Try again's is: past // wire.MaxDirectionNote, with a NUL, or blank, it is refused and nothing // is built; within it, Build goes ahead. func TestExploreBuildNote(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id, card := r.toDirection("b", "Barber app mockups") for name, note := range map[string]string{"too long": strings.Repeat("a", wire.MaxDirectionNote+1), "a NUL": "The bold\x00 grid.", "blank": " "} { if _, err := r.client.AnswerNote(r.ctx, card.ID, wire.ChoiceBuild, note, card.Revision); Status(err) != 422 { t.Fatalf("a note %s: %v", name, err) } } if k := r.task(id); k.BuiltAs != nil || k.Stage == wire.StageDone { t.Fatalf("a refused note built %+v", k.BuiltAs) } if _, err := r.client.AnswerNote(r.ctx, card.ID, wire.ChoiceBuild, strings.Repeat("a", wire.MaxDirectionNote), card.Revision); err != nil { t.Fatal(err) } d := r.nextDispatch() if k := r.task(id); k.Stage != wire.StageDone || k.BuiltAs == nil || k.BuiltAs.ID != d.TaskID { t.Fatalf("Build with a note: %+v %+v", k.Stage, k.BuiltAs) } } // TestExploreTryAgain: Try again needs the person's note and sends one // more round with it (brief and resumed-session feedback); its new // candidate is asked about afresh. func TestExploreTryAgain(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id, card := r.toDirection("a", "Barber app mockups") if _, err := r.client.AnswerNote(r.ctx, card.ID, wire.ChoiceAgain, "", card.Revision); Status(err) != 422 { t.Fatalf("no note: %v", err) } if _, err := r.client.AnswerNote(r.ctx, card.ID, wire.ChoiceAgain, "Make the booking button bigger.", card.Revision); err != nil { t.Fatal(err) } d := r.dispatched(wire.SpecialistEngineering, candX, "", 1) if strings.Contains(d.Brief, "Make the booking button bigger.") { t.Fatal("person note in coordinator brief", d.Brief) } for _, s := range []string{d.Feedback} { if !strings.Contains(s, "Make the booking button bigger.") { t.Fatalf("the note is missing: %q", s) } } if !strings.Contains(d.Feedback, "release/preview.json") { t.Fatalf("a resumed session misses the exploration's rule: %q", d.Feedback) } cand2 := strings.Repeat("3", 40) r.step("a2", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: candX, CandidateSHA: cand2, Pushed: true, Termination: true}) r.expect(wire.FrameWatchMerge) rv := r.dispatched(wire.SpecialistReview, baseX, cand2, 1) r.verdict("a2-r", rv, wire.VerdictApprove) again := r.directionCard(id) if again.ID == card.ID { t.Fatal("the same card") } r.noMerge() } // TestExploreDropIt: the exploration is cancelled; nothing is sent. func TestExploreDropIt(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id, card := r.toDirection("d", "Barber app mockups") before := r.commandsLike(wire.FrameDispatch, "") if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceDrop, card.Revision); err != nil { t.Fatal(err) } if k := r.task(id); k.Stage != wire.StageCancelled || r.commandsLike(wire.FrameDispatch, "") != before { t.Fatalf("dropped %+v", k.Stage) } } // changeAtReady is a change approved with checks passed, left at Ready to // merge with its merge card (the project asks before every merge). func (r *toolRig) changeAtReady(key, title string) (string, wire.Card) { r.t.Helper() r.asksBeforeMerging() id := r.judgedTask(key, title, baseX, candX, wire.ChecksPassed, "") return id, r.mergeCardsWait(id) } // TestExploreNeverMerges: once an exploration, nothing merges it: the // task page's Merge, the withdrawn merge card, a merge Retry. func TestExploreNeverMerges(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id, mc := r.changeAtReady("n", "Barber app mockups") if _, err := r.client.SetKind(r.ctx, id, wire.KindExplore, r.task(id).Revision); err != nil { t.Fatal(err) } if _, err := r.client.Answer(r.ctx, mc.ID, wire.ChoiceMerge, mc.Revision); Status(err) != 409 { t.Fatalf("the withdrawn merge card: %v", err) } if _, err := r.client.MergeTask(r.ctx, id); err == nil { t.Fatal("the task page's Merge merged an exploration") } if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); strings.Contains(page, "data-task-merge") { t.Fatal("Merge offered on an exploration") } // Even forced to Ready to merge, the gate and startMerge refuse it. if _, err := r.inst.DB.Writer().Exec("UPDATE chat_tasks SET stage = ?, merge_asked = '' WHERE id = ?", wire.StageReadyToMerge, id); err != nil { t.Fatal(err) } if _, err := r.client.MergeTask(r.ctx, id); err == nil { t.Fatal("a forced exploration merged") } r.syncNow("n-sync") r.noMerge() } // TestExploreKindSwitch: Paul's switch, only at rest, at the task's // revision, by its creator. A change at Ready to merge becomes an // exploration: its merge card goes and the direction is asked. Back to a // change, an exploration's approval no longer counts: checks, then a // change Review. A round trip on the same commit asks the direction again. func TestExploreKindSwitch(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id, card := r.toDirection("k", "Barber app mockups") // Another owner never switches it, at rest and at its revision: only // its creator. other := personToolRig(t, r, "second@example.com", equipo.RoleOwner) if _, err := other.client.SetKind(r.ctx, id, wire.KindChange, r.task(id).Revision); Status(err) != 403 { t.Fatalf("another owner: %v", err) } k := r.task(id) if _, err := r.client.SetKind(r.ctx, id, wire.KindChange, k.Revision-1); Status(err) != 409 { t.Fatalf("stale revision: %v", err) } if _, err := r.client.SetKind(r.ctx, id, "merge", k.Revision); Status(err) != 422 { t.Fatalf("unknown kind: %v", err) } if _, err := r.client.SetKind(r.ctx, id, wire.KindChange, k.Revision); err != nil { t.Fatal(err) } c := r.dispatched(wire.SpecialistChecks, baseX, candX, 0) if k := r.task(id); k.Kind != "" || k.NeedsYou != "" { t.Fatalf("a change again %+v", k.NeedsYou) } if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceBuild, card.Revision); Status(err) != 409 { t.Fatalf("the withdrawn direction card: %v", err) } // Not at rest: the checks are running. if _, err := r.client.SetKind(r.ctx, id, wire.KindExplore, r.task(id).Revision); Status(err) != 409 { t.Fatalf("switched while busy: %v", err) } r.checks("k-c2", c, wire.ChecksPassed, exit(0), "", "ok\n") rv := r.dispatched(wire.SpecialistReview, baseX, candX, 0) if strings.Contains(rv.Brief, "exploration") { t.Fatalf("a change's Review told it reads an exploration: %q", rv.Brief) } r.verdict("k-r2", rv, wire.VerdictChanges) r.dispatched(wire.SpecialistEngineering, candX, "", 1) } // TestExploreRoundTrip: explore, change and explore again on the same // approved commit (a change Review counts for an exploration) asks the // direction afresh. func TestExploreRoundTrip(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id, mc := r.changeAtReady("t", "Barber app mockups") if _, err := r.client.SetKind(r.ctx, id, wire.KindExplore, r.task(id).Revision); err != nil { t.Fatal(err) } first := r.directionCard(id) if k := r.task(id); k.NeedsYou != wire.NeedsDirection || k.Stage != wire.StageInReview { t.Fatalf("as an exploration %+v %+v", k.NeedsYou, k.Stage) } if c := r.cardOf(id); c.ID == mc.ID && c.State == wire.CardOpen { t.Fatal("the merge card stayed open") } if _, err := r.client.SetKind(r.ctx, id, wire.KindChange, r.task(id).Revision); err != nil { t.Fatal(err) } if _, err := r.client.SetKind(r.ctx, id, wire.KindExplore, r.task(id).Revision); err != nil { t.Fatal(err) } second := r.directionCard(id) if second.ID == first.ID { t.Fatal("not asked afresh") } r.noMerge() } // TestExplorePreviewsOff: a primary at 10 without previews gets no // preview step; the card says previews aren't set up and links the // branch. A primary at 9 says nothing about previews: no preview this // time, unless one deployed. func TestExplorePreviewsOff(t *testing.T) { t.Run("off", func(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id, _ := r.toDirection("o", "Barber app mockups") if pv := r.previewDispatch(candX); pv != nil { t.Fatalf("a preview with previews off: %+v", pv) } k := r.task(id) if k.Direction == nil || !k.Direction.PreviewsOff || k.Direction.BranchURL == "" { t.Fatalf("direction %+v", k.Direction) } page := r.get(r.inst.Cookie(), "/tasks/"+id, 200) if !strings.Contains(page, "data-direction-branch") || !strings.Contains(page, `href="/conversation/settings/machines#previews"`) || !strings.Contains(page, "Pair a preview host to open previews in your browser.") { t.Fatalf("no pairing and branch links: %s", page) } }) t.Run("protocol 9", func(t *testing.T) { r := newToolRigAt(t, wire.ProtocolPreview) id, _ := r.toDirection("p", "Barber app mockups") if k := r.task(id); k.Direction == nil || k.Direction.PreviewsOff { t.Fatalf("direction %+v", k.Direction) } }) t.Run("on later", func(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) _, _ = r.toDirection("l", "Barber app mockups") if pv := r.previewDispatch(candX); pv != nil { t.Fatal("previewed before the capability") } r.previewsOn() if pv := r.previewDispatch(candX); pv == nil { t.Fatal("no preview once previews are on") } r.previewsOn() if pv := r.previewDispatch(candX); pv != nil { t.Fatal("a second preview") } }) } // TestExploreOnce: the start-up switch of a change recorded before // explorations existed, its merge failed at Ready to merge: once, through // the same switch, raising the direction; Paul switching it back is never // undone; an ended task only writes the row; a busy one writes nothing. func TestExploreOnce(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id := r.judgedTask("o", "Barber app mockups", baseX, candX, wire.ChecksPassed, "") m := r.dispatched(wire.SpecialistMerge, baseX, candX, 0) r.step("o-m-run", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: baseX, CandidateSHA: candX}) // While the merge runs: transient, nothing written. if switched, err := r.inst.Store.Chat().ExploreOnce(r.ctx, id); err != nil || switched { t.Fatalf("while merging: %t %v", switched, err) } r.step("o-m-fail", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepFailed, Reason: "merge_failed", BaseSHA: baseX, CandidateSHA: candX, Termination: true}) r.wait("ready again", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageReadyToMerge }) if switched, err := r.inst.Store.Chat().ExploreOnce(r.ctx, id); err != nil || !switched { t.Fatalf("switch: %t %v", switched, err) } r.directionCard(id) if k := r.task(id); k.Kind != wire.KindExplore || k.NeedsYou != wire.NeedsDirection || k.Stage != wire.StageInReview { t.Fatalf("after the switch %+v %+v %+v", k.Kind, k.NeedsYou, k.Stage) } if _, err := r.client.SetKind(r.ctx, id, wire.KindChange, r.task(id).Revision); err != nil { t.Fatal(err) } if switched, err := r.inst.Store.Chat().ExploreOnce(r.ctx, id); err != nil || switched { t.Fatalf("again: %t %v", switched, err) } if k := r.task(id); k.Kind != "" { t.Fatal("Paul's switch back was undone") } // Missing: the row only. if switched, err := r.inst.Store.Chat().ExploreOnce(r.ctx, "tkmissing"); err != nil || switched { t.Fatalf("missing: %t %v", switched, err) } var rows int if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_housekeeping WHERE detector = 'kind_switch' AND finding_key IN (?, ?)", "explore:"+id, "explore:tkmissing").Scan(&rows); err != nil || rows != 2 { t.Fatalf("rows %d %v", rows, err) } // Only the merge it had as a change, before the switch. if n := r.commandsLike(wire.FrameDispatch, `"specialist":"merge"`); n != 1 { t.Fatalf("%d merge dispatches", n) } } // TestExploreKindsNotDuplicates: an exploration and a change that read // alike are never similar for record_task, never combined or linked by // housekeeping, never folded by the person API. func TestExploreKindsNotDuplicates(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) change := taskID(t, r.call("c-rec", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Barber booking page mockups", "brief": "Two clickable barber booking page mockups."})) res := r.call("e-rec", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Barber booking page mockups", "brief": "Two clickable barber booking page mockups.", "kind": wire.KindExplore}) if res.Code != "recorded" { t.Fatalf("an exploration read as a change's duplicate: %+v", res) } explore := taskID(t, res) if r.tidy() != 0 { t.Fatal("housekeeping combined an exploration with a change") } if k := r.task(explore); k.DuplicateOf != nil || k.Stage == wire.StageCancelled { t.Fatalf("linked or folded %+v", k.DuplicateOf) } if _, err := r.client.MarkDuplicate(r.ctx, explore, change); err == nil { t.Fatal("folded an exploration into a change") } if k := r.task(change); k.Reports != 0 || k.Stage == wire.StageCancelled { t.Fatalf("the change was touched %+v", k) } } // TestExploreDirectionStays: triage, re-triage and the stall sweep leave // an exploration's direction to its person. func TestExploreDirectionStays(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id, _ := r.toDirection("s", "Barber app mockups") dispatches := r.commands(wire.FrameDispatch) if _, err := r.inst.Store.Chat().Retriage(r.ctx, false); err != nil { t.Fatal(err) } r.clock(time.Now().UTC().Add(2 * time.Hour)) r.tick() if k := r.task(id); k.NeedsYou != wire.NeedsDirection || k.Triage != nil || r.commands(wire.FrameDispatch) != dispatches { t.Fatalf("after triage %+v %+v", k.NeedsYou, k.Triage) } if needs, _ := r.client.NeedsYou(r.ctx); len(needs.Items) != 1 || needs.Items[0].ID != id { t.Fatalf("Needs you %+v", needs.Items) } }