package thintest import ( "encoding/json" "slices" "strings" "testing" "amadan.net/oficina/equipo/internal/equipo/assist" "amadan.net/oficina/equipo/internal/wire" ) // team_reply (jobs design §4; D17): the Assistant answers the open // question on one of the person's jobs, as the person, through the // question card's own path: an option when the question has options, // else its own words, with no words check. One answer per key, audited // without payload. Only a question card, and in a team_update turn only // the job the update is about. const loginQuestion = "Which login page?" // askedJob hands "Login is broken" to the team from a new Assistant turn, // has the job's thread ask question (with options, none when nil), ends // the thread's turn and the Assistant's, and returns the request, the // thread's turn and the team_update turn that tells the Assistant, // dispatched. func (o *teamRig) askedJob(key, question string, options []string) (request, asked, update string) { o.t.Helper() o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff(key+"-h", "Login is broken", "") args := map[string]any{"question": question} if options != nil { args["options"] = options } o.in(cmd.TurnID, func() { if res := o.call(key+"-ask", wire.ToolAskPerson, args); res.Code != "asked" { o.t.Fatalf("ask %+v", res) } }) o.reply(cmd.TurnID) o.reply(o.turn) u := o.message(wire.LaneAssistant) if u.Kind != wire.TurnTeamUpdate { o.t.Fatalf("update frame %+v", u) } return request, cmd.TurnID, u.TurnID } // teamReply is team_reply for request in the rig's turn. func (o *teamRig) teamReply(id, request, answer string) wire.ToolResult { o.t.Helper() return o.use(id, "team_reply", map[string]any{"request": request, "answer": answer}) } // replied fails unless res is team_reply's answer for request. func replied(t *testing.T, res wire.ToolResult, request string) { t.Helper() want, _ := json.Marshal(map[string]string{"request": request, "status": "answered"}) if res.IsError || res.Code != "used" || res.Text != string(want) { t.Fatalf("team_reply %+v, want %s", res, want) } } // questionCard is the state, choice and revision of the request's newest // question card. func (o *teamRig) questionCard(request string) (state, choice string, revision int64) { o.t.Helper() q := "SELECT state, coalesce(choice, ''), revision FROM chat_cards c WHERE kind = ? AND (lane = ? OR turn_id IN (SELECT turn_id FROM chat_handoff_turns WHERE handoff_id = ?)) ORDER BY created_at DESC, rowid DESC LIMIT 1" if err := o.inst.DB.Writer().QueryRow(q, wire.CardQuestion, wire.JobLane(request), request).Scan(&state, &choice, &revision); err != nil { o.t.Fatal(err) } return state, choice, revision } // lastAudit is the newest audit row's id. func (o *teamRig) lastAudit() int { return o.rows("SELECT coalesce(max(id), 0) FROM audit_events") } // TestContractTeamReply: in the team_update turn that tells it of the // job's question, the Assistant answers it with team_reply, in any case: // the question card is answered with the option's own text, which the // job's thread gets as the person's message, dispatched with the // question it answers. One audit row, with neither the answer nor the // question. The job card never shows asking after it, and the same // question asked again is told again. func TestContractTeamReply(t *testing.T) { o := newTeamRig(t) request, asked, update := o.askedJob("rp", loginQuestion, []string{"Web", "App"}) card := o.jobCardID(request) events := len(o.jobEvents(card)) audit := o.lastAudit() var res wire.ToolResult o.in(update, func() { res = o.teamReply("rp-reply", request, " web ") }) replied(t, res, request) if state, choice, _ := o.questionCard(request); state != wire.CardAnswered || choice != "Web" { t.Fatalf("the question card %s %q", state, choice) } thread := o.thread(request) if last := thread[len(thread)-1]; last.Role != wire.RolePerson || last.Text != "Web" || last.TurnID == asked { t.Fatalf("the thread's last message %+v", last) } cmd := o.message(wire.JobLane(request)) if withoutProjectContext(t, cmd.Text) != `(My answer to your question "Which login page?") Web` || len(cmd.PersonText) != 0 { t.Fatalf("the answer's frame %+v", cmd) } if n := o.rows("SELECT count(*) FROM audit_events WHERE id > ? AND kind = 'assistant.team_reply' AND actor = ? AND record_id = ?", audit, Owner, request); n != 1 { t.Fatalf("%d team_reply audits", n) } if n := o.rows("SELECT count(*) FROM audit_events WHERE id > ? AND (record_id LIKE '%Web%' OR record_id LIKE '%login page%')", audit); n != 0 { t.Fatalf("%d audit rows carry the answer or the question", n) } o.reply(update) o.jobOf(request, "working", func(c wire.AssistantCard) bool { return c.State == wire.JobWorking }) for _, c := range o.jobEvents(card)[events:] { if c.State != wire.JobWorking { t.Fatalf("the job card after the answer %+v", c) } } // The same question asked again is news again. o.in(cmd.TurnID, func() { if res := o.call("rp-again", wire.ToolAskPerson, map[string]any{"question": loginQuestion, "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask again %+v", res) } }) o.reply(cmd.TurnID) o.until("the second update", func() bool { ids, _, _ := o.updates(); return len(ids) == 2 }) } // TestContractTeamReplyOptions: an answer that is none of the options is // not_an_option, naming them, and the card stays open; a question with // no options takes any words of 1 to 2000 characters (2001 and blank are // invalid_input); with no question open, no_question. func TestContractTeamReplyOptions(t *testing.T) { t.Run("options", func(t *testing.T) { o := newTeamRig(t) request, _, update := o.askedJob("ro", loginQuestion, []string{"Web", "App"}) _, _, revision := o.questionCard(request) o.in(update, func() { res := o.teamReply("ro-desktop", request, "Desktop") if !res.IsError || res.Code != "not_an_option" || res.Text != `The answer must be one of the question's options: "Web", "App".` { t.Fatalf("not an option %+v", res) } }) if state, _, rev := o.questionCard(request); state != wire.CardOpen || rev != revision { t.Fatalf("the card after a refusal %s %d", state, rev) } }) // Malformed UTF-8 in the raw input is refused before it is decoded // (the decoder would make it U+FFFD), for team_request too. t.Run("malformed bytes", func(t *testing.T) { o := newTeamRig(t) request, _, update := o.askedJob("rm", "What should the button say?", nil) _, _, revision := o.questionCard(request) raw := func(op, input string) json.RawMessage { return json.RawMessage(`{"operation":"` + op + `","input":` + input + `}`) } o.in(update, func() { if res := o.tool("rm-reply", wire.ToolUse, raw("team_reply", `{"request":"`+request+`","answer":"Sign in`+"\xff"+`"}`)); !res.IsError || res.Code != "invalid_input" { t.Fatalf("team_reply with a malformed byte %+v", res) } }) if state, _, rev := o.questionCard(request); state != wire.CardOpen || rev != revision { t.Fatalf("the card after malformed bytes %s %d", state, rev) } o.reply(update) o.ask("Can we fix a bug in Tito? Login is broken") before := o.rows("SELECT count(*) FROM chat_handoffs") if res := o.tool("rm-request", wire.ToolUse, raw("team_request", `{"words":"Login is broken","context":"Tito`+"\xff"+`"}`)); !res.IsError || res.Code != "invalid_input" { t.Fatalf("team_request with a malformed byte %+v", res) } if n := o.rows("SELECT count(*) FROM chat_handoffs"); n != before { t.Fatalf("%d hand-offs, %d before", n, before) } }) t.Run("free text", func(t *testing.T) { o := newTeamRig(t) request, _, update := o.askedJob("rf", "What should the button say?", nil) o.in(update, func() { for key, answer := range map[string]string{"rf-long": strings.Repeat("é", 2001), "rf-blank": " \n "} { if res := o.teamReply(key, request, answer); !res.IsError || res.Code != "invalid_input" { t.Fatalf("%s %+v", key, res) } } if state, _, _ := o.questionCard(request); state != wire.CardOpen { t.Fatalf("the card after refusals %s", state) } answer := strings.Repeat("é", 2000) replied(t, o.teamReply("rf-ok", request, answer), request) if state, choice, _ := o.questionCard(request); state != wire.CardAnswered || choice != answer { t.Fatalf("the card %s, %d runes", state, len([]rune(choice))) } res := o.teamReply("rf-none", request, "Sign in") if !res.IsError || res.Code != "no_question" || res.Text != "That job has no open question. Use team_status to see where it stands." { t.Fatalf("no question %+v", res) } }) }) } // TestContractTeamReplyFromContext: once the Assistant was told and the // job shows asking, it answers from the conversation in a turn the // person started, in words found in no message of theirs; the job card // is working again at once. func TestContractTeamReplyFromContext(t *testing.T) { o := newTeamRig(t) request, _, update := o.askedJob("rc", "What should the button say?", nil) o.reply(update) card := o.jobOf(request, "asking", func(c wire.AssistantCard) bool { return c.State == wire.JobAsking }) o.ask("Use the email one, like we said") events := len(o.jobEvents(card.ID)) replied(t, o.teamReply("rc-reply", request, "Sign in with email"), request) if state, choice, _ := o.questionCard(request); state != wire.CardAnswered || choice != "Sign in with email" { t.Fatalf("the question card %s %q", state, choice) } after := o.jobEvents(card.ID)[events:] if len(after) == 0 || after[0].State != wire.JobWorking { t.Fatalf("the job card's events after the answer %+v", after) } } // TestContractTeamReplyOnce: the same call under a new call id, then a // result lost before it was stored, in attempt 2: one answer, one // message in the thread, one action, one audit, equal results. func TestContractTeamReplyOnce(t *testing.T) { o := newTeamRig(t) request, _, update := o.askedJob("ron", loginQuestion, []string{"Web", "App"}) var first, again, lost wire.ToolResult o.in(update, func() { first = o.teamReply("ron-1", request, "Web") again = o.teamReply("ron-2", request, "Web") }) replied(t, first, request) if again.IsError || !again.Replayed || again.Text != first.Text { t.Fatalf("again %+v, first %+v", again, first) } o.runner.Send(o.ctx, "r-ron-wait", wire.FrameTurn, wire.TurnReport{TurnID: update, Attempt: 1, State: wire.TurnWaiting, Reason: "limited"}) o.runner.Send(o.ctx, "r-ron-run2", wire.FrameTurn, wire.TurnReport{TurnID: update, 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 = ?", update, wire.TurnRunning) == 1 }) // The ledger lost the result: the provider gets the same key again. o.exec("UPDATE chat_tool_calls SET ledger_key = '' WHERE turn_id = ?", update) o.in(update, func() { o.attempt = 2 lost = o.teamReply("ron-3", request, "Web") }) if lost.IsError || lost.Text != first.Text { t.Fatalf("after a lost result %+v, first %+v", lost, first) } if n := o.rows("SELECT count(*) FROM chat_messages WHERE lane = ? AND role = ? AND text = 'Web'", wire.JobLane(request), wire.RolePerson); n != 1 { t.Fatalf("%d answers in the thread", n) } if n := o.rows("SELECT count(*) FROM chat_handoff_actions WHERE handoff_id = ? AND kind = 'reply'", request); n != 1 { t.Fatalf("%d reply actions", n) } if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.team_reply'"); n != 1 { t.Fatalf("%d team_reply audits", n) } } // TestContractTeamReplyOnlyOwnJob: a team_update turn answers only the // job it is about (another job's is not_asked, and its card stays open); // another person's request is not_found; a turn the person started // answers any job of theirs. func TestContractTeamReplyOnlyOwnJob(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken, and the logo is blurry") requests := map[string]string{} for key, words := range map[string]string{"a": "Login is broken", "b": "the logo is blurry"} { request, cmd := o.handoff("oj-"+key, words, "") requests[key] = request o.in(cmd.TurnID, func() { if res := o.call("oj-ask-"+key, wire.ToolAskPerson, map[string]any{"question": "Which one?", "options": []string{"This", "That"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) o.reply(cmd.TurnID) } o.reply(o.turn) first := o.message(wire.LaneAssistant) var mine, other string for _, request := range requests { if o.rows("SELECT count(*) FROM chat_handoff_turns WHERE handoff_id = ? AND turn_id = ?", request, first.TurnID) == 1 { mine = request } else { other = request } } if first.Kind != wire.TurnTeamUpdate || mine == "" || other == "" { t.Fatalf("the first update %+v (%v)", first, requests) } _, _, revision := o.questionCard(other) o.in(first.TurnID, func() { res := o.teamReply("oj-other", other, "This") if !res.IsError || res.Code != "not_asked" || res.Text != "This update is about another job. Answer or nudge only the job it names." { t.Fatalf("another job's question %+v", res) } }) if state, _, rev := o.questionCard(other); state != wire.CardOpen || rev != revision { t.Fatalf("the other job's card %s %d", state, rev) } o.reply(first.TurnID) second := o.message(wire.LaneAssistant) o.reply(second.TurnID) mate := &teamRig{o.other("mate@example.com")} mate.connect(o.base.Mint()) mate.ask("Pick This for that one") if res := mate.teamReply("oj-mate", mine, "This"); !res.IsError || res.Code != "not_found" { t.Fatalf("another person's request %+v", res) } o.ask("This for both") for _, request := range []string{other, mine} { replied(t, o.teamReply("oj-own-"+request, request, "This"), request) } } // TestContractTeamReplyOnlyQuestions: team_reply answers only a // question: with only a go-ahead open for the job it is no_question, and // the go-ahead stays open, unmerged. func TestContractTeamReplyOnlyQuestions(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("oq-h", "Login is broken", "") base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) var id string o.in(cmd.TurnID, func() { id, _ = o.websiteReady("oqr", "Quick website", base, cand, false) }) outcome := o.assistantCard("the merge outcome", isMergeOutcome) team := o.cardOf(id) for i, answer := range []string{wire.ChoiceMerge, "Yes"} { res := o.teamReply("oq-reply-"+itoa(i), request, answer) if !res.IsError || res.Code != "no_question" { t.Fatalf("team_reply %q on a go-ahead %+v", answer, res) } } if got := o.cardOf(id); got.State != wire.CardOpen || got.Revision != team.Revision { t.Fatalf("the go-ahead %+v", got) } if got := o.assistantCard("still open", func(c wire.AssistantCard) bool { return c.ID == outcome.ID }); got.State != wire.CardOpen || got.Revision != outcome.Revision { t.Fatalf("the outcome %+v", got) } if n := o.rows("SELECT count(*) FROM chat_steps WHERE task_id = ? AND specialist = ?", id, wire.SpecialistMerge); n != 0 { t.Fatal("merged on a team_reply") } } // TestContractTeamReplyLegacy: a legacy hand-off's question, in the // person's own conversation, answered with team_reply: the answer goes // to lane "" with the question it answers, as slice 1's card answer did, // and its turn is the hand-off's. func TestContractTeamReplyLegacy(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, turn := o.legacyHandoff("lr", "Login is broken") o.in(turn, func() { if res := o.call("lr-ask", wire.ToolAskPerson, map[string]any{"question": loginQuestion, "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) o.reply(turn) replied(t, o.teamReply("lr-reply", request, "App"), request) next := o.message(wire.LaneCoordinator) if withoutProjectContext(t, next.Text) != `(My answer to your question "Which login page?") App` || o.laneOf(next.TurnID) != 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, next.TurnID); n != 1 { t.Fatal("the answer's turn is not the legacy hand-off's") } if n := o.rows("SELECT count(*) FROM chat_turns WHERE lane LIKE 'job:%'"); n != 0 { t.Fatalf("%d turns in a job thread", n) } } // team_nudge (jobs design §4; D6, D7; rulings P1j, P2j, P4j): the // Assistant pushes one of the person's stopped jobs through: a job that // stopped before any work started gets the person's own words again, in // its thread; a failed step the instance can retry is tried again. Any // other stop is the person's to move on. At most two nudges per job // until the person says something newer about it. // nudgeReference is the marker a nudge's message is dispatched with when // the Assistant gave no context. const nudgeReference = "[Reference from the Assistant, not the person's words: this stopped before any work started; the person still wants it.]" // teamNudge is team_nudge for request in the rig's turn. func (o *teamRig) teamNudge(id, request, words string) wire.ToolResult { o.t.Helper() return o.use(id, "team_nudge", map[string]any{"request": request, "words": words}) } // nudged fails unless res is team_nudge's answer for request with left // nudges. func nudged(t *testing.T, res wire.ToolResult, request string, left int) { t.Helper() want, _ := json.Marshal(map[string]any{"request": request, "status": "nudged", "nudges_left": left}) if res.IsError || res.Code != "used" || res.Text != string(want) { t.Fatalf("team_nudge %+v, want %s", res, want) } } // refusedWith fails unless res is the refusal code with text. func refusedWith(t *testing.T, res wire.ToolResult, code, text string) { t.Helper() if !res.IsError || res.Code != code || res.Text != text { t.Fatalf("got %+v, want %s %q", res, code, text) } } // nudges is the request's nudge count. func (o *teamRig) nudges(request string) int { o.t.Helper() return o.rows("SELECT nudges FROM chat_handoffs WHERE id = ?", request) } // nudgeKeys are the idempotency keys of the request's nudge messages, // oldest first. func (o *teamRig) nudgeKeys(request string) []string { o.t.Helper() rows, err := o.inst.DB.Writer().Query("SELECT idempotency_key FROM chat_messages WHERE idempotency_key LIKE ? ORDER BY seq", "handoff:"+request+":nudge:%") if err != nil { o.t.Fatal(err) } defer rows.Close() var out []string for rows.Next() { var key string if err := rows.Scan(&key); err != nil { o.t.Fatal(err) } out = append(out, key) } if err := rows.Err(); err != nil { o.t.Fatal(err) } return out } // stoppedJob hands "Build me a quick website" to the team from a new // Assistant turn; the thread's turn ends with no work and the Assistant's // turn ends. It returns the request and the team_update turn, dispatched, // that tells the Assistant to push it through. func (o *teamRig) stoppedJob(key string) (request, update string) { o.t.Helper() o.ask("Build me a quick website") request, cmd := o.handoff(key+"-h", "Build me a quick website", "") o.reply(cmd.TurnID) o.noteFor("the no-work note", noWork(request, 2)) o.reply(o.turn) u := o.message(wire.LaneAssistant) if u.Kind != wire.TurnTeamUpdate || !strings.Contains(u.Text, noWork(request, 2)) { o.t.Fatalf("update frame %+v", u) } return request, u.TurnID } // nudgeThrough nudges request with words in update, which leaves left // nudges; the update ends, and the thread's new turn ends with no work // again. It returns the next team_update, dispatched. func (o *teamRig) nudgeThrough(key, request, update, words string, left int) *wire.MessageCommand { o.t.Helper() var res wire.ToolResult o.in(update, func() { res = o.teamNudge(key, request, words) }) nudged(o.t, res, request, left) cmd := o.message(wire.JobLane(request)) o.reply(update) o.reply(cmd.TurnID) u := o.message(wire.LaneAssistant) if u.Kind != wire.TurnTeamUpdate { o.t.Fatalf("update frame %+v", u) } return u } // TestContractTeamNudgeNoWork: in the team_update about a job that // stopped before any work started, team_nudge quoting the person's // earlier words posts those words, as they wrote them, as the person's // message in the job's thread, keyed by the hand-off and the key the // call was invoked with, and dispatched with the default reference after // them; its turn is the hand-off's. One nudge left. The job card shows // working, never stopped, once the update ends. One audit row, without // the words. func TestContractTeamNudgeNoWork(t *testing.T) { o := newTeamRig(t) request, update := o.stoppedJob("nw") card := o.jobCardID(request) events := len(o.jobEvents(card)) audit := o.lastAudit() var res wire.ToolResult o.in(update, func() { res = o.teamNudge("nw-nudge", request, "quick website") }) nudged(t, res, request, 1) var ledger string if err := o.inst.DB.Writer().QueryRow("SELECT ledger_key FROM chat_tool_calls WHERE call_id = ?", update+"/1/nw-nudge").Scan(&ledger); err != nil || ledger == "" { t.Fatalf("the call's ledger key %q %v", ledger, err) } cmd := o.message(wire.JobLane(request)) if withoutProjectContext(t, cmd.Text) != "quick website\n\n"+nudgeReference || len(cmd.PersonText) != 0 { t.Fatalf("the nudge's frame %+v", cmd) } thread := o.thread(request) if last := thread[len(thread)-1]; len(thread) != 3 || last.Role != wire.RolePerson || last.Text != "quick website" || last.TurnID != cmd.TurnID || last.TurnID == thread[0].TurnID { t.Fatalf("the thread %+v", thread) } if keys := o.nudgeKeys(request); !slices.Equal(keys, []string{"handoff:" + request + ":nudge:" + assist.Key(ledger)}) { t.Fatalf("the nudge's keys %q", keys) } if n := o.rows("SELECT count(*) FROM chat_handoff_turns WHERE handoff_id = ? AND turn_id = ?", request, cmd.TurnID); n != 1 { t.Fatal("the nudge's turn is not the hand-off's") } if n := o.nudges(request); n != 1 { t.Fatalf("%d nudges", n) } if n := o.rows("SELECT count(*) FROM audit_events WHERE id > ? AND kind = 'assistant.team_nudge' AND actor = ? AND record_id = ?", audit, Owner, request); n != 1 { t.Fatalf("%d team_nudge audits", n) } if n := o.rows("SELECT count(*) FROM audit_events WHERE id > ? AND record_id LIKE '%website%'", audit); n != 0 { t.Fatalf("%d audit rows carry the words", n) } o.reply(update) o.jobOf(request, "working", func(c wire.AssistantCard) bool { return c.State == wire.JobWorking }) for _, c := range o.jobEvents(card)[events:] { if c.State != wire.JobWorking { t.Fatalf("the job card after the nudge %+v", c) } } } // TestContractTeamNudgeRetry: a failed Engineering step the instance can // retry gets a new attempt, as the person's Retry would place it, and // nothing is posted to the thread. func TestContractTeamNudgeRetry(t *testing.T) { o := newTeamRig(t) request, id, d := o.startedInThread("nr") o.step("nr-fail", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true}) o.noteFor("the failed note", failedStep(request, 2)) thread := len(o.thread(request)) o.reply(o.turn) u := o.message(wire.LaneAssistant) // Only the person's own task is tried again. o.exec("UPDATE chat_tasks SET creator = 'mate@example.com' WHERE id = ?", id) var res wire.ToolResult o.in(u.TurnID, func() { res = o.teamNudge("nr-theirs", request, "Login is broken") }) refusedWith(t, res, "needs_person", "Only the person can move that job on. Tell them plainly what is needed.") if n := o.rows("SELECT count(*) FROM chat_steps WHERE id = ? AND attempt = 1", d.StepID); n != 1 || o.nudges(request) != 0 { t.Fatalf("someone else's task was tried again (%d nudges)", o.nudges(request)) } o.exec("UPDATE chat_tasks SET creator = ? WHERE id = ?", Owner, id) o.in(u.TurnID, func() { res = o.teamNudge("nr-nudge", request, "Login is broken") }) nudged(t, res, request, 1) _, body := o.expect(wire.FrameDispatch) if again := body.(*wire.DispatchCommand); again.StepID != d.StepID || again.TaskID != id || again.Attempt != 2 || again.Specialist != wire.SpecialistEngineering { t.Fatalf("the retry's dispatch %+v", again) } if n := o.rows("SELECT count(*) FROM chat_steps WHERE task_id = ?", id); n != 1 { t.Fatalf("%d steps", n) } if n := len(o.thread(request)); n != thread || len(o.nudgeKeys(request)) != 0 { t.Fatalf("%d thread messages, %d before", n, thread) } if n := o.rows("SELECT count(*) FROM chat_handoff_actions WHERE handoff_id = ? AND kind = 'nudge' AND coalesce(message_id, '') = ''", request); n != 1 || o.nudges(request) != 1 { t.Fatalf("%d nudge actions, %d nudges", n, o.nudges(request)) } o.reply(u.TurnID) o.jobOf(request, "working", func(c wire.AssistantCard) bool { return c.State == wire.JobWorking }) } // refusesNudge: in the team_update the rig's turn ending dispatches, // team_nudge on request is needs_person and changes nothing: no step // placed or tried again, no message, no nudge counted. Once the update // ends the job is stopped. func (o *teamRig) refusesNudge(request, words string) { o.t.Helper() o.reply(o.turn) u := o.message(wire.LaneAssistant) if u.Kind != wire.TurnTeamUpdate { o.t.Fatalf("update frame %+v", u) } steps := o.rows("SELECT count(*) + coalesce(sum(attempt), 0) FROM chat_steps") messages := o.rows("SELECT count(*) FROM chat_messages WHERE role = ?", wire.RolePerson) var res wire.ToolResult o.in(u.TurnID, func() { res = o.teamNudge("pn-nudge", request, words) }) refusedWith(o.t, res, "needs_person", "Only the person can move that job on. Tell them plainly what is needed.") if n := o.rows("SELECT count(*) + coalesce(sum(attempt), 0) FROM chat_steps"); n != steps { o.t.Fatal("a step was placed") } if n := o.rows("SELECT count(*) FROM chat_messages WHERE role = ?", wire.RolePerson); n != messages { o.t.Fatalf("%d person messages, %d before", n, messages) } if n := o.nudges(request); n != 0 || o.rows("SELECT count(*) FROM chat_handoff_actions") != 0 { o.t.Fatalf("%d nudges", n) } o.reply(u.TurnID) o.jobOf(request, "stopped", func(c wire.AssistantCard) bool { return c.State == wire.JobStopped }) } // TestContractTeamNudgePersonNeeds (D6, ruling P4j): a job stopped on a // need only the person can meet is needs_person, with no fallback nudge: // each need a task reports (a failed merge step among them), a failed // publish step, and an open access card. A job still working is // not_stopped. func TestContractTeamNudgePersonNeeds(t *testing.T) { for _, c := range personNeeds() { t.Run(c.name, func(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) request, 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) } o.noteFor("the "+c.name+" note", blockedOn(c.line)) o.refusesNudge(request, "Login is broken") }) } // runner_offline is a need no task of the instance's reports now // (needsYou never returns it); like every need that is neither // no_work nor failed, stopReason makes it blocked, and blocked is // needs_person. t.Run("publish_failed", func(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) id, _, _, _ := o.mergedWebsite("pf", true) request := o.requestOf(id) 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) o.noteFor("the publish failure's note", blockedOn("going live failed, and they need to try it again")) // The Publish asked again is ready while it is open; Not now // leaves the failed go-live. again := o.assistantCard("the Publish asked again", func(c wire.AssistantCard) bool { return isPublishOutcome(c) && c.ID != card.ID && c.State == wire.CardOpen }) if _, err := o.a.Answer(o.ctx, again.ID, wire.ChoiceNotNow, again.Revision); err != nil { t.Fatal(err) } o.refusesNudge(request, "quick website") }) t.Run("access", func(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("pa1", "Login is broken", "") o.in(cmd.TurnID, func() { if res := o.call("pa-find", wire.ToolFind, map[string]string{"query": "moonbeam/app"}); res.Code != "none" { t.Fatalf("find %+v", res) } }) o.reply(cmd.TurnID) o.noteFor("the access card's note", blockedOn("they need to give access to where the work lives")) o.refusesNudge(request, "Login is broken") }) t.Run("working", func(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) request, _, _ := o.startedInThread("pw") refusedWith(t, o.teamNudge("pw-nudge", request, "Login is broken"), "not_stopped", "That job is not stopped. Nothing needs pushing.") if n := o.nudges(request); n != 0 { t.Fatalf("%d nudges", n) } }) } // TestContractTeamNudgeCap (D7): two nudges from team_update turns pass; // the update after the second tells the Assistant no nudges are left, // and a third nudge there is nudge_limit, posting nothing. func TestContractTeamNudgeCap(t *testing.T) { o := newTeamRig(t) request, update := o.stoppedJob("nc") u := o.nudgeThrough("nc-1", request, update, "quick website", 1) if !strings.Contains(u.Text, noWork(request, 1)) { t.Fatalf("the second update %q", u.Text) } u = o.nudgeThrough("nc-2", request, u.TurnID, "quick website", 0) if !strings.Contains(u.Text, "It stopped again and no nudges are left.") || strings.Contains(u.Text, "team_nudge") { t.Fatalf("the third update %q", u.Text) } messages := len(o.thread(request)) o.in(u.TurnID, func() { refusedWith(t, o.teamNudge("nc-3", request, "quick website"), "nudge_limit", "That job has been nudged twice already. Tell the person in one line that it stopped.") }) if n := len(o.thread(request)); n != messages || o.nudges(request) != 2 { t.Fatalf("%d thread messages, %d before; %d nudges", n, messages, o.nudges(request)) } } // TestContractTeamNudgeCapResetsOnlyOnNewerWords (ruling P1j): after two // nudges, an unrelated new message from the person resets nothing: a // nudge in its turn quoting their older words is still nudge_limit. A // nudge quoting a message sent after the last nudge passes, with one // nudge left. func TestContractTeamNudgeCapResetsOnlyOnNewerWords(t *testing.T) { o := newTeamRig(t) request, update := o.stoppedJob("cr") u := o.nudgeThrough("cr-1", request, update, "quick website", 1) u = o.nudgeThrough("cr-2", request, u.TurnID, "quick website", 0) o.reply(u.TurnID) o.ask("What is on my calendar today?") refusedWith(t, o.teamNudge("cr-old", request, "Build me a quick website"), "nudge_limit", "That job has been nudged twice already. Tell the person in one line that it stopped.") o.reply(o.turn) o.ask("I still want that quick website, please") nudged(t, o.teamNudge("cr-new", request, "still want that QUICK website"), request, 1) if thread := o.thread(request); thread[len(thread)-1].Text != "still want that quick website" { t.Fatalf("the thread %+v", thread) } } // TestContractTeamNudgeKeyAfterReset (ruling P2j): two nudges, a reset by // newer words, then a third and a fourth nudge: each posts its own // message, under four distinct keys, none of them a counter. func TestContractTeamNudgeKeyAfterReset(t *testing.T) { o := newTeamRig(t) request, update := o.stoppedJob("ka") u := o.nudgeThrough("ka-1", request, update, "quick website", 1) u = o.nudgeThrough("ka-2", request, u.TurnID, "quick website", 0) o.reply(u.TurnID) o.ask("I still want that quick website, please") nudged(t, o.teamNudge("ka-3", request, "still want that quick website"), request, 1) cmd := o.message(wire.JobLane(request)) o.reply(o.turn) o.reply(cmd.TurnID) u = o.message(wire.LaneAssistant) if u.Kind != wire.TurnTeamUpdate || !strings.Contains(u.Text, noWork(request, 1)) { t.Fatalf("the update after the reset %+v", u) } o.in(u.TurnID, func() { nudged(t, o.teamNudge("ka-4", request, "still want that quick website"), request, 0) }) o.message(wire.JobLane(request)) keys := o.nudgeKeys(request) seen := map[string]bool{} for _, key := range keys { if !uuidV5.MatchString(strings.TrimPrefix(key, "handoff:"+request+":nudge:")) { t.Fatalf("key %q", key) } seen[key] = true } if len(keys) != 4 || len(seen) != 4 { t.Fatalf("nudge keys %q", keys) } if n := o.rows("SELECT count(*) FROM chat_messages WHERE lane = ? AND role = ? AND idempotency_key LIKE 'handoff:%:nudge:%'", wire.JobLane(request), wire.RolePerson); n != 4 { t.Fatalf("%d nudge messages", n) } } // TestContractTeamNudgeWords: words found in no message the person sent // the Assistant (one in their own Equipo conversation among them), or // too short to quote, are not_their_words, and nothing is nudged. func TestContractTeamNudgeWords(t *testing.T) { o := newTeamRig(t) request, update := o.stoppedJob("tw") o.own("Make it purple") messages := len(o.thread(request)) o.in(update, func() { for i, words := range []string{"make it purple", "make it blue", "qu"} { refusedWith(t, o.teamNudge("tw-"+itoa(i), request, words), "not_their_words", "Not nudged: words must quote something the person said to you in this conversation, word for word, and be more than a couple of letters. Quote them; put anything of yours in context.") } }) if n := len(o.thread(request)); n != messages || o.nudges(request) != 0 { t.Fatalf("%d thread messages, %d before; %d nudges", n, messages, o.nudges(request)) } } // TestContractTeamNudgeOnce: the same nudge under a new call id, then a // result lost before it was stored, in attempt 2: one message, one // nudge counted, one action, one audit, equal results. The Assistant's // context rides after the words as reference, as kept. func TestContractTeamNudgeOnce(t *testing.T) { o := newTeamRig(t) request, update := o.stoppedJob("on") in := map[string]any{"request": request, "words": "quick website", "context": "A portfolio [with photos]"} var first, again, lost wire.ToolResult o.in(update, func() { first = o.use("on-1", "team_nudge", in) again = o.use("on-2", "team_nudge", in) }) nudged(t, first, request, 1) if again.IsError || !again.Replayed || again.Text != first.Text { t.Fatalf("again %+v, first %+v", again, first) } if cmd := o.message(wire.JobLane(request)); withoutProjectContext(t, cmd.Text) != "quick website\n\n[Reference from the Assistant, not the person's words: A portfolio (with photos)]" { t.Fatalf("the nudge's frame %+v", cmd) } o.runner.Send(o.ctx, "r-on-wait", wire.FrameTurn, wire.TurnReport{TurnID: update, Attempt: 1, State: wire.TurnWaiting, Reason: "limited"}) o.runner.Send(o.ctx, "r-on-run2", wire.FrameTurn, wire.TurnReport{TurnID: update, 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 = ?", update, wire.TurnRunning) == 1 }) // The ledger lost the result: the provider gets the same key again. o.exec("UPDATE chat_tool_calls SET ledger_key = '' WHERE turn_id = ?", update) o.in(update, func() { o.attempt = 2 lost = o.use("on-3", "team_nudge", in) }) if lost.IsError || lost.Text != first.Text { t.Fatalf("after a lost result %+v, first %+v", lost, first) } if keys := o.nudgeKeys(request); len(keys) != 1 || o.nudges(request) != 1 { t.Fatalf("nudge messages %q, %d nudges", keys, o.nudges(request)) } if n := o.rows("SELECT count(*) FROM chat_handoff_actions WHERE handoff_id = ? AND kind = 'nudge' AND context = 'A portfolio (with photos)'", request); n != 1 { t.Fatalf("%d nudge actions", n) } if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.team_nudge'"); n != 1 { t.Fatalf("%d team_nudge audits", n) } } // TestContractTeamNudgeLegacy (ruling P3j): a legacy hand-off that // stopped with no work is nudged in the person's own conversation (lane // ""), as slice 1's hand-off message was, its turn linked to it; no job // thread is made. func TestContractTeamNudgeLegacy(t *testing.T) { o := newTeamRig(t) o.ask("Build me a quick website") request, turn := o.legacyHandoff("ln", "Build me a quick website") o.reply(turn) o.noteFor("the legacy no-work note", noWork(request, 2)) o.reply(o.turn) u := o.message(wire.LaneAssistant) if u.Kind != wire.TurnTeamUpdate { t.Fatalf("update frame %+v", u) } o.in(u.TurnID, func() { nudged(t, o.teamNudge("ln-nudge", request, "quick website"), request, 1) }) next := o.message(wire.LaneCoordinator) if withoutProjectContext(t, next.Text) != "quick website\n\n"+nudgeReference || o.laneOf(next.TurnID) != wire.LaneCoordinator { t.Fatalf("the nudge's frame %+v", next) } if n := o.rows("SELECT count(*) FROM chat_handoff_turns WHERE handoff_id = ? AND turn_id = ?", request, next.TurnID); n != 1 { t.Fatal("the nudge's turn is not the legacy hand-off's") } if keys := o.nudgeKeys(request); len(keys) != 1 || o.rows("SELECT count(*) FROM chat_messages WHERE idempotency_key = ? AND coalesce(lane, '') = ''", keys[0]) != 1 { t.Fatalf("nudge messages %q", keys) } if n := o.rows("SELECT count(*) FROM chat_turns WHERE lane LIKE 'job:%'"); n != 0 { t.Fatalf("%d turns in a job thread", n) } } // TestContractTeamNudgeOnlyOwnJob: a team_update turn nudges only the job // it is about (another job's is not_asked); an unknown request is // not_found; a request the person cancelled is turn_ended; a job thread // the person's runner is too old to carry is runner_too_old. None of // them posts anything or counts a nudge. func TestContractTeamNudgeOnlyOwnJob(t *testing.T) { o := newTeamRig(t) o.ask("Build me a quick website, and the logo is blurry") requests := map[string]bool{} for key, words := range map[string]string{"a": "Build me a quick website", "b": "the logo is blurry"} { request, cmd := o.handoff("oj-"+key, words, "") requests[request] = true o.reply(cmd.TurnID) } o.reply(o.turn) u := o.message(wire.LaneAssistant) var mine, other string for request := range requests { if o.rows("SELECT count(*) FROM chat_handoff_turns WHERE handoff_id = ? AND turn_id = ?", request, u.TurnID) == 1 { mine = request } else { other = request } } if u.Kind != wire.TurnTeamUpdate || mine == "" || other == "" { t.Fatalf("the first update %+v (%v)", u, requests) } messages := o.rows("SELECT count(*) FROM chat_messages WHERE role = ?", wire.RolePerson) o.in(u.TurnID, func() { refusedWith(t, o.teamNudge("oj-other", other, "the logo is blurry"), "not_asked", "This update is about another job. Answer or nudge only the job it names.") if res := o.teamNudge("oj-none", "h_nothere", "the logo is blurry"); !res.IsError || res.Code != "not_found" { t.Fatalf("an unknown request %+v", res) } o.exec("UPDATE runner_sessions SET protocol = ?", wire.Protocol21) if res := o.teamNudge("oj-old", mine, "quick website"); !res.IsError || res.Code != "runner_too_old" { t.Fatalf("a runner too old for job threads %+v", res) } o.exec("UPDATE runner_sessions SET protocol = ?", wire.ProtocolJobs) o.exec("UPDATE chat_handoffs SET state = 'cancelled' WHERE id = ?", mine) if res := o.teamNudge("oj-cancelled", mine, "quick website"); !res.IsError || res.Code != "turn_ended" { t.Fatalf("a cancelled request %+v", res) } }) if n := o.rows("SELECT count(*) FROM chat_messages WHERE role = ?", wire.RolePerson); n != messages || o.rows("SELECT sum(nudges) FROM chat_handoffs") != 0 { t.Fatalf("%d person messages, %d before", n, messages) } } // TestContractTeamReplyQueued: an answer given while the job's thread // still has a turn running waits behind it, and is dispatched with the // question it answers and nothing of a nudge's. func TestContractTeamReplyQueued(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("rq-h", "Login is broken", "") o.in(cmd.TurnID, func() { if res := o.call("rq-ask", wire.ToolAskPerson, map[string]any{"question": loginQuestion, "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) replied(t, o.teamReply("rq-reply", request, "Web"), request) o.reply(cmd.TurnID) if next := o.message(wire.JobLane(request)); withoutProjectContext(t, next.Text) != `(My answer to your question "Which login page?") Web` { t.Fatalf("the answer's frame %+v", next) } } // TestContractTeamNudgeToldAgain: a nudge clears what the Assistant was // last told of the job: after a reset by newer words, the same note (one // nudge left) is told again when the job stops again. func TestContractTeamNudgeToldAgain(t *testing.T) { o := newTeamRig(t) request, update := o.stoppedJob("ta") u := o.nudgeThrough("ta-1", request, update, "quick website", 1) if !strings.Contains(u.Text, noWork(request, 1)) { t.Fatalf("the second update %q", u.Text) } o.reply(u.TurnID) o.ask("I still want that quick website, please") nudged(t, o.teamNudge("ta-2", request, "still want that quick website"), request, 1) cmd := o.message(wire.JobLane(request)) o.reply(o.turn) o.reply(cmd.TurnID) if again := o.message(wire.LaneAssistant); again.Kind != wire.TurnTeamUpdate || again.Text != u.Text { t.Fatalf("told again %+v", again) } } // TestContractTeamNudgeRetryOne (ruling R22): one nudge tries again // exactly one task: the hand-off's earliest one a failed step the // instance can retry holds. With two failed, the first nudge retries // only the first; once the first is done, a second nudge retries the // second. func TestContractTeamNudgeRetryOne(t *testing.T) { o := newTeamRig(t) request, first, d1 := o.startedInThread("n1") var second string var d2 *wire.DispatchCommand o.in(o.handoffTurn(request), func() { second = o.record("n1-rec2", "Fix the logo") if res := o.call("n1-start2", wire.ToolStartTask, map[string]string{"task": second, "brief": "Fix it."}); res.IsError { t.Fatalf("start %+v", res) } _, body := o.expect(wire.FrameDispatch) d2 = body.(*wire.DispatchCommand) }) o.step("n1-fail1", wire.StepReport{TaskID: first, StepID: d1.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true}) o.step("n1-fail2", wire.StepReport{TaskID: second, StepID: d2.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true}) o.noteFor("the failed note", failedStep(request, 2)) o.reply(o.turn) u := o.message(wire.LaneAssistant) attempts := func(want1, want2 int) { t.Helper() if o.rows("SELECT attempt FROM chat_steps WHERE id = ?", d1.StepID) != want1 || o.rows("SELECT attempt FROM chat_steps WHERE id = ?", d2.StepID) != want2 { t.Fatalf("attempts %d and %d, want %d and %d", o.rows("SELECT attempt FROM chat_steps WHERE id = ?", d1.StepID), o.rows("SELECT attempt FROM chat_steps WHERE id = ?", d2.StepID), want1, want2) } } o.in(u.TurnID, func() { nudged(t, o.teamNudge("n1-nudge1", request, "Login is broken"), request, 1) }) attempts(2, 1) o.reply(u.TurnID) // The first is done; the second still waits on its failed step. o.exec("UPDATE chat_steps SET state = ?, terminated = 1 WHERE id = ?", wire.StepDone, d1.StepID) o.exec("UPDATE chat_tasks SET stage = ? WHERE id = ?", wire.StageDone, first) o.ask("Try the logo again please") nudged(t, o.teamNudge("n1-nudge2", request, "Login is broken"), request, 0) attempts(2, 2) }