package thintest import ( "encoding/json" "fmt" "html" "net/http" "regexp" "slices" "strconv" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/wire" ) // teamRig is an Assistant rig whose runner can reach the sample // repository, so a hand-off's Coordinator turn can record work there. // The registry is the app's own: Base's provider, then the team's. Its // runner speaks job lanes (protocol 22). type teamRig struct{ *opsRig } func newTeamRig(t *testing.T) *teamRig { return newTeamRigAt(t, wire.ProtocolJobs) } // newTeamRigAt is newTeamRig whose runner speaks protocol. func newTeamRigAt(t *testing.T, protocol int) *teamRig { o := newOpsRigAt(t, protocol) // The person reached the Assistant through their Base, which holds // their abilities (all on): with Base's hosts set, nothing switched // runs for anyone without one (abilities §5.3). o.connect(o.base.Token) o.inst.Store.Chat().SetHousekeepingClock(daytime()) if err := o.runner.Send(o.ctx, "h-team", wire.FrameHello, primaryAt(toolHello(o.runner.Welcome.Generation), protocol)); err != nil { t.Fatal(err) } if refused := o.lease(o.runner, "h-team-ping", wire.LeaseCheck{}); refused != "" { t.Fatalf("ping refused %q", refused) } return &teamRig{o} } // message is the next message command in lane, acked: one already held, // or the next to arrive, holding the frames before it. func (o *teamRig) message(lane string) *wire.MessageCommand { o.t.Helper() for { for i, h := range o.held { if cmd, ok := h.body.(*wire.MessageCommand); ok && cmd.Lane == lane { o.held = append(o.held[:i:i], o.held[i+1:]...) if err := o.runner.Send(o.ctx, "a-"+h.f.ID, wire.FrameAck, wire.Ack{ID: h.f.ID}); err != nil { o.t.Fatal(err) } return cmd } } f, body, err := o.runner.Next(o.ctx) if err != nil { o.t.Fatalf("waiting for a message in lane %q: %v", lane, err) } if f.Type != wire.FrameAck { o.held = append(o.held, heldFrame{f, body, o.runner.Received[len(o.runner.Received)-1]}) } } } // ask sends an Assistant message and makes its turn the rig's. func (o *teamRig) ask(text string) string { o.t.Helper() sent, err := o.a.Send(o.ctx, text, "a-"+itoa(len(o.runner.Sent))) if err != nil { o.t.Fatal(err) } if cmd := o.message(wire.LaneAssistant); cmd.TurnID != sent.Turn.ID { o.t.Fatalf("the Assistant's message went as %+v", cmd) } o.turn, o.attempt = sent.Turn.ID, 0 return sent.Turn.ID } // request is team_request's answer: the request id. func (o *teamRig) request(id string, input map[string]any) string { o.t.Helper() res := o.use(id, "team_request", input) var out struct{ Request, Status string } if res.IsError || res.Code != "used" || json.Unmarshal([]byte(res.Text), &out) != nil || out.Request == "" || out.Status == "" { o.t.Fatalf("team_request %+v", res) } return out.Request } // handoff hands words to the team from the rig's Assistant turn and // returns the request and the message command of its thread. func (o *teamRig) handoff(id, words, context string) (string, *wire.MessageCommand) { o.t.Helper() in := map[string]any{"words": words} if context != "" { in["context"] = context } request := o.request(id, in) return request, o.message(wire.JobLane(request)) } // handoffTurn is the turn that carries the request's words. func (o *teamRig) handoffTurn(request string) string { o.t.Helper() var turn string 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 { o.t.Fatal(err) } return turn } // thread is the messages of the request's Coordinator thread, oldest // first. func (o *teamRig) thread(request string) []wire.Message { o.t.Helper() rows, err := o.inst.DB.Writer().Query("SELECT id, role, text, turn_id FROM chat_messages WHERE lane = ? ORDER BY seq", wire.JobLane(request)) if err != nil { o.t.Fatal(err) } defer rows.Close() var out []wire.Message for rows.Next() { var m wire.Message if err := rows.Scan(&m.ID, &m.Role, &m.Text, &m.TurnID); err != nil { o.t.Fatal(err) } out = append(out, m) } if err := rows.Err(); err != nil { o.t.Fatal(err) } return out } // handedTexts are the person messages of every job thread, oldest first. func (o *teamRig) handedTexts() []string { o.t.Helper() rows, err := o.inst.DB.Writer().Query("SELECT text FROM chat_messages WHERE lane LIKE 'job:%' AND role = ? ORDER BY seq", wire.RolePerson) if err != nil { o.t.Fatal(err) } defer rows.Close() var out []string for rows.Next() { var text string if err := rows.Scan(&text); err != nil { o.t.Fatal(err) } out = append(out, text) } if err := rows.Err(); err != nil { o.t.Fatal(err) } return out } // threadQuestion is the open question card raised in the request's // thread: its id and revision. func (o *teamRig) threadQuestion(request string) (string, int64) { o.t.Helper() var id string var revision int64 o.until("the thread's question card", func() bool { 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) return err == nil }) return id, revision } // laneOf is the turn's lane. func (o *teamRig) laneOf(turn string) string { o.t.Helper() var lane string if err := o.inst.DB.Writer().QueryRow("SELECT coalesce(lane, '') FROM chat_turns WHERE id = ?", turn).Scan(&lane); err != nil { o.t.Fatal(err) } return lane } // in runs f with the rig's tool calls in turn. func (o *teamRig) in(turn string, f func()) { o.t.Helper() was, attempt := o.turn, o.attempt o.turn, o.attempt = turn, 0 defer func() { o.turn, o.attempt = was, attempt }() f() } // reply ends a turn with a reply. func (o *teamRig) reply(turn string) { o.t.Helper() o.seq++ if err := o.runner.Send(o.ctx, "r-reply-"+itoa(o.seq), wire.FrameReply, wire.Reply{TurnID: turn, Attempt: 1, Text: "Done."}); err != nil { o.t.Fatal(err) } o.until("turn "+turn+" replied", func() bool { return o.rows("SELECT count(*) FROM chat_turns WHERE id = ? AND state = ?", turn, wire.TurnReplied) == 1 }) } // own is a Coordinator turn the person started in Equipo. func (o *teamRig) own(text string) string { o.t.Helper() sent, err := o.client.Send(o.ctx, text, "own-"+itoa(len(o.runner.Sent))) if err != nil { o.t.Fatal(err) } if cmd := o.message(wire.LaneCoordinator); cmd.TurnID != sent.Turn.ID { o.t.Fatalf("the person's message went as %+v", cmd) } return sent.Turn.ID } // record records a task in the rig's turn. func (o *teamRig) record(key, title string) string { o.t.Helper() return taskID(o.t, o.call(key, wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": title, "brief": title, "separate": true})) } type teamSummary struct { Request string `json:"request"` Summary string `json:"summary"` } // status is team_status's requests. func (o *teamRig) status(id string, input map[string]any) []teamSummary { o.t.Helper() res := o.use(id, "team_status", input) var out struct { Requests []teamSummary `json:"requests"` } if res.IsError || json.Unmarshal([]byte(res.Text), &out) != nil || out.Requests == nil { o.t.Fatalf("team_status %+v", res) } return out.Requests } // linked is the hand-off's tasks: task id to created. func (o *teamRig) linked(request string) map[string]bool { o.t.Helper() rows, err := o.inst.DB.Writer().Query("SELECT task_id, created FROM chat_handoff_tasks WHERE handoff_id = ?", request) if err != nil { o.t.Fatal(err) } defer rows.Close() out := map[string]bool{} for rows.Next() { var id string var created bool if err := rows.Scan(&id, &created); err != nil { o.t.Fatal(err) } out[id] = created } if err := rows.Err(); err != nil { o.t.Fatal(err) } return out } // updates are the person's team_update turns, oldest first. func (o *teamRig) updates() (ids, notes []string, dispatched []bool) { o.t.Helper() 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) if err != nil { o.t.Fatal(err) } defer rows.Close() for rows.Next() { var id, note string var d bool if err := rows.Scan(&id, ¬e, &d); err != nil { o.t.Fatal(err) } ids, notes, dispatched = append(ids, id), append(notes, note), append(dispatched, d) } if err := rows.Err(); err != nil { o.t.Fatal(err) } return ids, notes, dispatched } // TestContractTeamRequest: team_request posts the person's words into // a Coordinator thread of the request's own (lane job:) as // their message, with the Assistant's context beside it as marked // reference in the frame only, and links the Assistant turn, the message // and its turn. Their own conversation gets none of it. func TestContractTeamRequest(t *testing.T) { o := newTeamRig(t) turn := o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("tr1", "Login is broken", "They mean the Tito app") lane := wire.JobLane(request) 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]") { t.Fatalf("coordinator frame %+v", cmd) } thread := o.thread(request) if len(thread) != 1 { t.Fatalf("thread %+v", thread) } m := thread[0] if m.Role != wire.RolePerson || m.Text != "Login is broken" || m.TurnID != cmd.TurnID || o.laneOf(cmd.TurnID) != lane { t.Fatalf("thread message %+v", m) } if page, err := o.client.Messages(o.ctx, "", 50); err != nil || len(page.Items) != 0 { t.Fatalf("their own conversation %+v %v", page, err) } 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 { t.Fatalf("%d hand-off rows link the turns", n) } // The Assistant's lane keeps only its own words. 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" { t.Fatalf("assistant messages %+v %v", mine, err) } // Audited by its id alone, as the person. if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.handoff' AND record_id = ? AND actor = ?", request, Owner); n != 1 { t.Fatalf("%d hand-off audits", n) } // A hand-off's message key belongs to the instance. if _, err := o.client.Send(o.ctx, "Login is broken", "handoff:"+request); Status(err) != 422 { t.Fatalf("a client key in the instance's space: %v", err) } } // TestContractTeamRequestTitle (D10): team_request's title names the // job: stored, returned and listed on /jobs. A title of more than 60 // characters, or not one line, is refused and hands nothing over. With // none, the person's words name it, cut to 60 characters at a space. func TestContractTeamRequestTitle(t *testing.T) { o := newTeamRig(t) turn := o.ask("Can we fix a bug in Tito? Login is broken") 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"} { 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" { t.Fatalf("title %q: %+v", title, res) } } if n := o.rows("SELECT count(*) FROM chat_handoffs"); n != 0 || len(o.handedTexts()) != 0 { t.Fatalf("%d hand-offs after bad titles, handed %v", n, o.handedTexts()) } res := o.use("tt1", "team_request", map[string]any{"words": "Login is broken", "title": "Fixing the sign-in page"}) var out struct{ Request, Status, Title string } if res.IsError || json.Unmarshal([]byte(res.Text), &out) != nil || out.Request == "" || out.Status != "sent" || out.Title != "Fixing the sign-in page" { t.Fatalf("team_request %+v", res) } o.message(wire.JobLane(out.Request)) 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 { t.Fatalf("replayed %+v", again) } if n := o.rows("SELECT count(*) FROM chat_handoffs WHERE id = ? AND title = ?", out.Request, "Fixing the sign-in page"); n != 1 { t.Fatal("the title is not stored") } o.reply(turn) words := "Checkout is slow when I pay with a card on my phone at the weekend" o.ask(words) untitled := o.request("tt2", map[string]any{"words": words}) o.message(wire.JobLane(untitled)) fallback := "Checkout is slow when I pay with a card on my phone at the…" if n := o.rows("SELECT count(*) FROM chat_handoffs WHERE id = ? AND title = ?", untitled, fallback); n != 1 { t.Fatal("an untitled request is not named by the person's words") } list := html.UnescapeString(o.get(o.inst.Cookie(), "/jobs", http.StatusOK)) for request, title := range map[string]string{out.Request: "Fixing the sign-in page", untitled: fallback} { if !strings.Contains(list, `href="/jobs/`+request+`">`+title+``) { t.Fatalf("/jobs lacks %s titled %q: %.900s", request, title, list) } } if strings.Contains(list, "Login is broken") { t.Fatal("/jobs lists the words of a titled job") } } // TestContractTeamRequestNotTheirWords: words the person's messages in // the turn do not contain are refused and post nothing; a quote differing // only in case and spacing posts the person's own words. A team_update // turn has no words of the person's to hand over. func TestContractTeamRequestNotTheirWords(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") for i, words := range []string{"Checkout is slow", "lo", "Login is broken and so is checkout", " "} { if res := o.use("nw"+itoa(i), "team_request", map[string]any{"words": words}); !res.IsError || res.Code != "not_their_words" { t.Fatalf("words %q: %+v", words, res) } } if n := o.rows("SELECT count(*) FROM chat_handoffs"); n != 0 || len(o.handedTexts()) != 0 { t.Fatalf("%d hand-offs, handed %v", n, o.handedTexts()) } _, cmd := o.handoff("nw-ok", "LOGIN is \n broken", "") if len(cmd.PersonText) != 0 || withoutProjectContext(t, cmd.Text) != "Login is broken" || !slices.Equal(o.handedTexts(), []string{"Login is broken"}) { t.Fatalf("quoted %+v, messages %v", cmd, o.handedTexts()) } update := o.updateTurn(cmd) o.in(update, func() { if res := o.use("nw-update", "team_request", map[string]any{"words": "Login is broken"}); !res.IsError || res.Code != "not_asked" { t.Fatalf("team_request in a team_update turn %+v", res) } }) if n := o.rows("SELECT count(*) FROM chat_handoffs"); n != 1 || len(o.handedTexts()) != 1 { t.Fatalf("%d hand-offs after the update, handed %v", n, o.handedTexts()) } } // updateTurn takes a hand-off's Coordinator turn to a recorded task the // person then cancels in Equipo, ends the Assistant turn, and returns // the team_update turn that follows, dispatched. func (o *teamRig) updateTurn(cmd *wire.MessageCommand) string { o.t.Helper() var id string o.in(cmd.TurnID, func() { id = o.record("up-rec", "Fix the login") }) o.reply(cmd.TurnID) o.reply(o.turn) if _, err := o.client.CancelTask(o.ctx, id); err != nil { o.t.Fatal(err) } u := o.message(wire.LaneAssistant) if u.Kind != wire.TurnTeamUpdate { o.t.Fatalf("update frame %+v", u) } return u.TurnID } // TestContractTeamRequestOnce: a retry under another call id, worded // otherwise around the same words, or in attempt 2 is the one request. func TestContractTeamRequestOnce(t *testing.T) { o := newTeamRig(t) turn := o.ask("Can we fix a bug in Tito? Login is broken") in := map[string]any{"words": "Login is broken", "context": "They mean the Tito app"} request, _ := o.handoff("o1", "Login is broken", "They mean the Tito app") if again := o.use("o2", "team_request", in); again.IsError || !again.Replayed || !strings.Contains(again.Text, request) { t.Fatalf("again %+v", again) } if other := o.request("o3", map[string]any{"words": "login is broken", "context": "The Tito app, they said"}); other != request { t.Fatalf("reworded retry is %s, not %s", other, request) } o.runner.Send(o.ctx, "r-wait", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnWaiting, Reason: "limited"}) o.runner.Send(o.ctx, "r-run2", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 2, State: wire.TurnRunning}) o.until("attempt 2", func() bool { return o.rows("SELECT count(*) FROM chat_turns WHERE id = ? AND attempt = 2 AND state = ?", turn, wire.TurnRunning) == 1 }) o.attempt = 2 if moved := o.request("o4", in); moved != request { t.Fatalf("attempt 2 is %s", moved) } if n := o.rows("SELECT count(*) FROM chat_handoffs"); n != 1 || !slices.Equal(o.handedTexts(), []string{"Login is broken"}) { t.Fatalf("%d hand-offs, handed %v", n, o.handedTexts()) } if n := o.rows("SELECT count(*) FROM runner_commands WHERE kind = ? AND body NOT LIKE ?", wire.FrameMessage, `%"lane":"assistant"%`); n != 1 { t.Fatalf("%d coordinator message commands", n) } } // TestContractHandoffFollowsTasks: the hand-off follows the tasks its // turn records (created) or joins (touched), and those of the turn that // carries the answer to its question; work the person started in Equipo // is linked to nothing. func TestContractHandoffFollowsTasks(t *testing.T) { o := newTeamRig(t) mine := o.own("Two things of my own.") var joined, untouched string o.in(mine, func() { joined = o.record("f-own1", "Dark mode for settings") untouched = o.record("f-own2", "Export to CSV") }) o.reply(mine) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("f1", "Login is broken", "") var created string o.in(cmd.TurnID, func() { created = o.record("f-rec", "Fix the login") if res := o.call("f-rep", wire.ToolAddReport, map[string]string{"task": joined, "text": "Login is broken too."}); res.IsError { t.Fatalf("add_report %+v", res) } if res := o.call("f-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) o.reply(cmd.TurnID) card, revision := o.threadQuestion(request) ans, err := o.client.Answer(o.ctx, card, "Web", revision) if err != nil { t.Fatal(err) } if next := o.message(wire.JobLane(request)); next.TurnID != ans.Turn.ID { t.Fatalf("answer frame %+v", next) } var later string o.in(ans.Turn.ID, func() { later = o.record("f-later", "Fix the web login page") }) o.reply(ans.Turn.ID) // Then the person's own new work, in Equipo. again := o.own("One more of my own.") var own string o.in(again, func() { own = o.record("f-own3", "Bigger buttons") }) got := o.linked(request) want := map[string]bool{created: true, joined: false, later: true} if len(got) != len(want) { t.Fatalf("linked %v, want %v", got, want) } for id, c := range want { if v, ok := got[id]; !ok || v != c { t.Fatalf("linked %v, want %v", got, want) } } for _, id := range []string{untouched, own} { if n := o.rows("SELECT count(*) FROM chat_handoff_tasks WHERE task_id = ?", id); n != 0 { t.Fatalf("the person's own task %s is linked", id) } } // The answer's turn is the request's by its thread. 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) { t.Fatalf("%d hand-off turns, the answer's in %q", n, o.laneOf(ans.Turn.ID)) } } // TestContractTeamStatus: the summary says where the work is in plain // words, with each finding's headline, the preview link while it is up // and the published address once there is one, and nothing of the // team's machinery. all adds the person's own open work. func TestContractTeamStatus(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) o.sitesOn(wire.ProtocolCurrent, true) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("s1", "Login is broken", "") // A read runs again on each call, in the same words as before. if got := o.status("s-none", map[string]any{}); len(got) != 1 || got[0].Request != request || got[0].Summary != equipo.RunnerCopy("assistant.team.received") { t.Fatalf("before any task %+v", got) } base, cand, merged := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("e", 40) var id string o.in(cmd.TurnID, func() { id, _ = o.websiteReady("w", "Quick website", base, cand, true) 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 { t.Fatalf("finding %+v", res) } }) k, err := o.client.Task(o.ctx, id) if err != nil { t.Fatal(err) } machinery := func(summary string, preview string) { t.Helper() bare := strings.ReplaceAll(summary, preview, "") for _, bad := range []string{id, "amadan.net/oficina/sample", k.Branch, base, cand, merged, "/tasks/"} { if strings.Contains(bare, bad) { t.Fatalf("the summary says %q: %s", bad, summary) } } if regexp.MustCompile(`[0-9a-f]{40}`).MatchString(bare) { t.Fatalf("a SHA in the summary: %s", summary) } } one := func(key string) string { t.Helper() got := o.status("s-"+key, map[string]any{"request": request}) if len(got) != 1 || got[0].Request != request { t.Fatalf("status %+v", got) } return got[0].Summary } ready := one("ready") 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://") { t.Fatalf("ready %q", ready) } machinery(ready, "") pv := o.previewDispatch(cand) if pv == nil { t.Fatal("no preview") } o.built("s-pv-built", pv, digestA) link := "https://eq-" + id + ".docs-t1.example.ts.net/" o.previewDone("s-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, Outcome: wire.PreviewDeployed}) link = o.inst.URL + "/tasks/" + id + "/preview" previewed := one("preview") if !strings.Contains(previewed, strings.ReplaceAll(equipo.RunnerCopy("assistant.team.preview"), "%s", link)) { t.Fatalf("with the preview %q", previewed) } machinery(previewed, link) o.mergeFromCard("s-m", id, base, cand, merged) pub, ok := o.publishCard(id) if !ok { t.Fatal("no publish card") } if _, err := o.client.Answer(o.ctx, pub.ID, wire.ChoicePublish, pub.Revision); err != nil { t.Fatal(err) } d := o.publishDispatch() o.publishReport("s-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40}) site := "https://" + d.Publish.App + ".bds.oncarlos.com/" 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}) live := one("live") 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) { t.Fatalf("published %q", live) } machinery(live, "") o.reply(cmd.TurnID) // The person's own open work is in Equipo: only all reports it. mine := o.own("Something of my own.") o.in(mine, func() { o.record("s-own", "Dark mode for settings") }) if got := o.status("s-requests", map[string]any{}); len(got) != 1 || got[0].Request != request { t.Fatalf("requests %+v", got) } all := o.status("s-all", map[string]any{"all": true}) 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")) { t.Fatalf("all %+v", all) } if res := o.use("s-missing", "team_status", map[string]any{"request": "h_missing"}); !res.IsError || res.Code != "not_found" { t.Fatalf("an unknown request %+v", res) } } // TestContractTeamCancel: team_cancel cancels the tasks the request // created and none it joined; another person's request is not found. func TestContractTeamCancel(t *testing.T) { o := newTeamRig(t) mine := o.own("Something of my own.") var joined string o.in(mine, func() { joined = o.record("c-own", "Dark mode for settings") }) o.reply(mine) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("c1", "Login is broken", "") var created string o.in(cmd.TurnID, func() { created = o.record("c-rec", "Fix the login") if res := o.call("c-rep", wire.ToolAddReport, map[string]string{"task": joined, "text": "Login is broken too."}); res.IsError { t.Fatalf("add_report %+v", res) } }) o.reply(cmd.TurnID) // Another owner cannot see or cancel it. mate := &teamRig{o.other("mate@example.com")} mate.ask("Cancel that, Login is broken") for _, op := range []string{"team_cancel", "team_status"} { if res := mate.use("c-mate-"+op, op, map[string]any{"request": request}); !res.IsError || res.Code != "not_found" { t.Fatalf("%s for another person's request %+v", op, res) } } // Read, cancel, read: in the same words, the second read sees the // cancel. A delivery retry of a call (its id) gets what it got. read := map[string]any{"request": request} before := o.status("c-read1", read) res := o.use("c-cancel", "team_cancel", map[string]any{"request": request}) if res.IsError || res.Text != `{"cancelled":1,"still_running":0}` { t.Fatalf("cancel %+v", res) } after := o.use("c-read2", "team_status", read) 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")) { t.Fatalf("read before the cancel %+v, after %+v", before, after) } audits := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.use'") if retry := o.use("c-read2", "team_status", read); retry.Text != after.Text || retry.IsError { t.Fatalf("delivery retry %+v, first %+v", retry, after) } if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.use'"); n != audits { t.Fatalf("a delivery retry ran again: %d audits, %d before", n, audits) } for id, stage := range map[string]string{created: wire.StageCancelled, joined: wire.StageNoted} { if k, err := o.client.Task(o.ctx, id); err != nil || k.Stage != stage { t.Fatalf("task %s at %s %v", id, k.Stage, err) } } if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.team_cancel' AND record_id = ? AND actor = ?", request, Owner); n != 1 { t.Fatalf("%d cancel audits", n) } // Asked again in the turn, it answers as it did and cancels nothing more. if again := o.use("c-again", "team_cancel", map[string]any{"request": request}); again.IsError || !again.Replayed || again.Text != res.Text { t.Fatalf("again %+v", again) } if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.team_cancel'"); n != 1 { t.Fatalf("%d cancel audits after the retry", n) } } // TestContractTeamUpdate: when the hand-off's work stops, is cancelled // or is done, one team_update turn is queued with the job's note as its // text (where it stands is the summary; cancelled work is never done); a // change while it waits rewrites it; a change that leaves the note as it // was queues nothing. // That turn only looks and tells. func TestContractTeamUpdate(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("u1", "Login is broken", "") var id string o.in(cmd.TurnID, func() { id = o.record("u-rec", "Fix the login") if res := o.call("u-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}); res.IsError { t.Fatalf("start %+v", res) } _, body := o.expect(wire.FrameDispatch) d := body.(*wire.DispatchCommand) o.step("u-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: strings.Repeat("1", 40)}) if ids, _, _ := o.updates(); len(ids) != 0 { t.Fatalf("an update while the work runs: %v", ids) } o.step("u-fail", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true}) }) o.reply(cmd.TurnID) // The Assistant's turn still runs: the update waits behind it. ids, notes, dispatched := o.updates() 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.") { t.Fatalf("after the failure %v %q %v", ids, notes, dispatched) } if _, err := o.client.CancelTask(o.ctx, id); err != nil { t.Fatal(err) } summary := o.status("u-status", map[string]any{"request": request})[0].Summary again, notes, dispatched := o.updates() // Every followed task cancelled is not done (D5): the Assistant hears // it was cancelled, and speaks only if the person did not cancel it. 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 if !slices.Equal(again, ids) || dispatched[0] || notes[0] != cancelled || !strings.Contains(summary, equipo.RunnerCopy("assistant.team.stage.cancelled")) { t.Fatalf("after the cancel %v %q %v (summary %q)", again, notes, dispatched, summary) } o.reply(o.turn) u := o.message(wire.LaneAssistant) if u.TurnID != ids[0] || u.Kind != wire.TurnTeamUpdate || u.Text != notes[0] || len(u.PersonText) != 0 { t.Fatalf("update frame %+v", u) } o.in(u.TurnID, func() { for _, op := range []string{"team_request", "team_cancel"} { if res := o.use("u-"+op, op, map[string]any{"words": "Login is broken", "request": request}); !res.IsError || res.Code != "not_asked" { t.Fatalf("%s in the update %+v", op, res) } } if got := o.status("u-look", map[string]any{"request": request}); len(got) != 1 { t.Fatalf("status in the update %+v", got) } for _, tool := range []string{wire.ToolAskPerson, wire.ToolWriteNote} { if res := o.call("u-"+tool, tool, map[string]any{}); !res.IsError || res.Code != "unknown_tool" { t.Fatalf("%s in the update %+v", tool, res) } } }) o.reply(u.TurnID) // A note on the thread changes the task, not what the person is told. if _, err := o.client.PostThread(o.ctx, id, "For the record.", "n1"); err != nil { t.Fatal(err) } time.Sleep(50 * time.Millisecond) if after, _, _ := o.updates(); len(after) != 1 { t.Fatalf("updates after an equal summary %v", after) } } // TestContractHandoffTurnIsItsOwn: while the person's own conversation // is busy, the hand-off's words go at once in a turn of their own, in // the request's thread: they join no batch of the person's, and nothing // the person sends later joins theirs. func TestContractHandoffTurnIsItsOwn(t *testing.T) { o := newTeamRig(t) busy := o.own("Something of my own.") queued, err := o.client.Send(o.ctx, "And a second thing.", "own-queued") if err != nil || queued.Turn.ID == busy { t.Fatalf("queued %+v %v", queued, err) } o.ask("Can we fix a bug in Tito? Login is broken") request := o.request("b1", map[string]any{"words": "Login is broken"}) turn := o.handoffTurn(request) if turn == queued.Turn.ID || turn == busy || o.laneOf(turn) != wire.JobLane(request) { t.Fatalf("the hand-off's turn %q in %q (queued %s)", turn, o.laneOf(turn), queued.Turn.ID) } if cmd := o.message(wire.JobLane(request)); cmd.TurnID != turn { t.Fatalf("the hand-off's frame %+v", cmd) } later, err := o.client.Send(o.ctx, "And a third thing.", "own-later") if err != nil || later.Turn.ID != queued.Turn.ID { t.Fatalf("later %+v %v", later.Turn, err) } if n := o.rows("SELECT count(*) FROM chat_messages WHERE turn_id = ?", turn); n != 1 { t.Fatalf("%d messages in the hand-off's turn", n) } } // TestContractHandoffAnswerTurnIsItsOwn: the answer to a hand-off's // question, sent while its thread is busy, waits in the thread and joins // none of the person's own work: that work stays theirs, and team_cancel // cannot reach what it records. func TestContractHandoffAnswerTurnIsItsOwn(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("aq1", "Login is broken", "") o.in(cmd.TurnID, func() { if res := o.call("aq-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) // The hand-off's turn still runs; the person's own work goes at once. mine, err := o.client.Send(o.ctx, "Export to CSV, please.", "own-mine") if err != nil || mine.Turn.ID == cmd.TurnID { t.Fatalf("mine %+v %v", mine.Turn, err) } if next := o.message(wire.LaneCoordinator); next.TurnID != mine.Turn.ID { t.Fatalf("their own frame %+v", next) } card, revision := o.threadQuestion(request) ans, err := o.client.Answer(o.ctx, card, "Web", revision) if err != nil { t.Fatal(err) } if ans.Turn.ID == mine.Turn.ID || ans.Turn.State != wire.TurnQueued || o.laneOf(ans.Turn.ID) != wire.JobLane(request) { t.Fatalf("the answer's turn %+v in %q", ans.Turn, o.laneOf(ans.Turn.ID)) } if n := o.rows("SELECT count(*) FROM chat_handoff_turns WHERE turn_id = ?", mine.Turn.ID); n != 0 { t.Fatal("the person's own turn is the hand-off's") } o.reply(cmd.TurnID) if next := o.message(wire.JobLane(request)); next.TurnID != ans.Turn.ID { t.Fatalf("next frame %+v", next) } var own string o.in(mine.Turn.ID, func() { own = o.record("aq-own", "Export to CSV") }) if n := o.rows("SELECT count(*) FROM chat_handoff_tasks WHERE task_id = ?", own); n != 0 { t.Fatalf("the person's own task %s is linked", own) } } // TestContractTeamCancelWhileMerging: a task the request created that is // merging cannot be cancelled; team_cancel says it is still running and // the request stays followed, so its end is still told. func TestContractTeamCancelWhileMerging(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("cm1", "Login is broken", "") base, cand, merged := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("e", 40) var id string o.in(cmd.TurnID, func() { id, _ = o.websiteReady("cm", "Quick website", base, cand, false) }) card := o.cardOf(id) if _, err := o.client.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil { t.Fatalf("merge %v", err) } m := o.dispatched(wire.SpecialistMerge, base, cand, 0) res := o.use("cm-cancel", "team_cancel", map[string]any{"request": request}) if res.IsError || res.Text != `{"cancelled":0,"still_running":1}` { t.Fatalf("cancel while merging %+v", res) } // Cancelled while its work goes on: followed (stopping) until it ends. if n := o.rows("SELECT count(*) FROM chat_handoffs WHERE id = ? AND state = 'stopping'", request); n != 1 { t.Fatal("the request stopped being followed") } if got := o.status("cm-status", map[string]any{}); len(got) != 1 || got[0].Request != request { t.Fatalf("open requests %+v", got) } // Its turns start no new work while it is followed. o.in(cmd.TurnID, func() { 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" { t.Fatalf("record_task while stopping %+v", res) } }) o.mergedStep("cm-m", m, merged) o.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) if ids, notes, _ := o.updates(); len(ids) != 1 || !strings.Contains(notes[0], equipo.RunnerCopy("assistant.team.stage.done")) { t.Fatalf("updates after the merge %v %q", ids, notes) } } // commandsFor counts the runner commands of kind that name the turn. func (o *teamRig) commandsFor(kind, turn string) int { o.t.Helper() return o.rows("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", kind, `%"turn_id":"`+turn+`"%`) } // turnState is the turn's state. func (o *teamRig) turnState(turn string) string { o.t.Helper() var s string if err := o.inst.DB.Writer().QueryRow("SELECT state FROM chat_turns WHERE id = ?", turn).Scan(&s); err != nil { o.t.Fatal(err) } return s } // TestContractTeamCancelStopsQueuedTurn: a request cancelled while a // turn of its thread still waits behind another ends that turn: it never // runs, and the person is told nothing more. The waiting turn here // carries the answer the person gave in Equipo to the thread's question. func TestContractTeamCancelStopsQueuedTurn(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("cq1", "Login is broken", "") o.in(cmd.TurnID, func() { if res := o.call("cq-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) card, revision := o.threadQuestion(request) ans, err := o.client.Answer(o.ctx, card, "Web", revision) if err != nil { t.Fatal(err) } turn := ans.Turn.ID if s := o.turnState(turn); s != wire.TurnQueued || o.laneOf(turn) != wire.JobLane(request) { t.Fatalf("the answer's turn is %s in %q", s, o.laneOf(turn)) } told, notes, _ := o.updates() res := o.use("cq-cancel", "team_cancel", map[string]any{"request": request}) if res.IsError || res.Text != `{"cancelled":0,"still_running":0}` { t.Fatalf("cancel %+v", res) } if s := o.turnState(turn); s != wire.TurnCancelled { t.Fatalf("after the cancel the answer's turn is %s", s) } if n := o.commandsFor(wire.FrameCancel, cmd.TurnID); n != 1 { t.Fatalf("%d cancel commands for the running turn", n) } o.runner.Send(o.ctx, "r-cq-end", wire.FrameTurn, wire.TurnReport{TurnID: cmd.TurnID, Attempt: 1, State: wire.TurnCancelled}) o.until("the running turn ended", func() bool { return o.turnState(cmd.TurnID) == wire.TurnCancelled }) // The person's next message runs; the answer never does. next, err := o.client.Send(o.ctx, "And another thing.", "own-next") if err != nil { t.Fatal(err) } if cmd := o.message(wire.LaneCoordinator); cmd.TurnID != next.Turn.ID { t.Fatalf("next coordinator frame %+v", cmd) } if n := o.commandsFor(wire.FrameMessage, turn); n != 0 { t.Fatalf("the cancelled answer's turn went to the runner %d times", n) } // Told of the question before the cancel; nothing after it. if ids, after, _ := o.updates(); !slices.Equal(ids, told) || !slices.Equal(after, notes) { t.Fatalf("updates after the cancel %v %q, before %v %q", ids, after, told, notes) } } // TestContractTeamCancelStopsRunningTurn: a request cancelled while its // Coordinator turn runs asks the runner to end the turn; until it ends, // the turn can create or start no work (record_task, start_task on a task // the request follows), and the person is told nothing more. func TestContractTeamCancelStopsRunningTurn(t *testing.T) { o := newTeamRig(t) mine := o.own("Something of my own.") var joined string o.in(mine, func() { joined = o.record("cr-own", "Dark mode for settings") }) o.reply(mine) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("cr1", "Login is broken", "") o.in(cmd.TurnID, func() { if res := o.call("cr-rep", wire.ToolAddReport, map[string]string{"task": joined, "text": "Login is broken too."}); res.IsError { t.Fatalf("add_report %+v", res) } }) res := o.use("cr-cancel", "team_cancel", map[string]any{"request": request}) if res.IsError || res.Text != `{"cancelled":0,"still_running":0}` { t.Fatalf("cancel %+v", res) } if n := o.commandsFor(wire.FrameCancel, cmd.TurnID); n != 1 { t.Fatalf("%d cancel commands for the hand-off's turn", n) } tasks := o.rows("SELECT count(*) FROM chat_tasks") o.in(cmd.TurnID, func() { late := o.call("cr-late", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Fix the login", "brief": "Fix the login", "separate": true}) if !late.IsError || late.Code != "request_cancelled" { t.Fatalf("record_task after the cancel %+v", late) } start := o.call("cr-start", wire.ToolStartTask, map[string]string{"task": joined}) if !start.IsError || start.Code != "request_cancelled" { t.Fatalf("start_task after the cancel %+v", start) } if res := o.call("cr-read", wire.ToolReadTask, map[string]string{"task": joined}); res.IsError { t.Fatalf("read_task after the cancel %+v", res) } if res := o.call("cr-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) if n := o.rows("SELECT count(*) FROM chat_tasks"); n != tasks { t.Fatalf("%d tasks after the cancel, %d before", n, tasks) } if n := o.rows("SELECT count(*) FROM chat_steps WHERE task_id = ?", joined); n != 0 { t.Fatalf("the followed task started after the cancel: %d steps", n) } if got := o.linked(request); len(got) != 1 || got[joined] { t.Fatalf("linked after the cancel %v", got) } o.runner.Send(o.ctx, "r-cr-end", wire.FrameTurn, wire.TurnReport{TurnID: cmd.TurnID, Attempt: 1, State: wire.TurnCancelled}) o.until("the turn ended", func() bool { return o.turnState(cmd.TurnID) == wire.TurnCancelled }) if ids, _, _ := o.updates(); len(ids) != 0 { t.Fatalf("updates after the cancel %v", ids) } if cards := o.assistantCards(); len(cards) != 0 { t.Fatalf("assistant cards after the cancel %+v", cards) } if n := o.rows("SELECT count(*) FROM chat_handoffs WHERE id = ? AND state = 'cancelled'", request); n != 1 { t.Fatal("the request is not cancelled") } // The person's own turn is not the request's: it still records work. again := o.own("One more of my own.") o.in(again, func() { o.record("cr-own2", "Bigger buttons") }) } // TestContractTeamCancelStopsAnswerTurn: a request cancelled while the // turn carrying the answer to its question waits in its thread ends // that turn too. func TestContractTeamCancelStopsAnswerTurn(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("ca1", "Login is broken", "") o.in(cmd.TurnID, func() { if res := o.call("ca-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) card, revision := o.threadQuestion(request) if _, err := o.client.Answer(o.ctx, card, "Web", revision); err != nil { t.Fatal(err) } var answer string 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 { t.Fatal(err) } if s := o.turnState(answer); s != wire.TurnQueued { t.Fatalf("the answer's turn is %s", s) } res := o.use("ca-cancel", "team_cancel", map[string]any{"request": request}) if res.IsError || res.Text != `{"cancelled":0,"still_running":0}` { t.Fatalf("cancel %+v", res) } if s := o.turnState(answer); s != wire.TurnCancelled { t.Fatalf("after the cancel the answer's turn is %s", s) } o.reply(cmd.TurnID) time.Sleep(50 * time.Millisecond) if n := o.commandsFor(wire.FrameMessage, answer); n != 0 { t.Fatalf("the cancelled answer's turn went to the runner %d times", n) } } // TestContractHandoffTurnFails: a hand-off whose Coordinator turn fails // before it records or joins any work has stopped with no work: the // Assistant is told once, to push it through itself, and team_status // says it stopped. A turn found gone when the runner reconnects has // failed the same way. func TestContractHandoffTurnFails(t *testing.T) { stopped := equipo.RunnerCopy("assistant.team.stopped") check := func(o *teamRig, request string) { t.Helper() o.until("the update", func() bool { ids, _, _ := o.updates(); return len(ids) == 1 }) want := jobLine("Login is broken", request, "Login is broken") + noWork(request, 2) + "\nWhere it stands:\n" + stopped if _, notes, _ := o.updates(); notes[0] != want { t.Fatalf("update %q, want %q", notes, want) } if got := o.status("hf-status", map[string]any{"request": request}); len(got) != 1 || got[0].Summary != stopped { t.Fatalf("status %+v", got) } } t.Run("failed", func(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("hf1", "Login is broken", "") if ids, _, _ := o.updates(); len(ids) != 0 { t.Fatalf("an update while the turn runs: %v", ids) } o.runner.Send(o.ctx, "r-hf-fail", wire.FrameTurn, wire.TurnReport{TurnID: cmd.TurnID, Attempt: 1, State: wire.TurnFailed, Reason: "provider_failed"}) check(o, request) }) t.Run("recovery", func(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("hf2", "Login is broken", "") // The runner comes back holding the Assistant's turn alone. 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{}}) o.until("the hand-off's turn failed", func() bool { return o.turnState(cmd.TurnID) == wire.TurnFailed }) check(o, request) }) } // TestContractHandoffJoinsOpenCards: a hand-off that joins the person's // own work already waiting on a merge go-ahead and the project's ships // question raises nothing in the Assistant lane and tells the person // nothing (J4): that work stays theirs, its cards in their conversation, // where Merge merges. func TestContractHandoffJoinsOpenCards(t *testing.T) { o := newTeamRig(t) o.sitesOn(wire.ProtocolAssistant, false) mine := o.own("Something of my own.") base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) var id string o.in(mine, func() { id, _ = o.websiteReady("jc", "Quick website", base, cand, false) }) o.reply(mine) merge, ships := o.cardOf(id), o.teamCard(wire.CardMergeShips, "", "") if merge.ID == "" || merge.State != wire.CardOpen || ships.ID == "" || ships.State != wire.CardOpen { t.Fatalf("merge card %+v, ships card %+v", merge, ships) } if cards := o.assistantCards(); len(cards) != 0 { t.Fatalf("assistant cards before the hand-off %+v", cards) } o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("jc1", "Login is broken", "") o.in(cmd.TurnID, func() { if res := o.call("jc-rep", wire.ToolAddReport, map[string]string{"task": id, "text": "Login is broken too."}); res.IsError { t.Fatalf("add_report %+v", res) } }) if got := o.linked(request); len(got) != 1 || got[id] { t.Fatalf("linked %v", got) } if cards := o.assistantCards(); len(cards) != 0 { t.Fatalf("assistant cards after the join %+v", cards) } if n := o.rows("SELECT count(*) FROM chat_cards WHERE source_card IN (?, ?)", merge.ID, ships.ID); n != 0 { t.Fatalf("%d mirrors of the person's own cards", n) } if ids, _, _ := o.updates(); len(ids) != 0 { t.Fatalf("the person is told of their own work: %v", ids) } if o.teamCard(wire.CardMerge, "", id).ID != merge.ID || o.teamCard(wire.CardMergeShips, "", "").ID != ships.ID { t.Fatal("the person's own cards left their conversation") } ans, err := o.client.Answer(o.ctx, merge.ID, wire.ChoiceMerge, merge.Revision) if err != nil || ans.Card.State != wire.CardAnswered { t.Fatalf("answer %+v %v", ans, err) } if after := o.teamCard(wire.CardMerge, "", id); after.ID != merge.ID || after.State != wire.CardAnswered || after.Choice != wire.ChoiceMerge { t.Fatalf("merge card %+v", after) } } // TestContractHandoffCardsFollowTheJob: work a job's thread records is // the job's (J4): the task is stored in lane job:, and its task // card, merge card, the project's ships question and its Publish card are // raised in the thread, never in the person's /api/v1/snapshot or // /api/v1/events. The go-ahead and Publish are mirrored to the Assistant // lane from there. func TestContractHandoffCardsFollowTheJob(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) // Handed over, merged from the go-ahead, and asked to publish. id, _, _, _ := o.mergedWebsite("cj", true) var request string if err := o.inst.DB.Writer().QueryRow("SELECT id FROM chat_handoffs").Scan(&request); err != nil { t.Fatal(err) } lane, turn := wire.JobLane(request), o.handoffTurn(request) if n := o.rows("SELECT count(*) FROM chat_tasks WHERE id = ? AND lane = ?", id, lane); n != 1 { t.Fatal("the task is not stored in the job's lane") } o.assistantCard("the publish outcome", isPublishOutcome) // Every card of the work: the task's, the turn's and the project's own. 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) if err != nil { t.Fatal(err) } cards := map[string]string{} var kinds []string for rows.Next() { var c, kind, in string if err := rows.Scan(&c, &kind, &in); err != nil { t.Fatal(err) } if in != lane { t.Fatalf("the job's %s card %s is in %q", kind, c, in) } cards[c] = kind kinds = append(kinds, kind) } if err := rows.Close(); err != nil { t.Fatal(err) } for _, kind := range []string{wire.CardTask, wire.CardMerge, wire.CardMergeShips, wire.CardPublish} { if !slices.Contains(kinds, kind) { t.Fatalf("no %s card in the thread: %v", kind, kinds) } } 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 { t.Fatalf("%d of the go-ahead and Publish mirrored from the thread", n) } // None of them is in the person's own conversation. snap, err := o.client.Snapshot(o.ctx) if err != nil { t.Fatal(err) } for _, c := range snap.Cards { if cards[c.ID] != "" || c.TaskID == id { t.Fatalf("the job's card in their snapshot %+v", c) } } o.conv.Locked(func(c *Conversation) { for _, k := range c.Cards { if cards[k.ID] != "" || k.TaskID == id { t.Errorf("the job's card in their events %+v", k) } } }) for c := range cards { if n := o.rows("SELECT count(*) FROM chat_events WHERE coalesce(lane, '') = '' AND body LIKE ?", `%"`+c+`"%`); n != 0 { t.Fatalf("%d events of the job's card %s in their stream", n, c) } } } // TestContractJoinedTaskStaysTheirs: a task the person started in their // own conversation that a job's thread joins (add_report) stays theirs // (lane ""): its merge card, raised after the join, is in their // conversation and is not mirrored, and they are told nothing of it. The // task card the join shows is in the thread, with the turn that joined. func TestContractJoinedTaskStaysTheirs(t *testing.T) { o := newTeamRig(t) mine := o.own("Something of my own.") var id string o.in(mine, func() { id = o.record("js-own", "Quick website") }) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("js1", "Login is broken", "") o.in(cmd.TurnID, func() { if res := o.call("js-rep", wire.ToolAddReport, map[string]string{"task": id, "text": "Login is broken too."}); res.IsError { t.Fatalf("add_report %+v", res) } }) if created, ok := o.linked(request)[id]; !ok || created { t.Fatalf("the job does not follow the task it joined: %v", o.linked(request)) } if joined := o.threadCard(wire.CardTask, cmd.TurnID); joined.ID == "" || o.laneOfCard(joined.ID) != wire.JobLane(request) || o.teamCard(wire.CardTask, cmd.TurnID, "").ID != "" { t.Fatalf("the join's task card %+v is not in the thread", joined) } base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) o.in(mine, func() { if res := o.call("js-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}); res.IsError { t.Fatalf("start %+v", res) } _, body := o.expect(wire.FrameDispatch) d := body.(*wire.DispatchCommand) o.step("js-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "claude-a"}) 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"}) o.expect(wire.FrameWatchMerge) c := o.dispatched(wire.SpecialistChecks, base, cand, 0) o.checks("js-c", c, wire.ChecksNone, nil, "", "") o.verdict("js-r", o.dispatched(wire.SpecialistReview, base, cand, 0), wire.VerdictApprove) }) o.until("the merge card", func() bool { return o.cardOf(id).ID != "" }) merge := o.cardOf(id) if o.laneOfCard(merge.ID) != "" || o.teamCard(wire.CardMerge, "", id).ID != merge.ID { t.Fatalf("the merge card %+v is not in their conversation", merge) } if n := o.rows("SELECT count(*) FROM chat_tasks WHERE id = ? AND coalesce(lane, '') = ''", id); n != 1 { t.Fatal("the joined task left the person's lane") } if cards := o.assistantCards(); len(cards) != 0 { t.Fatalf("assistant cards %+v", cards) } if ids, _, _ := o.updates(); len(ids) != 0 { t.Fatalf("the person is told of their own work: %v", ids) } } // TestContractHandoffLegacyApprovalsMirror: a legacy hand-off (lane "") // keeps slice 1's route for its approvals (J7): the task its turn records // stays in the person's conversation, and the merge card raised there // after this release still raises the go-ahead in the Assistant lane // through slice 1's path and tells the person; Merge there merges, and // the merge card stays in their conversation. func TestContractHandoffLegacyApprovalsMirror(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, turn := o.legacyHandoff("ap", "Login is broken") base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) var id string o.in(turn, func() { id, _ = o.websiteReady("ap", "Quick website", base, cand, false) }) if got := o.linked(request); !got[id] { t.Fatalf("linked %v", got) } if n := o.rows("SELECT count(*) FROM chat_tasks WHERE id = ? AND coalesce(lane, '') = ''", id); n != 1 { t.Fatal("the legacy hand-off's task is not in the person's lane") } merge := o.teamCard(wire.CardMerge, "", id) if merge.ID == "" || merge.State != wire.CardOpen { t.Fatalf("the merge card %+v is not in their conversation", merge) } card := o.assistantCard("the merge outcome", isMergeOutcome) if n := o.rows("SELECT count(*) FROM chat_cards WHERE id = ? AND source_card = ?", card.ID, merge.ID); n != 1 { t.Fatalf("the go-ahead %+v does not point at the merge card", card) } if ids, _, _ := o.updates(); len(ids) != 1 { t.Fatalf("the person is not told: %v", ids) } if ans, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil || ans.Card.State != wire.CardAnswered { t.Fatalf("answer %+v %v", ans, err) } if after := o.teamCard(wire.CardMerge, "", id); after.ID != merge.ID || after.State != wire.CardAnswered || after.Choice != wire.ChoiceMerge { t.Fatalf("merge card %+v", after) } } // TestContractHandoffThreadIsNotTheirConversation: a hand-off's thread // (its words, the Coordinator's reply, its question card, its turns) // never shows in the person's own conversation: not in // /api/v1/snapshot, /api/v1/messages, /api/v1/events or /conversation, // while that conversation answers in its own lane meanwhile. Answering // the thread's question through the person API puts the answer in the // thread and dispatches it there. func TestContractHandoffThreadIsNotTheirConversation(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("nc1", "Login is broken", "") lane := wire.JobLane(request) o.in(cmd.TurnID, func() { if res := o.call("nc-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page is it?", "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) 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 { t.Fatal(err) } o.until("the thread's reply", func() bool { return o.turnState(cmd.TurnID) == wire.TurnReplied }) // Meanwhile their own conversation answers in its own lane. mine := o.own("Something of my own.") o.reply(mine) o.wait("their own reply", func(c *Conversation) bool { return c.Turns[mine].State == wire.TurnReplied && len(c.Replies()) == 1 }) card, revision := o.threadQuestion(request) thread := o.thread(request) if len(thread) != 2 || thread[1].Role != wire.RoleCoordinator || thread[1].Text != "Looking at the sign in page." { t.Fatalf("thread %+v", thread) } hidden := map[string]bool{cmd.TurnID: true, card: true, request: true} for _, m := range thread { hidden[m.ID] = true } words := []string{"Login is broken", "Which login page is it?", "Looking at the sign in page."} theirs := func(stage string) { t.Helper() snap, err := o.client.Snapshot(o.ctx) if err != nil { t.Fatal(err) } page, err := o.client.Messages(o.ctx, "", 50) if err != nil { t.Fatal(err) } for _, m := range append(snap.Messages, page.Items...) { if hidden[m.ID] || hidden[m.TurnID] { t.Fatalf("%s: the thread's message in their conversation %+v", stage, m) } } for _, r := range snap.Turns { if hidden[r.ID] { t.Fatalf("%s: the thread's turn in their snapshot %+v", stage, r) } } for _, c := range snap.Cards { if hidden[c.ID] || hidden[c.TurnID] { t.Fatalf("%s: the thread's card in their snapshot %+v", stage, c) } } if len(snap.Messages) != len(page.Items) || len(snap.Messages) == 0 { t.Fatalf("%s: their conversation %+v, page %+v", stage, snap.Messages, page.Items) } o.conv.Locked(func(c *Conversation) { for id, m := range c.Messages { if hidden[id] || hidden[m.TurnID] { t.Errorf("%s: the thread's message in their events %+v", stage, m) } } for id := range c.Turns { if hidden[id] { t.Errorf("%s: the thread's turn in their events %s", stage, id) } } for id, k := range c.Cards { if hidden[id] || hidden[k.TurnID] { t.Errorf("%s: the thread's card in their events %+v", stage, k) } } }) body := o.inst.Get(t, "/conversation") for _, s := range append(words, card, cmd.TurnID) { if strings.Contains(body, s) { t.Fatalf("%s: /conversation shows %q", stage, s) } } } theirs("before the answer") // The thread's question, answered through the person API: the answer // is the thread's next message, dispatched there. ans, err := o.client.Answer(o.ctx, card, "Web", revision) if err != nil { t.Fatal(err) } 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 { t.Fatalf("the answer %+v is not in the thread", ans) } if next := o.message(lane); next.TurnID != ans.Turn.ID || len(next.PersonText) != 0 { t.Fatalf("the answer's frame %+v", next) } hidden[ans.Message.ID], hidden[ans.Turn.ID] = true, true o.reply(ans.Turn.ID) // Their next message is all their conversation hears meanwhile. again := o.own("One more of my own.") o.wait("their next message", func(c *Conversation) bool { _, ok := c.Turns[again]; return ok }) theirs("after the answer") } // TestContractHandoffThreadsRunApart: two hand-offs and a message of the // person's own go to the runner at once, each in its own lane: no one // waits behind another. func TestContractHandoffThreadsRunApart(t *testing.T) { o := newTeamRig(t) o.ask("Two things. Login is broken. Checkout is slow.") first := o.request("ra1", map[string]any{"words": "Login is broken"}) second := o.request("ra2", map[string]any{"words": "Checkout is slow"}) mine, err := o.client.Send(o.ctx, "Something of my own.", "own-ra") if err != nil { t.Fatal(err) } turns := map[string]string{wire.JobLane(first): o.handoffTurn(first), wire.JobLane(second): o.handoffTurn(second), wire.LaneCoordinator: mine.Turn.ID} if first == second || len(turns) != 3 { t.Fatalf("requests %s %s", first, second) } for lane, turn := range turns { if n := o.commandsFor(wire.FrameMessage, turn); n != 1 { t.Fatalf("the turn in %q went %d times before any reply", lane, n) } } for lane, turn := range turns { if cmd := o.message(lane); cmd.TurnID != turn { t.Fatalf("the frame in %q %+v", lane, cmd) } } } // TestContractHandoffNeedsJobsRunner: a hand-off needs the person's // primary at protocol 22. Last seen at 21, team_request is refused // (runner_too_old) and stores nothing; a thread's turn not yet taken // when the primary comes back at 21 ends failed (runner_too_old) and is // never sent. func TestContractHandoffNeedsJobsRunner(t *testing.T) { t.Run("refused", func(t *testing.T) { o := newTeamRigAt(t, wire.Protocol21) o.ask("Can we fix a bug in Tito? Login is broken") res := o.use("nj1", "team_request", map[string]any{"words": "Login is broken"}) 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." { t.Fatalf("team_request at 21 %+v", res) } 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 { t.Fatalf("%d rows stored for a refused hand-off", n) } }) t.Run("fenced", func(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request := o.request("nj2", map[string]any{"words": "Login is broken"}) turn := o.handoffTurn(request) if s := o.turnState(turn); s != wire.TurnQueued || o.commandsFor(wire.FrameMessage, turn) != 1 { t.Fatalf("the thread's turn is %s", s) } // The runner goes before it takes the frame, and comes back older. o.runner.Close() o.wait("offline", func(c *Conversation) bool { return !c.Runner.Online }) old := o.dialAt(wire.Protocol21) o.until("the thread's turn failed", func() bool { return o.turnState(turn) == wire.TurnFailed }) if n := o.rows("SELECT count(*) FROM chat_turns WHERE id = ? AND reason = 'runner_too_old'", turn); n != 1 { t.Fatal("the thread's turn failed for another reason") } 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 { t.Fatalf("the thread's frame still waits %d times", n) } if s := o.turnState(o.turn); s == wire.TurnFailed { t.Fatal("the Assistant's own turn failed at 21") } // Their own conversation still works, and its frame is the first. mine, err := o.client.Send(o.ctx, "Something of my own.", "own-nj") if err != nil { t.Fatal(err) } if _, frame, err := old.Expect(o.ctx, wire.FrameMessage); err != nil || frame.(*wire.MessageCommand).TurnID != mine.Turn.ID { t.Fatalf("their own frame at 21 %v %+v", err, frame) } }) } // legacyHandoff is a hand-off as slice 1 made them: the words in the // person's own conversation (lane ""), and its row with no lane. func (o *teamRig) legacyHandoff(id, words string) (request, turn string) { o.t.Helper() sent, err := o.client.Send(o.ctx, words, "legacy-"+id) if err != nil { o.t.Fatal(err) } if cmd := o.message(wire.LaneCoordinator); cmd.TurnID != sent.Turn.ID { o.t.Fatalf("the legacy frame %+v", cmd) } request = "h_legacy" + id db := o.inst.DB.Writer() 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 { o.t.Fatal(err) } if _, err := db.Exec("INSERT INTO chat_handoff_turns(handoff_id, turn_id) VALUES (?, ?)", request, sent.Turn.ID); err != nil { o.t.Fatal(err) } return request, sent.Turn.ID } // TestContractHandoffLegacyKeepsItsRoute: a hand-off made before job // threads (lane "", its message and turn in the person's conversation) // keeps slice 1's routing: it follows the tasks its turns record, its // question stays in their conversation, the answer starts a follow-up // turn there linked to it, and its turn's end still tells it. func TestContractHandoffLegacyKeepsItsRoute(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, turn := o.legacyHandoff("1", "Login is broken") var id string o.in(turn, func() { id = o.record("lg-rec", "Fix the login") if res := o.call("lg-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) o.reply(turn) var card wire.Card o.wait("the question in their conversation", func(c *Conversation) bool { for _, k := range c.Cards { if k.Kind == wire.CardQuestion && k.TurnID == turn { card = k } } return card.ID != "" }) ans, err := o.client.Answer(o.ctx, card.ID, "Web", card.Revision) if err != nil { t.Fatal(err) } if next := o.message(wire.LaneCoordinator); next.TurnID != ans.Turn.ID || o.laneOf(ans.Turn.ID) != wire.LaneCoordinator { t.Fatalf("the answer's frame %+v", next) } if n := o.rows("SELECT count(*) FROM chat_handoff_turns WHERE handoff_id = ? AND turn_id = ?", request, ans.Turn.ID); n != 1 { t.Fatal("the answer's turn is not the legacy hand-off's") } var later string o.in(ans.Turn.ID, func() { later = o.record("lg-later", "Fix the web login page") }) o.reply(ans.Turn.ID) if got := o.linked(request); len(got) != 2 || !got[id] || !got[later] { t.Fatalf("linked %v", got) } if n := o.rows("SELECT count(*) FROM chat_turns WHERE lane LIKE 'job:%'"); n != 0 { t.Fatalf("%d turns in a job thread", n) } // A legacy hand-off whose turn ends with no work has stopped, and the // person is told: only its own turns count, not the person's own // work waiting behind it. stopped, other := o.legacyHandoff("2", "Login is broken") if waiting, err := o.client.Send(o.ctx, "Something of my own.", "own-lg"); err != nil || waiting.Turn.State != wire.TurnQueued { t.Fatalf("their own waiting turn %+v %v", waiting.Turn, err) } o.runner.Send(o.ctx, "r-lg-fail", wire.FrameTurn, wire.TurnReport{TurnID: other, Attempt: 1, State: wire.TurnFailed, Reason: "provider_failed"}) 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 = ?" note := jobLine("Login is broken", stopped, "Login is broken") + noWork(stopped, 2) + "\nWhere it stands:\n" + equipo.RunnerCopy("assistant.team.stopped") o.until("the legacy hand-off's update", func() bool { return o.rows(update, stopped, wire.TurnTeamUpdate, note) == 1 }) } // TestContractHandoffAnswerNeedsJobsRunner: a thread's question asked at // protocol 22 and answered after the primary came back at 21 is refused // (409 runner_too_old) through the person API: the card stays open at // its revision, and no message or turn is made that no runner could // carry. func TestContractHandoffAnswerNeedsJobsRunner(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("na1", "Login is broken", "") o.in(cmd.TurnID, func() { if res := o.call("na-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) o.reply(cmd.TurnID) card, revision := o.threadQuestion(request) o.runner.Close() o.wait("offline", func(c *Conversation) bool { return !c.Runner.Online }) o.dialAt(wire.Protocol21) lane := wire.JobLane(request) before := o.rows("SELECT (SELECT count(*) FROM chat_messages WHERE lane = ?) + (SELECT count(*) FROM chat_turns WHERE lane = ?)", lane, lane) refusedTooOld := func(what string, err error) { t.Helper() var e wire.Error if s, ok := err.(*ErrStatus); !ok || s.Status != http.StatusConflict || json.Unmarshal(s.Body, &e) != nil || e.Code != "runner_too_old" { t.Fatalf("%s at 21: %v", what, err) } if n := o.rows("SELECT count(*) FROM chat_cards WHERE id = ? AND state = ? AND revision = ?", card, wire.CardOpen, revision); n != 1 { t.Fatalf("%s at 21: the card changed", what) } if n := o.rows("SELECT (SELECT count(*) FROM chat_messages WHERE lane = ?) + (SELECT count(*) FROM chat_turns WHERE lane = ?)", lane, lane); n != before { t.Fatalf("%s at 21: %d thread rows, %d before", what, n, before) } } _, err := o.client.Answer(o.ctx, card, "Web", revision) refusedTooOld("the person's answer", err) } // noWork is the note's line for a job that stopped before any work // started, with nudges left (noteNoWork). func noWork(request string, left int) string { 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) } // failedStep is the note's line for a job whose step failed and can be // tried again (noteFailed). func failedStep(request string, left int) string { 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) } // blockedOn is the note's line for a job only the person can move on // (noteBlocked). func blockedOn(line string) string { return "It stopped, and only the person can move it on: " + line + ". Tell the person that plainly, in one line. Do not nudge it." } // startedInThread hands "Login is broken" to the team and records and // starts a task in the job's thread: the request, the task and its // Engineering step. func (o *teamRig) startedInThread(key string) (request, id string, d *wire.DispatchCommand) { o.t.Helper() o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff(key+"1", "Login is broken", "") o.in(cmd.TurnID, func() { id = o.record(key+"-rec", "Fix the login") if res := o.call(key+"-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}); res.IsError { o.t.Fatalf("start %+v", res) } _, body := o.expect(wire.FrameDispatch) d = body.(*wire.DispatchCommand) }) return request, id, d } // TestContractTeamUpdateStops: a job that stops where the Assistant can // push it through tells it so: a thread turn that ended with no work, to // nudge it with the person's words; a retryable failed Engineering step, // to have it tried again; each with the nudges it has left. With none // left, the Assistant is to tell the person it stopped. func TestContractTeamUpdateStops(t *testing.T) { t.Run("no_work", func(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("sw1", "Login is broken", "") o.reply(cmd.TurnID) note := o.noteFor("the no-work note", noWork(request, 2)) if !strings.HasPrefix(note, jobLine("Login is broken", request, "Login is broken")+noWork(request, 2)+"\nWhere it stands:\n") { t.Fatalf("note %q", note) } }) t.Run("failed", func(t *testing.T) { o := newTeamRig(t) request, id, d := o.startedInThread("sf") o.step("sf-fail", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true}) note := o.noteFor("the failed note", failedStep(request, 2)) if strings.Contains(note, "only the person can move it on") { t.Fatalf("note %q", note) } }) t.Run("no_nudges", func(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("sn1", "Login is broken", "") if _, err := o.inst.DB.Writer().Exec("UPDATE chat_handoffs SET nudges = 2 WHERE id = ?", request); err != nil { t.Fatal(err) } o.reply(cmd.TurnID) 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.") if strings.Contains(note, "team_nudge") { t.Fatalf("note %q", note) } }) } // personNeed is a need only the person can meet: its name, the note's // plain line for it, and how a task's steps are written as it leaves // them (step is the task's Engineering step). type personNeed struct { name, line string set func(o *teamRig, id, step string) } // personNeeds are the needs a task reports that only the person meets // (ruling P4j), a failed merge step among them. func personNeeds() []personNeed { cand := strings.Repeat("2", 40) return []personNeed{ {"held", "they need to say when it can run", func(o *teamRig, id, step string) { o.exec("UPDATE chat_steps SET state = ?, hold = ? WHERE id = ?", wire.StepQueued, `{"reason":"limited","wake_at":null,"needs_person":"connection","step_revision":1}`, step) }}, {"branch_moved", "someone else changed the same work, and they need to look at it", func(o *teamRig, id, step string) { o.exec("UPDATE chat_steps SET state = ?, pushed = 1, terminated = 1, candidate_sha = ? WHERE id = ?", wire.StepDone, cand, step) o.exec("UPDATE chat_tasks SET moved_from = ? WHERE id = ?", cand, id) }}, {"review_blocked", "the check of the work could not finish, and they need to decide what next", func(o *teamRig, id, step string) { o.exec("UPDATE chat_steps SET specialist = ?, state = ?, terminated = 1 WHERE id = ?", wire.SpecialistReview, wire.StepFailed, step) }}, {"fix_rounds", "the checks still find problems after the automatic fixes, and they need to decide what next", func(o *teamRig, id, step string) { o.exec("UPDATE chat_steps SET state = ?, pushed = 1, terminated = 1, candidate_sha = ?, round = ? WHERE id = ?", wire.StepDone, cand, wire.MaxFixRounds, step) 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) }}, {"merge_conflict", "it clashes with other changes, and they need to sort it out", func(o *teamRig, id, step string) { o.exec("UPDATE chat_steps SET specialist = ?, state = ?, terminated = 1, reason = 'merge_conflict' WHERE id = ?", wire.SpecialistMerge, wire.StepFailed, step) }}, {"machine_removed", "they need to bring their computer back online", func(o *teamRig, id, step string) { o.exec("UPDATE chat_steps SET state = ?, terminated = 0, reason = 'machine_removed' WHERE id = ?", wire.StepFailed, step) }}, {"mac_sandbox", "they need to let it be tested on their Mac", func(o *teamRig, id, step string) { o.exec("UPDATE chat_steps SET specialist = ?, state = ?, placement = ? WHERE id = ?", wire.SpecialistChecks, wire.StepQueued, wire.PlacementSandbox, step) }}, {"merge_failed", "going live failed, and they need to try it again", func(o *teamRig, id, step string) { o.exec("UPDATE chat_steps SET specialist = ?, state = ?, terminated = 1, reason = 'provider_failed' WHERE id = ?", wire.SpecialistMerge, wire.StepFailed, step) }}, {"merge_credential", noAccessLine, func(o *teamRig, id, step string) { o.exec("UPDATE chat_steps SET specialist = ?, state = ?, terminated = 1, reason = ? WHERE id = ?", wire.SpecialistMerge, wire.StepFailed, wire.ReasonMergeCredential, step) }}, } } // noAccessLine is the note's plain line for going live refused for want // of access to the repository: what is missing, not "try it again". const 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" // TestContractTeamUpdatePersonNeeds (ruling P4j): every need only the // person can meet stops the job for them: the note says what in plain // words and never asks the Assistant to nudge it, however its step // failed. The task's steps are written as each stop leaves them; a note // on the task's thread saves the task, as any change would. func TestContractTeamUpdatePersonNeeds(t *testing.T) { for _, c := range personNeeds() { t.Run(c.name, func(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) _, id, d := o.startedInThread("pn") c.set(o, id, d.StepID) if _, err := o.client.PostThread(o.ctx, id, "For the record.", "pn-note"); err != nil { t.Fatal(err) } if note := o.noteFor("the "+c.name+" note", blockedOn(c.line)); strings.Contains(note, "team_nudge") { t.Fatalf("note %q", note) } }) } // runner_offline is a need no task of the instance's reports now // (needsYou never returns it); its plain line is checked where the // lines are kept (TestJobNoteBlockedLines). t.Run("publish_failed", func(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) o.mergedWebsite("pf", true) // The project's ships question, answered in the thread, waits on // the person no more. var ships string var revision int64 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 { t.Fatal(err) } if _, err := o.client.Answer(o.ctx, ships, wire.ChoiceNotShips, revision); err != nil { t.Fatal(err) } card := o.assistantCard("the publish outcome", isPublishOutcome) if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoicePublish, card.Revision); err != nil { t.Fatal(err) } o.publishReport("pf-failed", o.publishDispatch(), wire.StepFailed, nil) 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") { t.Fatalf("note %q", note) } }) } // exec runs a statement on the instance's database. func (o *teamRig) exec(q string, args ...any) { o.t.Helper() if _, err := o.inst.DB.Writer().Exec(q, args...); err != nil { o.t.Fatal(err) } } // TestContractTeamUpdateQuietProgress: routine progress tells the // Assistant nothing: a followed task noted, in progress and in review // queues no team_update; the go-ahead raised does; a finding while it // waits, and merging after it, change nothing it was told. func TestContractTeamUpdateQuietProgress(t *testing.T) { o := newTeamRig(t) o.sitesOn(wire.ProtocolAssistant, false) o.shipsNo(o.project()) quiet := func(stage string, n int) { t.Helper() time.Sleep(20 * time.Millisecond) if ids, notes, _ := o.updates(); len(ids) != n { t.Fatalf("at %s: updates %v %q", stage, ids, notes) } } stage := func(id, want string) { t.Helper() o.wait(want, func(c *Conversation) bool { return c.Tasks[id].Stage == want }) } o.ask("Can we fix a bug in Tito? Login is broken") _, cmd := o.handoff("qp1", "Login is broken", "") base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) var id string o.in(cmd.TurnID, func() { id = o.record("qp-rec", "Fix the login") stage(id, wire.StageNoted) quiet("noted", 0) if res := o.call("qp-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}); res.IsError { t.Fatalf("start %+v", res) } _, body := o.expect(wire.FrameDispatch) d := body.(*wire.DispatchCommand) o.step("qp-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "claude-a"}) stage(id, wire.StageInProgress) quiet("in progress", 0) 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"}) o.expect(wire.FrameWatchMerge) c := o.dispatched(wire.SpecialistChecks, base, cand, 0) stage(id, wire.StageInReview) quiet("in review", 0) o.checks("qp-c", c, wire.ChecksNone, nil, "", "") o.verdict("qp-r", o.dispatched(wire.SpecialistReview, base, cand, 0), wire.VerdictApprove) }) card := o.assistantCard("the go-ahead", isMergeOutcome) o.noteFor("the go-ahead's note", "It is ready for the person to try.") quiet("ready", 1) // A finding while the go-ahead waits changes where it stands, and // tells nothing new. _, told, _ := o.updates() o.in(cmd.TurnID, func() { 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 { t.Fatalf("finding %+v", res) } }) quiet("a finding", 1) if _, notes, _ := o.updates(); !slices.Equal(notes, told) { t.Fatalf("after a finding %q, before %q", notes, told) } if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil { t.Fatal(err) } o.dispatched(wire.SpecialistMerge, base, cand, 0) stage(id, wire.StageMerging) quiet("merging", 1) } // statusOf is team_status's answer for one request, as JSON. func (o *teamRig) statusOf(key, request string) map[string]any { o.t.Helper() res := o.use(key, "team_status", map[string]any{"request": request}) var out struct { Requests []map[string]any `json:"requests"` } if res.IsError || json.Unmarshal([]byte(res.Text), &out) != nil || len(out.Requests) != 1 { o.t.Fatalf("team_status %+v", res) } return out.Requests[0] } // TestContractTeamStatusQuestion: team_status names the job's title and, // while the job has an open question, the question and its options // (never null); with none open, no question at all. func TestContractTeamStatusQuestion(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request := o.request("tq1", map[string]any{"words": "Login is broken", "title": "Fixing the sign-in page"}) cmd := o.message(wire.JobLane(request)) if got := o.statusOf("tq-none", request); got["title"] != "Fixing the sign-in page" || got["question"] != nil { t.Fatalf("before a question %+v", got) } o.in(cmd.TurnID, func() { if res := o.call("tq-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) got := o.statusOf("tq-open", request) 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" { t.Fatalf("with the question %+v", got) } o.reply(cmd.TurnID) card, revision := o.threadQuestion(request) ans, err := o.client.Answer(o.ctx, card, "Web", revision) if err != nil { t.Fatal(err) } if got := o.statusOf("tq-answered", request); got["question"] != nil { t.Fatalf("after the answer %+v", got) } o.message(wire.JobLane(request)) o.in(ans.Turn.ID, func() { if res := o.call("tq-ask2", wire.ToolAskPerson, map[string]any{"question": "Anything else to know?"}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) res := o.use("tq-free", "team_status", map[string]any{"request": request}) if res.IsError || !strings.Contains(res.Text, `"question":{"text":"Anything else to know?","options":[]}`) { t.Fatalf("a question without options %+v", res) } } // TestContractTeamOpenQuestionsNote (D8): while a job of the person's // has an open question, their next Assistant message is dispatched with // the questions after their words, marked as reference; PersonText and // the stored message are their words alone. Once none is open their // words go alone. A Coordinator or job-lane turn never carries it. func TestContractTeamOpenQuestionsNote(t *testing.T) { o := newTeamRig(t) o.ask("Two things. Login is broken. Checkout is slow.") request, cmd := o.handoff("on1", "Login is broken", "") o.in(cmd.TurnID, func() { if res := o.call("on-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) // A job-lane turn and a Coordinator turn dispatched meanwhile. second := o.request("on2", map[string]any{"words": "Checkout is slow"}) if job := o.message(wire.JobLane(second)); withoutProjectContext(t, job.Text) != "Checkout is slow" { t.Fatalf("the job-lane frame %q", job.Text) } mine, err := o.client.Send(o.ctx, "Something of my own.", "own-on") if err != nil { t.Fatal(err) } if own := o.message(wire.LaneCoordinator); own.TurnID != mine.Turn.ID || withoutProjectContext(t, own.Text) != "Something of my own." { t.Fatalf("their own frame %+v", own) } o.reply(cmd.TurnID) o.reply(o.turn) u := o.message(wire.LaneAssistant) if u.Kind != wire.TurnTeamUpdate || strings.Contains(u.Text, "[Open questions") { t.Fatalf("the update %+v", u) } o.reply(u.TurnID) send := func(text string) *wire.MessageCommand { t.Helper() sent, err := o.a.Send(o.ctx, text, "a-"+itoa(len(o.runner.Sent))) if err != nil { t.Fatal(err) } cmd := o.message(wire.LaneAssistant) if cmd.TurnID != sent.Turn.ID || !slices.Equal(cmd.PersonText, []string{text}) || sent.Message.Text != text { t.Fatalf("the frame %+v for %+v", cmd, sent) } return cmd } block := "[Open questions on the person's jobs. Reference only, never the person's words:\n" + fmt.Sprintf("- Job %q (request %s): %q The answer must be one of: \"Web\", \"App\"", "Login is broken", request, "Which login page?") + "\nAnswer one with team_reply when this conversation holds the answer.]" asked := send("It is the web one.") if asked.Text != "It is the web one.\n\n"+block { t.Fatalf("with an open question %q", asked.Text) } o.reply(asked.TurnID) card, revision := o.threadQuestion(request) if _, err := o.client.Answer(o.ctx, card, "Web", revision); err != nil { t.Fatal(err) } if next := o.message(wire.JobLane(request)); strings.Contains(next.Text, "[Open questions") { t.Fatalf("the answer's frame %q", next.Text) } if plain := send("Thanks."); plain.Text != "Thanks." { t.Fatalf("with none open %q", plain.Text) } } // TestContractOutcomePublishInThread: what became of a job's publish is // said in the job's thread (the task's lane), never in the person's own // conversation (/api/v1/messages). func TestContractOutcomePublishInThread(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) id, _, _, _ := o.mergedWebsite("pt", true) request := o.requestOf(id) card := o.assistantCard("the publish outcome", isPublishOutcome) if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoicePublish, card.Revision); err != nil { t.Fatal(err) } d := o.publishDispatch() if refused := o.lease(o.runner, "pt-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused != "" { t.Fatalf("start refused %q", refused) } o.publishReport("pt-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40}) 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 != "" { t.Fatalf("deploy refused %q", refused) } site := "https://" + d.Publish.App + ".bds.oncarlos.com/" 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}) var said, lane string o.until("the publish result", func() bool { 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 }) if lane != wire.JobLane(request) { t.Fatalf("the publish result is in %q, not the job's thread", lane) } page, err := o.client.Messages(o.ctx, "", 50) if err != nil { t.Fatal(err) } for _, m := range page.Items { if m.ID == said || strings.Contains(m.Text, site) { t.Fatalf("the job's publish result in their conversation %+v", m) } } if !slices.ContainsFunc(o.thread(request), func(m wire.Message) bool { return m.ID == said }) { t.Fatal("the publish result is not in the thread") } } // TestContractTeamUpdateNoAccessAmongTasks: a job following two tasks, // one whose merge failed and one refused for want of access, in either // order: the note says access is missing, never "try it again". func TestContractTeamUpdateNoAccessAmongTasks(t *testing.T) { for _, order := range []string{"failed_first", "refused_first"} { t.Run(order, func(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) o.ask("Can we fix two bugs in Tito? Login is broken and so is search") _, cmd := o.handoff("na1", "Login is broken and so is search", "") var ids, steps []string o.in(cmd.TurnID, func() { for i, title := range []string{"Fix the login", "Fix the search"} { key := "na-" + strconv.Itoa(i) id := o.record(key+"-rec", title) if res := o.call(key+"-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}); res.IsError { o.t.Fatalf("start %+v", res) } _, body := o.expect(wire.FrameDispatch) ids, steps = append(ids, id), append(steps, body.(*wire.DispatchCommand).StepID) } }) reasons := []string{"provider_failed", wire.ReasonMergeCredential} if order == "refused_first" { reasons[0], reasons[1] = reasons[1], reasons[0] } for i, step := range steps { o.exec("UPDATE chat_steps SET specialist = ?, state = ?, terminated = 1, reason = ? WHERE id = ?", wire.SpecialistMerge, wire.StepFailed, reasons[i], step) } if _, err := o.client.PostThread(o.ctx, ids[0], "For the record.", "na-note"); err != nil { t.Fatal(err) } if note := o.noteFor("the note", blockedOn(noAccessLine)); strings.Contains(note, "try it again") { t.Fatalf("note %q", note) } }) } }