oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thintest
2
3import (
4 "encoding/json"
5 "net/http"
6 "net/url"
7 "os"
8 "slices"
9 "strings"
10 "testing"
11 "time"
12
13 "amadan.net/oficina/equipo/internal/equipo"
14 "amadan.net/oficina/equipo/internal/wire"
15)
16
17// judgedTask is a task pushed on cand whose checks ended with outcome
18// (reason for cannot_run) and whose review approved it.
19func (r *toolRig) judgedTask(key, title, base, cand, outcome, reason string) string {
20 r.t.Helper()
21 id, _ := r.pushed(key, title, base, cand)
22 r.expect(wire.FrameWatchMerge)
23 c := r.dispatched(wire.SpecialistChecks, base, cand, 0)
24 code := exit(0)
25 if outcome != wire.ChecksPassed {
26 code = nil
27 }
28 r.checks(key+"-c", c, outcome, code, reason, "")
29 rv := r.dispatched(wire.SpecialistReview, base, cand, 0)
30 r.verdict(key+"-r", rv, wire.VerdictApprove)
31 return id
32}
33
34// merged reports a merge step done the way the runner does once the hub
35// confirmed it.
36func (r *toolRig) mergedStep(key string, d *wire.DispatchCommand, sha string) {
37 r.t.Helper()
38 r.step(key+"-run", wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, BaseSHA: d.BaseSHA, CandidateSHA: d.CandidateSHA})
39 r.step(key, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepDone, BaseSHA: d.BaseSHA, CandidateSHA: d.CandidateSHA, Termination: true, Findings: []wire.Finding{}, MergeSHA: sha, Into: "main", Strategy: wire.MergeCommit})
40 if r.placeOnMerge {
41 r.confirmPlace(d.TaskID)
42 }
43}
44
45// confirmPlace answers the task's place card, if the merge raised one
46// (in whatever lane), with its best candidate (sitesOn's Carloku
47// account).
48func (r *toolRig) confirmPlace(task string) {
49 r.t.Helper()
50 deadline := time.Now().Add(2 * time.Second)
51 for time.Now().Before(deadline) {
52 var id, options string
53 var revision int64
54 err := r.inst.DB.Writer().QueryRow("SELECT id, options, revision FROM chat_cards WHERE kind = ? AND task_id = ? AND state = ?", wire.CardPlace, task, wire.CardOpen).Scan(&id, &options, &revision)
55 if err == nil {
56 var opts []string
57 if json.Unmarshal([]byte(options), &opts) != nil || len(opts) == 0 {
58 r.t.Fatalf("place card options %s", options)
59 }
60 if _, err := r.client.Answer(r.ctx, id, opts[0], revision); err != nil {
61 r.t.Fatalf("place card: %v", err)
62 }
63 return
64 }
65 var n int
66 if r.inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_cards WHERE kind = ? AND task_id = ?", wire.CardPublish, task).Scan(&n) == nil && n > 0 {
67 return
68 }
69 time.Sleep(20 * time.Millisecond)
70 }
71}
72
73// replies are the coordinator's messages so far, as text.
74func (r *toolRig) replies() []string {
75 var out []string
76 r.conv.Locked(func(c *Conversation) {
77 for _, m := range c.Replies() {
78 out = append(out, m.Text)
79 }
80 })
81 return out
82}
83
84// TestContractAutoMerge: a task whose checks passed and whose review
85// approved, both on the branch's head, is ready to merge and then merged
86// by Equipo: a merge step for exactly that SHA goes to the person's
87// runner; only the hub's confirmed merge of that SHA makes it done, with
88// the commit, the branch it went into and how; the coordinator says so in
89// one outcome-level line, once.
90func TestContractAutoMerge(t *testing.T) {
91 r := newToolRigAt(t, wire.ProtocolInjectionDefences)
92 ctx := r.ctx
93 base, cand, other := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("3", 40)
94 id := r.judgedTask("a", "Fix the README typo", base, cand, wire.ChecksPassed, "")
95 _, body := r.expect(wire.FrameDispatch)
96 m := body.(*wire.DispatchCommand)
97 if m.Specialist != wire.SpecialistMerge || m.CandidateSHA != cand || m.BaseSHA != base || m.Attempt != 1 || m.Person != Owner || m.Repo != "amadan.net/oficina/sample" || !wire.ValidTaskBranch(m.Branch) {
98 t.Fatalf("merge dispatch %+v", m)
99 }
100 r.wait("merging", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageMerging })
101 // Only a whole, confirmed merge of the dispatched SHA counts.
102 r.step("a-m-run", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, CandidateSHA: cand})
103 r.step("a-m-other", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepDone, CandidateSHA: other, Termination: true, MergeSHA: strings.Repeat("e", 40), Into: "main", Strategy: wire.MergeCommit})
104 r.step("a-m-nosha", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepDone, CandidateSHA: cand, Termination: true, Into: "main", Strategy: wire.MergeCommit})
105 r.step("a-m-nointo", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepDone, CandidateSHA: cand, Termination: true, MergeSHA: strings.Repeat("e", 40), Into: "../main", Strategy: wire.MergeCommit})
106 if k, _ := r.client.Task(ctx, id); k.Stage != wire.StageMerging || k.Merged != nil {
107 t.Fatalf("an incomplete merge report counted: %+v", k)
108 }
109 sha := strings.Repeat("e", 40)
110 r.mergedStep("a-m", m, sha)
111 shape(t, "frames/step.json", r.runner.Sent[len(r.runner.Sent)-1])
112 r.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone })
113 k, _ := r.client.Task(ctx, id)
114 shape(t, "api/task-merged.json", k)
115 if k.Merged == nil || k.Merged.SHA != sha || k.Merged.Into != "main" || k.Merged.Strategy != wire.MergeCommit || k.Merged.WithoutChecks || k.NeedsYou != "" {
116 t.Fatalf("merged %+v", k)
117 }
118 if s := k.Steps[len(k.Steps)-1]; s.Specialist != wire.SpecialistMerge || s.MergeSHA != sha || s.Into != "main" || s.State != wire.StepDone {
119 t.Fatalf("merge step %+v", s)
120 }
121 var stages []string
122 r.conv.Locked(func(c *Conversation) { stages = c.Stages[id] })
123 if i, j := slices.Index(stages, wire.StageReadyToMerge), slices.Index(stages, wire.StageMerging); i < 0 || j < i || !slices.Contains(stages, wire.StageDone) {
124 t.Fatalf("stages %v", stages)
125 }
126 want := "Merged [Fix the README typo](/tasks/" + id + ") into Sample."
127 r.wait("the coordinator's line", func(c *Conversation) bool {
128 rs := c.Replies()
129 return len(rs) > 0 && rs[len(rs)-1].Text == want
130 })
131 // Outcome level: no SHA, no path. A repeated report says nothing more.
132 r.step("a-m-again", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepDone, CandidateSHA: cand, Termination: true, MergeSHA: sha, Into: "main", Strategy: wire.MergeCommit})
133 n := 0
134 for _, text := range r.replies() {
135 if strings.Contains(text, sha[:7]) || strings.Contains(text, "README.md") {
136 t.Fatalf("a SHA or path in chat: %q", text)
137 }
138 if strings.HasPrefix(text, "Merged ") {
139 n++
140 }
141 }
142 if n != 1 {
143 t.Fatalf("%d merged lines", n)
144 }
145 if needs, _ := r.client.NeedsYou(ctx); len(needs.Items) != 0 {
146 t.Fatalf("done still needs you: %+v", needs)
147 }
148 // The merged line is the person's own: a teammate's conversation has
149 // none, and the task's merge is the team's to read.
150 mate := personToolRig(t, r, "mate@example.com", equipo.RoleMember)
151 if mk, err := mate.client.Task(ctx, id); err != nil || mk.Merged == nil {
152 t.Fatalf("teammate reads %+v %v", mk, err)
153 }
154 snap, _ := mate.client.Snapshot(ctx)
155 for _, msg := range snap.Messages {
156 if strings.HasPrefix(msg.Text, "Merged ") {
157 t.Fatalf("the merged line reached a teammate's conversation: %+v", msg)
158 }
159 }
160}
161
162// TestContractMergeWithoutChecks: checks that could not run are never a
163// pass, so no automatic merge: the creator gets one quiet card, "Merge
164// <title> without checks?", in their own conversation, and only they
165// answer it. Wait leaves the task at Ready to merge; Merge merges exactly
166// that SHA, labelled without checks. A new candidate withdraws the card.
167func TestContractMergeWithoutChecks(t *testing.T) {
168 r := newToolRigAt(t, wire.ProtocolInjectionDefences)
169 ctx := r.ctx
170 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
171 id := r.judgedTask("w", "Swipe back on iOS", base, cand, wire.ChecksCannotRun, "needs_macos")
172 r.wait("ready, asking", func(c *Conversation) bool {
173 if c.Tasks[id].Stage != wire.StageReadyToMerge {
174 return false
175 }
176 for _, card := range c.Cards {
177 if card.Kind == wire.CardMerge && card.TaskID == id {
178 return true
179 }
180 }
181 return false
182 })
183 var card wire.Card
184 cards := 0
185 r.conv.Locked(func(c *Conversation) {
186 for _, k := range c.Cards {
187 if k.Kind == wire.CardMerge {
188 card, cards = k, cards+1
189 }
190 }
191 })
192 shape(t, "api/card-merge.json", card)
193 if cards != 1 || card.State != wire.CardOpen || card.Question != "Merge Swipe back on iOS? I'd wait: I don't know yet whether merging to Sample's main branch ships to users." || !slices.Equal(card.Options, []string{"merge", "wait_mac"}) || card.Name != "Swipe back on iOS" || card.TaskID != id {
194 t.Fatalf("merge card %+v (%d)", card, cards)
195 }
196 if r.heldKinds(wire.FrameDispatch) != 0 {
197 t.Fatal("merged without asking")
198 }
199 k, _ := r.client.Task(ctx, id)
200 if k.NeedsYou != wire.NeedsMerge || k.Checks != wire.ChecksCannotRun {
201 t.Fatalf("waiting for the person %+v", k)
202 }
203 needs, _ := r.client.NeedsYou(ctx)
204 shape(t, "api/needs-you.json", needs)
205 // Asked once: another pass over the task (a sync) asks nothing more.
206 if err := r.runner.Send(ctx, "w-sync", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{{TurnID: r.turn, Attempt: 1, State: wire.TurnRunning}}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}}); err != nil {
207 t.Fatal(err)
208 }
209 r.client.Task(ctx, id)
210 r.conv.Locked(func(c *Conversation) {
211 n := 0
212 for _, k := range c.Cards {
213 if k.Kind == wire.CardMerge {
214 n++
215 }
216 }
217 if n != 1 {
218 t.Errorf("%d merge cards after a sync", n)
219 }
220 })
221 // Only the creator answers: a teammate cannot see or answer the card.
222 mate := personToolRig(t, r, "mate@example.com", equipo.RoleOwner)
223 if _, err := mate.client.Answer(ctx, card.ID, wire.ChoiceMerge, card.Revision); Status(err) != http.StatusNotFound {
224 t.Fatalf("teammate answered: %v", err)
225 }
226 // A stale revision is a conflict with the current card.
227 if _, err := r.client.Answer(ctx, card.ID, wire.ChoiceMerge, card.Revision+1); Status(err) != http.StatusConflict {
228 t.Fatalf("stale answer: %v", err)
229 }
230 if _, err := r.client.Answer(ctx, card.ID, "maybe", card.Revision); Status(err) != http.StatusUnprocessableEntity {
231 t.Fatalf("other choice: %v", err)
232 }
233 // Wait: stays ready to merge, no merge.
234 out, err := r.client.Answer(ctx, card.ID, wire.ChoiceWaitMac, card.Revision)
235 if err != nil || out.Card.State != wire.CardAnswered || out.Card.Choice != wire.ChoiceWaitMac {
236 t.Fatalf("wait %+v %v", out, err)
237 }
238 if page := r.get(r.inst.Cookie(), "/conversation", 200); !strings.Contains(page, `data-card="`+card.ID+`"`) || !strings.Contains(page, "Waiting for a Mac.") || strings.Contains(page, `data-merge-choice="merge"`) {
239 t.Fatalf("answered card: %s", page)
240 }
241 if k, _ := r.client.Task(ctx, id); k.Stage != wire.StageReadyToMerge || k.NeedsYou != wire.NeedsMerge || r.heldKinds(wire.FrameDispatch) != 0 {
242 t.Fatalf("after wait %+v", k)
243 }
244 if _, err := r.client.Answer(ctx, card.ID, wire.ChoiceMerge, out.Card.Revision); Status(err) != http.StatusConflict {
245 t.Fatalf("answered twice: %v", err)
246 }
247
248 // Another task: Merge merges that SHA, labelled without checks.
249 cand2 := strings.Repeat("4", 40)
250 id2 := r.judgedTask("x", "Edge swipe on iPad", base, cand2, wire.ChecksCannotRun, "needs_macos")
251 var card2 wire.Card
252 r.wait("second card", func(c *Conversation) bool {
253 for _, k := range c.Cards {
254 if k.Kind == wire.CardMerge && k.TaskID == id2 {
255 card2 = k
256 return true
257 }
258 }
259 return false
260 })
261 if page := r.get(r.inst.Cookie(), "/conversation", 200); !strings.Contains(page, `data-merge-choice="merge"`) || !strings.Contains(page, ">Wait for a Mac</button>") {
262 t.Fatalf("open card: %s", page)
263 }
264 if out, err := r.client.Answer(ctx, card2.ID, wire.ChoiceMerge, card2.Revision); err != nil || out.Card.Choice != wire.ChoiceMerge {
265 t.Fatalf("merge %+v %v", out, err)
266 }
267 m := r.dispatched(wire.SpecialistMerge, base, cand2, 0)
268 r.wait("merging", func(c *Conversation) bool { return c.Tasks[id2].Stage == wire.StageMerging })
269 r.mergedStep("x-m", m, strings.Repeat("f", 40))
270 r.wait("done", func(c *Conversation) bool { return c.Tasks[id2].Stage == wire.StageDone })
271 if k, _ := r.client.Task(ctx, id2); k.Merged == nil || !k.Merged.WithoutChecks || !k.Steps[len(k.Steps)-1].WithoutChecks {
272 t.Fatalf("merged without checks %+v", k.Merged)
273 }
274 want := "Merged [Edge swipe on iPad](/tasks/" + id2 + ") into Sample without checks."
275 r.wait("the coordinator's line", func(c *Conversation) bool {
276 rs := c.Replies()
277 return len(rs) > 0 && rs[len(rs)-1].Text == want
278 })
279 if page := r.get(r.inst.Cookie(), "/conversation", 200); !strings.Contains(page, "Merged into main at fffffff, without checks") || !strings.Contains(page, "Merging without checks.") {
280 t.Fatalf("merged without checks: %s", page)
281 }
282 // A merge card answered Wait stays answered; a task that ends
283 // withdraws an open card.
284 id3 := r.judgedTask("y", "Haptics on iOS", base, strings.Repeat("5", 40), wire.ChecksCannotRun, "needs_macos")
285 var card3 wire.Card
286 r.wait("third card", func(c *Conversation) bool {
287 for _, k := range c.Cards {
288 if k.Kind == wire.CardMerge && k.TaskID == id3 {
289 card3 = k
290 return true
291 }
292 }
293 return false
294 })
295 // While the branch is not at the SHA the card asks about, Merge
296 // merges nothing and the card stays open for when it is back.
297 cand3 := strings.Repeat("5", 40)
298 if err := r.runner.Send(ctx, "y-moved", wire.FrameBranch, wire.BranchReport{TaskID: id3, CandidateSHA: cand3, Head: strings.Repeat("9", 40)}); err != nil {
299 t.Fatal(err)
300 }
301 r.wait("moved", func(c *Conversation) bool { return c.Tasks[id3].NeedsYou == wire.NeedsBranchMoved })
302 if _, err := r.client.Answer(ctx, card3.ID, wire.ChoiceMerge, card3.Revision); Status(err) != http.StatusConflict {
303 t.Fatalf("merged a moved branch from the card: %v", err)
304 }
305 if r.heldKinds(wire.FrameDispatch) != 0 {
306 t.Fatal("a merge was dispatched for a moved branch")
307 }
308 if k, _ := r.client.Task(ctx, id3); k.Stage == wire.StageMerging {
309 t.Fatalf("merging a moved branch %+v", k)
310 }
311 snap, _ := r.client.Snapshot(ctx)
312 for _, c := range snap.Cards {
313 if c.ID == card3.ID && c.State != wire.CardOpen {
314 t.Fatalf("card closed while the branch is away: %+v", c)
315 }
316 }
317 if _, err := r.client.CancelTask(ctx, id3); err != nil {
318 t.Fatal(err)
319 }
320 r.wait("withdrawn", func(c *Conversation) bool { return c.Cards[card3.ID].State == wire.CardResolved })
321 if _, err := r.client.Answer(ctx, card3.ID, wire.ChoiceMerge, card3.Revision+1); Status(err) != http.StatusConflict {
322 t.Fatalf("answered a withdrawn card: %v", err)
323 }
324 if page := r.get(r.inst.Cookie(), "/conversation", 200); !strings.Contains(page, "Nothing to decide any more.") {
325 t.Fatalf("withdrawn card: %s", page)
326 }
327}
328
329// TestContractMergeConflictRebase: a merge refused because the branch
330// conflicts with a default branch that moved sends Engineering one rebase
331// round onto the new tip; its candidate invalidates checks and review and
332// is judged afresh, from the new base, then merged. A second conflict
333// gets needs-you triage's own rebase (triage_contract_test.go follows the
334// chain to the person).
335func TestContractMergeConflictRebase(t *testing.T) {
336 r := newToolRigAt(t, wire.ProtocolInjectionDefences)
337 ctx := r.ctx
338 base, cand, tip, cand2 := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("6", 40), strings.Repeat("7", 40)
339 id := r.judgedTask("c", "Fix the README typo", base, cand, wire.ChecksPassed, "")
340 m := r.dispatched(wire.SpecialistMerge, base, cand, 0)
341 r.step("c-m-run", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, CandidateSHA: cand})
342 r.step("c-m-conflict", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepFailed, Reason: "merge_conflict", BaseSHA: base, CandidateSHA: cand, Termination: true})
343 _, body := r.expect(wire.FrameDispatch)
344 rb := body.(*wire.DispatchCommand)
345 if rb.Specialist != wire.SpecialistEngineering || !rb.Rebase || rb.BaseSHA != "" || rb.FromBase != base || rb.CandidateSHA != cand || rb.Round != 0 {
346 t.Fatalf("rebase round %+v", rb)
347 }
348 r.wait("rebasing", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageInProgress })
349 // The rebase pushes a new candidate on the new tip: nothing judged of
350 // the old one applies, and checks and review read it from there.
351 r.step("c-rb-run", wire.StepReport{TaskID: id, StepID: rb.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: tip})
352 r.step("c-rb-done", wire.StepReport{TaskID: id, StepID: rb.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: tip, CandidateSHA: cand2, Pushed: true, Termination: true})
353 r.expect(wire.FrameWatchMerge)
354 k, _ := r.client.Task(ctx, id)
355 rebased := slices.IndexFunc(k.Steps, func(s wire.Step) bool { return s.ID == rb.StepID })
356 if k.CandidateSHA != cand2 || k.Checks != "" || k.Verdict != "" || k.BaseSHA != tip || rebased < 0 || !k.Steps[rebased].Rebase {
357 t.Fatalf("after the rebase %+v", k)
358 }
359 c2 := r.dispatched(wire.SpecialistChecks, tip, cand2, 0)
360 r.checks("c-c2", c2, wire.ChecksPassed, exit(0), "", "ok\n")
361 rv2 := r.dispatched(wire.SpecialistReview, tip, cand2, 0)
362 r.verdict("c-r2", rv2, wire.VerdictApprove)
363 m2 := r.dispatched(wire.SpecialistMerge, tip, cand2, 0)
364 // It conflicts again: the merge's own rebase round is used, so
365 // needs-you triage rebases this candidate once more on its own.
366 r.step("c-m2-run", wire.StepReport{TaskID: id, StepID: m2.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: tip, CandidateSHA: cand2})
367 r.step("c-m2-conflict", wire.StepReport{TaskID: id, StepID: m2.StepID, Attempt: 1, State: wire.StepFailed, Reason: "merge_conflict", BaseSHA: tip, CandidateSHA: cand2, Termination: true})
368 _, body = r.expect(wire.FrameDispatch)
369 if rb2 := body.(*wire.DispatchCommand); rb2.Specialist != wire.SpecialistEngineering || !rb2.Rebase || rb2.CandidateSHA != cand2 {
370 t.Fatalf("second rebase %+v", rb2)
371 }
372 if k, _ := r.client.Task(ctx, id); k.NeedsYou != "" || k.Stage != wire.StageInProgress {
373 t.Fatalf("after the second conflict %+v", k)
374 }
375 if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); !strings.Contains(page, "Engineering is fixing conflicting changes.") || !strings.Contains(page, "(rebase)") {
376 t.Fatalf("task page: %s", page)
377 }
378}
379
380// TestContractMergeRefusedAndRetry: the hub's other refusals leave the
381// task at Ready to merge with the reason and Retry; Retry merges the same
382// judged SHA again (a new attempt), and a cancel is not offered mid-merge.
383func TestContractMergeRefusedAndRetry(t *testing.T) {
384 r := newToolRigAt(t, wire.ProtocolInjectionDefences)
385 ctx := r.ctx
386 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
387 id := r.judgedTask("p", "Fix the README typo", base, cand, wire.ChecksPassed, "")
388 m := r.dispatched(wire.SpecialistMerge, base, cand, 0)
389 if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); strings.Contains(page, `action="/tasks/`+id+`/cancel"`) {
390 t.Fatalf("cancel offered while merging: %s", page)
391 }
392 r.step("p-m-run", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, CandidateSHA: cand})
393 r.step("p-m-ci", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepFailed, Reason: "amadan_ci_pending", BaseSHA: base, CandidateSHA: cand, Termination: true})
394 r.wait("ready again", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageReadyToMerge })
395 if page := r.get(r.inst.Cookie(), "/conversation", 200); !strings.Contains(page, "Stopped: Amadan&#39;s own CI had not finished") {
396 t.Fatalf("card after the refusal: %s", page)
397 }
398 acc, err := r.client.RetryTask(ctx, id)
399 if err != nil || acc.Attempt != 2 {
400 t.Fatalf("retry %+v %v", acc, err)
401 }
402 _, body := r.expect(wire.FrameDispatch)
403 if d := body.(*wire.DispatchCommand); d.Specialist != wire.SpecialistMerge || d.CandidateSHA != cand || d.Attempt != 2 {
404 t.Fatalf("retry dispatch %+v", d)
405 }
406 r.wait("merging", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageMerging })
407 m.Attempt = 2
408 r.mergedStep("p-m2", m, strings.Repeat("e", 40))
409 r.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone })
410}
411
412// TestContractDuplicateReports: Paul's coordinator filed one bug three
413// times. record_task now looks first: an open task in the same project
414// that reads like the report comes back as similar and nothing is
415// recorded; add_report puts the new report on that task (its thread, a
416// task card in this turn); separate records a different problem anyway.
417func TestContractDuplicateReports(t *testing.T) {
418 r := newToolRig(t)
419 ctx := r.ctx
420 first := taskID(t, r.call("d1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "iOS edge swipe to go back doesn't work", "brief": "Swiping from the left edge on iPhone does nothing."}))
421 res := r.call("d2", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Swipe back doesn't work", "brief": "On the iPhone, swiping back from the edge does nothing."})
422 var similar struct {
423 Similar []struct{ Task, Title, Link, Stage string } `json:"similar"`
424 Note string
425 }
426 if res.IsError || res.Code != "similar" || json.Unmarshal([]byte(res.Text), &similar) != nil || len(similar.Similar) != 1 || similar.Similar[0].Task != first || similar.Similar[0].Link != "/tasks/"+first || !strings.Contains(similar.Note, "add_report") {
427 t.Fatalf("similar %+v", res)
428 }
429 if list, _ := r.client.Tasks(ctx); len(list.Items) != 1 {
430 t.Fatalf("a duplicate was recorded: %d tasks", len(list.Items))
431 }
432 // Unrelated work in the same project is recorded as usual.
433 other := taskID(t, r.call("d3", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "README typo", "brief": "The README says teh panes."}))
434 if other == first {
435 t.Fatal("unrelated work joined the first task")
436 }
437 // The report goes on the open task.
438 add := r.call("d4", wire.ToolAddReport, map[string]string{"task": first, "text": "Swipe back still doesn't work on my iPhone."})
439 if add.IsError || add.Code != "reported" || !strings.Contains(add.Text, `"link":"/tasks/`+first+`"`) {
440 t.Fatalf("add_report %+v", add)
441 }
442 k, _ := r.client.Task(ctx, first)
443 if k.Reports != 1 || len(k.Thread) != 1 || k.Thread[0].Text != "Swipe back still doesn't work on my iPhone." || k.Thread[0].Author != Owner {
444 t.Fatalf("report on the task %+v", k)
445 }
446 r.wait("task card in this turn", func(c *Conversation) bool {
447 n := 0
448 for _, card := range c.Cards {
449 if card.Kind == wire.CardTask && card.TaskID == first {
450 n++
451 }
452 }
453 return n == 2
454 })
455 // A different problem, recorded on purpose.
456 sep := r.call("d5", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Swipe back doesn't work on iPad", "brief": "iPad only, from the edge.", "separate": true})
457 if third := taskID(t, sep); third == first || third == other {
458 t.Fatalf("separate %+v", sep)
459 }
460 // Bounds and endings.
461 for _, args := range []map[string]string{{"task": first, "text": ""}, {"task": "tknotthere", "text": "x"}, {"task": first}} {
462 if res := r.call("d6-"+args["task"]+args["text"], wire.ToolAddReport, args); !res.IsError {
463 t.Fatalf("add_report %v accepted: %+v", args, res)
464 }
465 }
466 if _, err := r.client.CancelTask(ctx, other); err != nil {
467 t.Fatal(err)
468 }
469 if res := r.call("d7", wire.ToolAddReport, map[string]string{"task": other, "text": "Again."}); !res.IsError || res.Code != "task_ended" {
470 t.Fatalf("report on an ended task %+v", res)
471 }
472 // An ended task is never offered as similar.
473 again := r.call("d8", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "README typo", "brief": "The README says teh panes."})
474 if again.Code == "similar" {
475 t.Fatalf("a cancelled task offered as similar: %+v", again)
476 }
477}
478
479// syncNow sends a runner sync holding the rig's turn, so the instance
480// passes over every open task again.
481func (r *toolRig) syncNow(key string) {
482 r.t.Helper()
483 if err := r.runner.Send(r.ctx, key, wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{{TurnID: r.turn, Attempt: 1, State: wire.TurnRunning}}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}}); err != nil {
484 r.t.Fatal(err)
485 }
486 r.client.Snapshot(r.ctx)
487}
488
489// legacyReady is a task that was Ready to merge before Equipo merged on
490// its own: judged and approved, no merge step, and migration 0047's own
491// statements applied to it.
492func (r *toolRig) legacyReady(key, title, base, cand string) string {
493 r.t.Helper()
494 id := r.judgedTask(key, title, base, cand, wire.ChecksPassed, "")
495 m := r.dispatched(wire.SpecialistMerge, base, cand, 0)
496 db := r.inst.DB.Writer()
497 if _, err := db.Exec("DELETE FROM chat_steps WHERE id = ?", m.StepID); err != nil {
498 r.t.Fatal(err)
499 }
500 if _, err := db.Exec("UPDATE chat_tasks SET stage = 'ready_to_merge', ready_sha = NULL, merge_eligible = NULL WHERE id = ?", id); err != nil {
501 r.t.Fatal(err)
502 }
503 raw, err := os.ReadFile("../equipo/migrations/0047_thin_merge_eligibility.sql")
504 if err != nil {
505 r.t.Fatal(err)
506 }
507 for _, stmt := range strings.Split(string(raw), ";") {
508 if s := strings.TrimSpace(stmt); strings.HasPrefix(s, "UPDATE") {
509 if _, err := db.Exec(s); err != nil {
510 r.t.Fatal(err)
511 }
512 }
513 }
514 return id
515}
516
517func (r *toolRig) cardOf(id string) wire.Card {
518 r.t.Helper()
519 snap, err := r.client.Snapshot(r.ctx)
520 if err != nil {
521 r.t.Fatal(err)
522 }
523 for _, c := range snap.Cards {
524 if c.Kind == wire.CardMerge && c.TaskID == id {
525 return c
526 }
527 }
528 return wire.Card{}
529}
530
531// Astra 4c round 1, finding 2: the merge policy is not retroactive. A
532// candidate already Ready when it arrived (migration 0047) is never
533// merged on its own: the creator gets one card, "Merge <title>?" with
534// Merge and Not now. Leaving Ready and coming back grants nothing; Merge
535// on the card adopts it.
536func TestContractNoRetroactiveMerge(t *testing.T) {
537 r := newToolRigAt(t, wire.ProtocolInjectionDefences)
538 ctx := r.ctx
539 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
540 id := r.legacyReady("l", "Fix the README typo", base, cand)
541 if k, _ := r.client.Task(ctx, id); k.Stage != wire.StageReadyToMerge {
542 t.Fatalf("legacy %+v", k)
543 }
544 r.syncNow("l-sync")
545 card := r.cardOf(id)
546 if card.State != wire.CardOpen || card.Question != "Merge Fix the README typo? I'd merge: approved by Review, but it was ready before I could merge on my own." || !slices.Equal(card.Options, []string{"merge", "not_now"}) {
547 t.Fatalf("adoption card %+v", card)
548 }
549 if r.heldKinds(wire.FrameDispatch) != 0 {
550 t.Fatal("merged a candidate that was Ready before the policy")
551 }
552 // Away and back: still not eligible, and the card's old revision is
553 // stale.
554 for _, head := range []string{strings.Repeat("9", 40), cand} {
555 if err := r.runner.Send(ctx, "l-b-"+head[:1], wire.FrameBranch, wire.BranchReport{TaskID: id, CandidateSHA: cand, Head: head}); err != nil {
556 t.Fatal(err)
557 }
558 if head != cand {
559 r.wait("moved", func(c *Conversation) bool { return c.Tasks[id].NeedsYou == wire.NeedsBranchMoved })
560 }
561 }
562 r.wait("ready again", func(c *Conversation) bool {
563 return c.Tasks[id].Stage == wire.StageReadyToMerge && c.Tasks[id].NeedsYou == wire.NeedsMerge
564 })
565 r.syncNow("l-sync2")
566 if r.heldKinds(wire.FrameDispatch) != 0 {
567 t.Fatal("leaving Ready and coming back made it eligible")
568 }
569 if page := r.get(r.inst.Cookie(), "/conversation", 200); !strings.Contains(page, ">Not now</button>") || !strings.Contains(page, "Merge Fix the README typo?") {
570 t.Fatalf("adoption card on the page: %s", page)
571 }
572 fresh := r.cardOf(id)
573 if out, err := r.client.Answer(ctx, fresh.ID, wire.ChoiceNotNow, fresh.Revision); err != nil || out.Card.Choice != wire.ChoiceNotNow {
574 t.Fatalf("not now %+v %v", out, err)
575 }
576 if k, _ := r.client.Task(ctx, id); k.Stage != wire.StageReadyToMerge || r.heldKinds(wire.FrameDispatch) != 0 {
577 t.Fatalf("after Not now %+v", k)
578 }
579 // Astra 4c round 2: Not now is not final. The creator's quiet Merge
580 // reopens it, validated afresh: refused while the branch is away, then
581 // merged once it is back at the judged SHA.
582 if k, _ := r.client.Task(ctx, id); !k.MergeOffered {
583 t.Fatalf("no Merge offered after Not now %+v", k)
584 }
585 if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); !strings.Contains(page, `action="/conversation/tasks/`+id+`/merge"`) || !strings.Contains(page, ">Merge</button>") {
586 t.Fatalf("task page offers no Merge: %s", page)
587 }
588 if p := r.get(r.memberCookie(), "/tasks/"+id, 200); strings.Contains(p, "data-task-merge") {
589 t.Fatal("a teammate is offered Merge")
590 }
591 mate := personToolRig(t, r, "mate@example.com", equipo.RoleOwner)
592 if _, err := mate.client.MergeTask(ctx, id); Status(err) != http.StatusForbidden {
593 t.Fatalf("a teammate merged: %v", err)
594 }
595 if err := r.runner.Send(ctx, "l-away", wire.FrameBranch, wire.BranchReport{TaskID: id, CandidateSHA: cand, Head: strings.Repeat("8", 40)}); err != nil {
596 t.Fatal(err)
597 }
598 r.wait("away", func(c *Conversation) bool { return c.Tasks[id].NeedsYou == wire.NeedsBranchMoved })
599 if _, err := r.client.MergeTask(ctx, id); Status(err) != http.StatusConflict || !strings.Contains(err.Error(), "not_mergeable") {
600 t.Fatalf("merged while the branch is away: %v", err)
601 }
602 if err := r.runner.Send(ctx, "l-home", wire.FrameBranch, wire.BranchReport{TaskID: id, CandidateSHA: cand, Head: cand}); err != nil {
603 t.Fatal(err)
604 }
605 r.wait("back", func(c *Conversation) bool {
606 return c.Tasks[id].Stage == wire.StageReadyToMerge && c.Tasks[id].NeedsYou == wire.NeedsMerge
607 })
608 if status, loc := r.post(r.inst.Cookie(), "/conversation/tasks/"+id+"/merge", url.Values{"from": {"task"}}); status != http.StatusSeeOther || loc != "/tasks/"+id {
609 t.Fatalf("page merge %d %s", status, loc)
610 }
611 mm := r.dispatched(wire.SpecialistMerge, base, cand, 0)
612 if k, _ := r.client.Task(ctx, id); k.Stage != wire.StageMerging || k.MergeOffered || mm.TaskID != id {
613 t.Fatalf("after Merge %+v", k)
614 }
615 if _, err := r.client.MergeTask(ctx, id); Status(err) != http.StatusConflict {
616 t.Fatalf("merged twice: %v", err)
617 }
618 // Another legacy task, adopted: merged (checks passed, so not labelled
619 // without checks).
620 id2 := r.legacyReady("m", "Fix the second typo", base, strings.Repeat("3", 40))
621 r.syncNow("m-sync")
622 c2 := r.cardOf(id2)
623 if _, err := r.client.Answer(ctx, c2.ID, wire.ChoiceMerge, c2.Revision); err != nil {
624 t.Fatal(err)
625 }
626 m := r.dispatched(wire.SpecialistMerge, base, strings.Repeat("3", 40), 0)
627 r.mergedStep("m-m", m, strings.Repeat("e", 40))
628 r.wait("adopted and merged", func(c *Conversation) bool { return c.Tasks[id2].Stage == wire.StageDone })
629 if k, _ := r.client.Task(ctx, id2); k.Merged == nil || k.Merged.WithoutChecks {
630 t.Fatalf("adopted merge %+v", k.Merged)
631 }
632}
633
634// Astra 4c round 1, finding 4: the branch moving bumps an open merge
635// card's revision, so an answer from before the move is refused once the
636// branch is back; the refreshed revision merges.
637func TestContractMergeCardStaleAfterMove(t *testing.T) {
638 r := newToolRig(t)
639 ctx := r.ctx
640 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
641 id := r.judgedTask("s", "Swipe back on iOS", base, cand, wire.ChecksCannotRun, "needs_macos")
642 r.wait("card", func(c *Conversation) bool { return r.cardOf(id).ID != "" })
643 before := r.cardOf(id)
644 for _, head := range []string{strings.Repeat("9", 40), cand} {
645 if err := r.runner.Send(ctx, "s-b-"+head[:1], wire.FrameBranch, wire.BranchReport{TaskID: id, CandidateSHA: cand, Head: head}); err != nil {
646 t.Fatal(err)
647 }
648 if head != cand {
649 r.wait("moved", func(c *Conversation) bool { return c.Tasks[id].NeedsYou == wire.NeedsBranchMoved })
650 }
651 }
652 r.wait("ready again", func(c *Conversation) bool {
653 return c.Tasks[id].Stage == wire.StageReadyToMerge && c.Tasks[id].NeedsYou == wire.NeedsMerge
654 })
655 after := r.cardOf(id)
656 if after.Revision <= before.Revision || after.State != wire.CardOpen {
657 t.Fatalf("card after the move %+v (before %+v)", after, before)
658 }
659 if _, err := r.client.Answer(ctx, before.ID, wire.ChoiceMerge, before.Revision); Status(err) != http.StatusConflict {
660 t.Fatalf("an answer from before the move: %v", err)
661 }
662 if r.heldKinds(wire.FrameDispatch) != 0 {
663 t.Fatal("merged on a stale answer")
664 }
665 if _, err := r.client.Answer(ctx, after.ID, wire.ChoiceMerge, after.Revision); err != nil {
666 t.Fatal(err)
667 }
668 r.dispatched(wire.SpecialistMerge, base, cand, 0)
669}
670
671// Astra 4c round 1, finding 1: a task cannot be cancelled while Equipo is
672// merging it (API and the coordinator's tool); the runner's report of the
673// hub's outcome ends it, here Done after a lost answer was settled.
674func TestContractCancelRefusedWhileMerging(t *testing.T) {
675 r := newToolRigAt(t, wire.ProtocolInjectionDefences)
676 ctx := r.ctx
677 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
678 id := r.judgedTask("c", "Fix the README typo", base, cand, wire.ChecksPassed, "")
679 m := r.dispatched(wire.SpecialistMerge, base, cand, 0)
680 r.step("c-m-run", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, CandidateSHA: cand})
681 if _, err := r.client.CancelTask(ctx, id); Status(err) != http.StatusConflict || !strings.Contains(err.Error(), "task_merging") {
682 t.Fatalf("cancelled while merging: %v", err)
683 }
684 if res := r.call("c-cancel", wire.ToolCancelTask, map[string]string{"task": id}); !res.IsError || res.Code != "merging" {
685 t.Fatalf("tool cancelled while merging: %+v", res)
686 }
687 if status, _ := r.post(r.inst.Cookie(), "/conversation/tasks/"+id+"/cancel", url.Values{"from": {"task"}}); status != http.StatusConflict {
688 t.Fatalf("page cancel while merging: %d", status)
689 }
690 if r.heldKinds(wire.FrameCancelStep) != 0 {
691 t.Fatal("a cancel reached the runner")
692 }
693 r.step("c-m-done", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Termination: true, Findings: []wire.Finding{}, MergeSHA: strings.Repeat("e", 40), Into: "main", Strategy: wire.MergeCommit})
694 r.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone })
695}
696
697// Paul, 2026-11-08: only a cancelled task forgets its sessions at once.
698func TestContractCancelledTaskForgetsNow(t *testing.T) {
699 r := newToolRig(t)
700 id, _ := r.pushed("f", "Fix the README typo", strings.Repeat("1", 40), strings.Repeat("2", 40))
701 r.expect(wire.FrameWatchMerge)
702 r.dispatched(wire.SpecialistChecks, strings.Repeat("1", 40), strings.Repeat("2", 40), 0)
703 // The checks step is queued: cancel goes through the runner.
704 if _, err := r.client.CancelTask(r.ctx, id); err != nil {
705 t.Fatal(err)
706 }
707 _, body := r.expect(wire.FrameCancelStep)
708 c := body.(*wire.CancelStepCommand)
709 r.step("f-cancelled", wire.StepReport{TaskID: id, StepID: c.StepID, Attempt: c.Attempt, State: wire.StepCancelled, Reason: "cancelled", Termination: true})
710 _, body = r.expect(wire.FrameForgetTask)
711 if f := body.(*wire.ForgetTaskCommand); f.TaskID != id || f.KeepUntil != nil {
712 t.Fatalf("forget %+v", f)
713 }
714}
715