package thintest import ( "context" "database/sql" "encoding/json" "fmt" "net/http" "net/url" "regexp" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/wire" ) // Outcome cards (spec ยง5, Cards): when a hand-off's task or turn raises a // team card, the Assistant lane gets a card that points at it, in its // own plain words, answered through the team card's own path. // assistantCards are the Assistant snapshot's cards but its job cards // (the job card tests read those: jobOf). func (o *teamRig) assistantCards() []wire.AssistantCard { o.t.Helper() snap, err := o.a.Snapshot(o.ctx) if err != nil { o.t.Fatal(err) } return slices.DeleteFunc(snap.Cards, func(c wire.AssistantCard) bool { return c.Kind == wire.CardJob }) } // assistantCard waits for the Assistant card that matches. func (o *teamRig) assistantCard(what string, match func(wire.AssistantCard) bool) wire.AssistantCard { o.t.Helper() var out wire.AssistantCard o.until(what, func() bool { for _, c := range o.assistantCards() { if match(c) { out = c return true } } return false }) return out } // teamCard is the person's Coordinator card of kind for the turn or task. func (o *teamRig) teamCard(kind, turn, task string) wire.Card { o.t.Helper() snap, err := o.client.Snapshot(o.ctx) if err != nil { o.t.Fatal(err) } for _, c := range snap.Cards { if c.Kind == kind && (turn == "" || c.TurnID == turn) && (task == "" || c.TaskID == task) { return c } } return wire.Card{} } // threadCard is the card of kind raised in the turn, wherever its lane: // a job thread's never shows in the person's snapshot. func (o *teamRig) threadCard(kind, turn string) wire.Card { o.t.Helper() var c wire.Card err := o.inst.DB.Writer().QueryRow("SELECT id, revision, kind, state, coalesce(turn_id, ''), coalesce(task_id, ''), coalesce(choice, '') FROM chat_cards WHERE kind = ? AND turn_id = ? AND coalesce(lane, '') <> ? ORDER BY created_at, id LIMIT 1", kind, turn, wire.LaneAssistant).Scan(&c.ID, &c.Revision, &c.Kind, &c.State, &c.TurnID, &c.TaskID, &c.Choice) if err != nil && err != sql.ErrNoRows { o.t.Fatal(err) } return c } // coordinatorCards are the person's Coordinator cards of kind on the // task, oldest first, as stored, wherever their lane: their own // conversation or a job thread, which never shows in their snapshot. func (o *teamRig) coordinatorCards(kind, task string) []wire.Card { o.t.Helper() rows, err := o.inst.DB.Writer().Query("SELECT id, revision, kind, state, coalesce(turn_id, ''), coalesce(task_id, ''), coalesce(question, ''), coalesce(choice, '') FROM chat_cards WHERE person = ? AND kind = ? AND task_id = ? AND (coalesce(lane, '') = '' OR lane LIKE 'job:%') ORDER BY created_at, rowid", Owner, kind, task) if err != nil { o.t.Fatal(err) } defer rows.Close() var out []wire.Card for rows.Next() { var c wire.Card if err := rows.Scan(&c.ID, &c.Revision, &c.Kind, &c.State, &c.TurnID, &c.TaskID, &c.Question, &c.Choice); err != nil { o.t.Fatal(err) } out = append(out, c) } if err := rows.Err(); err != nil { o.t.Fatal(err) } return out } // cardOf is the task's merge card wherever its lane (coordinatorCards). func (o *teamRig) cardOf(id string) wire.Card { o.t.Helper() if cards := o.coordinatorCards(wire.CardMerge, id); len(cards) > 0 { return cards[0] } return wire.Card{} } // publishCard is the task's newest publish card wherever its lane. func (o *teamRig) publishCard(id string) (wire.Card, bool) { o.t.Helper() cards := o.coordinatorCards(wire.CardPublish, id) if len(cards) == 0 { return wire.Card{}, false } return cards[len(cards)-1], true } // websiteReady is toolRig's, its merge card found wherever its lane. func (o *teamRig) websiteReady(key, title, base, cand string, has bool) (string, wire.Card) { o.t.Helper() id := o.websiteJudged(key, title, base, cand, has) var card wire.Card o.until("the merge card", func() bool { card = o.cardOf(id); return card.ID != "" }) return id, card } // mergeFromCard is toolRig's, its merge card found wherever its lane. func (o *teamRig) mergeFromCard(key, id, base, cand, sha string) { o.t.Helper() card := o.cardOf(id) if _, err := o.client.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil { o.t.Fatalf("merge %v", err) } o.mergedStep(key, o.dispatched(wire.SpecialistMerge, base, cand, 0), sha) o.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) } // requestOf is the hand-off that follows the task. func (o *teamRig) requestOf(task string) string { o.t.Helper() var request string if err := o.inst.DB.Writer().QueryRow("SELECT handoff_id FROM chat_handoff_tasks WHERE task_id = ?", task).Scan(&request); err != nil { o.t.Fatal(err) } return request } // laneOfCard is the card's lane. func (o *teamRig) laneOfCard(id string) string { o.t.Helper() var lane string if err := o.inst.DB.Writer().QueryRow("SELECT coalesce(lane, '') FROM chat_cards WHERE id = ?", id).Scan(&lane); err != nil { o.t.Fatal(err) } return lane } // conflictOf is a 409's AssistantConflict. func conflictOf(t *testing.T, err error) wire.AssistantConflict { t.Helper() var out wire.AssistantConflict s, ok := err.(*ErrStatus) if !ok || s.Status != http.StatusConflict || wire.Strict(s.Body, &out) != nil { t.Fatalf("not a card conflict: %v", err) } return out } // storeLink writes a preview link into an Assistant card's stored links, // as a card raised before previews were read live would hold it. func (o *teamRig) storeLink(card, url string) { o.t.Helper() raw, _ := json.Marshal([]wire.CardLink{{Label: equipo.RunnerCopy("assistant.outcome.preview"), URL: url}}) if _, err := o.inst.DB.Writer().Exec("UPDATE chat_cards SET links = ? WHERE id = ?", string(raw), card); err != nil { o.t.Fatal(err) } } // isMergeOutcome: the outcome card of a merge card (not one that sends // the person to Equipo). func isMergeOutcome(c wire.AssistantCard) bool { return c.Kind == wire.CardOutcome && c.Question != equipo.RunnerCopy("assistant.outcome.needs_you") && !isPublishOutcome(c) } // isPublishOutcome: the outcome card of a publish card. func isPublishOutcome(c wire.AssistantCard) bool { return c.Kind == wire.CardOutcome && c.Question == equipo.RunnerCopy("assistant.outcome.publish_question") } // mergeQuestion is the outcome card's question for a merge card asked // because of reason. func mergeQuestion(reason string) string { return fmt.Sprintf(equipo.RunnerCopy("assistant.outcome.merge"), equipo.RunnerCopy("assistant.outcome.reason."+reason)) } // jobLine is the note's first line for a job (noteJob), and its second, // the person's words (noteAsked). func jobLine(title, request, words string) string { return fmt.Sprintf("Job %q (request %s).\nThe person asked for it in these words: %q\n", title, request, words) } // noteFor waits for the newest team_update note that contains want. func (o *teamRig) noteFor(what, want string) string { o.t.Helper() var note string o.until(what, func() bool { _, notes, _ := o.updates() if len(notes) > 0 { note = notes[len(notes)-1] } return strings.Contains(note, want) }) return note } // TestContractOutcomeQuestionNotMirrored: the Coordinator's ask_person // in a job's thread raises no card in the Assistant lane: the Assistant // hears of it in one team_update turn, whose note names the job and its // request, quotes the person's words, the question and its options, and // says how to answer it (team_reply). The note is the instance's: the // frame carries no words of the person's. func TestContractOutcomeQuestionNotMirrored(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("oq1", "Login is broken", "") o.in(cmd.TurnID, func() { if res := o.call("oq-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) o.until("the update", func() bool { ids, _, _ := o.updates(); return len(ids) == 1 }) team := o.threadCard(wire.CardQuestion, cmd.TurnID) if team.ID == "" || team.State != wire.CardOpen || o.teamCard(wire.CardQuestion, cmd.TurnID, "").ID != "" { t.Fatalf("the thread's question %+v", team) } if cards := o.assistantCards(); len(cards) != 0 { t.Fatalf("assistant cards %+v", cards) } o.reply(cmd.TurnID) o.reply(o.turn) u := o.message(wire.LaneAssistant) if u.Kind != wire.TurnTeamUpdate || len(u.PersonText) != 0 { t.Fatalf("update frame %+v", u) } for _, want := range []string{jobLine("Login is broken", request, "Login is broken"), `The work on it has a question: "Which login page?"`, `The answer must be one of: "Web", "App"`, "team_reply"} { if !strings.Contains(u.Text, want) { t.Fatalf("the note lacks %q: %s", want, u.Text) } } if ids, _, _ := o.updates(); len(ids) != 1 { t.Fatalf("updates %v", ids) } if cards := o.assistantCards(); len(cards) != 0 { t.Fatalf("assistant cards after the turns %+v", cards) } } // TestContractOutcomeLegacyQuestionTold: a legacy hand-off's question, // raised on its turn in the person's own conversation, raises no // Assistant card either: the Assistant is told in a team_update note. func TestContractOutcomeLegacyQuestionTold(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, turn := o.legacyHandoff("lq", "Login is broken") o.in(turn, func() { if res := o.call("lq-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } }) note := o.noteFor("the legacy question's note", `The work on it has a question: "Which login page?"`) if !strings.Contains(note, "(request "+request+")") || !strings.Contains(note, `"Web", "App"`) { t.Fatalf("note %q", note) } if o.teamCard(wire.CardQuestion, turn, "").ID == "" { t.Fatal("the legacy question left their conversation") } if cards := o.assistantCards(); len(cards) != 0 { t.Fatalf("assistant cards %+v", cards) } } // TestContractOutcomeLegacyMirrorStillFollows: an Assistant question // card mirrored before this release (as slice 1 raised it, pointing at // its team card) still follows that card: answered in Equipo, it is // answered with the same choice. func TestContractOutcomeLegacyMirrorStillFollows(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") _, turn := o.legacyHandoff("lm", "Login is broken") o.in(turn, func() { if res := o.call("lm-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 team 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 { team = k } } return team.ID != "" }) options := `[{"value":"Web","label":"Web"},{"value":"App","label":"App"}]` if _, err := o.inst.DB.Writer().Exec("INSERT INTO chat_cards(id, person, kind, state, question, options, links, source_card, revision, created_at, updated_at, lane) VALUES ('c_slice1', ?, ?, ?, 'Which login page?', ?, '[]', ?, 1, ?, ?, ?)", Owner, wire.CardQuestion, wire.CardOpen, options, team.ID, time.Now().UTC(), time.Now().UTC(), wire.LaneAssistant); err != nil { t.Fatal(err) } if _, err := o.client.Answer(o.ctx, team.ID, "App", team.Revision); err != nil { t.Fatal(err) } got := o.assistantCard("the old mirror answered", func(c wire.AssistantCard) bool { return c.ID == "c_slice1" && c.State == wire.CardAnswered }) if got.Result != "App" || got.Revision <= 1 { t.Fatalf("the old mirror %+v", got) } } // TestContractOutcomeMerge: a merge card on a hand-off's task raises an // outcome card, in plain words with the preview once it is up; Merge on // it at its revision merges as the card's Merge does: the person's // decision, bound to the SHA the team card asked about. func TestContractOutcomeMerge(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) o.sitesOn(wire.ProtocolCurrent, false) o.ask("Can we fix a bug in Tito? Login is broken") _, cmd := o.handoff("om1", "Login is broken", "") base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) var id string o.in(cmd.TurnID, func() { id, _ = o.websiteReady("om", "Quick website", base, cand, true) }) team := o.cardOf(id) card := o.assistantCard("the merge outcome", isMergeOutcome) want := []wire.CardOption{{Value: wire.ChoiceMerge, Label: equipo.RunnerCopy("assistant.outcome.option.merge")}, {Value: wire.ChoiceWait, Label: equipo.RunnerCopy("assistant.outcome.option.wait")}} if card.State != wire.CardOpen || card.Question != mergeQuestion("environment_reason") || !slices.Equal(card.Options, want) || card.Links == nil || len(card.Links) != 0 { t.Fatalf("card %+v", card) } if strings.Contains(card.Question, team.Question) || strings.Contains(card.Question, "Quick website") { t.Fatalf("the outcome quotes the team card: %q", card.Question) } pv := o.previewDispatch(cand) o.built("om-pv-built", pv, digestA) link := "https://eq-" + id + ".docs-t1.example.ts.net/" o.previewDone("om-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, Outcome: wire.PreviewDeployed}) shown := o.assistantCard("the preview", func(c wire.AssistantCard) bool { return c.ID == card.ID && len(c.Links) == 1 }) if shown.Links[0] != (wire.CardLink{Label: equipo.RunnerCopy("assistant.outcome.preview"), URL: link}) || shown.Revision <= card.Revision || shown.State != wire.CardOpen { t.Fatalf("with the preview %+v", shown) } // The card changed since it was first read: an answer to that is // stale, though the team card would take a Merge now. _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision) if c := conflictOf(t, err); c.Code != "card_stale" || c.Card.Revision != shown.Revision || len(c.Card.Links) != 1 { t.Fatalf("an answer from before the preview %+v", c) } if n := o.rows("SELECT count(*) FROM chat_steps WHERE task_id = ? AND specialist = ?", id, wire.SpecialistMerge); n != 0 { t.Fatal("merged on a stale answer") } ans, err := o.a.Answer(o.ctx, shown.ID, wire.ChoiceMerge, shown.Revision) if err != nil || ans.Card.State != wire.CardAnswered || ans.Card.Result != equipo.RunnerCopy("assistant.outcome.option.merge") { t.Fatalf("answer %+v %v", ans, err) } m := o.dispatched(wire.SpecialistMerge, base, cand, 0) if n := o.rows("SELECT count(*) FROM chat_steps WHERE id = ? AND decided_by = ? AND candidate_sha = ?", m.StepID, "person:"+Owner, cand); n != 1 { t.Fatal("the merge step is not the person's decision on the asked SHA") } if after := o.cardOf(id); after.ID != team.ID || after.State != wire.CardAnswered || after.Choice != wire.ChoiceMerge { t.Fatalf("team card %+v", after) } answered := o.assistantCard("answered", func(c wire.AssistantCard) bool { return c.ID == card.ID }) if answered.State != wire.CardAnswered || len(answered.Links) != 1 { t.Fatalf("outcome card %+v", answered) } // Merged, the task is done and its devbox preview gone: the answered // card stops showing it, and says so as a change. // A preview stored on the card (as before it was read live) is // never shown from there. o.storeLink(card.ID, link) o.mergedStep("om-m", m, strings.Repeat("e", 40)) o.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) if done := o.assistantCard("done", func(c wire.AssistantCard) bool { return c.ID == card.ID }); len(done.Links) != 0 || done.Revision <= answered.Revision || done.State != wire.CardAnswered { t.Fatalf("after the merge %+v (answered %+v)", done, answered) } // Raised once for the merge card, however often it changed; the // ships question raises none (the Assistant is told). if cards := o.assistantCards(); len(cards) != 1 { t.Fatalf("assistant cards %+v", cards) } } // TestContractOutcomePreviewExpires: a preview that expires is no longer // offered, on a card already answered too. func TestContractOutcomePreviewExpires(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) o.sitesOn(wire.ProtocolCurrent, false) o.ask("Can we fix a bug in Tito? Login is broken") _, cmd := o.handoff("ox1", "Login is broken", "") base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) var id string o.in(cmd.TurnID, func() { id, _ = o.websiteReady("ox", "Quick website", base, cand, true) }) pv := o.previewDispatch(cand) o.built("ox-pv-built", pv, digestA) expires := time.Now().Add(time.Hour) link := "https://eq-" + id + ".docs-t1.example.ts.net/" o.previewDone("ox-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, ExpiresAt: &expires, Outcome: wire.PreviewDeployed}) card := o.assistantCard("the preview", func(c wire.AssistantCard) bool { return isMergeOutcome(c) && len(c.Links) == 1 }) if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceWait, card.Revision); err != nil { t.Fatal(err) } o.storeLink(card.ID, link) o.inst.Store.Chat().SetClock(func() time.Time { return time.Now().UTC().Add(2 * time.Hour) }) t.Cleanup(func() { o.inst.Store.Chat().SetClock(func() time.Time { return time.Now().UTC() }) }) if got := o.assistantCard("expired", func(c wire.AssistantCard) bool { return c.ID == card.ID }); len(got.Links) != 0 || got.State != wire.CardAnswered { t.Fatalf("after the preview expired %+v", got) } } // TestContractOutcomeShips: the ships question belongs to a project, not // a task, and is raised in the lane of the work that asked it: for a // job's work, in its thread. It raises no Assistant card; the go-ahead // raised beside it is what the Assistant is told of. func TestContractOutcomeShips(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("sh1", "Login is broken", "") base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) o.in(cmd.TurnID, func() { o.websiteReady("sh", "Quick website", base, cand, false) }) var ships, task, turn, lane string if err := o.inst.DB.Writer().QueryRow("SELECT id, coalesce(task_id, ''), coalesce(turn_id, ''), coalesce(lane, '') FROM chat_cards WHERE kind = ?", wire.CardMergeShips).Scan(&ships, &task, &turn, &lane); err != nil { t.Fatal(err) } if task != "" || turn != "" || lane != wire.JobLane(request) || o.teamCard(wire.CardMergeShips, "", "").ID != "" { t.Fatalf("ships card %s for %q in %q, %q", ships, task, turn, lane) } // The go-ahead in front of the person is what the Assistant hears of. if note := o.noteFor("the job's note", "It is ready for the person to try."); strings.Contains(note, "only the person can move it on") { t.Fatalf("note %q", note) } if cards := o.assistantCards(); len(cards) != 1 || !isMergeOutcome(cards[0]) { t.Fatalf("assistant cards %+v", cards) } } // TestContractOutcomeShipsNotTheirs: the ships question raises nothing // for a person whose hand-off's work in the project has ended, when the // question comes from work they started in Equipo. func TestContractOutcomeShipsNotTheirs(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") _, cmd := o.handoff("sn1", "Login is broken", "") var ended string o.in(cmd.TurnID, func() { ended = o.record("sn-rec", "Fix the login") }) o.reply(cmd.TurnID) if _, err := o.client.CancelTask(o.ctx, ended); err != nil { t.Fatal(err) } mine := o.own("Something of my own.") base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) o.in(mine, func() { o.websiteReady("sn", "Quick website", base, cand, false) }) if o.teamCard(wire.CardMergeShips, "", "").ID == "" { t.Fatal("no ships card") } if cards := o.assistantCards(); len(cards) != 0 { t.Fatalf("assistant cards %+v", cards) } } // TestContractOutcomeOnlyTheirs: a team card raises an Assistant card only // for a hand-off of its own person's: another person's hand-off that // joined the task (add_report) raises none, in either lane. func TestContractOutcomeOnlyTheirs(t *testing.T) { o := newTeamRig(t) mine := o.own("Something of my own.") var id string o.in(mine, func() { id = o.record("ot-own", "Quick website") }) mate := &teamRig{o.other("mate@example.com")} mate.connect(o.base.Mint()) mate.ask("Can we fix a bug in Tito? Login is broken") request, cmd := mate.handoff("ot1", "Login is broken", "") mate.in(cmd.TurnID, func() { if res := mate.call("ot-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 other hand-off does not follow the task: %v", o.linked(request)) } base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) o.in(mine, func() { if res := o.call("ot-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("ot-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "claude-a"}) o.step("ot-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("ot-c", c, wire.ChecksNone, nil, "", "") o.verdict("ot-r", o.dispatched(wire.SpecialistReview, base, cand, 0), wire.VerdictApprove) }) o.until("the merge card", func() bool { return o.cardOf(id).ID != "" }) if cards := o.assistantCards(); len(cards) != 0 { t.Fatalf("the creator's Assistant cards %+v", cards) } // Their job card follows the work; no go-ahead is theirs. if cards := mate.assistantCards(); len(cards) != 0 { t.Fatalf("the other person's Assistant cards %+v", cards) } } // TestContractOutcomeGoesStale: the outcome card's revision follows the // team card's, so an answer from before the branch moved is refused with // the card as it is now; a withdrawn team card resolves it. func TestContractOutcomeGoesStale(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") _, cmd := o.handoff("os1", "Login is broken", "") base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) var id string o.in(cmd.TurnID, func() { id, _ = o.websiteReady("os", "Quick website", base, cand, false) }) before := o.assistantCard("the merge outcome", isMergeOutcome) team := o.cardOf(id) if err := o.runner.Send(o.ctx, "os-moved", wire.FrameBranch, wire.BranchReport{TaskID: id, CandidateSHA: cand, Head: strings.Repeat("9", 40)}); err != nil { t.Fatal(err) } o.wait("moved", func(c *Conversation) bool { return c.Tasks[id].NeedsYou == wire.NeedsBranchMoved }) moved := o.cardOf(id) after := o.assistantCard("the moved card", func(c wire.AssistantCard) bool { return c.ID == before.ID && c.Revision > before.Revision }) if moved.Revision <= team.Revision || after.State != wire.CardOpen { t.Fatalf("team %d to %d, outcome %+v", team.Revision, moved.Revision, after) } _, err := o.a.Answer(o.ctx, before.ID, wire.ChoiceMerge, before.Revision) if c := conflictOf(t, err); c.Code != "card_stale" || c.Card.ID != before.ID || c.Card.Revision != after.Revision || c.Card.Options == nil || c.Card.Links == nil { t.Fatalf("stale answer %+v", c) } if n := o.rows("SELECT count(*) FROM chat_steps WHERE task_id = ? AND specialist = ?", id, wire.SpecialistMerge); n != 0 { t.Fatal("merged on a stale answer") } if _, err := o.client.CancelTask(o.ctx, id); err != nil { t.Fatal(err) } resolved := o.assistantCard("resolved", func(c wire.AssistantCard) bool { return c.ID == before.ID && c.State == wire.CardResolved }) if resolved.Result != equipo.RunnerCopy("assistant.outcome.resolved") || resolved.Revision <= after.Revision { t.Fatalf("resolved %+v", resolved) } if c := conflictOf(t, func() error { _, err := o.a.Answer(o.ctx, before.ID, wire.ChoiceMerge, resolved.Revision); return err }()); c.Code != "card_answered" || c.Card.State != wire.CardResolved { t.Fatalf("answer on a resolved card %+v", c) } } // TestContractOutcomeOnlyOwnAnswer: only the person answers their // outcome card: another member does not find it, no tool of the model's // answers it, and the team card's own rule still holds (a person who is // no longer an owner cannot merge). func TestContractOutcomeOnlyOwnAnswer(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") _, cmd := o.handoff("oo1", "Login is broken", "") base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) var id string o.in(cmd.TurnID, func() { id, _ = o.websiteReady("oo", "Quick website", base, cand, false) }) card := o.assistantCard("the merge outcome", isMergeOutcome) mate := &teamRig{o.other("mate@example.com")} mate.connect(o.base.Mint()) if _, err := mate.a.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision); Status(err) != http.StatusNotFound { t.Fatalf("another member's answer: %v", err) } if snap, err := mate.a.Snapshot(o.ctx); err != nil || len(snap.Cards) != 0 { t.Fatalf("another member sees %+v %v", snap.Cards, err) } // The model: no Assistant tool or operation answers a card, and the // Coordinator has none either. for _, name := range []string{"answer_card", "answer"} { if res := o.tool("oo-"+name, name, map[string]any{"card": card.ID, "choice": wire.ChoiceMerge, "revision": card.Revision}); !res.IsError || res.Code != "unknown_tool" { t.Fatalf("Assistant tool %s %+v", name, res) } } if res := o.use("oo-use", "answer_card", map[string]any{"card": card.ID, "choice": wire.ChoiceMerge}); !res.IsError { t.Fatalf("use answer_card %+v", res) } o.in(cmd.TurnID, func() { if res := o.call("oo-coord", "answer_card", map[string]any{"card": card.ID, "choice": wire.ChoiceMerge}); !res.IsError || res.Code != "unknown_tool" { t.Fatalf("Coordinator tool %+v", res) } }) if got := o.assistantCard("still open", func(c wire.AssistantCard) bool { return c.ID == card.ID }); got.State != wire.CardOpen || got.Revision != card.Revision { t.Fatalf("after the model %+v", got) } if n := o.rows("SELECT count(*) FROM chat_steps WHERE task_id = ? AND specialist = ?", id, wire.SpecialistMerge); n != 0 { t.Fatal("merged without the person") } // The person stops being an owner: the merge card's own rule refuses. var revision int64 if err := o.inst.DB.Writer().QueryRow("SELECT revision FROM members WHERE address = ?", Owner).Scan(&revision); err != nil { t.Fatal(err) } if err := o.inst.Store.SetMember(context.Background(), equipo.Actor{Address: "mate@example.com"}, Owner, equipo.RoleMember, true, revision); err != nil { t.Fatal(err) } if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision); Status(err) != http.StatusForbidden { t.Fatalf("a member's merge: %v", err) } if n := o.rows("SELECT count(*) FROM chat_steps WHERE task_id = ? AND specialist = ?", id, wire.SpecialistMerge); n != 0 || o.cardOf(id).State != wire.CardOpen { t.Fatal("a member merged") } } // TestContractNoMergeQuestionWhenGateMerges: work Equipo merges on its // own raises no outcome card: the person is told it is done. func TestContractNoMergeQuestionWhenGateMerges(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) o.ask("Can we fix a bug in Tito? Login is broken") _, cmd := o.handoff("og1", "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.judgedTask("og", "Fix the login", base, cand, wire.ChecksPassed, "") }) m := o.dispatched(wire.SpecialistMerge, base, cand, 0) o.mergedStep("og-m", m, merged) o.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) if cards := o.assistantCards(); len(cards) != 0 { t.Fatalf("assistant cards %+v", cards) } if ids, notes, _ := o.updates(); len(ids) != 1 || !strings.Contains(notes[0], equipo.RunnerCopy("assistant.team.stage.done")) { t.Fatalf("updates %v %q", ids, notes) } } // TestContractOutcomeBlockedNotMirrored: a card in a job's thread that // stops the work on something only the person can give (access) raises // no Assistant card: the Assistant is told, in plain words, that only // the person can move the job on, and not to nudge it. A task card and a // merge receipt need nothing of the person and queue nothing. func TestContractOutcomeBlockedNotMirrored(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) o.shipsNo(o.project()) mine := o.own("Something of my own.") var joined string o.in(mine, func() { joined = o.record("ob-own", "Dark mode for settings") }) o.reply(mine) o.ask("Can we fix a bug in Tito? Login is broken") request, cmd := o.handoff("ob1", "Login is broken", "") o.in(cmd.TurnID, func() { if res := o.call("ob-find", wire.ToolFind, map[string]string{"query": "moonbeam/app"}); res.Code != "none" { t.Fatalf("find %+v", res) } }) note := o.noteFor("the access card's note", "It stopped, and only the person can move it on: they need to give access to where the work lives. Tell the person that plainly, in one line. Do not nudge it.") if !strings.HasPrefix(note, jobLine("Login is broken", request, "Login is broken")) || strings.Contains(note, "Moonbeam") || strings.Contains(note, "team_nudge") { t.Fatalf("note %q", note) } if o.threadCard(wire.CardAccess, cmd.TurnID).ID == "" { t.Fatal("no access card in the thread") } if cards := o.assistantCards(); len(cards) != 0 { t.Fatalf("assistant cards %+v", cards) } told, notes, _ := o.updates() // A task card (add_report) and a merge receipt (Equipo merged on its // own) need nothing of the person. base, cand, merge := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("e", 40) var id string o.in(cmd.TurnID, func() { if res := o.call("ob-rep", wire.ToolAddReport, map[string]string{"task": joined, "text": "Login is broken too."}); res.IsError { t.Fatalf("add_report %+v", res) } id, _ = o.measured("ob", "Swipe back from the edge", base, cand, wire.ChecksCannotRun, "needs_macos", func(d *wire.DispatchCommand) *wire.ChangeFacts { return facts(d) }) }) if o.threadCard(wire.CardTask, cmd.TurnID).TaskID != joined { t.Fatal("no task card") } m := o.dispatched(wire.SpecialistMerge, base, cand, 0) if refused := o.lease(o.runner, "ob-lease", wire.LeaseCheck{StepID: m.StepID, Attempt: m.Attempt}); refused != "" { t.Fatalf("start refused %q", refused) } if refused := o.lease(o.runner, "ob-confirm", wire.LeaseCheck{StepID: m.StepID, Attempt: m.Attempt, Purpose: wire.LeasePurposeMerge}); refused != "" { t.Fatalf("confirmation refused %q", refused) } o.step("ob-m-run", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, CandidateSHA: cand}) o.step("ob-m", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Termination: true, Findings: []wire.Finding{}, MergeSHA: merge, Into: "main", Strategy: wire.MergeCommit, MergeSource: wire.MergeSourceHub, MergeParents: []string{strings.Repeat("9", 40), cand}}) o.until("the receipt", func() bool { return len(o.coordinatorCards(wire.CardMergeReceipt, id)) == 1 }) if cards := o.assistantCards(); len(cards) != 0 { t.Fatalf("assistant cards %+v", cards) } if ids, after, _ := o.updates(); !slices.Equal(ids, told) || !slices.Equal(after, notes) { t.Fatalf("updates after the task card and the receipt %v %q, before %v %q", ids, after, told, notes) } } // TestContractAssistantLaneLeaksNoMachinery: a hand-off through a // question (answered in its thread), a merge card and its answer, then // the publish card and its answer to a published site, leaves nothing of // the team's machinery in the Assistant lane: no task id, repository, // branch, SHA, link into Equipo's tasks or team keys, in the snapshot, // any event or an answer; every card has exactly its eight keys, plus // job on the go-ahead and the Publish card, plus detail and started_at // on the job card. func TestContractAssistantLaneLeaksNoMachinery(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("ol1", "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() { if res := o.call("ol-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { t.Fatalf("ask %+v", res) } id, _ = o.websiteReady("ol", "Quick website", base, cand, true) }) pv := o.previewDispatch(cand) o.built("ol-pv-built", pv, digestA) link := "https://eq-" + id + ".docs-t1.example.ts.net/" o.previewDone("ol-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, Outcome: wire.PreviewDeployed}) outcome := o.assistantCard("the merge outcome", func(c wire.AssistantCard) bool { return isMergeOutcome(c) && slices.ContainsFunc(c.Links, func(l wire.CardLink) bool { return l.URL == link }) }) var answers [][]byte answer := func(card wire.AssistantCard, choice string) { body, _ := json.Marshal(wire.AnswerCard{Choice: choice, Revision: card.Revision}) status, _, out := raw(t, "POST", o.inst.URL+"/api/v1/assistant/cards/"+card.ID+"/answer", o.client.Token, nil, string(body)) if status != 200 { t.Fatalf("answer %s: %d %s", card.ID, status, out) } answers = append(answers, out) } // The Assistant answers the thread's question itself (team_reply). o.threadQuestion(request) if res := o.use("ol-reply", "team_reply", map[string]any{"request": request, "answer": "Web"}); res.IsError { t.Fatalf("team_reply %+v", res) } answer(outcome, wire.ChoiceMerge) m := o.dispatched(wire.SpecialistMerge, base, cand, 0) o.mergedStep("ol-m", m, merged) o.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) answer(o.assistantCard("the publish outcome", isPublishOutcome), wire.ChoicePublish) d := o.publishDispatch() if refused := o.lease(o.runner, "ol-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused != "" { t.Fatalf("start refused %q", refused) } o.publishReport("ol-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40}) if refused := o.lease(o.runner, "ol-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("ol-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}) o.assistantCard("published", func(c wire.AssistantCard) bool { return isPublishOutcome(c) && len(c.Links) == 1 && c.Links[0].URL == site }) k, err := o.client.Task(o.ctx, id) if err != nil || k.Branch == "" { t.Fatalf("task %+v %v", k, err) } status, _, snap := raw(t, "GET", o.inst.URL+"/api/v1/assistant/snapshot", o.client.Token, nil, "") if status != 200 { t.Fatalf("snapshot %d %s", status, snap) } n := o.rows("SELECT count(*) FROM chat_events WHERE person = ? AND lane = ?", Owner, wire.LaneAssistant) s, err := o.a.Open(o.ctx, 0) if err != nil { t.Fatal(err) } defer s.Close() var events []wire.Event assistEvents(t, s, "every Assistant event", &events, func(es []wire.Event) bool { return len(es) >= n }) if !slices.ContainsFunc(events, func(e wire.Event) bool { return e.Type == wire.EventCard && e.ID == outcome.ID }) { t.Fatal("no outcome card event") } check := noMachinery(t, id, []string{"amadan.net/oficina/sample", "oficina/sample", k.Branch, "/tasks/"}) decode := func(what string, b []byte) any { var v any if err := json.Unmarshal(b, &v); err != nil { t.Fatalf("%s: %v", what, err) } return v } eight := func(what string, card any) { cardKeys(t, what, card) } sv := decode("snapshot", snap) check("the snapshot", sv, false) cards := sv.(map[string]any)["cards"].([]any) // The go-ahead, the publish card and the job's. if len(cards) != 3 { t.Fatalf("snapshot cards %s", snap) } for _, c := range cards { eight("snapshot", c) } for _, e := range events { b, _ := json.Marshal(e) check("event "+e.Type, decode("event", b), false) if e.Type == wire.EventCard { eight("event", decode("card", e.Data)) } } for _, b := range answers { av := decode("answer", b) check("an answer", av, false) eight("answer", av.(map[string]any)["card"]) } // The preview was the one place the task's name could be. if !strings.Contains(string(snap), link) && !slices.ContainsFunc(events, func(e wire.Event) bool { return strings.Contains(string(e.Data), link) }) { t.Fatal("the preview was never shown") } } // noMachinery fails t on the first piece of the team's machinery a // decoded value from the Assistant lane carries (machineryIn). func noMachinery(t *testing.T, task string, forbidden []string) func(what string, v any, link bool) { return func(what string, v any, link bool) { t.Helper() if bad := machineryIn(task, forbidden, v, link); bad != "" { t.Fatalf("%s %s", what, bad) } } } var sha40 = regexp.MustCompile(`[0-9a-f]{40}`) // machineryIn is the first piece of the team's machinery a decoded value // from the Assistant lane carries, said plainly ("" for none): forbidden // text, a 40-hex SHA, the task id or one of the team's keys. A card // link's url may be a preview, whose host is the devbox app Equipo // names for the task (eq-, tmp-; ruling R9): only there the // task id is not refused; every other rule holds for it too. func machineryIn(task string, forbidden []string, v any, link bool) string { keys := []string{"task_id", "project_id", "preview_url", "site", "runner"} switch x := v.(type) { case string: for _, bad := range forbidden { if strings.Contains(x, bad) { return fmt.Sprintf("says %q: %q", bad, x) } } rest := x if link { rest = previewHostless(x, task) } if sha40.MatchString(x) || strings.Contains(rest, task) { return fmt.Sprintf("says the task or a SHA: %q", x) } case []any: for _, e := range x { if bad := machineryIn(task, forbidden, e, false); bad != "" { return bad } } case map[string]any: for key, e := range x { if slices.Contains(keys, key) { return fmt.Sprintf("has the key %q", key) } if links, ok := e.([]any); ok && key == "links" { for _, l := range links { for lk, lv := range l.(map[string]any) { if bad := machineryIn(task, forbidden, lv, lk == "url"); bad != "" { return bad } } } continue } if bad := machineryIn(task, forbidden, e, false); bad != "" { return bad } } } return "" } // previewHostless is a link's url without its host's first label when // that label is the devbox app named for the task (eq-, // tmp-): the one place the task id may be (R9). Any other url, or // one that does not parse as an absolute url, is as it is. func previewHostless(raw, task string) string { u, err := url.Parse(raw) if err != nil || u.Host == "" { return raw } label, after, _ := strings.Cut(u.Host, ".") if label != "eq-"+task && label != "tmp-"+task { return raw } u.Host = "." + after return u.String() } // TestContractAssistantLeakCheckLinks (ruling R20): the leak check lets // the task id through only as a preview host's first label (eq-, // tmp-); in a link's path or query, another host label, or the // Equipo job link, it is machinery. func TestContractAssistantLeakCheckLinks(t *testing.T) { task := "k_7c4qhxw2" link := func(url string) any { return map[string]any{"links": []any{map[string]any{"label": "Try it", "url": url}}} } for _, ok := range []string{"https://eq-" + task + ".docs-t1.example.ts.net/", "https://tmp-" + task + ".docs-t1.example.ts.net/", "https://site.bds.oncarlos.com/", "http://127.0.0.1:1/jobs/h_abc"} { if bad := machineryIn(task, nil, link(ok), false); bad != "" { t.Errorf("%s refused: %s", ok, bad) } } for _, leak := range []string{"https://eq-" + task + ".docs-t1.example.ts.net/" + task, "https://eq-" + task + ".docs-t1.example.ts.net/?t=" + task, "https://site.example.com/" + task, "https://x." + "eq-" + task + ".example.com/", "https://" + task + ".example.com/", "http://127.0.0.1:1/jobs/" + task, "https://eq-" + task + "x.example.com/", "not a url " + task} { if bad := machineryIn(task, nil, link(leak), false); bad == "" { t.Errorf("%s let through", leak) } } } // cardKeys checks a decoded Assistant card has exactly its keys: the // eight every card has, plus job on a go-ahead or Publish card that // belongs to a job, plus detail and started_at on a job card. func cardKeys(t *testing.T, what string, card any) { t.Helper() c := card.(map[string]any) want := []string{"id", "revision", "kind", "state", "question", "options", "links", "result"} switch c["kind"] { case wire.CardOutcome: want = append(want, "job") case wire.CardJob: want = append(want, "detail", "started_at") } got := []string{} for key := range c { got = append(got, key) } slices.Sort(got) slices.Sort(want) if !slices.Equal(got, want) { t.Fatalf("%s card keys %v, want %v", what, got, want) } } // TestContractOutcomeAudited: an outcome answer is audited as the person // in one row naming the card and the option's value, and nothing else. func TestContractOutcomeAudited(t *testing.T) { o := newTeamRig(t) o.ask("Can we fix a bug in Tito? Login is broken") _, cmd := o.handoff("oa1", "Login is broken", "") base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) o.in(cmd.TurnID, func() { o.websiteReady("oa", "Quick website", base, cand, false) }) card := o.assistantCard("the merge outcome", isMergeOutcome) before := o.rows("SELECT count(*) FROM audit_events") if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceWait, card.Revision); err != nil { t.Fatal(err) } if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.outcome' AND actor = ? AND record_id = ?", Owner, card.ID+":"+wire.ChoiceWait); n != 1 { t.Fatalf("%d outcome audits", n) } if after := o.rows("SELECT count(*) FROM audit_events"); after != before+1 { t.Fatalf("%d audit rows for one answer", after-before) } // A refused answer is not audited. if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision); Status(err) != http.StatusConflict { t.Fatalf("a second answer %v", err) } time.Sleep(20 * time.Millisecond) if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.outcome'"); n != 1 { t.Fatalf("%d outcome audits after a refusal", n) } } // mergedWebsite hands a quick website to the team, brings its devbox // preview up and merges it from the merge outcome card: Equipo asks to // publish it when sites. It returns the task, its preview link, the // merged SHA and the forget_task frame the task's end sent. func (o *teamRig) mergedWebsite(key string, sites bool) (id, link, merged string, forget *wire.ForgetTaskCommand) { o.t.Helper() o.sitesOn(wire.ProtocolCurrent, sites) o.ask("Build me a quick website") _, cmd := o.handoff(key+"1", "Build me a quick website", "") base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) merged = strings.Repeat("e", 40) o.in(cmd.TurnID, func() { id, _ = o.websiteReady(key, "Quick website", base, cand, true) }) pv := o.previewDispatch(cand) o.built(key+"-pv-built", pv, digestA) link = "https://eq-" + id + ".docs-t1.example.ts.net/" o.previewDone(key+"-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, Outcome: wire.PreviewDeployed}) ahead := o.assistantCard("the merge outcome", func(c wire.AssistantCard) bool { return isMergeOutcome(c) && len(c.Links) == 1 }) if _, err := o.a.Answer(o.ctx, ahead.ID, wire.ChoiceMerge, ahead.Revision); err != nil { o.t.Fatal(err) } o.mergedStep(key+"-m", o.dispatched(wire.SpecialistMerge, base, cand, 0), merged) o.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) if forget = o.forgetFrame(id, 5*time.Second); forget == nil { o.t.Fatal("no forget_task at the merge") } return id, link, merged, forget } // forgetFrame is the next forget_task for the task, acked, waiting up to // wait for it (nil when none came); every other frame is held. func (o *teamRig) forgetFrame(task string, wait time.Duration) *wire.ForgetTaskCommand { o.t.Helper() deadline := time.Now().Add(wait) for { for i, h := range o.held { if f, ok := h.body.(*wire.ForgetTaskCommand); ok && f.TaskID == task { 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 f } } if time.Now().After(deadline) { return nil } if refused := o.lease(o.runner, "fg-poll-"+itoa(int(time.Now().UnixNano()%1e9)), wire.LeaseCheck{}); refused != "" { o.t.Fatalf("poll lease refused %q", refused) } } } // publishOptions are a publish outcome card's options. func publishOptions() []wire.CardOption { return []wire.CardOption{{Value: wire.ChoicePublish, Label: equipo.RunnerCopy("assistant.outcome.publish_option")}, {Value: wire.ChoiceNotNow, Label: equipo.RunnerCopy("assistant.outcome.publish_not_now")}} } // previewOf is the card's preview link ("" when it shows none). func previewOf(c wire.AssistantCard) string { for _, l := range c.Links { if l.Label == equipo.RunnerCopy("assistant.outcome.preview") { return l.URL } } return "" } // TestContractOutcomePublish: a merged website on a hand-off's task // raises the publish outcome card, "Your site is ready. Publish it?" with // its preview. Publish there places the publish step as the publish // card's Publish does: the person's decision, for the project's app and // the merged SHA. Once the step reports it published, the card says so // with the site's address, and the person hears of it in a team_update // turn. Not now ends the card with no step. func TestContractOutcomePublish(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) id, link, merged, _ := o.mergedWebsite("op", true) card := o.assistantCard("the publish outcome", isPublishOutcome) if card.State != wire.CardOpen || !slices.Equal(card.Options, publishOptions()) || !slices.Equal(card.Links, []wire.CardLink{{Label: equipo.RunnerCopy("assistant.outcome.preview"), URL: link}}) || card.Result != "" { t.Fatalf("card %+v", card) } team, _ := o.publishCard(id) k, err := o.client.Task(o.ctx, id) if err != nil || k.Site == nil || team.State != wire.CardOpen { t.Fatalf("publish card %+v, site %+v %v", team, k.Site, err) } told, notes, _ := o.updates() ans, err := o.a.Answer(o.ctx, card.ID, wire.ChoicePublish, card.Revision) if err != nil || ans.Card.State != wire.CardAnswered || ans.Card.Result != equipo.RunnerCopy("assistant.outcome.publish_publishing") { t.Fatalf("answer %+v %v", ans, err) } if after, _ := o.publishCard(id); after.ID != team.ID || after.State != wire.CardAnswered || after.Choice != wire.ChoicePublish { t.Fatalf("publish card after %+v", after) } d := o.publishDispatch() if d.CandidateSHA != merged || d.Person != Owner || d.Publish == nil || d.Publish.App != k.Site.App { t.Fatalf("publish dispatch %+v %+v", d, d.Publish) } if n := o.rows("SELECT count(*) FROM chat_steps WHERE id = ? AND specialist = ? AND decided_by = ? AND candidate_sha = ?", d.StepID, wire.SpecialistPublish, "person:"+Owner, merged); n != 1 { t.Fatal("the publish step is not the person's decision on the merged SHA") } if refused := o.lease(o.runner, "op-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused != "" { t.Fatalf("start refused %q", refused) } o.publishReport("op-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40}) // Publishing moves on its own: the Assistant hears nothing until it // is live. if ids, after, _ := o.updates(); !slices.Equal(ids, told) || !slices.Equal(after, notes) { t.Fatalf("updates while publishing %v %q, before %v %q", ids, after, told, notes) } if refused := o.lease(o.runner, "op-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://" + k.Site.App + ".bds.oncarlos.com/" o.publishReport("op-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: k.Site.App, URL: site, Version: "s-eeeeeeeeeeee-x-1", Digest: digestA, Outcome: wire.PublishPublished, DeployHeld: true}) done := o.assistantCard("published", func(c wire.AssistantCard) bool { return c.ID == card.ID && c.Result == equipo.RunnerCopy("assistant.outcome.publish_published") }) if done.State != wire.CardAnswered || !slices.Equal(done.Links, []wire.CardLink{{Label: equipo.RunnerCopy("assistant.outcome.publish_site"), URL: site}}) { t.Fatalf("published card %+v", done) } // Done, though the project's ships question is still open: that is // not the job's stop. o.until("a team_update with the address", func() bool { _, notes, _ := o.updates() return len(notes) > 0 && strings.Contains(notes[len(notes)-1], site) && strings.Contains(notes[len(notes)-1], "\nIt is done. Tell the person in one short line") }) // Not now: answered, and nothing published. n := newTeamRigAt(t, wire.ProtocolCurrent) id, _, _, _ = n.mergedWebsite("on", true) card = n.assistantCard("the publish outcome", isPublishOutcome) ans, err = n.a.Answer(n.ctx, card.ID, wire.ChoiceNotNow, card.Revision) if err != nil || ans.Card.State != wire.CardAnswered || ans.Card.Result != equipo.RunnerCopy("assistant.outcome.publish_declined") || len(ans.Card.Links) != 0 { t.Fatalf("not now %+v %v", ans, err) } if after, _ := n.publishCard(id); after.State != wire.CardAnswered || after.Choice != wire.ChoiceNotNow { t.Fatalf("publish card after not now %+v", after) } n.syncNow("on-sync") if c := n.rows("SELECT count(*) FROM chat_steps WHERE task_id = ? AND specialist = ?", id, wire.SpecialistPublish); c != 0 || n.audits("publish.declined") != 1 { t.Fatal("not now placed a publish step, or was not audited") } } // TestContractPreviewHeldUntilPublishAnswer: a merged website whose // Publish is asked keeps its devbox preview up: the forget_task at its // merge keeps the preview, and the cards show it though the task is // done. Either answer releases it with a second forget_task (the // sessions still kept), after which no card shows it. A publish asked // again after a failed one shows none; a merged task with nothing to // publish keeps nothing, in one forget_task as before. func TestContractPreviewHeldUntilPublishAnswer(t *testing.T) { for _, choice := range []string{wire.ChoicePublish, wire.ChoiceNotNow} { o := newTeamRigAt(t, wire.ProtocolCurrent) id, link, _, forget := o.mergedWebsite("ph"+choice[:1], true) if !forget.KeepPreview || forget.KeepUntil == nil { t.Fatalf("%s: the merge's forget_task %+v", choice, forget) } card := o.assistantCard("the publish outcome", isPublishOutcome) if previewOf(card) != link { t.Fatalf("%s: the publish outcome shows no preview: %+v", choice, card) } // The merge card itself is in the job's thread, read as the // thread's page reads it. request := o.requestOf(id) ahead := o.assistantCard("the merge outcome", isMergeOutcome) if previewOf(ahead) != link || o.jobCard(request, wire.CardMerge, id).PreviewURL != link { t.Fatalf("%s: the merge cards lost the held preview: %+v", choice, ahead) } if _, err := o.a.Answer(o.ctx, card.ID, choice, card.Revision); err != nil { t.Fatal(err) } release := o.forgetFrame(id, 5*time.Second) if release == nil || release.KeepPreview || release.KeepUntil == nil || release.Person != Owner || time.Until(*release.KeepUntil) < wire.KeepMergedSessions-time.Hour { t.Fatalf("%s: the releasing forget_task %+v", choice, release) } for _, c := range o.assistantCards() { if strings.Contains(fmt.Sprint(c.Links), link) { t.Fatalf("%s: a card shows the released preview: %+v", choice, c) } } if c := o.jobCard(request, wire.CardMerge, id); c.ID == "" || c.PreviewURL != "" { t.Fatalf("%s: the merge card shows the released preview: %+v", choice, c) } if choice != wire.ChoicePublish { continue } // The publish fails: asked again, with no preview, and nothing more // to release. d := o.publishDispatch() o.publishReport("ph-failed", d, wire.StepFailed, nil) again := o.assistantCard("asked again", func(c wire.AssistantCard) bool { return isPublishOutcome(c) && c.ID != card.ID && c.State == wire.CardOpen }) if len(again.Links) != 0 { t.Fatalf("asked again with a link %+v", again) } if f := o.forgetFrame(id, time.Second); f != nil { t.Fatalf("a forget_task after the failure %+v", f) } } o := newTeamRigAt(t, wire.ProtocolCurrent) id, _, _, forget := o.mergedWebsite("pn", false) if forget.KeepPreview || forget.KeepUntil == nil { t.Fatalf("the forget_task with nothing to publish %+v", forget) } if f := o.forgetFrame(id, time.Second); f != nil { t.Fatalf("a second forget_task %+v", f) } } // TestContractPublishNeedsOwnerAnswer: the gate is the publish card's // own. A publish step placed by the person's Publish on the outcome card // starts; the same step standing on anything but the person's answer is // refused by authorizePublish, the outcome card there all along: decided // by anyone else, or decided by the person with no answered Publish on // the task's publish card for the merged commit behind it. func TestContractPublishNeedsOwnerAnswer(t *testing.T) { o := newTeamRigAt(t, wire.ProtocolCurrent) id, _, merged, _ := o.mergedWebsite("pg", true) 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() for _, by := range []string{"", "assistant:" + Owner, "policy", "person:mate@example.com"} { if _, err := o.inst.DB.Writer().Exec("UPDATE chat_steps SET decided_by = ? WHERE id = ?", by, d.StepID); err != nil { t.Fatal(err) } if refused := o.lease(o.runner, "pg-start-"+itoa(len(by)), wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused == "" { t.Fatalf("a publish standing on %q started", by) } } if _, err := o.inst.DB.Writer().Exec("UPDATE chat_steps SET decided_by = ? WHERE id = ?", "person:"+Owner, d.StepID); err != nil { t.Fatal(err) } team, _ := o.publishCard(id) for i, c := range []struct{ state, choice, asked string }{ {wire.CardOpen, "", merged}, {wire.CardAnswered, wire.ChoiceNotNow, merged}, {wire.CardResolved, "", merged}, {wire.CardAnswered, wire.ChoicePublish, strings.Repeat("9", 40)}, } { if _, err := o.inst.DB.Writer().Exec("UPDATE chat_cards SET state = ?, choice = ? WHERE id = ?", c.state, c.choice, team.ID); err != nil { t.Fatal(err) } if _, err := o.inst.DB.Writer().Exec("UPDATE chat_tasks SET publish_asked = ? WHERE id = ?", c.asked, id); err != nil { t.Fatal(err) } if refused := o.lease(o.runner, "pg-card-"+itoa(i), wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused == "" { t.Fatalf("a person's publish started with its card %+v", c) } } if _, err := o.inst.DB.Writer().Exec("UPDATE chat_cards SET state = ?, choice = ? WHERE id = ?", wire.CardAnswered, wire.ChoicePublish, team.ID); err != nil { t.Fatal(err) } if _, err := o.inst.DB.Writer().Exec("UPDATE chat_tasks SET publish_asked = ? WHERE id = ?", merged, id); err != nil { t.Fatal(err) } if refused := o.lease(o.runner, "pg-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused != "" { t.Fatalf("the person's publish refused %q", refused) } // The task has no publish card at all: the person's decision stands on // nothing, and the outcome card is still there. if _, err := o.inst.DB.Writer().Exec("DELETE FROM chat_cards WHERE id = ?", team.ID); err != nil { t.Fatal(err) } if n := o.rows("SELECT count(*) FROM chat_cards WHERE task_id = ? AND kind = ?", id, wire.CardPublish); n != 0 { t.Fatalf("%d publish cards left", n) } if n := o.rows("SELECT count(*) FROM chat_steps WHERE id = ? AND decided_by = ?", d.StepID, "person:"+Owner); n != 1 { t.Fatal("the step lost its decision") } if n := o.rows("SELECT count(*) FROM chat_cards WHERE id = ? AND lane = ?", card.ID, wire.LaneAssistant); n != 1 { t.Fatal("no outcome card") } if refused := o.lease(o.runner, "pg-no-card", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused == "" { t.Fatal("a person's publish started with no publish card behind it") } } // TestContractPreviewNotHeldBelow19: a runner below wire.ProtocolAssistant // cannot keep a preview past its task (Encode drops KeepPreview, and it // takes the link down), so a merged website it previewed holds nothing: // the forget_task asks for no retention and no card shows the link once // the task is done. Publish is not asked of it (places need protocol 31): // the task says why instead. func TestContractPreviewNotHeldBelow19(t *testing.T) { r := newToolRigAt(t, wire.ProtocolAssistant-1) r.sitesOn(wire.ProtocolAssistant-1, true) base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) id, _ := r.websiteReady("p18", "Quick website", base, cand, true) if pv := r.previewDispatch(cand); pv != nil { t.Fatal("old runner received a preview without injection defences") } r.mergeFromCard("p18-m", id, base, cand, strings.Repeat("e", 40)) if _, ok := r.publishCard(id); ok || r.audits("publish.not_offered") != 1 { t.Fatal("Publish asked of a protocol 18 runner, or not said why") } if n := r.rows("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", wire.FrameForgetTask, `%"keep_preview":true%`); n != 0 { t.Fatalf("%d forget_task commands keep the preview on a protocol 18 runner", n) } if r.cardOf(id).PreviewURL != "" { t.Fatal("the merge card shows a preview the runner took down") } }