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 "fmt"
6 "html"
7 "net/http"
8 "regexp"
9 "slices"
10 "strconv"
11 "strings"
12 "testing"
13 "time"
14
15 "amadan.net/oficina/equipo/internal/equipo"
16 "amadan.net/oficina/equipo/internal/wire"
17)
18
19// teamRig is an Assistant rig whose runner can reach the sample
20// repository, so a hand-off's Coordinator turn can record work there.
21// The registry is the app's own: Base's provider, then the team's. Its
22// runner speaks job lanes (protocol 22).
23type teamRig struct{ *opsRig }
24
25func newTeamRig(t *testing.T) *teamRig { return newTeamRigAt(t, wire.ProtocolJobs) }
26
27// newTeamRigAt is newTeamRig whose runner speaks protocol.
28func newTeamRigAt(t *testing.T, protocol int) *teamRig {
29 o := newOpsRigAt(t, protocol)
30 // The person reached the Assistant through their Base, which holds
31 // their abilities (all on): with Base's hosts set, nothing switched
32 // runs for anyone without one (abilities §5.3).
33 o.connect(o.base.Token)
34 o.inst.Store.Chat().SetHousekeepingClock(daytime())
35 if err := o.runner.Send(o.ctx, "h-team", wire.FrameHello, primaryAt(toolHello(o.runner.Welcome.Generation), protocol)); err != nil {
36 t.Fatal(err)
37 }
38 if refused := o.lease(o.runner, "h-team-ping", wire.LeaseCheck{}); refused != "" {
39 t.Fatalf("ping refused %q", refused)
40 }
41 return &teamRig{o}
42}
43
44// message is the next message command in lane, acked: one already held,
45// or the next to arrive, holding the frames before it.
46func (o *teamRig) message(lane string) *wire.MessageCommand {
47 o.t.Helper()
48 for {
49 for i, h := range o.held {
50 if cmd, ok := h.body.(*wire.MessageCommand); ok && cmd.Lane == lane {
51 o.held = append(o.held[:i:i], o.held[i+1:]...)
52 if err := o.runner.Send(o.ctx, "a-"+h.f.ID, wire.FrameAck, wire.Ack{ID: h.f.ID}); err != nil {
53 o.t.Fatal(err)
54 }
55 return cmd
56 }
57 }
58 f, body, err := o.runner.Next(o.ctx)
59 if err != nil {
60 o.t.Fatalf("waiting for a message in lane %q: %v", lane, err)
61 }
62 if f.Type != wire.FrameAck {
63 o.held = append(o.held, heldFrame{f, body, o.runner.Received[len(o.runner.Received)-1]})
64 }
65 }
66}
67
68// ask sends an Assistant message and makes its turn the rig's.
69func (o *teamRig) ask(text string) string {
70 o.t.Helper()
71 sent, err := o.a.Send(o.ctx, text, "a-"+itoa(len(o.runner.Sent)))
72 if err != nil {
73 o.t.Fatal(err)
74 }
75 if cmd := o.message(wire.LaneAssistant); cmd.TurnID != sent.Turn.ID {
76 o.t.Fatalf("the Assistant's message went as %+v", cmd)
77 }
78 o.turn, o.attempt = sent.Turn.ID, 0
79 return sent.Turn.ID
80}
81
82// request is team_request's answer: the request id.
83func (o *teamRig) request(id string, input map[string]any) string {
84 o.t.Helper()
85 res := o.use(id, "team_request", input)
86 var out struct{ Request, Status string }
87 if res.IsError || res.Code != "used" || json.Unmarshal([]byte(res.Text), &out) != nil || out.Request == "" || out.Status == "" {
88 o.t.Fatalf("team_request %+v", res)
89 }
90 return out.Request
91}
92
93// handoff hands words to the team from the rig's Assistant turn and
94// returns the request and the message command of its thread.
95func (o *teamRig) handoff(id, words, context string) (string, *wire.MessageCommand) {
96 o.t.Helper()
97 in := map[string]any{"words": words}
98 if context != "" {
99 in["context"] = context
100 }
101 request := o.request(id, in)
102 return request, o.message(wire.JobLane(request))
103}
104
105// handoffTurn is the turn that carries the request's words.
106func (o *teamRig) handoffTurn(request string) string {
107 o.t.Helper()
108 var turn string
109 if err := o.inst.DB.Writer().QueryRow("SELECT m.turn_id FROM chat_handoffs h JOIN chat_messages m ON m.id = h.message_id WHERE h.id = ?", request).Scan(&turn); err != nil {
110 o.t.Fatal(err)
111 }
112 return turn
113}
114
115// thread is the messages of the request's Coordinator thread, oldest
116// first.
117func (o *teamRig) thread(request string) []wire.Message {
118 o.t.Helper()
119 rows, err := o.inst.DB.Writer().Query("SELECT id, role, text, turn_id FROM chat_messages WHERE lane = ? ORDER BY seq", wire.JobLane(request))
120 if err != nil {
121 o.t.Fatal(err)
122 }
123 defer rows.Close()
124 var out []wire.Message
125 for rows.Next() {
126 var m wire.Message
127 if err := rows.Scan(&m.ID, &m.Role, &m.Text, &m.TurnID); err != nil {
128 o.t.Fatal(err)
129 }
130 out = append(out, m)
131 }
132 if err := rows.Err(); err != nil {
133 o.t.Fatal(err)
134 }
135 return out
136}
137
138// handedTexts are the person messages of every job thread, oldest first.
139func (o *teamRig) handedTexts() []string {
140 o.t.Helper()
141 rows, err := o.inst.DB.Writer().Query("SELECT text FROM chat_messages WHERE lane LIKE 'job:%' AND role = ? ORDER BY seq", wire.RolePerson)
142 if err != nil {
143 o.t.Fatal(err)
144 }
145 defer rows.Close()
146 var out []string
147 for rows.Next() {
148 var text string
149 if err := rows.Scan(&text); err != nil {
150 o.t.Fatal(err)
151 }
152 out = append(out, text)
153 }
154 if err := rows.Err(); err != nil {
155 o.t.Fatal(err)
156 }
157 return out
158}
159
160// threadQuestion is the open question card raised in the request's
161// thread: its id and revision.
162func (o *teamRig) threadQuestion(request string) (string, int64) {
163 o.t.Helper()
164 var id string
165 var revision int64
166 o.until("the thread's question card", func() bool {
167 err := o.inst.DB.Writer().QueryRow("SELECT id, revision FROM chat_cards WHERE lane = ? AND kind = ? AND state = ?", wire.JobLane(request), wire.CardQuestion, wire.CardOpen).Scan(&id, &revision)
168 return err == nil
169 })
170 return id, revision
171}
172
173// laneOf is the turn's lane.
174func (o *teamRig) laneOf(turn string) string {
175 o.t.Helper()
176 var lane string
177 if err := o.inst.DB.Writer().QueryRow("SELECT coalesce(lane, '') FROM chat_turns WHERE id = ?", turn).Scan(&lane); err != nil {
178 o.t.Fatal(err)
179 }
180 return lane
181}
182
183// in runs f with the rig's tool calls in turn.
184func (o *teamRig) in(turn string, f func()) {
185 o.t.Helper()
186 was, attempt := o.turn, o.attempt
187 o.turn, o.attempt = turn, 0
188 defer func() { o.turn, o.attempt = was, attempt }()
189 f()
190}
191
192// reply ends a turn with a reply.
193func (o *teamRig) reply(turn string) {
194 o.t.Helper()
195 o.seq++
196 if err := o.runner.Send(o.ctx, "r-reply-"+itoa(o.seq), wire.FrameReply, wire.Reply{TurnID: turn, Attempt: 1, Text: "Done."}); err != nil {
197 o.t.Fatal(err)
198 }
199 o.until("turn "+turn+" replied", func() bool {
200 return o.rows("SELECT count(*) FROM chat_turns WHERE id = ? AND state = ?", turn, wire.TurnReplied) == 1
201 })
202}
203
204// own is a Coordinator turn the person started in Equipo.
205func (o *teamRig) own(text string) string {
206 o.t.Helper()
207 sent, err := o.client.Send(o.ctx, text, "own-"+itoa(len(o.runner.Sent)))
208 if err != nil {
209 o.t.Fatal(err)
210 }
211 if cmd := o.message(wire.LaneCoordinator); cmd.TurnID != sent.Turn.ID {
212 o.t.Fatalf("the person's message went as %+v", cmd)
213 }
214 return sent.Turn.ID
215}
216
217// record records a task in the rig's turn.
218func (o *teamRig) record(key, title string) string {
219 o.t.Helper()
220 return taskID(o.t, o.call(key, wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": title, "brief": title, "separate": true}))
221}
222
223type teamSummary struct {
224 Request string `json:"request"`
225 Summary string `json:"summary"`
226}
227
228// status is team_status's requests.
229func (o *teamRig) status(id string, input map[string]any) []teamSummary {
230 o.t.Helper()
231 res := o.use(id, "team_status", input)
232 var out struct {
233 Requests []teamSummary `json:"requests"`
234 }
235 if res.IsError || json.Unmarshal([]byte(res.Text), &out) != nil || out.Requests == nil {
236 o.t.Fatalf("team_status %+v", res)
237 }
238 return out.Requests
239}
240
241// linked is the hand-off's tasks: task id to created.
242func (o *teamRig) linked(request string) map[string]bool {
243 o.t.Helper()
244 rows, err := o.inst.DB.Writer().Query("SELECT task_id, created FROM chat_handoff_tasks WHERE handoff_id = ?", request)
245 if err != nil {
246 o.t.Fatal(err)
247 }
248 defer rows.Close()
249 out := map[string]bool{}
250 for rows.Next() {
251 var id string
252 var created bool
253 if err := rows.Scan(&id, &created); err != nil {
254 o.t.Fatal(err)
255 }
256 out[id] = created
257 }
258 if err := rows.Err(); err != nil {
259 o.t.Fatal(err)
260 }
261 return out
262}
263
264// updates are the person's team_update turns, oldest first.
265func (o *teamRig) updates() (ids, notes []string, dispatched []bool) {
266 o.t.Helper()
267 rows, err := o.inst.DB.Writer().Query("SELECT id, coalesce(note, ''), dispatched FROM chat_turns WHERE kind = ? AND lane = ? ORDER BY created_at, id", wire.TurnTeamUpdate, wire.LaneAssistant)
268 if err != nil {
269 o.t.Fatal(err)
270 }
271 defer rows.Close()
272 for rows.Next() {
273 var id, note string
274 var d bool
275 if err := rows.Scan(&id, &note, &d); err != nil {
276 o.t.Fatal(err)
277 }
278 ids, notes, dispatched = append(ids, id), append(notes, note), append(dispatched, d)
279 }
280 if err := rows.Err(); err != nil {
281 o.t.Fatal(err)
282 }
283 return ids, notes, dispatched
284}
285
286// TestContractTeamRequest: team_request posts the person's words into
287// a Coordinator thread of the request's own (lane job:<request>) as
288// their message, with the Assistant's context beside it as marked
289// reference in the frame only, and links the Assistant turn, the message
290// and its turn. Their own conversation gets none of it.
291func TestContractTeamRequest(t *testing.T) {
292 o := newTeamRig(t)
293 turn := o.ask("Can we fix a bug in Tito? Login is broken")
294 request, cmd := o.handoff("tr1", "Login is broken", "They mean the Tito app")
295 lane := wire.JobLane(request)
296 if cmd.Lane != lane || cmd.Kind != wire.TurnPerson || len(cmd.PersonText) != 0 || !strings.HasPrefix(cmd.Text, "Login is broken") || !strings.HasSuffix(withoutProjectContext(t, cmd.Text), "[Reference from the Assistant, not the person's words: They mean the Tito app]") {
297 t.Fatalf("coordinator frame %+v", cmd)
298 }
299 thread := o.thread(request)
300 if len(thread) != 1 {
301 t.Fatalf("thread %+v", thread)
302 }
303 m := thread[0]
304 if m.Role != wire.RolePerson || m.Text != "Login is broken" || m.TurnID != cmd.TurnID || o.laneOf(cmd.TurnID) != lane {
305 t.Fatalf("thread message %+v", m)
306 }
307 if page, err := o.client.Messages(o.ctx, "", 50); err != nil || len(page.Items) != 0 {
308 t.Fatalf("their own conversation %+v %v", page, err)
309 }
310 if n := o.rows("SELECT count(*) FROM chat_handoffs h JOIN chat_handoff_turns ht ON ht.handoff_id = h.id WHERE h.id = ? AND h.person = ? AND h.assistant_turn = ? AND h.message_id = ? AND ht.turn_id = ? AND h.lane = ?", request, Owner, turn, m.ID, cmd.TurnID, lane); n != 1 {
311 t.Fatalf("%d hand-off rows link the turns", n)
312 }
313 // The Assistant's lane keeps only its own words.
314 if mine, err := o.a.Messages(o.ctx, "", 50); err != nil || len(mine.Items) != 1 || mine.Items[0].Text != "Can we fix a bug in Tito? Login is broken" {
315 t.Fatalf("assistant messages %+v %v", mine, err)
316 }
317 // Audited by its id alone, as the person.
318 if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.handoff' AND record_id = ? AND actor = ?", request, Owner); n != 1 {
319 t.Fatalf("%d hand-off audits", n)
320 }
321 // A hand-off's message key belongs to the instance.
322 if _, err := o.client.Send(o.ctx, "Login is broken", "handoff:"+request); Status(err) != 422 {
323 t.Fatalf("a client key in the instance's space: %v", err)
324 }
325}
326
327// TestContractTeamRequestTitle (D10): team_request's title names the
328// job: stored, returned and listed on /jobs. A title of more than 60
329// characters, or not one line, is refused and hands nothing over. With
330// none, the person's words name it, cut to 60 characters at a space.
331func TestContractTeamRequestTitle(t *testing.T) {
332 o := newTeamRig(t)
333 turn := o.ask("Can we fix a bug in Tito? Login is broken")
334 for i, title := range []string{strings.Repeat("a", 61), "Fixing the\nsign-in page", "Fixing the\tsign-in page", "Fixing the\x00 sign-in page", "Fixing the\u0085sign-in page", "Fixing the\x1bsign-in page", "Fixing the\u2028sign-in page", "Fixing the\u2029sign-in page"} {
335 if res := o.use("tt-bad"+itoa(i), "team_request", map[string]any{"words": "Login is broken", "title": title}); !res.IsError || res.Code != "invalid_input" {
336 t.Fatalf("title %q: %+v", title, res)
337 }
338 }
339 if n := o.rows("SELECT count(*) FROM chat_handoffs"); n != 0 || len(o.handedTexts()) != 0 {
340 t.Fatalf("%d hand-offs after bad titles, handed %v", n, o.handedTexts())
341 }
342 res := o.use("tt1", "team_request", map[string]any{"words": "Login is broken", "title": "Fixing the sign-in page"})
343 var out struct{ Request, Status, Title string }
344 if res.IsError || json.Unmarshal([]byte(res.Text), &out) != nil || out.Request == "" || out.Status != "sent" || out.Title != "Fixing the sign-in page" {
345 t.Fatalf("team_request %+v", res)
346 }
347 o.message(wire.JobLane(out.Request))
348 if again := o.use("tt1-again", "team_request", map[string]any{"words": "Login is broken", "title": "Fixing the sign-in page"}); !again.Replayed || again.Text != res.Text {
349 t.Fatalf("replayed %+v", again)
350 }
351 if n := o.rows("SELECT count(*) FROM chat_handoffs WHERE id = ? AND title = ?", out.Request, "Fixing the sign-in page"); n != 1 {
352 t.Fatal("the title is not stored")
353 }
354 o.reply(turn)
355
356 words := "Checkout is slow when I pay with a card on my phone at the weekend"
357 o.ask(words)
358 untitled := o.request("tt2", map[string]any{"words": words})
359 o.message(wire.JobLane(untitled))
360 fallback := "Checkout is slow when I pay with a card on my phone at the…"
361 if n := o.rows("SELECT count(*) FROM chat_handoffs WHERE id = ? AND title = ?", untitled, fallback); n != 1 {
362 t.Fatal("an untitled request is not named by the person's words")
363 }
364
365 list := html.UnescapeString(o.get(o.inst.Cookie(), "/jobs", http.StatusOK))
366 for request, title := range map[string]string{out.Request: "Fixing the sign-in page", untitled: fallback} {
367 if !strings.Contains(list, `href="/jobs/`+request+`">`+title+`</a>`) {
368 t.Fatalf("/jobs lacks %s titled %q: %.900s", request, title, list)
369 }
370 }
371 if strings.Contains(list, "Login is broken") {
372 t.Fatal("/jobs lists the words of a titled job")
373 }
374}
375
376// TestContractTeamRequestNotTheirWords: words the person's messages in
377// the turn do not contain are refused and post nothing; a quote differing
378// only in case and spacing posts the person's own words. A team_update
379// turn has no words of the person's to hand over.
380func TestContractTeamRequestNotTheirWords(t *testing.T) {
381 o := newTeamRig(t)
382 o.ask("Can we fix a bug in Tito? Login is broken")
383 for i, words := range []string{"Checkout is slow", "lo", "Login is broken and so is checkout", " "} {
384 if res := o.use("nw"+itoa(i), "team_request", map[string]any{"words": words}); !res.IsError || res.Code != "not_their_words" {
385 t.Fatalf("words %q: %+v", words, res)
386 }
387 }
388 if n := o.rows("SELECT count(*) FROM chat_handoffs"); n != 0 || len(o.handedTexts()) != 0 {
389 t.Fatalf("%d hand-offs, handed %v", n, o.handedTexts())
390 }
391 _, cmd := o.handoff("nw-ok", "LOGIN is \n broken", "")
392 if len(cmd.PersonText) != 0 || withoutProjectContext(t, cmd.Text) != "Login is broken" || !slices.Equal(o.handedTexts(), []string{"Login is broken"}) {
393 t.Fatalf("quoted %+v, messages %v", cmd, o.handedTexts())
394 }
395 update := o.updateTurn(cmd)
396 o.in(update, func() {
397 if res := o.use("nw-update", "team_request", map[string]any{"words": "Login is broken"}); !res.IsError || res.Code != "not_asked" {
398 t.Fatalf("team_request in a team_update turn %+v", res)
399 }
400 })
401 if n := o.rows("SELECT count(*) FROM chat_handoffs"); n != 1 || len(o.handedTexts()) != 1 {
402 t.Fatalf("%d hand-offs after the update, handed %v", n, o.handedTexts())
403 }
404}
405
406// updateTurn takes a hand-off's Coordinator turn to a recorded task the
407// person then cancels in Equipo, ends the Assistant turn, and returns
408// the team_update turn that follows, dispatched.
409func (o *teamRig) updateTurn(cmd *wire.MessageCommand) string {
410 o.t.Helper()
411 var id string
412 o.in(cmd.TurnID, func() { id = o.record("up-rec", "Fix the login") })
413 o.reply(cmd.TurnID)
414 o.reply(o.turn)
415 if _, err := o.client.CancelTask(o.ctx, id); err != nil {
416 o.t.Fatal(err)
417 }
418 u := o.message(wire.LaneAssistant)
419 if u.Kind != wire.TurnTeamUpdate {
420 o.t.Fatalf("update frame %+v", u)
421 }
422 return u.TurnID
423}
424
425// TestContractTeamRequestOnce: a retry under another call id, worded
426// otherwise around the same words, or in attempt 2 is the one request.
427func TestContractTeamRequestOnce(t *testing.T) {
428 o := newTeamRig(t)
429 turn := o.ask("Can we fix a bug in Tito? Login is broken")
430 in := map[string]any{"words": "Login is broken", "context": "They mean the Tito app"}
431 request, _ := o.handoff("o1", "Login is broken", "They mean the Tito app")
432 if again := o.use("o2", "team_request", in); again.IsError || !again.Replayed || !strings.Contains(again.Text, request) {
433 t.Fatalf("again %+v", again)
434 }
435 if other := o.request("o3", map[string]any{"words": "login is broken", "context": "The Tito app, they said"}); other != request {
436 t.Fatalf("reworded retry is %s, not %s", other, request)
437 }
438 o.runner.Send(o.ctx, "r-wait", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnWaiting, Reason: "limited"})
439 o.runner.Send(o.ctx, "r-run2", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 2, State: wire.TurnRunning})
440 o.until("attempt 2", func() bool {
441 return o.rows("SELECT count(*) FROM chat_turns WHERE id = ? AND attempt = 2 AND state = ?", turn, wire.TurnRunning) == 1
442 })
443 o.attempt = 2
444 if moved := o.request("o4", in); moved != request {
445 t.Fatalf("attempt 2 is %s", moved)
446 }
447 if n := o.rows("SELECT count(*) FROM chat_handoffs"); n != 1 || !slices.Equal(o.handedTexts(), []string{"Login is broken"}) {
448 t.Fatalf("%d hand-offs, handed %v", n, o.handedTexts())
449 }
450 if n := o.rows("SELECT count(*) FROM runner_commands WHERE kind = ? AND body NOT LIKE ?", wire.FrameMessage, `%"lane":"assistant"%`); n != 1 {
451 t.Fatalf("%d coordinator message commands", n)
452 }
453}
454
455// TestContractHandoffFollowsTasks: the hand-off follows the tasks its
456// turn records (created) or joins (touched), and those of the turn that
457// carries the answer to its question; work the person started in Equipo
458// is linked to nothing.
459func TestContractHandoffFollowsTasks(t *testing.T) {
460 o := newTeamRig(t)
461 mine := o.own("Two things of my own.")
462 var joined, untouched string
463 o.in(mine, func() {
464 joined = o.record("f-own1", "Dark mode for settings")
465 untouched = o.record("f-own2", "Export to CSV")
466 })
467 o.reply(mine)
468
469 o.ask("Can we fix a bug in Tito? Login is broken")
470 request, cmd := o.handoff("f1", "Login is broken", "")
471 var created string
472 o.in(cmd.TurnID, func() {
473 created = o.record("f-rec", "Fix the login")
474 if res := o.call("f-rep", wire.ToolAddReport, map[string]string{"task": joined, "text": "Login is broken too."}); res.IsError {
475 t.Fatalf("add_report %+v", res)
476 }
477 if res := o.call("f-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" {
478 t.Fatalf("ask %+v", res)
479 }
480 })
481 o.reply(cmd.TurnID)
482 card, revision := o.threadQuestion(request)
483 ans, err := o.client.Answer(o.ctx, card, "Web", revision)
484 if err != nil {
485 t.Fatal(err)
486 }
487 if next := o.message(wire.JobLane(request)); next.TurnID != ans.Turn.ID {
488 t.Fatalf("answer frame %+v", next)
489 }
490 var later string
491 o.in(ans.Turn.ID, func() { later = o.record("f-later", "Fix the web login page") })
492 o.reply(ans.Turn.ID)
493
494 // Then the person's own new work, in Equipo.
495 again := o.own("One more of my own.")
496 var own string
497 o.in(again, func() { own = o.record("f-own3", "Bigger buttons") })
498
499 got := o.linked(request)
500 want := map[string]bool{created: true, joined: false, later: true}
501 if len(got) != len(want) {
502 t.Fatalf("linked %v, want %v", got, want)
503 }
504 for id, c := range want {
505 if v, ok := got[id]; !ok || v != c {
506 t.Fatalf("linked %v, want %v", got, want)
507 }
508 }
509 for _, id := range []string{untouched, own} {
510 if n := o.rows("SELECT count(*) FROM chat_handoff_tasks WHERE task_id = ?", id); n != 0 {
511 t.Fatalf("the person's own task %s is linked", id)
512 }
513 }
514 // The answer's turn is the request's by its thread.
515 if n := o.rows("SELECT count(*) FROM chat_handoff_turns WHERE handoff_id = ? AND turn_id = ?", request, cmd.TurnID); n != 1 || o.laneOf(ans.Turn.ID) != wire.JobLane(request) {
516 t.Fatalf("%d hand-off turns, the answer's in %q", n, o.laneOf(ans.Turn.ID))
517 }
518}
519
520// TestContractTeamStatus: the summary says where the work is in plain
521// words, with each finding's headline, the preview link while it is up
522// and the published address once there is one, and nothing of the
523// team's machinery. all adds the person's own open work.
524func TestContractTeamStatus(t *testing.T) {
525 o := newTeamRigAt(t, wire.ProtocolCurrent)
526 o.sitesOn(wire.ProtocolCurrent, true)
527 o.ask("Can we fix a bug in Tito? Login is broken")
528 request, cmd := o.handoff("s1", "Login is broken", "")
529 // A read runs again on each call, in the same words as before.
530 if got := o.status("s-none", map[string]any{}); len(got) != 1 || got[0].Request != request || got[0].Summary != equipo.RunnerCopy("assistant.team.received") {
531 t.Fatalf("before any task %+v", got)
532 }
533 base, cand, merged := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("e", 40)
534 var id string
535 o.in(cmd.TurnID, func() {
536 id, _ = o.websiteReady("w", "Quick website", base, cand, true)
537 if res := o.call("s-find", wire.ToolAddFinding, map[string]any{"task": id, "headline": "The sign in button posts to the old address.", "text": "login.js posts to /v1/login.", "repo": "oficina/sample", "path": "login.js", "line": 3}); res.IsError {
538 t.Fatalf("finding %+v", res)
539 }
540 })
541 k, err := o.client.Task(o.ctx, id)
542 if err != nil {
543 t.Fatal(err)
544 }
545 machinery := func(summary string, preview string) {
546 t.Helper()
547 bare := strings.ReplaceAll(summary, preview, "")
548 for _, bad := range []string{id, "amadan.net/oficina/sample", k.Branch, base, cand, merged, "/tasks/"} {
549 if strings.Contains(bare, bad) {
550 t.Fatalf("the summary says %q: %s", bad, summary)
551 }
552 }
553 if regexp.MustCompile(`[0-9a-f]{40}`).MatchString(bare) {
554 t.Fatalf("a SHA in the summary: %s", summary)
555 }
556 }
557 one := func(key string) string {
558 t.Helper()
559 got := o.status("s-"+key, map[string]any{"request": request})
560 if len(got) != 1 || got[0].Request != request {
561 t.Fatalf("status %+v", got)
562 }
563 return got[0].Summary
564 }
565 ready := one("ready")
566 if !strings.Contains(ready, equipo.RunnerCopy("assistant.team.stage.ready_to_merge")) || !strings.Contains(ready, "The sign in button posts to the old address.") || strings.Contains(ready, "https://") {
567 t.Fatalf("ready %q", ready)
568 }
569 machinery(ready, "")
570
571 pv := o.previewDispatch(cand)
572 if pv == nil {
573 t.Fatal("no preview")
574 }
575 o.built("s-pv-built", pv, digestA)
576 link := "https://eq-" + id + ".docs-t1.example.ts.net/"
577 o.previewDone("s-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, Outcome: wire.PreviewDeployed})
578 link = o.inst.URL + "/tasks/" + id + "/preview"
579 previewed := one("preview")
580 if !strings.Contains(previewed, strings.ReplaceAll(equipo.RunnerCopy("assistant.team.preview"), "%s", link)) {
581 t.Fatalf("with the preview %q", previewed)
582 }
583 machinery(previewed, link)
584
585 o.mergeFromCard("s-m", id, base, cand, merged)
586 pub, ok := o.publishCard(id)
587 if !ok {
588 t.Fatal("no publish card")
589 }
590 if _, err := o.client.Answer(o.ctx, pub.ID, wire.ChoicePublish, pub.Revision); err != nil {
591 t.Fatal(err)
592 }
593 d := o.publishDispatch()
594 o.publishReport("s-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40})
595 site := "https://" + d.Publish.App + ".bds.oncarlos.com/"
596 o.publishReport("s-done", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: d.Publish.App, URL: site, Digest: digestA, Outcome: wire.PublishPublished, DeployHeld: true})
597 live := one("live")
598 if !strings.Contains(live, equipo.RunnerCopy("assistant.team.stage.done")) || !strings.Contains(live, strings.ReplaceAll(equipo.RunnerCopy("assistant.team.published"), "%s", site)) || strings.Contains(live, link) {
599 t.Fatalf("published %q", live)
600 }
601 machinery(live, "")
602 o.reply(cmd.TurnID)
603
604 // The person's own open work is in Equipo: only all reports it.
605 mine := o.own("Something of my own.")
606 o.in(mine, func() { o.record("s-own", "Dark mode for settings") })
607 if got := o.status("s-requests", map[string]any{}); len(got) != 1 || got[0].Request != request {
608 t.Fatalf("requests %+v", got)
609 }
610 all := o.status("s-all", map[string]any{"all": true})
611 if len(all) != 2 || all[0].Request != request || all[1].Request != "" || !strings.Contains(all[1].Summary, "Dark mode for settings") || !strings.Contains(all[1].Summary, equipo.RunnerCopy("assistant.team.stage.noted")) {
612 t.Fatalf("all %+v", all)
613 }
614 if res := o.use("s-missing", "team_status", map[string]any{"request": "h_missing"}); !res.IsError || res.Code != "not_found" {
615 t.Fatalf("an unknown request %+v", res)
616 }
617}
618
619// TestContractTeamCancel: team_cancel cancels the tasks the request
620// created and none it joined; another person's request is not found.
621func TestContractTeamCancel(t *testing.T) {
622 o := newTeamRig(t)
623 mine := o.own("Something of my own.")
624 var joined string
625 o.in(mine, func() { joined = o.record("c-own", "Dark mode for settings") })
626 o.reply(mine)
627 o.ask("Can we fix a bug in Tito? Login is broken")
628 request, cmd := o.handoff("c1", "Login is broken", "")
629 var created string
630 o.in(cmd.TurnID, func() {
631 created = o.record("c-rec", "Fix the login")
632 if res := o.call("c-rep", wire.ToolAddReport, map[string]string{"task": joined, "text": "Login is broken too."}); res.IsError {
633 t.Fatalf("add_report %+v", res)
634 }
635 })
636 o.reply(cmd.TurnID)
637
638 // Another owner cannot see or cancel it.
639 mate := &teamRig{o.other("mate@example.com")}
640 mate.ask("Cancel that, Login is broken")
641 for _, op := range []string{"team_cancel", "team_status"} {
642 if res := mate.use("c-mate-"+op, op, map[string]any{"request": request}); !res.IsError || res.Code != "not_found" {
643 t.Fatalf("%s for another person's request %+v", op, res)
644 }
645 }
646
647 // Read, cancel, read: in the same words, the second read sees the
648 // cancel. A delivery retry of a call (its id) gets what it got.
649 read := map[string]any{"request": request}
650 before := o.status("c-read1", read)
651 res := o.use("c-cancel", "team_cancel", map[string]any{"request": request})
652 if res.IsError || res.Text != `{"cancelled":1,"still_running":0}` {
653 t.Fatalf("cancel %+v", res)
654 }
655 after := o.use("c-read2", "team_status", read)
656 if after.IsError || after.Replayed || len(before) != 1 || strings.Contains(before[0].Summary, equipo.RunnerCopy("assistant.team.stage.cancelled")) || !strings.Contains(after.Text, equipo.RunnerCopy("assistant.team.stage.cancelled")) {
657 t.Fatalf("read before the cancel %+v, after %+v", before, after)
658 }
659 audits := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.use'")
660 if retry := o.use("c-read2", "team_status", read); retry.Text != after.Text || retry.IsError {
661 t.Fatalf("delivery retry %+v, first %+v", retry, after)
662 }
663 if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.use'"); n != audits {
664 t.Fatalf("a delivery retry ran again: %d audits, %d before", n, audits)
665 }
666 for id, stage := range map[string]string{created: wire.StageCancelled, joined: wire.StageNoted} {
667 if k, err := o.client.Task(o.ctx, id); err != nil || k.Stage != stage {
668 t.Fatalf("task %s at %s %v", id, k.Stage, err)
669 }
670 }
671 if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.team_cancel' AND record_id = ? AND actor = ?", request, Owner); n != 1 {
672 t.Fatalf("%d cancel audits", n)
673 }
674 // Asked again in the turn, it answers as it did and cancels nothing more.
675 if again := o.use("c-again", "team_cancel", map[string]any{"request": request}); again.IsError || !again.Replayed || again.Text != res.Text {
676 t.Fatalf("again %+v", again)
677 }
678 if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.team_cancel'"); n != 1 {
679 t.Fatalf("%d cancel audits after the retry", n)
680 }
681}
682
683// TestContractTeamUpdate: when the hand-off's work stops, is cancelled
684// or is done, one team_update turn is queued with the job's note as its
685// text (where it stands is the summary; cancelled work is never done); a
686// change while it waits rewrites it; a change that leaves the note as it
687// was queues nothing.
688// That turn only looks and tells.
689func TestContractTeamUpdate(t *testing.T) {
690 o := newTeamRig(t)
691 o.ask("Can we fix a bug in Tito? Login is broken")
692 request, cmd := o.handoff("u1", "Login is broken", "")
693 var id string
694 o.in(cmd.TurnID, func() {
695 id = o.record("u-rec", "Fix the login")
696 if res := o.call("u-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}); res.IsError {
697 t.Fatalf("start %+v", res)
698 }
699 _, body := o.expect(wire.FrameDispatch)
700 d := body.(*wire.DispatchCommand)
701 o.step("u-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: strings.Repeat("1", 40)})
702 if ids, _, _ := o.updates(); len(ids) != 0 {
703 t.Fatalf("an update while the work runs: %v", ids)
704 }
705 o.step("u-fail", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true})
706 })
707 o.reply(cmd.TurnID)
708 // The Assistant's turn still runs: the update waits behind it.
709 ids, notes, dispatched := o.updates()
710 if len(ids) != 1 || dispatched[0] || !strings.Contains(notes[0], equipo.RunnerCopy("assistant.team.stopped")) || !strings.Contains(notes[0], "A step of it failed and can be tried again.") {
711 t.Fatalf("after the failure %v %q %v", ids, notes, dispatched)
712 }
713 if _, err := o.client.CancelTask(o.ctx, id); err != nil {
714 t.Fatal(err)
715 }
716 summary := o.status("u-status", map[string]any{"request": request})[0].Summary
717 again, notes, dispatched := o.updates()
718 // Every followed task cancelled is not done (D5): the Assistant hears
719 // it was cancelled, and speaks only if the person did not cancel it.
720 cancelled := jobLine("Login is broken", request, "Login is broken") + "It was cancelled before it was finished. If the person cancelled it themselves, say nothing; otherwise tell them in one short line that it was cancelled.\nWhere it stands:\n" + summary
721 if !slices.Equal(again, ids) || dispatched[0] || notes[0] != cancelled || !strings.Contains(summary, equipo.RunnerCopy("assistant.team.stage.cancelled")) {
722 t.Fatalf("after the cancel %v %q %v (summary %q)", again, notes, dispatched, summary)
723 }
724 o.reply(o.turn)
725 u := o.message(wire.LaneAssistant)
726 if u.TurnID != ids[0] || u.Kind != wire.TurnTeamUpdate || u.Text != notes[0] || len(u.PersonText) != 0 {
727 t.Fatalf("update frame %+v", u)
728 }
729 o.in(u.TurnID, func() {
730 for _, op := range []string{"team_request", "team_cancel"} {
731 if res := o.use("u-"+op, op, map[string]any{"words": "Login is broken", "request": request}); !res.IsError || res.Code != "not_asked" {
732 t.Fatalf("%s in the update %+v", op, res)
733 }
734 }
735 if got := o.status("u-look", map[string]any{"request": request}); len(got) != 1 {
736 t.Fatalf("status in the update %+v", got)
737 }
738 for _, tool := range []string{wire.ToolAskPerson, wire.ToolWriteNote} {
739 if res := o.call("u-"+tool, tool, map[string]any{}); !res.IsError || res.Code != "unknown_tool" {
740 t.Fatalf("%s in the update %+v", tool, res)
741 }
742 }
743 })
744 o.reply(u.TurnID)
745 // A note on the thread changes the task, not what the person is told.
746 if _, err := o.client.PostThread(o.ctx, id, "For the record.", "n1"); err != nil {
747 t.Fatal(err)
748 }
749 time.Sleep(50 * time.Millisecond)
750 if after, _, _ := o.updates(); len(after) != 1 {
751 t.Fatalf("updates after an equal summary %v", after)
752 }
753}
754
755// TestContractHandoffTurnIsItsOwn: while the person's own conversation
756// is busy, the hand-off's words go at once in a turn of their own, in
757// the request's thread: they join no batch of the person's, and nothing
758// the person sends later joins theirs.
759func TestContractHandoffTurnIsItsOwn(t *testing.T) {
760 o := newTeamRig(t)
761 busy := o.own("Something of my own.")
762 queued, err := o.client.Send(o.ctx, "And a second thing.", "own-queued")
763 if err != nil || queued.Turn.ID == busy {
764 t.Fatalf("queued %+v %v", queued, err)
765 }
766 o.ask("Can we fix a bug in Tito? Login is broken")
767 request := o.request("b1", map[string]any{"words": "Login is broken"})
768 turn := o.handoffTurn(request)
769 if turn == queued.Turn.ID || turn == busy || o.laneOf(turn) != wire.JobLane(request) {
770 t.Fatalf("the hand-off's turn %q in %q (queued %s)", turn, o.laneOf(turn), queued.Turn.ID)
771 }
772 if cmd := o.message(wire.JobLane(request)); cmd.TurnID != turn {
773 t.Fatalf("the hand-off's frame %+v", cmd)
774 }
775 later, err := o.client.Send(o.ctx, "And a third thing.", "own-later")
776 if err != nil || later.Turn.ID != queued.Turn.ID {
777 t.Fatalf("later %+v %v", later.Turn, err)
778 }
779 if n := o.rows("SELECT count(*) FROM chat_messages WHERE turn_id = ?", turn); n != 1 {
780 t.Fatalf("%d messages in the hand-off's turn", n)
781 }
782}
783
784// TestContractHandoffAnswerTurnIsItsOwn: the answer to a hand-off's
785// question, sent while its thread is busy, waits in the thread and joins
786// none of the person's own work: that work stays theirs, and team_cancel
787// cannot reach what it records.
788func TestContractHandoffAnswerTurnIsItsOwn(t *testing.T) {
789 o := newTeamRig(t)
790 o.ask("Can we fix a bug in Tito? Login is broken")
791 request, cmd := o.handoff("aq1", "Login is broken", "")
792 o.in(cmd.TurnID, func() {
793 if res := o.call("aq-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" {
794 t.Fatalf("ask %+v", res)
795 }
796 })
797 // The hand-off's turn still runs; the person's own work goes at once.
798 mine, err := o.client.Send(o.ctx, "Export to CSV, please.", "own-mine")
799 if err != nil || mine.Turn.ID == cmd.TurnID {
800 t.Fatalf("mine %+v %v", mine.Turn, err)
801 }
802 if next := o.message(wire.LaneCoordinator); next.TurnID != mine.Turn.ID {
803 t.Fatalf("their own frame %+v", next)
804 }
805 card, revision := o.threadQuestion(request)
806 ans, err := o.client.Answer(o.ctx, card, "Web", revision)
807 if err != nil {
808 t.Fatal(err)
809 }
810 if ans.Turn.ID == mine.Turn.ID || ans.Turn.State != wire.TurnQueued || o.laneOf(ans.Turn.ID) != wire.JobLane(request) {
811 t.Fatalf("the answer's turn %+v in %q", ans.Turn, o.laneOf(ans.Turn.ID))
812 }
813 if n := o.rows("SELECT count(*) FROM chat_handoff_turns WHERE turn_id = ?", mine.Turn.ID); n != 0 {
814 t.Fatal("the person's own turn is the hand-off's")
815 }
816 o.reply(cmd.TurnID)
817 if next := o.message(wire.JobLane(request)); next.TurnID != ans.Turn.ID {
818 t.Fatalf("next frame %+v", next)
819 }
820 var own string
821 o.in(mine.Turn.ID, func() { own = o.record("aq-own", "Export to CSV") })
822 if n := o.rows("SELECT count(*) FROM chat_handoff_tasks WHERE task_id = ?", own); n != 0 {
823 t.Fatalf("the person's own task %s is linked", own)
824 }
825}
826
827// TestContractTeamCancelWhileMerging: a task the request created that is
828// merging cannot be cancelled; team_cancel says it is still running and
829// the request stays followed, so its end is still told.
830func TestContractTeamCancelWhileMerging(t *testing.T) {
831 o := newTeamRig(t)
832 o.ask("Can we fix a bug in Tito? Login is broken")
833 request, cmd := o.handoff("cm1", "Login is broken", "")
834 base, cand, merged := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("e", 40)
835 var id string
836 o.in(cmd.TurnID, func() { id, _ = o.websiteReady("cm", "Quick website", base, cand, false) })
837 card := o.cardOf(id)
838 if _, err := o.client.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil {
839 t.Fatalf("merge %v", err)
840 }
841 m := o.dispatched(wire.SpecialistMerge, base, cand, 0)
842 res := o.use("cm-cancel", "team_cancel", map[string]any{"request": request})
843 if res.IsError || res.Text != `{"cancelled":0,"still_running":1}` {
844 t.Fatalf("cancel while merging %+v", res)
845 }
846 // Cancelled while its work goes on: followed (stopping) until it ends.
847 if n := o.rows("SELECT count(*) FROM chat_handoffs WHERE id = ? AND state = 'stopping'", request); n != 1 {
848 t.Fatal("the request stopped being followed")
849 }
850 if got := o.status("cm-status", map[string]any{}); len(got) != 1 || got[0].Request != request {
851 t.Fatalf("open requests %+v", got)
852 }
853 // Its turns start no new work while it is followed.
854 o.in(cmd.TurnID, func() {
855 if res := o.call("cm-late", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Fix the login", "brief": "Fix the login", "separate": true}); !res.IsError || res.Code != "request_cancelled" {
856 t.Fatalf("record_task while stopping %+v", res)
857 }
858 })
859 o.mergedStep("cm-m", m, merged)
860 o.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone })
861 if ids, notes, _ := o.updates(); len(ids) != 1 || !strings.Contains(notes[0], equipo.RunnerCopy("assistant.team.stage.done")) {
862 t.Fatalf("updates after the merge %v %q", ids, notes)
863 }
864}
865
866// commandsFor counts the runner commands of kind that name the turn.
867func (o *teamRig) commandsFor(kind, turn string) int {
868 o.t.Helper()
869 return o.rows("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", kind, `%"turn_id":"`+turn+`"%`)
870}
871
872// turnState is the turn's state.
873func (o *teamRig) turnState(turn string) string {
874 o.t.Helper()
875 var s string
876 if err := o.inst.DB.Writer().QueryRow("SELECT state FROM chat_turns WHERE id = ?", turn).Scan(&s); err != nil {
877 o.t.Fatal(err)
878 }
879 return s
880}
881
882// TestContractTeamCancelStopsQueuedTurn: a request cancelled while a
883// turn of its thread still waits behind another ends that turn: it never
884// runs, and the person is told nothing more. The waiting turn here
885// carries the answer the person gave in Equipo to the thread's question.
886func TestContractTeamCancelStopsQueuedTurn(t *testing.T) {
887 o := newTeamRig(t)
888 o.ask("Can we fix a bug in Tito? Login is broken")
889 request, cmd := o.handoff("cq1", "Login is broken", "")
890 o.in(cmd.TurnID, func() {
891 if res := o.call("cq-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" {
892 t.Fatalf("ask %+v", res)
893 }
894 })
895 card, revision := o.threadQuestion(request)
896 ans, err := o.client.Answer(o.ctx, card, "Web", revision)
897 if err != nil {
898 t.Fatal(err)
899 }
900 turn := ans.Turn.ID
901 if s := o.turnState(turn); s != wire.TurnQueued || o.laneOf(turn) != wire.JobLane(request) {
902 t.Fatalf("the answer's turn is %s in %q", s, o.laneOf(turn))
903 }
904 told, notes, _ := o.updates()
905 res := o.use("cq-cancel", "team_cancel", map[string]any{"request": request})
906 if res.IsError || res.Text != `{"cancelled":0,"still_running":0}` {
907 t.Fatalf("cancel %+v", res)
908 }
909 if s := o.turnState(turn); s != wire.TurnCancelled {
910 t.Fatalf("after the cancel the answer's turn is %s", s)
911 }
912 if n := o.commandsFor(wire.FrameCancel, cmd.TurnID); n != 1 {
913 t.Fatalf("%d cancel commands for the running turn", n)
914 }
915 o.runner.Send(o.ctx, "r-cq-end", wire.FrameTurn, wire.TurnReport{TurnID: cmd.TurnID, Attempt: 1, State: wire.TurnCancelled})
916 o.until("the running turn ended", func() bool { return o.turnState(cmd.TurnID) == wire.TurnCancelled })
917 // The person's next message runs; the answer never does.
918 next, err := o.client.Send(o.ctx, "And another thing.", "own-next")
919 if err != nil {
920 t.Fatal(err)
921 }
922 if cmd := o.message(wire.LaneCoordinator); cmd.TurnID != next.Turn.ID {
923 t.Fatalf("next coordinator frame %+v", cmd)
924 }
925 if n := o.commandsFor(wire.FrameMessage, turn); n != 0 {
926 t.Fatalf("the cancelled answer's turn went to the runner %d times", n)
927 }
928 // Told of the question before the cancel; nothing after it.
929 if ids, after, _ := o.updates(); !slices.Equal(ids, told) || !slices.Equal(after, notes) {
930 t.Fatalf("updates after the cancel %v %q, before %v %q", ids, after, told, notes)
931 }
932}
933
934// TestContractTeamCancelStopsRunningTurn: a request cancelled while its
935// Coordinator turn runs asks the runner to end the turn; until it ends,
936// the turn can create or start no work (record_task, start_task on a task
937// the request follows), and the person is told nothing more.
938func TestContractTeamCancelStopsRunningTurn(t *testing.T) {
939 o := newTeamRig(t)
940 mine := o.own("Something of my own.")
941 var joined string
942 o.in(mine, func() { joined = o.record("cr-own", "Dark mode for settings") })
943 o.reply(mine)
944 o.ask("Can we fix a bug in Tito? Login is broken")
945 request, cmd := o.handoff("cr1", "Login is broken", "")
946 o.in(cmd.TurnID, func() {
947 if res := o.call("cr-rep", wire.ToolAddReport, map[string]string{"task": joined, "text": "Login is broken too."}); res.IsError {
948 t.Fatalf("add_report %+v", res)
949 }
950 })
951 res := o.use("cr-cancel", "team_cancel", map[string]any{"request": request})
952 if res.IsError || res.Text != `{"cancelled":0,"still_running":0}` {
953 t.Fatalf("cancel %+v", res)
954 }
955 if n := o.commandsFor(wire.FrameCancel, cmd.TurnID); n != 1 {
956 t.Fatalf("%d cancel commands for the hand-off's turn", n)
957 }
958 tasks := o.rows("SELECT count(*) FROM chat_tasks")
959 o.in(cmd.TurnID, func() {
960 late := o.call("cr-late", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Fix the login", "brief": "Fix the login", "separate": true})
961 if !late.IsError || late.Code != "request_cancelled" {
962 t.Fatalf("record_task after the cancel %+v", late)
963 }
964 start := o.call("cr-start", wire.ToolStartTask, map[string]string{"task": joined})
965 if !start.IsError || start.Code != "request_cancelled" {
966 t.Fatalf("start_task after the cancel %+v", start)
967 }
968 if res := o.call("cr-read", wire.ToolReadTask, map[string]string{"task": joined}); res.IsError {
969 t.Fatalf("read_task after the cancel %+v", res)
970 }
971 if res := o.call("cr-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" {
972 t.Fatalf("ask %+v", res)
973 }
974 })
975 if n := o.rows("SELECT count(*) FROM chat_tasks"); n != tasks {
976 t.Fatalf("%d tasks after the cancel, %d before", n, tasks)
977 }
978 if n := o.rows("SELECT count(*) FROM chat_steps WHERE task_id = ?", joined); n != 0 {
979 t.Fatalf("the followed task started after the cancel: %d steps", n)
980 }
981 if got := o.linked(request); len(got) != 1 || got[joined] {
982 t.Fatalf("linked after the cancel %v", got)
983 }
984 o.runner.Send(o.ctx, "r-cr-end", wire.FrameTurn, wire.TurnReport{TurnID: cmd.TurnID, Attempt: 1, State: wire.TurnCancelled})
985 o.until("the turn ended", func() bool { return o.turnState(cmd.TurnID) == wire.TurnCancelled })
986 if ids, _, _ := o.updates(); len(ids) != 0 {
987 t.Fatalf("updates after the cancel %v", ids)
988 }
989 if cards := o.assistantCards(); len(cards) != 0 {
990 t.Fatalf("assistant cards after the cancel %+v", cards)
991 }
992 if n := o.rows("SELECT count(*) FROM chat_handoffs WHERE id = ? AND state = 'cancelled'", request); n != 1 {
993 t.Fatal("the request is not cancelled")
994 }
995 // The person's own turn is not the request's: it still records work.
996 again := o.own("One more of my own.")
997 o.in(again, func() { o.record("cr-own2", "Bigger buttons") })
998}
999
1000// TestContractTeamCancelStopsAnswerTurn: a request cancelled while the
1001// turn carrying the answer to its question waits in its thread ends
1002// that turn too.
1003func TestContractTeamCancelStopsAnswerTurn(t *testing.T) {
1004 o := newTeamRig(t)
1005 o.ask("Can we fix a bug in Tito? Login is broken")
1006 request, cmd := o.handoff("ca1", "Login is broken", "")
1007 o.in(cmd.TurnID, func() {
1008 if res := o.call("ca-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" {
1009 t.Fatalf("ask %+v", res)
1010 }
1011 })
1012 card, revision := o.threadQuestion(request)
1013 if _, err := o.client.Answer(o.ctx, card, "Web", revision); err != nil {
1014 t.Fatal(err)
1015 }
1016 var answer string
1017 if err := o.inst.DB.Writer().QueryRow("SELECT id FROM chat_turns WHERE lane = ? AND id <> ?", wire.JobLane(request), cmd.TurnID).Scan(&answer); err != nil {
1018 t.Fatal(err)
1019 }
1020 if s := o.turnState(answer); s != wire.TurnQueued {
1021 t.Fatalf("the answer's turn is %s", s)
1022 }
1023 res := o.use("ca-cancel", "team_cancel", map[string]any{"request": request})
1024 if res.IsError || res.Text != `{"cancelled":0,"still_running":0}` {
1025 t.Fatalf("cancel %+v", res)
1026 }
1027 if s := o.turnState(answer); s != wire.TurnCancelled {
1028 t.Fatalf("after the cancel the answer's turn is %s", s)
1029 }
1030 o.reply(cmd.TurnID)
1031 time.Sleep(50 * time.Millisecond)
1032 if n := o.commandsFor(wire.FrameMessage, answer); n != 0 {
1033 t.Fatalf("the cancelled answer's turn went to the runner %d times", n)
1034 }
1035}
1036
1037// TestContractHandoffTurnFails: a hand-off whose Coordinator turn fails
1038// before it records or joins any work has stopped with no work: the
1039// Assistant is told once, to push it through itself, and team_status
1040// says it stopped. A turn found gone when the runner reconnects has
1041// failed the same way.
1042func TestContractHandoffTurnFails(t *testing.T) {
1043 stopped := equipo.RunnerCopy("assistant.team.stopped")
1044 check := func(o *teamRig, request string) {
1045 t.Helper()
1046 o.until("the update", func() bool { ids, _, _ := o.updates(); return len(ids) == 1 })
1047 want := jobLine("Login is broken", request, "Login is broken") + noWork(request, 2) + "\nWhere it stands:\n" + stopped
1048 if _, notes, _ := o.updates(); notes[0] != want {
1049 t.Fatalf("update %q, want %q", notes, want)
1050 }
1051 if got := o.status("hf-status", map[string]any{"request": request}); len(got) != 1 || got[0].Summary != stopped {
1052 t.Fatalf("status %+v", got)
1053 }
1054 }
1055 t.Run("failed", func(t *testing.T) {
1056 o := newTeamRig(t)
1057 o.ask("Can we fix a bug in Tito? Login is broken")
1058 request, cmd := o.handoff("hf1", "Login is broken", "")
1059 if ids, _, _ := o.updates(); len(ids) != 0 {
1060 t.Fatalf("an update while the turn runs: %v", ids)
1061 }
1062 o.runner.Send(o.ctx, "r-hf-fail", wire.FrameTurn, wire.TurnReport{TurnID: cmd.TurnID, Attempt: 1, State: wire.TurnFailed, Reason: "provider_failed"})
1063 check(o, request)
1064 })
1065 t.Run("recovery", func(t *testing.T) {
1066 o := newTeamRig(t)
1067 o.ask("Can we fix a bug in Tito? Login is broken")
1068 request, cmd := o.handoff("hf2", "Login is broken", "")
1069 // The runner comes back holding the Assistant's turn alone.
1070 o.runner.Send(o.ctx, "r-hf-sync", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{{TurnID: o.turn, Attempt: 1, State: wire.TurnRunning}}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}})
1071 o.until("the hand-off's turn failed", func() bool { return o.turnState(cmd.TurnID) == wire.TurnFailed })
1072 check(o, request)
1073 })
1074}
1075
1076// TestContractHandoffJoinsOpenCards: a hand-off that joins the person's
1077// own work already waiting on a merge go-ahead and the project's ships
1078// question raises nothing in the Assistant lane and tells the person
1079// nothing (J4): that work stays theirs, its cards in their conversation,
1080// where Merge merges.
1081func TestContractHandoffJoinsOpenCards(t *testing.T) {
1082 o := newTeamRig(t)
1083 o.sitesOn(wire.ProtocolAssistant, false)
1084 mine := o.own("Something of my own.")
1085 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
1086 var id string
1087 o.in(mine, func() { id, _ = o.websiteReady("jc", "Quick website", base, cand, false) })
1088 o.reply(mine)
1089 merge, ships := o.cardOf(id), o.teamCard(wire.CardMergeShips, "", "")
1090 if merge.ID == "" || merge.State != wire.CardOpen || ships.ID == "" || ships.State != wire.CardOpen {
1091 t.Fatalf("merge card %+v, ships card %+v", merge, ships)
1092 }
1093 if cards := o.assistantCards(); len(cards) != 0 {
1094 t.Fatalf("assistant cards before the hand-off %+v", cards)
1095 }
1096 o.ask("Can we fix a bug in Tito? Login is broken")
1097 request, cmd := o.handoff("jc1", "Login is broken", "")
1098 o.in(cmd.TurnID, func() {
1099 if res := o.call("jc-rep", wire.ToolAddReport, map[string]string{"task": id, "text": "Login is broken too."}); res.IsError {
1100 t.Fatalf("add_report %+v", res)
1101 }
1102 })
1103 if got := o.linked(request); len(got) != 1 || got[id] {
1104 t.Fatalf("linked %v", got)
1105 }
1106 if cards := o.assistantCards(); len(cards) != 0 {
1107 t.Fatalf("assistant cards after the join %+v", cards)
1108 }
1109 if n := o.rows("SELECT count(*) FROM chat_cards WHERE source_card IN (?, ?)", merge.ID, ships.ID); n != 0 {
1110 t.Fatalf("%d mirrors of the person's own cards", n)
1111 }
1112 if ids, _, _ := o.updates(); len(ids) != 0 {
1113 t.Fatalf("the person is told of their own work: %v", ids)
1114 }
1115 if o.teamCard(wire.CardMerge, "", id).ID != merge.ID || o.teamCard(wire.CardMergeShips, "", "").ID != ships.ID {
1116 t.Fatal("the person's own cards left their conversation")
1117 }
1118 ans, err := o.client.Answer(o.ctx, merge.ID, wire.ChoiceMerge, merge.Revision)
1119 if err != nil || ans.Card.State != wire.CardAnswered {
1120 t.Fatalf("answer %+v %v", ans, err)
1121 }
1122 if after := o.teamCard(wire.CardMerge, "", id); after.ID != merge.ID || after.State != wire.CardAnswered || after.Choice != wire.ChoiceMerge {
1123 t.Fatalf("merge card %+v", after)
1124 }
1125}
1126
1127// TestContractHandoffCardsFollowTheJob: work a job's thread records is
1128// the job's (J4): the task is stored in lane job:<request>, and its task
1129// card, merge card, the project's ships question and its Publish card are
1130// raised in the thread, never in the person's /api/v1/snapshot or
1131// /api/v1/events. The go-ahead and Publish are mirrored to the Assistant
1132// lane from there.
1133func TestContractHandoffCardsFollowTheJob(t *testing.T) {
1134 o := newTeamRigAt(t, wire.ProtocolCurrent)
1135 // Handed over, merged from the go-ahead, and asked to publish.
1136 id, _, _, _ := o.mergedWebsite("cj", true)
1137 var request string
1138 if err := o.inst.DB.Writer().QueryRow("SELECT id FROM chat_handoffs").Scan(&request); err != nil {
1139 t.Fatal(err)
1140 }
1141 lane, turn := wire.JobLane(request), o.handoffTurn(request)
1142 if n := o.rows("SELECT count(*) FROM chat_tasks WHERE id = ? AND lane = ?", id, lane); n != 1 {
1143 t.Fatal("the task is not stored in the job's lane")
1144 }
1145 o.assistantCard("the publish outcome", isPublishOutcome)
1146
1147 // Every card of the work: the task's, the turn's and the project's own.
1148 rows, err := o.inst.DB.Writer().Query("SELECT id, kind, coalesce(lane, '') FROM chat_cards WHERE task_id = ? OR turn_id = ? OR project_id = (SELECT project_id FROM chat_tasks WHERE id = ?) AND coalesce(task_id, '') = '' AND coalesce(turn_id, '') = ''", id, turn, id)
1149 if err != nil {
1150 t.Fatal(err)
1151 }
1152 cards := map[string]string{}
1153 var kinds []string
1154 for rows.Next() {
1155 var c, kind, in string
1156 if err := rows.Scan(&c, &kind, &in); err != nil {
1157 t.Fatal(err)
1158 }
1159 if in != lane {
1160 t.Fatalf("the job's %s card %s is in %q", kind, c, in)
1161 }
1162 cards[c] = kind
1163 kinds = append(kinds, kind)
1164 }
1165 if err := rows.Close(); err != nil {
1166 t.Fatal(err)
1167 }
1168 for _, kind := range []string{wire.CardTask, wire.CardMerge, wire.CardMergeShips, wire.CardPublish} {
1169 if !slices.Contains(kinds, kind) {
1170 t.Fatalf("no %s card in the thread: %v", kind, kinds)
1171 }
1172 }
1173 if n := o.rows("SELECT count(*) FROM chat_cards m JOIN chat_cards s ON s.id = m.source_card WHERE m.lane = ? AND s.lane = ? AND s.kind IN (?, ?)", wire.LaneAssistant, lane, wire.CardMerge, wire.CardPublish); n != 2 {
1174 t.Fatalf("%d of the go-ahead and Publish mirrored from the thread", n)
1175 }
1176
1177 // None of them is in the person's own conversation.
1178 snap, err := o.client.Snapshot(o.ctx)
1179 if err != nil {
1180 t.Fatal(err)
1181 }
1182 for _, c := range snap.Cards {
1183 if cards[c.ID] != "" || c.TaskID == id {
1184 t.Fatalf("the job's card in their snapshot %+v", c)
1185 }
1186 }
1187 o.conv.Locked(func(c *Conversation) {
1188 for _, k := range c.Cards {
1189 if cards[k.ID] != "" || k.TaskID == id {
1190 t.Errorf("the job's card in their events %+v", k)
1191 }
1192 }
1193 })
1194 for c := range cards {
1195 if n := o.rows("SELECT count(*) FROM chat_events WHERE coalesce(lane, '') = '' AND body LIKE ?", `%"`+c+`"%`); n != 0 {
1196 t.Fatalf("%d events of the job's card %s in their stream", n, c)
1197 }
1198 }
1199}
1200
1201// TestContractJoinedTaskStaysTheirs: a task the person started in their
1202// own conversation that a job's thread joins (add_report) stays theirs
1203// (lane ""): its merge card, raised after the join, is in their
1204// conversation and is not mirrored, and they are told nothing of it. The
1205// task card the join shows is in the thread, with the turn that joined.
1206func TestContractJoinedTaskStaysTheirs(t *testing.T) {
1207 o := newTeamRig(t)
1208 mine := o.own("Something of my own.")
1209 var id string
1210 o.in(mine, func() { id = o.record("js-own", "Quick website") })
1211 o.ask("Can we fix a bug in Tito? Login is broken")
1212 request, cmd := o.handoff("js1", "Login is broken", "")
1213 o.in(cmd.TurnID, func() {
1214 if res := o.call("js-rep", wire.ToolAddReport, map[string]string{"task": id, "text": "Login is broken too."}); res.IsError {
1215 t.Fatalf("add_report %+v", res)
1216 }
1217 })
1218 if created, ok := o.linked(request)[id]; !ok || created {
1219 t.Fatalf("the job does not follow the task it joined: %v", o.linked(request))
1220 }
1221 if joined := o.threadCard(wire.CardTask, cmd.TurnID); joined.ID == "" || o.laneOfCard(joined.ID) != wire.JobLane(request) || o.teamCard(wire.CardTask, cmd.TurnID, "").ID != "" {
1222 t.Fatalf("the join's task card %+v is not in the thread", joined)
1223 }
1224 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
1225 o.in(mine, func() {
1226 if res := o.call("js-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}); res.IsError {
1227 t.Fatalf("start %+v", res)
1228 }
1229 _, body := o.expect(wire.FrameDispatch)
1230 d := body.(*wire.DispatchCommand)
1231 o.step("js-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "claude-a"})
1232 o.step("js-done", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Pushed: true, Termination: true, Family: "claude", Account: "claude-a"})
1233 o.expect(wire.FrameWatchMerge)
1234 c := o.dispatched(wire.SpecialistChecks, base, cand, 0)
1235 o.checks("js-c", c, wire.ChecksNone, nil, "", "")
1236 o.verdict("js-r", o.dispatched(wire.SpecialistReview, base, cand, 0), wire.VerdictApprove)
1237 })
1238 o.until("the merge card", func() bool { return o.cardOf(id).ID != "" })
1239 merge := o.cardOf(id)
1240 if o.laneOfCard(merge.ID) != "" || o.teamCard(wire.CardMerge, "", id).ID != merge.ID {
1241 t.Fatalf("the merge card %+v is not in their conversation", merge)
1242 }
1243 if n := o.rows("SELECT count(*) FROM chat_tasks WHERE id = ? AND coalesce(lane, '') = ''", id); n != 1 {
1244 t.Fatal("the joined task left the person's lane")
1245 }
1246 if cards := o.assistantCards(); len(cards) != 0 {
1247 t.Fatalf("assistant cards %+v", cards)
1248 }
1249 if ids, _, _ := o.updates(); len(ids) != 0 {
1250 t.Fatalf("the person is told of their own work: %v", ids)
1251 }
1252}
1253
1254// TestContractHandoffLegacyApprovalsMirror: a legacy hand-off (lane "")
1255// keeps slice 1's route for its approvals (J7): the task its turn records
1256// stays in the person's conversation, and the merge card raised there
1257// after this release still raises the go-ahead in the Assistant lane
1258// through slice 1's path and tells the person; Merge there merges, and
1259// the merge card stays in their conversation.
1260func TestContractHandoffLegacyApprovalsMirror(t *testing.T) {
1261 o := newTeamRig(t)
1262 o.ask("Can we fix a bug in Tito? Login is broken")
1263 request, turn := o.legacyHandoff("ap", "Login is broken")
1264 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
1265 var id string
1266 o.in(turn, func() { id, _ = o.websiteReady("ap", "Quick website", base, cand, false) })
1267 if got := o.linked(request); !got[id] {
1268 t.Fatalf("linked %v", got)
1269 }
1270 if n := o.rows("SELECT count(*) FROM chat_tasks WHERE id = ? AND coalesce(lane, '') = ''", id); n != 1 {
1271 t.Fatal("the legacy hand-off's task is not in the person's lane")
1272 }
1273 merge := o.teamCard(wire.CardMerge, "", id)
1274 if merge.ID == "" || merge.State != wire.CardOpen {
1275 t.Fatalf("the merge card %+v is not in their conversation", merge)
1276 }
1277 card := o.assistantCard("the merge outcome", isMergeOutcome)
1278 if n := o.rows("SELECT count(*) FROM chat_cards WHERE id = ? AND source_card = ?", card.ID, merge.ID); n != 1 {
1279 t.Fatalf("the go-ahead %+v does not point at the merge card", card)
1280 }
1281 if ids, _, _ := o.updates(); len(ids) != 1 {
1282 t.Fatalf("the person is not told: %v", ids)
1283 }
1284 if ans, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil || ans.Card.State != wire.CardAnswered {
1285 t.Fatalf("answer %+v %v", ans, err)
1286 }
1287 if after := o.teamCard(wire.CardMerge, "", id); after.ID != merge.ID || after.State != wire.CardAnswered || after.Choice != wire.ChoiceMerge {
1288 t.Fatalf("merge card %+v", after)
1289 }
1290}
1291
1292// TestContractHandoffThreadIsNotTheirConversation: a hand-off's thread
1293// (its words, the Coordinator's reply, its question card, its turns)
1294// never shows in the person's own conversation: not in
1295// /api/v1/snapshot, /api/v1/messages, /api/v1/events or /conversation,
1296// while that conversation answers in its own lane meanwhile. Answering
1297// the thread's question through the person API puts the answer in the
1298// thread and dispatches it there.
1299func TestContractHandoffThreadIsNotTheirConversation(t *testing.T) {
1300 o := newTeamRig(t)
1301 o.ask("Can we fix a bug in Tito? Login is broken")
1302 request, cmd := o.handoff("nc1", "Login is broken", "")
1303 lane := wire.JobLane(request)
1304 o.in(cmd.TurnID, func() {
1305 if res := o.call("nc-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page is it?", "options": []string{"Web", "App"}}); res.Code != "asked" {
1306 t.Fatalf("ask %+v", res)
1307 }
1308 })
1309 if err := o.runner.Send(o.ctx, "r-nc-reply", wire.FrameReply, wire.Reply{TurnID: cmd.TurnID, Attempt: 1, Text: "Looking at the sign in page."}); err != nil {
1310 t.Fatal(err)
1311 }
1312 o.until("the thread's reply", func() bool { return o.turnState(cmd.TurnID) == wire.TurnReplied })
1313 // Meanwhile their own conversation answers in its own lane.
1314 mine := o.own("Something of my own.")
1315 o.reply(mine)
1316 o.wait("their own reply", func(c *Conversation) bool { return c.Turns[mine].State == wire.TurnReplied && len(c.Replies()) == 1 })
1317
1318 card, revision := o.threadQuestion(request)
1319 thread := o.thread(request)
1320 if len(thread) != 2 || thread[1].Role != wire.RoleCoordinator || thread[1].Text != "Looking at the sign in page." {
1321 t.Fatalf("thread %+v", thread)
1322 }
1323 hidden := map[string]bool{cmd.TurnID: true, card: true, request: true}
1324 for _, m := range thread {
1325 hidden[m.ID] = true
1326 }
1327 words := []string{"Login is broken", "Which login page is it?", "Looking at the sign in page."}
1328 theirs := func(stage string) {
1329 t.Helper()
1330 snap, err := o.client.Snapshot(o.ctx)
1331 if err != nil {
1332 t.Fatal(err)
1333 }
1334 page, err := o.client.Messages(o.ctx, "", 50)
1335 if err != nil {
1336 t.Fatal(err)
1337 }
1338 for _, m := range append(snap.Messages, page.Items...) {
1339 if hidden[m.ID] || hidden[m.TurnID] {
1340 t.Fatalf("%s: the thread's message in their conversation %+v", stage, m)
1341 }
1342 }
1343 for _, r := range snap.Turns {
1344 if hidden[r.ID] {
1345 t.Fatalf("%s: the thread's turn in their snapshot %+v", stage, r)
1346 }
1347 }
1348 for _, c := range snap.Cards {
1349 if hidden[c.ID] || hidden[c.TurnID] {
1350 t.Fatalf("%s: the thread's card in their snapshot %+v", stage, c)
1351 }
1352 }
1353 if len(snap.Messages) != len(page.Items) || len(snap.Messages) == 0 {
1354 t.Fatalf("%s: their conversation %+v, page %+v", stage, snap.Messages, page.Items)
1355 }
1356 o.conv.Locked(func(c *Conversation) {
1357 for id, m := range c.Messages {
1358 if hidden[id] || hidden[m.TurnID] {
1359 t.Errorf("%s: the thread's message in their events %+v", stage, m)
1360 }
1361 }
1362 for id := range c.Turns {
1363 if hidden[id] {
1364 t.Errorf("%s: the thread's turn in their events %s", stage, id)
1365 }
1366 }
1367 for id, k := range c.Cards {
1368 if hidden[id] || hidden[k.TurnID] {
1369 t.Errorf("%s: the thread's card in their events %+v", stage, k)
1370 }
1371 }
1372 })
1373 body := o.inst.Get(t, "/conversation")
1374 for _, s := range append(words, card, cmd.TurnID) {
1375 if strings.Contains(body, s) {
1376 t.Fatalf("%s: /conversation shows %q", stage, s)
1377 }
1378 }
1379 }
1380 theirs("before the answer")
1381
1382 // The thread's question, answered through the person API: the answer
1383 // is the thread's next message, dispatched there.
1384 ans, err := o.client.Answer(o.ctx, card, "Web", revision)
1385 if err != nil {
1386 t.Fatal(err)
1387 }
1388 if o.laneOf(ans.Turn.ID) != lane || o.rows("SELECT count(*) FROM chat_messages WHERE id = ? AND lane = ? AND text = 'Web'", ans.Message.ID, lane) != 1 {
1389 t.Fatalf("the answer %+v is not in the thread", ans)
1390 }
1391 if next := o.message(lane); next.TurnID != ans.Turn.ID || len(next.PersonText) != 0 {
1392 t.Fatalf("the answer's frame %+v", next)
1393 }
1394 hidden[ans.Message.ID], hidden[ans.Turn.ID] = true, true
1395 o.reply(ans.Turn.ID)
1396 // Their next message is all their conversation hears meanwhile.
1397 again := o.own("One more of my own.")
1398 o.wait("their next message", func(c *Conversation) bool { _, ok := c.Turns[again]; return ok })
1399 theirs("after the answer")
1400}
1401
1402// TestContractHandoffThreadsRunApart: two hand-offs and a message of the
1403// person's own go to the runner at once, each in its own lane: no one
1404// waits behind another.
1405func TestContractHandoffThreadsRunApart(t *testing.T) {
1406 o := newTeamRig(t)
1407 o.ask("Two things. Login is broken. Checkout is slow.")
1408 first := o.request("ra1", map[string]any{"words": "Login is broken"})
1409 second := o.request("ra2", map[string]any{"words": "Checkout is slow"})
1410 mine, err := o.client.Send(o.ctx, "Something of my own.", "own-ra")
1411 if err != nil {
1412 t.Fatal(err)
1413 }
1414 turns := map[string]string{wire.JobLane(first): o.handoffTurn(first), wire.JobLane(second): o.handoffTurn(second), wire.LaneCoordinator: mine.Turn.ID}
1415 if first == second || len(turns) != 3 {
1416 t.Fatalf("requests %s %s", first, second)
1417 }
1418 for lane, turn := range turns {
1419 if n := o.commandsFor(wire.FrameMessage, turn); n != 1 {
1420 t.Fatalf("the turn in %q went %d times before any reply", lane, n)
1421 }
1422 }
1423 for lane, turn := range turns {
1424 if cmd := o.message(lane); cmd.TurnID != turn {
1425 t.Fatalf("the frame in %q %+v", lane, cmd)
1426 }
1427 }
1428}
1429
1430// TestContractHandoffNeedsJobsRunner: a hand-off needs the person's
1431// primary at protocol 22. Last seen at 21, team_request is refused
1432// (runner_too_old) and stores nothing; a thread's turn not yet taken
1433// when the primary comes back at 21 ends failed (runner_too_old) and is
1434// never sent.
1435func TestContractHandoffNeedsJobsRunner(t *testing.T) {
1436 t.Run("refused", func(t *testing.T) {
1437 o := newTeamRigAt(t, wire.Protocol21)
1438 o.ask("Can we fix a bug in Tito? Login is broken")
1439 res := o.use("nj1", "team_request", map[string]any{"words": "Login is broken"})
1440 if !res.IsError || res.Code != "runner_too_old" || res.Text != "This can't be started until the person's setup is updated. Tell them plainly that it needs an update first." {
1441 t.Fatalf("team_request at 21 %+v", res)
1442 }
1443 if n := o.rows("SELECT (SELECT count(*) FROM chat_handoffs) + (SELECT count(*) FROM chat_messages WHERE coalesce(lane, '') <> ?) + (SELECT count(*) FROM chat_turns WHERE coalesce(lane, '') <> ?) + (SELECT count(*) FROM audit_events WHERE kind = 'assistant.handoff')", wire.LaneAssistant, wire.LaneAssistant); n != 0 {
1444 t.Fatalf("%d rows stored for a refused hand-off", n)
1445 }
1446 })
1447 t.Run("fenced", func(t *testing.T) {
1448 o := newTeamRig(t)
1449 o.ask("Can we fix a bug in Tito? Login is broken")
1450 request := o.request("nj2", map[string]any{"words": "Login is broken"})
1451 turn := o.handoffTurn(request)
1452 if s := o.turnState(turn); s != wire.TurnQueued || o.commandsFor(wire.FrameMessage, turn) != 1 {
1453 t.Fatalf("the thread's turn is %s", s)
1454 }
1455 // The runner goes before it takes the frame, and comes back older.
1456 o.runner.Close()
1457 o.wait("offline", func(c *Conversation) bool { return !c.Runner.Online })
1458 old := o.dialAt(wire.Protocol21)
1459 o.until("the thread's turn failed", func() bool { return o.turnState(turn) == wire.TurnFailed })
1460 if n := o.rows("SELECT count(*) FROM chat_turns WHERE id = ? AND reason = 'runner_too_old'", turn); n != 1 {
1461 t.Fatal("the thread's turn failed for another reason")
1462 }
1463 if n := o.rows("SELECT count(*) FROM runner_commands WHERE kind = ? AND acked_at IS NULL AND body LIKE ?", wire.FrameMessage, `%"turn_id":"`+turn+`"%`); n != 0 {
1464 t.Fatalf("the thread's frame still waits %d times", n)
1465 }
1466 if s := o.turnState(o.turn); s == wire.TurnFailed {
1467 t.Fatal("the Assistant's own turn failed at 21")
1468 }
1469 // Their own conversation still works, and its frame is the first.
1470 mine, err := o.client.Send(o.ctx, "Something of my own.", "own-nj")
1471 if err != nil {
1472 t.Fatal(err)
1473 }
1474 if _, frame, err := old.Expect(o.ctx, wire.FrameMessage); err != nil || frame.(*wire.MessageCommand).TurnID != mine.Turn.ID {
1475 t.Fatalf("their own frame at 21 %v %+v", err, frame)
1476 }
1477 })
1478}
1479
1480// legacyHandoff is a hand-off as slice 1 made them: the words in the
1481// person's own conversation (lane ""), and its row with no lane.
1482func (o *teamRig) legacyHandoff(id, words string) (request, turn string) {
1483 o.t.Helper()
1484 sent, err := o.client.Send(o.ctx, words, "legacy-"+id)
1485 if err != nil {
1486 o.t.Fatal(err)
1487 }
1488 if cmd := o.message(wire.LaneCoordinator); cmd.TurnID != sent.Turn.ID {
1489 o.t.Fatalf("the legacy frame %+v", cmd)
1490 }
1491 request = "h_legacy" + id
1492 db := o.inst.DB.Writer()
1493 if _, err := db.Exec("INSERT INTO chat_handoffs(id, person, assistant_turn, message_id, context, ledger_key, state, digest, created_at, updated_at) SELECT ?, person, ?, ?, '', ?, 'open', '', created_at, updated_at FROM chat_turns WHERE id = ?", request, o.turn, sent.Message.ID, "legacy-"+id, sent.Turn.ID); err != nil {
1494 o.t.Fatal(err)
1495 }
1496 if _, err := db.Exec("INSERT INTO chat_handoff_turns(handoff_id, turn_id) VALUES (?, ?)", request, sent.Turn.ID); err != nil {
1497 o.t.Fatal(err)
1498 }
1499 return request, sent.Turn.ID
1500}
1501
1502// TestContractHandoffLegacyKeepsItsRoute: a hand-off made before job
1503// threads (lane "", its message and turn in the person's conversation)
1504// keeps slice 1's routing: it follows the tasks its turns record, its
1505// question stays in their conversation, the answer starts a follow-up
1506// turn there linked to it, and its turn's end still tells it.
1507func TestContractHandoffLegacyKeepsItsRoute(t *testing.T) {
1508 o := newTeamRig(t)
1509 o.ask("Can we fix a bug in Tito? Login is broken")
1510 request, turn := o.legacyHandoff("1", "Login is broken")
1511 var id string
1512 o.in(turn, func() {
1513 id = o.record("lg-rec", "Fix the login")
1514 if res := o.call("lg-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" {
1515 t.Fatalf("ask %+v", res)
1516 }
1517 })
1518 o.reply(turn)
1519 var card wire.Card
1520 o.wait("the question in their conversation", func(c *Conversation) bool {
1521 for _, k := range c.Cards {
1522 if k.Kind == wire.CardQuestion && k.TurnID == turn {
1523 card = k
1524 }
1525 }
1526 return card.ID != ""
1527 })
1528 ans, err := o.client.Answer(o.ctx, card.ID, "Web", card.Revision)
1529 if err != nil {
1530 t.Fatal(err)
1531 }
1532 if next := o.message(wire.LaneCoordinator); next.TurnID != ans.Turn.ID || o.laneOf(ans.Turn.ID) != wire.LaneCoordinator {
1533 t.Fatalf("the answer's frame %+v", next)
1534 }
1535 if n := o.rows("SELECT count(*) FROM chat_handoff_turns WHERE handoff_id = ? AND turn_id = ?", request, ans.Turn.ID); n != 1 {
1536 t.Fatal("the answer's turn is not the legacy hand-off's")
1537 }
1538 var later string
1539 o.in(ans.Turn.ID, func() { later = o.record("lg-later", "Fix the web login page") })
1540 o.reply(ans.Turn.ID)
1541 if got := o.linked(request); len(got) != 2 || !got[id] || !got[later] {
1542 t.Fatalf("linked %v", got)
1543 }
1544 if n := o.rows("SELECT count(*) FROM chat_turns WHERE lane LIKE 'job:%'"); n != 0 {
1545 t.Fatalf("%d turns in a job thread", n)
1546 }
1547
1548 // A legacy hand-off whose turn ends with no work has stopped, and the
1549 // person is told: only its own turns count, not the person's own
1550 // work waiting behind it.
1551 stopped, other := o.legacyHandoff("2", "Login is broken")
1552 if waiting, err := o.client.Send(o.ctx, "Something of my own.", "own-lg"); err != nil || waiting.Turn.State != wire.TurnQueued {
1553 t.Fatalf("their own waiting turn %+v %v", waiting.Turn, err)
1554 }
1555 o.runner.Send(o.ctx, "r-lg-fail", wire.FrameTurn, wire.TurnReport{TurnID: other, Attempt: 1, State: wire.TurnFailed, Reason: "provider_failed"})
1556 update := "SELECT count(*) FROM chat_turns t JOIN chat_handoff_turns ht ON ht.turn_id = t.id WHERE ht.handoff_id = ? AND t.kind = ? AND t.note = ?"
1557 note := jobLine("Login is broken", stopped, "Login is broken") + noWork(stopped, 2) + "\nWhere it stands:\n" + equipo.RunnerCopy("assistant.team.stopped")
1558 o.until("the legacy hand-off's update", func() bool {
1559 return o.rows(update, stopped, wire.TurnTeamUpdate, note) == 1
1560 })
1561}
1562
1563// TestContractHandoffAnswerNeedsJobsRunner: a thread's question asked at
1564// protocol 22 and answered after the primary came back at 21 is refused
1565// (409 runner_too_old) through the person API: the card stays open at
1566// its revision, and no message or turn is made that no runner could
1567// carry.
1568func TestContractHandoffAnswerNeedsJobsRunner(t *testing.T) {
1569 o := newTeamRig(t)
1570 o.ask("Can we fix a bug in Tito? Login is broken")
1571 request, cmd := o.handoff("na1", "Login is broken", "")
1572 o.in(cmd.TurnID, func() {
1573 if res := o.call("na-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" {
1574 t.Fatalf("ask %+v", res)
1575 }
1576 })
1577 o.reply(cmd.TurnID)
1578 card, revision := o.threadQuestion(request)
1579 o.runner.Close()
1580 o.wait("offline", func(c *Conversation) bool { return !c.Runner.Online })
1581 o.dialAt(wire.Protocol21)
1582 lane := wire.JobLane(request)
1583 before := o.rows("SELECT (SELECT count(*) FROM chat_messages WHERE lane = ?) + (SELECT count(*) FROM chat_turns WHERE lane = ?)", lane, lane)
1584 refusedTooOld := func(what string, err error) {
1585 t.Helper()
1586 var e wire.Error
1587 if s, ok := err.(*ErrStatus); !ok || s.Status != http.StatusConflict || json.Unmarshal(s.Body, &e) != nil || e.Code != "runner_too_old" {
1588 t.Fatalf("%s at 21: %v", what, err)
1589 }
1590 if n := o.rows("SELECT count(*) FROM chat_cards WHERE id = ? AND state = ? AND revision = ?", card, wire.CardOpen, revision); n != 1 {
1591 t.Fatalf("%s at 21: the card changed", what)
1592 }
1593 if n := o.rows("SELECT (SELECT count(*) FROM chat_messages WHERE lane = ?) + (SELECT count(*) FROM chat_turns WHERE lane = ?)", lane, lane); n != before {
1594 t.Fatalf("%s at 21: %d thread rows, %d before", what, n, before)
1595 }
1596 }
1597 _, err := o.client.Answer(o.ctx, card, "Web", revision)
1598 refusedTooOld("the person's answer", err)
1599}
1600
1601// noWork is the note's line for a job that stopped before any work
1602// started, with nudges left (noteNoWork).
1603func noWork(request string, left int) string {
1604 return fmt.Sprintf("It stopped before any work started. Push it through yourself: use team_nudge {\"request\": %q, \"words\": ...} with words quoted from what the person asked. Nudges left: %d. Say nothing to the person.", request, left)
1605}
1606
1607// failedStep is the note's line for a job whose step failed and can be
1608// tried again (noteFailed).
1609func failedStep(request string, left int) string {
1610 return fmt.Sprintf("A step of it failed and can be tried again. Push it through yourself: use team_nudge {\"request\": %q, \"words\": ...} to have it tried again. Nudges left: %d. Say nothing to the person.", request, left)
1611}
1612
1613// blockedOn is the note's line for a job only the person can move on
1614// (noteBlocked).
1615func blockedOn(line string) string {
1616 return "It stopped, and only the person can move it on: " + line + ". Tell the person that plainly, in one line. Do not nudge it."
1617}
1618
1619// startedInThread hands "Login is broken" to the team and records and
1620// starts a task in the job's thread: the request, the task and its
1621// Engineering step.
1622func (o *teamRig) startedInThread(key string) (request, id string, d *wire.DispatchCommand) {
1623 o.t.Helper()
1624 o.ask("Can we fix a bug in Tito? Login is broken")
1625 request, cmd := o.handoff(key+"1", "Login is broken", "")
1626 o.in(cmd.TurnID, func() {
1627 id = o.record(key+"-rec", "Fix the login")
1628 if res := o.call(key+"-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}); res.IsError {
1629 o.t.Fatalf("start %+v", res)
1630 }
1631 _, body := o.expect(wire.FrameDispatch)
1632 d = body.(*wire.DispatchCommand)
1633 })
1634 return request, id, d
1635}
1636
1637// TestContractTeamUpdateStops: a job that stops where the Assistant can
1638// push it through tells it so: a thread turn that ended with no work, to
1639// nudge it with the person's words; a retryable failed Engineering step,
1640// to have it tried again; each with the nudges it has left. With none
1641// left, the Assistant is to tell the person it stopped.
1642func TestContractTeamUpdateStops(t *testing.T) {
1643 t.Run("no_work", func(t *testing.T) {
1644 o := newTeamRig(t)
1645 o.ask("Can we fix a bug in Tito? Login is broken")
1646 request, cmd := o.handoff("sw1", "Login is broken", "")
1647 o.reply(cmd.TurnID)
1648 note := o.noteFor("the no-work note", noWork(request, 2))
1649 if !strings.HasPrefix(note, jobLine("Login is broken", request, "Login is broken")+noWork(request, 2)+"\nWhere it stands:\n") {
1650 t.Fatalf("note %q", note)
1651 }
1652 })
1653 t.Run("failed", func(t *testing.T) {
1654 o := newTeamRig(t)
1655 request, id, d := o.startedInThread("sf")
1656 o.step("sf-fail", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true})
1657 note := o.noteFor("the failed note", failedStep(request, 2))
1658 if strings.Contains(note, "only the person can move it on") {
1659 t.Fatalf("note %q", note)
1660 }
1661 })
1662 t.Run("no_nudges", func(t *testing.T) {
1663 o := newTeamRig(t)
1664 o.ask("Can we fix a bug in Tito? Login is broken")
1665 request, cmd := o.handoff("sn1", "Login is broken", "")
1666 if _, err := o.inst.DB.Writer().Exec("UPDATE chat_handoffs SET nudges = 2 WHERE id = ?", request); err != nil {
1667 t.Fatal(err)
1668 }
1669 o.reply(cmd.TurnID)
1670 note := o.noteFor("the no-nudges note", "It stopped again and no nudges are left. Tell the person in one line that it stopped, and what would help if you know.")
1671 if strings.Contains(note, "team_nudge") {
1672 t.Fatalf("note %q", note)
1673 }
1674 })
1675}
1676
1677// personNeed is a need only the person can meet: its name, the note's
1678// plain line for it, and how a task's steps are written as it leaves
1679// them (step is the task's Engineering step).
1680type personNeed struct {
1681 name, line string
1682 set func(o *teamRig, id, step string)
1683}
1684
1685// personNeeds are the needs a task reports that only the person meets
1686// (ruling P4j), a failed merge step among them.
1687func personNeeds() []personNeed {
1688 cand := strings.Repeat("2", 40)
1689 return []personNeed{
1690 {"held", "they need to say when it can run", func(o *teamRig, id, step string) {
1691 o.exec("UPDATE chat_steps SET state = ?, hold = ? WHERE id = ?", wire.StepQueued, `{"reason":"limited","wake_at":null,"needs_person":"connection","step_revision":1}`, step)
1692 }},
1693 {"branch_moved", "someone else changed the same work, and they need to look at it", func(o *teamRig, id, step string) {
1694 o.exec("UPDATE chat_steps SET state = ?, pushed = 1, terminated = 1, candidate_sha = ? WHERE id = ?", wire.StepDone, cand, step)
1695 o.exec("UPDATE chat_tasks SET moved_from = ? WHERE id = ?", cand, id)
1696 }},
1697 {"review_blocked", "the check of the work could not finish, and they need to decide what next", func(o *teamRig, id, step string) {
1698 o.exec("UPDATE chat_steps SET specialist = ?, state = ?, terminated = 1 WHERE id = ?", wire.SpecialistReview, wire.StepFailed, step)
1699 }},
1700 {"fix_rounds", "the checks still find problems after the automatic fixes, and they need to decide what next", func(o *teamRig, id, step string) {
1701 o.exec("UPDATE chat_steps SET state = ?, pushed = 1, terminated = 1, candidate_sha = ?, round = ? WHERE id = ?", wire.StepDone, cand, wire.MaxFixRounds, step)
1702 o.exec("INSERT INTO chat_steps(id, task_id, idx, specialist, person, state, attempt, candidate_sha, checks, terminated, revision, created_at, updated_at) SELECT 's_fixed', task_id, idx + 1, ?, person, ?, 1, ?, ?, 1, 1, created_at, updated_at FROM chat_steps WHERE id = ?", wire.SpecialistChecks, wire.StepDone, cand, wire.ChecksFailed, step)
1703 }},
1704 {"merge_conflict", "it clashes with other changes, and they need to sort it out", func(o *teamRig, id, step string) {
1705 o.exec("UPDATE chat_steps SET specialist = ?, state = ?, terminated = 1, reason = 'merge_conflict' WHERE id = ?", wire.SpecialistMerge, wire.StepFailed, step)
1706 }},
1707 {"machine_removed", "they need to bring their computer back online", func(o *teamRig, id, step string) {
1708 o.exec("UPDATE chat_steps SET state = ?, terminated = 0, reason = 'machine_removed' WHERE id = ?", wire.StepFailed, step)
1709 }},
1710 {"mac_sandbox", "they need to let it be tested on their Mac", func(o *teamRig, id, step string) {
1711 o.exec("UPDATE chat_steps SET specialist = ?, state = ?, placement = ? WHERE id = ?", wire.SpecialistChecks, wire.StepQueued, wire.PlacementSandbox, step)
1712 }},
1713 {"merge_failed", "going live failed, and they need to try it again", func(o *teamRig, id, step string) {
1714 o.exec("UPDATE chat_steps SET specialist = ?, state = ?, terminated = 1, reason = 'provider_failed' WHERE id = ?", wire.SpecialistMerge, wire.StepFailed, step)
1715 }},
1716 {"merge_credential", noAccessLine, func(o *teamRig, id, step string) {
1717 o.exec("UPDATE chat_steps SET specialist = ?, state = ?, terminated = 1, reason = ? WHERE id = ?", wire.SpecialistMerge, wire.StepFailed, wire.ReasonMergeCredential, step)
1718 }},
1719 }
1720}
1721
1722// noAccessLine is the note's plain line for going live refused for want
1723// of access to the repository: what is missing, not "try it again".
1724const noAccessLine = "there is no access to publish it where the work lives, and someone needs to set that access up before it can go live; trying again will not help until then"
1725
1726// TestContractTeamUpdatePersonNeeds (ruling P4j): every need only the
1727// person can meet stops the job for them: the note says what in plain
1728// words and never asks the Assistant to nudge it, however its step
1729// failed. The task's steps are written as each stop leaves them; a note
1730// on the task's thread saves the task, as any change would.
1731func TestContractTeamUpdatePersonNeeds(t *testing.T) {
1732 for _, c := range personNeeds() {
1733 t.Run(c.name, func(t *testing.T) {
1734 o := newTeamRigAt(t, wire.ProtocolCurrent)
1735 _, id, d := o.startedInThread("pn")
1736 c.set(o, id, d.StepID)
1737 if _, err := o.client.PostThread(o.ctx, id, "For the record.", "pn-note"); err != nil {
1738 t.Fatal(err)
1739 }
1740 if note := o.noteFor("the "+c.name+" note", blockedOn(c.line)); strings.Contains(note, "team_nudge") {
1741 t.Fatalf("note %q", note)
1742 }
1743 })
1744 }
1745 // runner_offline is a need no task of the instance's reports now
1746 // (needsYou never returns it); its plain line is checked where the
1747 // lines are kept (TestJobNoteBlockedLines).
1748 t.Run("publish_failed", func(t *testing.T) {
1749 o := newTeamRigAt(t, wire.ProtocolCurrent)
1750 o.mergedWebsite("pf", true)
1751 // The project's ships question, answered in the thread, waits on
1752 // the person no more.
1753 var ships string
1754 var revision int64
1755 if err := o.inst.DB.Writer().QueryRow("SELECT id, revision FROM chat_cards WHERE kind = ? AND state = ?", wire.CardMergeShips, wire.CardOpen).Scan(&ships, &revision); err != nil {
1756 t.Fatal(err)
1757 }
1758 if _, err := o.client.Answer(o.ctx, ships, wire.ChoiceNotShips, revision); err != nil {
1759 t.Fatal(err)
1760 }
1761 card := o.assistantCard("the publish outcome", isPublishOutcome)
1762 if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoicePublish, card.Revision); err != nil {
1763 t.Fatal(err)
1764 }
1765 o.publishReport("pf-failed", o.publishDispatch(), wire.StepFailed, nil)
1766 if note := o.noteFor("the publish failure's note", blockedOn("going live failed, and they need to try it again")); strings.Contains(note, "team_nudge") {
1767 t.Fatalf("note %q", note)
1768 }
1769 })
1770}
1771
1772// exec runs a statement on the instance's database.
1773func (o *teamRig) exec(q string, args ...any) {
1774 o.t.Helper()
1775 if _, err := o.inst.DB.Writer().Exec(q, args...); err != nil {
1776 o.t.Fatal(err)
1777 }
1778}
1779
1780// TestContractTeamUpdateQuietProgress: routine progress tells the
1781// Assistant nothing: a followed task noted, in progress and in review
1782// queues no team_update; the go-ahead raised does; a finding while it
1783// waits, and merging after it, change nothing it was told.
1784func TestContractTeamUpdateQuietProgress(t *testing.T) {
1785 o := newTeamRig(t)
1786 o.sitesOn(wire.ProtocolAssistant, false)
1787 o.shipsNo(o.project())
1788 quiet := func(stage string, n int) {
1789 t.Helper()
1790 time.Sleep(20 * time.Millisecond)
1791 if ids, notes, _ := o.updates(); len(ids) != n {
1792 t.Fatalf("at %s: updates %v %q", stage, ids, notes)
1793 }
1794 }
1795 stage := func(id, want string) {
1796 t.Helper()
1797 o.wait(want, func(c *Conversation) bool { return c.Tasks[id].Stage == want })
1798 }
1799 o.ask("Can we fix a bug in Tito? Login is broken")
1800 _, cmd := o.handoff("qp1", "Login is broken", "")
1801 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
1802 var id string
1803 o.in(cmd.TurnID, func() {
1804 id = o.record("qp-rec", "Fix the login")
1805 stage(id, wire.StageNoted)
1806 quiet("noted", 0)
1807 if res := o.call("qp-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}); res.IsError {
1808 t.Fatalf("start %+v", res)
1809 }
1810 _, body := o.expect(wire.FrameDispatch)
1811 d := body.(*wire.DispatchCommand)
1812 o.step("qp-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "claude-a"})
1813 stage(id, wire.StageInProgress)
1814 quiet("in progress", 0)
1815 o.step("qp-done", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Pushed: true, Termination: true, Family: "claude", Account: "claude-a"})
1816 o.expect(wire.FrameWatchMerge)
1817 c := o.dispatched(wire.SpecialistChecks, base, cand, 0)
1818 stage(id, wire.StageInReview)
1819 quiet("in review", 0)
1820 o.checks("qp-c", c, wire.ChecksNone, nil, "", "")
1821 o.verdict("qp-r", o.dispatched(wire.SpecialistReview, base, cand, 0), wire.VerdictApprove)
1822 })
1823 card := o.assistantCard("the go-ahead", isMergeOutcome)
1824 o.noteFor("the go-ahead's note", "It is ready for the person to try.")
1825 quiet("ready", 1)
1826 // A finding while the go-ahead waits changes where it stands, and
1827 // tells nothing new.
1828 _, told, _ := o.updates()
1829 o.in(cmd.TurnID, func() {
1830 if res := o.call("qp-find", wire.ToolAddFinding, map[string]any{"task": id, "headline": "The sign in button posts to the old address.", "text": "login.js posts to /v1/login.", "repo": "oficina/sample", "path": "login.js", "line": 3}); res.IsError {
1831 t.Fatalf("finding %+v", res)
1832 }
1833 })
1834 quiet("a finding", 1)
1835 if _, notes, _ := o.updates(); !slices.Equal(notes, told) {
1836 t.Fatalf("after a finding %q, before %q", notes, told)
1837 }
1838 if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil {
1839 t.Fatal(err)
1840 }
1841 o.dispatched(wire.SpecialistMerge, base, cand, 0)
1842 stage(id, wire.StageMerging)
1843 quiet("merging", 1)
1844}
1845
1846// statusOf is team_status's answer for one request, as JSON.
1847func (o *teamRig) statusOf(key, request string) map[string]any {
1848 o.t.Helper()
1849 res := o.use(key, "team_status", map[string]any{"request": request})
1850 var out struct {
1851 Requests []map[string]any `json:"requests"`
1852 }
1853 if res.IsError || json.Unmarshal([]byte(res.Text), &out) != nil || len(out.Requests) != 1 {
1854 o.t.Fatalf("team_status %+v", res)
1855 }
1856 return out.Requests[0]
1857}
1858
1859// TestContractTeamStatusQuestion: team_status names the job's title and,
1860// while the job has an open question, the question and its options
1861// (never null); with none open, no question at all.
1862func TestContractTeamStatusQuestion(t *testing.T) {
1863 o := newTeamRig(t)
1864 o.ask("Can we fix a bug in Tito? Login is broken")
1865 request := o.request("tq1", map[string]any{"words": "Login is broken", "title": "Fixing the sign-in page"})
1866 cmd := o.message(wire.JobLane(request))
1867 if got := o.statusOf("tq-none", request); got["title"] != "Fixing the sign-in page" || got["question"] != nil {
1868 t.Fatalf("before a question %+v", got)
1869 }
1870 o.in(cmd.TurnID, func() {
1871 if res := o.call("tq-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" {
1872 t.Fatalf("ask %+v", res)
1873 }
1874 })
1875 got := o.statusOf("tq-open", request)
1876 if q, ok := got["question"].(map[string]any); !ok || q["text"] != "Which login page?" || fmt.Sprint(q["options"]) != "[Web App]" || got["title"] != "Fixing the sign-in page" {
1877 t.Fatalf("with the question %+v", got)
1878 }
1879 o.reply(cmd.TurnID)
1880 card, revision := o.threadQuestion(request)
1881 ans, err := o.client.Answer(o.ctx, card, "Web", revision)
1882 if err != nil {
1883 t.Fatal(err)
1884 }
1885 if got := o.statusOf("tq-answered", request); got["question"] != nil {
1886 t.Fatalf("after the answer %+v", got)
1887 }
1888 o.message(wire.JobLane(request))
1889 o.in(ans.Turn.ID, func() {
1890 if res := o.call("tq-ask2", wire.ToolAskPerson, map[string]any{"question": "Anything else to know?"}); res.Code != "asked" {
1891 t.Fatalf("ask %+v", res)
1892 }
1893 })
1894 res := o.use("tq-free", "team_status", map[string]any{"request": request})
1895 if res.IsError || !strings.Contains(res.Text, `"question":{"text":"Anything else to know?","options":[]}`) {
1896 t.Fatalf("a question without options %+v", res)
1897 }
1898}
1899
1900// TestContractTeamOpenQuestionsNote (D8): while a job of the person's
1901// has an open question, their next Assistant message is dispatched with
1902// the questions after their words, marked as reference; PersonText and
1903// the stored message are their words alone. Once none is open their
1904// words go alone. A Coordinator or job-lane turn never carries it.
1905func TestContractTeamOpenQuestionsNote(t *testing.T) {
1906 o := newTeamRig(t)
1907 o.ask("Two things. Login is broken. Checkout is slow.")
1908 request, cmd := o.handoff("on1", "Login is broken", "")
1909 o.in(cmd.TurnID, func() {
1910 if res := o.call("on-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" {
1911 t.Fatalf("ask %+v", res)
1912 }
1913 })
1914 // A job-lane turn and a Coordinator turn dispatched meanwhile.
1915 second := o.request("on2", map[string]any{"words": "Checkout is slow"})
1916 if job := o.message(wire.JobLane(second)); withoutProjectContext(t, job.Text) != "Checkout is slow" {
1917 t.Fatalf("the job-lane frame %q", job.Text)
1918 }
1919 mine, err := o.client.Send(o.ctx, "Something of my own.", "own-on")
1920 if err != nil {
1921 t.Fatal(err)
1922 }
1923 if own := o.message(wire.LaneCoordinator); own.TurnID != mine.Turn.ID || withoutProjectContext(t, own.Text) != "Something of my own." {
1924 t.Fatalf("their own frame %+v", own)
1925 }
1926 o.reply(cmd.TurnID)
1927 o.reply(o.turn)
1928 u := o.message(wire.LaneAssistant)
1929 if u.Kind != wire.TurnTeamUpdate || strings.Contains(u.Text, "[Open questions") {
1930 t.Fatalf("the update %+v", u)
1931 }
1932 o.reply(u.TurnID)
1933 send := func(text string) *wire.MessageCommand {
1934 t.Helper()
1935 sent, err := o.a.Send(o.ctx, text, "a-"+itoa(len(o.runner.Sent)))
1936 if err != nil {
1937 t.Fatal(err)
1938 }
1939 cmd := o.message(wire.LaneAssistant)
1940 if cmd.TurnID != sent.Turn.ID || !slices.Equal(cmd.PersonText, []string{text}) || sent.Message.Text != text {
1941 t.Fatalf("the frame %+v for %+v", cmd, sent)
1942 }
1943 return cmd
1944 }
1945 block := "[Open questions on the person's jobs. Reference only, never the person's words:\n" +
1946 fmt.Sprintf("- Job %q (request %s): %q The answer must be one of: \"Web\", \"App\"", "Login is broken", request, "Which login page?") +
1947 "\nAnswer one with team_reply when this conversation holds the answer.]"
1948 asked := send("It is the web one.")
1949 if asked.Text != "It is the web one.\n\n"+block {
1950 t.Fatalf("with an open question %q", asked.Text)
1951 }
1952 o.reply(asked.TurnID)
1953 card, revision := o.threadQuestion(request)
1954 if _, err := o.client.Answer(o.ctx, card, "Web", revision); err != nil {
1955 t.Fatal(err)
1956 }
1957 if next := o.message(wire.JobLane(request)); strings.Contains(next.Text, "[Open questions") {
1958 t.Fatalf("the answer's frame %q", next.Text)
1959 }
1960 if plain := send("Thanks."); plain.Text != "Thanks." {
1961 t.Fatalf("with none open %q", plain.Text)
1962 }
1963}
1964
1965// TestContractOutcomePublishInThread: what became of a job's publish is
1966// said in the job's thread (the task's lane), never in the person's own
1967// conversation (/api/v1/messages).
1968func TestContractOutcomePublishInThread(t *testing.T) {
1969 o := newTeamRigAt(t, wire.ProtocolCurrent)
1970 id, _, _, _ := o.mergedWebsite("pt", true)
1971 request := o.requestOf(id)
1972 card := o.assistantCard("the publish outcome", isPublishOutcome)
1973 if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoicePublish, card.Revision); err != nil {
1974 t.Fatal(err)
1975 }
1976 d := o.publishDispatch()
1977 if refused := o.lease(o.runner, "pt-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused != "" {
1978 t.Fatalf("start refused %q", refused)
1979 }
1980 o.publishReport("pt-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40})
1981 if refused := o.lease(o.runner, "pt-deploy", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: d.Publish.Destination}); refused != "" {
1982 t.Fatalf("deploy refused %q", refused)
1983 }
1984 site := "https://" + d.Publish.App + ".bds.oncarlos.com/"
1985 o.publishReport("pt-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: d.Publish.App, URL: site, Version: "s-eeeeeeeeeeee-x-1", Digest: digestA, Outcome: wire.PublishPublished, DeployHeld: true})
1986 var said, lane string
1987 o.until("the publish result", func() bool {
1988 return o.inst.DB.Writer().QueryRow("SELECT id, coalesce(lane, '') FROM chat_messages WHERE idempotency_key = ?", "publish:"+d.StepID+":"+itoa(int(d.Attempt))).Scan(&said, &lane) == nil
1989 })
1990 if lane != wire.JobLane(request) {
1991 t.Fatalf("the publish result is in %q, not the job's thread", lane)
1992 }
1993 page, err := o.client.Messages(o.ctx, "", 50)
1994 if err != nil {
1995 t.Fatal(err)
1996 }
1997 for _, m := range page.Items {
1998 if m.ID == said || strings.Contains(m.Text, site) {
1999 t.Fatalf("the job's publish result in their conversation %+v", m)
2000 }
2001 }
2002 if !slices.ContainsFunc(o.thread(request), func(m wire.Message) bool { return m.ID == said }) {
2003 t.Fatal("the publish result is not in the thread")
2004 }
2005}
2006
2007// TestContractTeamUpdateNoAccessAmongTasks: a job following two tasks,
2008// one whose merge failed and one refused for want of access, in either
2009// order: the note says access is missing, never "try it again".
2010func TestContractTeamUpdateNoAccessAmongTasks(t *testing.T) {
2011 for _, order := range []string{"failed_first", "refused_first"} {
2012 t.Run(order, func(t *testing.T) {
2013 o := newTeamRigAt(t, wire.ProtocolCurrent)
2014 o.ask("Can we fix two bugs in Tito? Login is broken and so is search")
2015 _, cmd := o.handoff("na1", "Login is broken and so is search", "")
2016 var ids, steps []string
2017 o.in(cmd.TurnID, func() {
2018 for i, title := range []string{"Fix the login", "Fix the search"} {
2019 key := "na-" + strconv.Itoa(i)
2020 id := o.record(key+"-rec", title)
2021 if res := o.call(key+"-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}); res.IsError {
2022 o.t.Fatalf("start %+v", res)
2023 }
2024 _, body := o.expect(wire.FrameDispatch)
2025 ids, steps = append(ids, id), append(steps, body.(*wire.DispatchCommand).StepID)
2026 }
2027 })
2028 reasons := []string{"provider_failed", wire.ReasonMergeCredential}
2029 if order == "refused_first" {
2030 reasons[0], reasons[1] = reasons[1], reasons[0]
2031 }
2032 for i, step := range steps {
2033 o.exec("UPDATE chat_steps SET specialist = ?, state = ?, terminated = 1, reason = ? WHERE id = ?", wire.SpecialistMerge, wire.StepFailed, reasons[i], step)
2034 }
2035 if _, err := o.client.PostThread(o.ctx, ids[0], "For the record.", "na-note"); err != nil {
2036 t.Fatal(err)
2037 }
2038 if note := o.noteFor("the note", blockedOn(noAccessLine)); strings.Contains(note, "try it again") {
2039 t.Fatalf("note %q", note)
2040 }
2041 })
2042 }
2043}
2044