| 1 | package thintest |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "net/http" |
| 9 | "net/url" |
| 10 | "regexp" |
| 11 | "slices" |
| 12 | "strings" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/equipo" |
| 17 | "amadan.net/oficina/equipo/internal/wire" |
| 18 | ) |
| 19 | |
| 20 | // Outcome cards (spec §5, Cards): when a hand-off's task or turn raises a |
| 21 | // team card, the Assistant lane gets a card that points at it, in its |
| 22 | // own plain words, answered through the team card's own path. |
| 23 | |
| 24 | // assistantCards are the Assistant snapshot's cards but its job cards |
| 25 | // (the job card tests read those: jobOf). |
| 26 | func (o *teamRig) assistantCards() []wire.AssistantCard { |
| 27 | o.t.Helper() |
| 28 | snap, err := o.a.Snapshot(o.ctx) |
| 29 | if err != nil { |
| 30 | o.t.Fatal(err) |
| 31 | } |
| 32 | return slices.DeleteFunc(snap.Cards, func(c wire.AssistantCard) bool { return c.Kind == wire.CardJob }) |
| 33 | } |
| 34 | |
| 35 | // assistantCard waits for the Assistant card that matches. |
| 36 | func (o *teamRig) assistantCard(what string, match func(wire.AssistantCard) bool) wire.AssistantCard { |
| 37 | o.t.Helper() |
| 38 | var out wire.AssistantCard |
| 39 | o.until(what, func() bool { |
| 40 | for _, c := range o.assistantCards() { |
| 41 | if match(c) { |
| 42 | out = c |
| 43 | return true |
| 44 | } |
| 45 | } |
| 46 | return false |
| 47 | }) |
| 48 | return out |
| 49 | } |
| 50 | |
| 51 | // teamCard is the person's Coordinator card of kind for the turn or task. |
| 52 | func (o *teamRig) teamCard(kind, turn, task string) wire.Card { |
| 53 | o.t.Helper() |
| 54 | snap, err := o.client.Snapshot(o.ctx) |
| 55 | if err != nil { |
| 56 | o.t.Fatal(err) |
| 57 | } |
| 58 | for _, c := range snap.Cards { |
| 59 | if c.Kind == kind && (turn == "" || c.TurnID == turn) && (task == "" || c.TaskID == task) { |
| 60 | return c |
| 61 | } |
| 62 | } |
| 63 | return wire.Card{} |
| 64 | } |
| 65 | |
| 66 | // threadCard is the card of kind raised in the turn, wherever its lane: |
| 67 | // a job thread's never shows in the person's snapshot. |
| 68 | func (o *teamRig) threadCard(kind, turn string) wire.Card { |
| 69 | o.t.Helper() |
| 70 | var c wire.Card |
| 71 | 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) |
| 72 | if err != nil && err != sql.ErrNoRows { |
| 73 | o.t.Fatal(err) |
| 74 | } |
| 75 | return c |
| 76 | } |
| 77 | |
| 78 | // coordinatorCards are the person's Coordinator cards of kind on the |
| 79 | // task, oldest first, as stored, wherever their lane: their own |
| 80 | // conversation or a job thread, which never shows in their snapshot. |
| 81 | func (o *teamRig) coordinatorCards(kind, task string) []wire.Card { |
| 82 | o.t.Helper() |
| 83 | 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) |
| 84 | if err != nil { |
| 85 | o.t.Fatal(err) |
| 86 | } |
| 87 | defer rows.Close() |
| 88 | var out []wire.Card |
| 89 | for rows.Next() { |
| 90 | var c wire.Card |
| 91 | if err := rows.Scan(&c.ID, &c.Revision, &c.Kind, &c.State, &c.TurnID, &c.TaskID, &c.Question, &c.Choice); err != nil { |
| 92 | o.t.Fatal(err) |
| 93 | } |
| 94 | out = append(out, c) |
| 95 | } |
| 96 | if err := rows.Err(); err != nil { |
| 97 | o.t.Fatal(err) |
| 98 | } |
| 99 | return out |
| 100 | } |
| 101 | |
| 102 | // cardOf is the task's merge card wherever its lane (coordinatorCards). |
| 103 | func (o *teamRig) cardOf(id string) wire.Card { |
| 104 | o.t.Helper() |
| 105 | if cards := o.coordinatorCards(wire.CardMerge, id); len(cards) > 0 { |
| 106 | return cards[0] |
| 107 | } |
| 108 | return wire.Card{} |
| 109 | } |
| 110 | |
| 111 | // publishCard is the task's newest publish card wherever its lane. |
| 112 | func (o *teamRig) publishCard(id string) (wire.Card, bool) { |
| 113 | o.t.Helper() |
| 114 | cards := o.coordinatorCards(wire.CardPublish, id) |
| 115 | if len(cards) == 0 { |
| 116 | return wire.Card{}, false |
| 117 | } |
| 118 | return cards[len(cards)-1], true |
| 119 | } |
| 120 | |
| 121 | // websiteReady is toolRig's, its merge card found wherever its lane. |
| 122 | func (o *teamRig) websiteReady(key, title, base, cand string, has bool) (string, wire.Card) { |
| 123 | o.t.Helper() |
| 124 | id := o.websiteJudged(key, title, base, cand, has) |
| 125 | var card wire.Card |
| 126 | o.until("the merge card", func() bool { card = o.cardOf(id); return card.ID != "" }) |
| 127 | return id, card |
| 128 | } |
| 129 | |
| 130 | // mergeFromCard is toolRig's, its merge card found wherever its lane. |
| 131 | func (o *teamRig) mergeFromCard(key, id, base, cand, sha string) { |
| 132 | o.t.Helper() |
| 133 | card := o.cardOf(id) |
| 134 | if _, err := o.client.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil { |
| 135 | o.t.Fatalf("merge %v", err) |
| 136 | } |
| 137 | o.mergedStep(key, o.dispatched(wire.SpecialistMerge, base, cand, 0), sha) |
| 138 | o.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) |
| 139 | } |
| 140 | |
| 141 | // requestOf is the hand-off that follows the task. |
| 142 | func (o *teamRig) requestOf(task string) string { |
| 143 | o.t.Helper() |
| 144 | var request string |
| 145 | if err := o.inst.DB.Writer().QueryRow("SELECT handoff_id FROM chat_handoff_tasks WHERE task_id = ?", task).Scan(&request); err != nil { |
| 146 | o.t.Fatal(err) |
| 147 | } |
| 148 | return request |
| 149 | } |
| 150 | |
| 151 | // laneOfCard is the card's lane. |
| 152 | func (o *teamRig) laneOfCard(id string) string { |
| 153 | o.t.Helper() |
| 154 | var lane string |
| 155 | if err := o.inst.DB.Writer().QueryRow("SELECT coalesce(lane, '') FROM chat_cards WHERE id = ?", id).Scan(&lane); err != nil { |
| 156 | o.t.Fatal(err) |
| 157 | } |
| 158 | return lane |
| 159 | } |
| 160 | |
| 161 | // conflictOf is a 409's AssistantConflict. |
| 162 | func conflictOf(t *testing.T, err error) wire.AssistantConflict { |
| 163 | t.Helper() |
| 164 | var out wire.AssistantConflict |
| 165 | s, ok := err.(*ErrStatus) |
| 166 | if !ok || s.Status != http.StatusConflict || wire.Strict(s.Body, &out) != nil { |
| 167 | t.Fatalf("not a card conflict: %v", err) |
| 168 | } |
| 169 | return out |
| 170 | } |
| 171 | |
| 172 | // storeLink writes a preview link into an Assistant card's stored links, |
| 173 | // as a card raised before previews were read live would hold it. |
| 174 | func (o *teamRig) storeLink(card, url string) { |
| 175 | o.t.Helper() |
| 176 | raw, _ := json.Marshal([]wire.CardLink{{Label: equipo.RunnerCopy("assistant.outcome.preview"), URL: url}}) |
| 177 | if _, err := o.inst.DB.Writer().Exec("UPDATE chat_cards SET links = ? WHERE id = ?", string(raw), card); err != nil { |
| 178 | o.t.Fatal(err) |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | // isMergeOutcome: the outcome card of a merge card (not one that sends |
| 183 | // the person to Equipo). |
| 184 | func isMergeOutcome(c wire.AssistantCard) bool { |
| 185 | return c.Kind == wire.CardOutcome && c.Question != equipo.RunnerCopy("assistant.outcome.needs_you") && !isPublishOutcome(c) |
| 186 | } |
| 187 | |
| 188 | // isPublishOutcome: the outcome card of a publish card. |
| 189 | func isPublishOutcome(c wire.AssistantCard) bool { |
| 190 | return c.Kind == wire.CardOutcome && c.Question == equipo.RunnerCopy("assistant.outcome.publish_question") |
| 191 | } |
| 192 | |
| 193 | // mergeQuestion is the outcome card's question for a merge card asked |
| 194 | // because of reason. |
| 195 | func mergeQuestion(reason string) string { |
| 196 | return fmt.Sprintf(equipo.RunnerCopy("assistant.outcome.merge"), equipo.RunnerCopy("assistant.outcome.reason."+reason)) |
| 197 | } |
| 198 | |
| 199 | // jobLine is the note's first line for a job (noteJob), and its second, |
| 200 | // the person's words (noteAsked). |
| 201 | func jobLine(title, request, words string) string { |
| 202 | return fmt.Sprintf("Job %q (request %s).\nThe person asked for it in these words: %q\n", title, request, words) |
| 203 | } |
| 204 | |
| 205 | // noteFor waits for the newest team_update note that contains want. |
| 206 | func (o *teamRig) noteFor(what, want string) string { |
| 207 | o.t.Helper() |
| 208 | var note string |
| 209 | o.until(what, func() bool { |
| 210 | _, notes, _ := o.updates() |
| 211 | if len(notes) > 0 { |
| 212 | note = notes[len(notes)-1] |
| 213 | } |
| 214 | return strings.Contains(note, want) |
| 215 | }) |
| 216 | return note |
| 217 | } |
| 218 | |
| 219 | // TestContractOutcomeQuestionNotMirrored: the Coordinator's ask_person |
| 220 | // in a job's thread raises no card in the Assistant lane: the Assistant |
| 221 | // hears of it in one team_update turn, whose note names the job and its |
| 222 | // request, quotes the person's words, the question and its options, and |
| 223 | // says how to answer it (team_reply). The note is the instance's: the |
| 224 | // frame carries no words of the person's. |
| 225 | func TestContractOutcomeQuestionNotMirrored(t *testing.T) { |
| 226 | o := newTeamRig(t) |
| 227 | o.ask("Can we fix a bug in Tito? Login is broken") |
| 228 | request, cmd := o.handoff("oq1", "Login is broken", "") |
| 229 | o.in(cmd.TurnID, func() { |
| 230 | if res := o.call("oq-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { |
| 231 | t.Fatalf("ask %+v", res) |
| 232 | } |
| 233 | }) |
| 234 | o.until("the update", func() bool { ids, _, _ := o.updates(); return len(ids) == 1 }) |
| 235 | team := o.threadCard(wire.CardQuestion, cmd.TurnID) |
| 236 | if team.ID == "" || team.State != wire.CardOpen || o.teamCard(wire.CardQuestion, cmd.TurnID, "").ID != "" { |
| 237 | t.Fatalf("the thread's question %+v", team) |
| 238 | } |
| 239 | if cards := o.assistantCards(); len(cards) != 0 { |
| 240 | t.Fatalf("assistant cards %+v", cards) |
| 241 | } |
| 242 | o.reply(cmd.TurnID) |
| 243 | o.reply(o.turn) |
| 244 | u := o.message(wire.LaneAssistant) |
| 245 | if u.Kind != wire.TurnTeamUpdate || len(u.PersonText) != 0 { |
| 246 | t.Fatalf("update frame %+v", u) |
| 247 | } |
| 248 | 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"} { |
| 249 | if !strings.Contains(u.Text, want) { |
| 250 | t.Fatalf("the note lacks %q: %s", want, u.Text) |
| 251 | } |
| 252 | } |
| 253 | if ids, _, _ := o.updates(); len(ids) != 1 { |
| 254 | t.Fatalf("updates %v", ids) |
| 255 | } |
| 256 | if cards := o.assistantCards(); len(cards) != 0 { |
| 257 | t.Fatalf("assistant cards after the turns %+v", cards) |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | // TestContractOutcomeLegacyQuestionTold: a legacy hand-off's question, |
| 262 | // raised on its turn in the person's own conversation, raises no |
| 263 | // Assistant card either: the Assistant is told in a team_update note. |
| 264 | func TestContractOutcomeLegacyQuestionTold(t *testing.T) { |
| 265 | o := newTeamRig(t) |
| 266 | o.ask("Can we fix a bug in Tito? Login is broken") |
| 267 | request, turn := o.legacyHandoff("lq", "Login is broken") |
| 268 | o.in(turn, func() { |
| 269 | if res := o.call("lq-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { |
| 270 | t.Fatalf("ask %+v", res) |
| 271 | } |
| 272 | }) |
| 273 | note := o.noteFor("the legacy question's note", `The work on it has a question: "Which login page?"`) |
| 274 | if !strings.Contains(note, "(request "+request+")") || !strings.Contains(note, `"Web", "App"`) { |
| 275 | t.Fatalf("note %q", note) |
| 276 | } |
| 277 | if o.teamCard(wire.CardQuestion, turn, "").ID == "" { |
| 278 | t.Fatal("the legacy question left their conversation") |
| 279 | } |
| 280 | if cards := o.assistantCards(); len(cards) != 0 { |
| 281 | t.Fatalf("assistant cards %+v", cards) |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | // TestContractOutcomeLegacyMirrorStillFollows: an Assistant question |
| 286 | // card mirrored before this release (as slice 1 raised it, pointing at |
| 287 | // its team card) still follows that card: answered in Equipo, it is |
| 288 | // answered with the same choice. |
| 289 | func TestContractOutcomeLegacyMirrorStillFollows(t *testing.T) { |
| 290 | o := newTeamRig(t) |
| 291 | o.ask("Can we fix a bug in Tito? Login is broken") |
| 292 | _, turn := o.legacyHandoff("lm", "Login is broken") |
| 293 | o.in(turn, func() { |
| 294 | if res := o.call("lm-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { |
| 295 | t.Fatalf("ask %+v", res) |
| 296 | } |
| 297 | }) |
| 298 | o.reply(turn) |
| 299 | var team wire.Card |
| 300 | o.wait("the question in their conversation", func(c *Conversation) bool { |
| 301 | for _, k := range c.Cards { |
| 302 | if k.Kind == wire.CardQuestion && k.TurnID == turn { |
| 303 | team = k |
| 304 | } |
| 305 | } |
| 306 | return team.ID != "" |
| 307 | }) |
| 308 | options := `[{"value":"Web","label":"Web"},{"value":"App","label":"App"}]` |
| 309 | 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 { |
| 310 | t.Fatal(err) |
| 311 | } |
| 312 | if _, err := o.client.Answer(o.ctx, team.ID, "App", team.Revision); err != nil { |
| 313 | t.Fatal(err) |
| 314 | } |
| 315 | got := o.assistantCard("the old mirror answered", func(c wire.AssistantCard) bool { return c.ID == "c_slice1" && c.State == wire.CardAnswered }) |
| 316 | if got.Result != "App" || got.Revision <= 1 { |
| 317 | t.Fatalf("the old mirror %+v", got) |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | // TestContractOutcomeMerge: a merge card on a hand-off's task raises an |
| 322 | // outcome card, in plain words with the preview once it is up; Merge on |
| 323 | // it at its revision merges as the card's Merge does: the person's |
| 324 | // decision, bound to the SHA the team card asked about. |
| 325 | func TestContractOutcomeMerge(t *testing.T) { |
| 326 | o := newTeamRigAt(t, wire.ProtocolCurrent) |
| 327 | o.sitesOn(wire.ProtocolCurrent, false) |
| 328 | o.ask("Can we fix a bug in Tito? Login is broken") |
| 329 | _, cmd := o.handoff("om1", "Login is broken", "") |
| 330 | base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| 331 | var id string |
| 332 | o.in(cmd.TurnID, func() { id, _ = o.websiteReady("om", "Quick website", base, cand, true) }) |
| 333 | team := o.cardOf(id) |
| 334 | card := o.assistantCard("the merge outcome", isMergeOutcome) |
| 335 | want := []wire.CardOption{{Value: wire.ChoiceMerge, Label: equipo.RunnerCopy("assistant.outcome.option.merge")}, {Value: wire.ChoiceWait, Label: equipo.RunnerCopy("assistant.outcome.option.wait")}} |
| 336 | if card.State != wire.CardOpen || card.Question != mergeQuestion("environment_reason") || !slices.Equal(card.Options, want) || card.Links == nil || len(card.Links) != 0 { |
| 337 | t.Fatalf("card %+v", card) |
| 338 | } |
| 339 | if strings.Contains(card.Question, team.Question) || strings.Contains(card.Question, "Quick website") { |
| 340 | t.Fatalf("the outcome quotes the team card: %q", card.Question) |
| 341 | } |
| 342 | pv := o.previewDispatch(cand) |
| 343 | o.built("om-pv-built", pv, digestA) |
| 344 | link := "https://eq-" + id + ".docs-t1.example.ts.net/" |
| 345 | o.previewDone("om-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, Outcome: wire.PreviewDeployed}) |
| 346 | shown := o.assistantCard("the preview", func(c wire.AssistantCard) bool { return c.ID == card.ID && len(c.Links) == 1 }) |
| 347 | if shown.Links[0] != (wire.CardLink{Label: equipo.RunnerCopy("assistant.outcome.preview"), URL: link}) || shown.Revision <= card.Revision || shown.State != wire.CardOpen { |
| 348 | t.Fatalf("with the preview %+v", shown) |
| 349 | } |
| 350 | // The card changed since it was first read: an answer to that is |
| 351 | // stale, though the team card would take a Merge now. |
| 352 | _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision) |
| 353 | if c := conflictOf(t, err); c.Code != "card_stale" || c.Card.Revision != shown.Revision || len(c.Card.Links) != 1 { |
| 354 | t.Fatalf("an answer from before the preview %+v", c) |
| 355 | } |
| 356 | if n := o.rows("SELECT count(*) FROM chat_steps WHERE task_id = ? AND specialist = ?", id, wire.SpecialistMerge); n != 0 { |
| 357 | t.Fatal("merged on a stale answer") |
| 358 | } |
| 359 | ans, err := o.a.Answer(o.ctx, shown.ID, wire.ChoiceMerge, shown.Revision) |
| 360 | if err != nil || ans.Card.State != wire.CardAnswered || ans.Card.Result != equipo.RunnerCopy("assistant.outcome.option.merge") { |
| 361 | t.Fatalf("answer %+v %v", ans, err) |
| 362 | } |
| 363 | m := o.dispatched(wire.SpecialistMerge, base, cand, 0) |
| 364 | if n := o.rows("SELECT count(*) FROM chat_steps WHERE id = ? AND decided_by = ? AND candidate_sha = ?", m.StepID, "person:"+Owner, cand); n != 1 { |
| 365 | t.Fatal("the merge step is not the person's decision on the asked SHA") |
| 366 | } |
| 367 | if after := o.cardOf(id); after.ID != team.ID || after.State != wire.CardAnswered || after.Choice != wire.ChoiceMerge { |
| 368 | t.Fatalf("team card %+v", after) |
| 369 | } |
| 370 | answered := o.assistantCard("answered", func(c wire.AssistantCard) bool { return c.ID == card.ID }) |
| 371 | if answered.State != wire.CardAnswered || len(answered.Links) != 1 { |
| 372 | t.Fatalf("outcome card %+v", answered) |
| 373 | } |
| 374 | // Merged, the task is done and its devbox preview gone: the answered |
| 375 | // card stops showing it, and says so as a change. |
| 376 | // A preview stored on the card (as before it was read live) is |
| 377 | // never shown from there. |
| 378 | o.storeLink(card.ID, link) |
| 379 | o.mergedStep("om-m", m, strings.Repeat("e", 40)) |
| 380 | o.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) |
| 381 | 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 { |
| 382 | t.Fatalf("after the merge %+v (answered %+v)", done, answered) |
| 383 | } |
| 384 | // Raised once for the merge card, however often it changed; the |
| 385 | // ships question raises none (the Assistant is told). |
| 386 | if cards := o.assistantCards(); len(cards) != 1 { |
| 387 | t.Fatalf("assistant cards %+v", cards) |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | // TestContractOutcomePreviewExpires: a preview that expires is no longer |
| 392 | // offered, on a card already answered too. |
| 393 | func TestContractOutcomePreviewExpires(t *testing.T) { |
| 394 | o := newTeamRigAt(t, wire.ProtocolCurrent) |
| 395 | o.sitesOn(wire.ProtocolCurrent, false) |
| 396 | o.ask("Can we fix a bug in Tito? Login is broken") |
| 397 | _, cmd := o.handoff("ox1", "Login is broken", "") |
| 398 | base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| 399 | var id string |
| 400 | o.in(cmd.TurnID, func() { id, _ = o.websiteReady("ox", "Quick website", base, cand, true) }) |
| 401 | pv := o.previewDispatch(cand) |
| 402 | o.built("ox-pv-built", pv, digestA) |
| 403 | expires := time.Now().Add(time.Hour) |
| 404 | link := "https://eq-" + id + ".docs-t1.example.ts.net/" |
| 405 | o.previewDone("ox-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, ExpiresAt: &expires, Outcome: wire.PreviewDeployed}) |
| 406 | card := o.assistantCard("the preview", func(c wire.AssistantCard) bool { return isMergeOutcome(c) && len(c.Links) == 1 }) |
| 407 | if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceWait, card.Revision); err != nil { |
| 408 | t.Fatal(err) |
| 409 | } |
| 410 | o.storeLink(card.ID, link) |
| 411 | o.inst.Store.Chat().SetClock(func() time.Time { return time.Now().UTC().Add(2 * time.Hour) }) |
| 412 | t.Cleanup(func() { o.inst.Store.Chat().SetClock(func() time.Time { return time.Now().UTC() }) }) |
| 413 | if got := o.assistantCard("expired", func(c wire.AssistantCard) bool { return c.ID == card.ID }); len(got.Links) != 0 || got.State != wire.CardAnswered { |
| 414 | t.Fatalf("after the preview expired %+v", got) |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | // TestContractOutcomeShips: the ships question belongs to a project, not |
| 419 | // a task, and is raised in the lane of the work that asked it: for a |
| 420 | // job's work, in its thread. It raises no Assistant card; the go-ahead |
| 421 | // raised beside it is what the Assistant is told of. |
| 422 | func TestContractOutcomeShips(t *testing.T) { |
| 423 | o := newTeamRig(t) |
| 424 | o.ask("Can we fix a bug in Tito? Login is broken") |
| 425 | request, cmd := o.handoff("sh1", "Login is broken", "") |
| 426 | base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| 427 | o.in(cmd.TurnID, func() { o.websiteReady("sh", "Quick website", base, cand, false) }) |
| 428 | var ships, task, turn, lane string |
| 429 | 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 { |
| 430 | t.Fatal(err) |
| 431 | } |
| 432 | if task != "" || turn != "" || lane != wire.JobLane(request) || o.teamCard(wire.CardMergeShips, "", "").ID != "" { |
| 433 | t.Fatalf("ships card %s for %q in %q, %q", ships, task, turn, lane) |
| 434 | } |
| 435 | // The go-ahead in front of the person is what the Assistant hears of. |
| 436 | 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") { |
| 437 | t.Fatalf("note %q", note) |
| 438 | } |
| 439 | if cards := o.assistantCards(); len(cards) != 1 || !isMergeOutcome(cards[0]) { |
| 440 | t.Fatalf("assistant cards %+v", cards) |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | // TestContractOutcomeShipsNotTheirs: the ships question raises nothing |
| 445 | // for a person whose hand-off's work in the project has ended, when the |
| 446 | // question comes from work they started in Equipo. |
| 447 | func TestContractOutcomeShipsNotTheirs(t *testing.T) { |
| 448 | o := newTeamRig(t) |
| 449 | o.ask("Can we fix a bug in Tito? Login is broken") |
| 450 | _, cmd := o.handoff("sn1", "Login is broken", "") |
| 451 | var ended string |
| 452 | o.in(cmd.TurnID, func() { ended = o.record("sn-rec", "Fix the login") }) |
| 453 | o.reply(cmd.TurnID) |
| 454 | if _, err := o.client.CancelTask(o.ctx, ended); err != nil { |
| 455 | t.Fatal(err) |
| 456 | } |
| 457 | mine := o.own("Something of my own.") |
| 458 | base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| 459 | o.in(mine, func() { o.websiteReady("sn", "Quick website", base, cand, false) }) |
| 460 | if o.teamCard(wire.CardMergeShips, "", "").ID == "" { |
| 461 | t.Fatal("no ships card") |
| 462 | } |
| 463 | if cards := o.assistantCards(); len(cards) != 0 { |
| 464 | t.Fatalf("assistant cards %+v", cards) |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | // TestContractOutcomeOnlyTheirs: a team card raises an Assistant card only |
| 469 | // for a hand-off of its own person's: another person's hand-off that |
| 470 | // joined the task (add_report) raises none, in either lane. |
| 471 | func TestContractOutcomeOnlyTheirs(t *testing.T) { |
| 472 | o := newTeamRig(t) |
| 473 | mine := o.own("Something of my own.") |
| 474 | var id string |
| 475 | o.in(mine, func() { id = o.record("ot-own", "Quick website") }) |
| 476 | mate := &teamRig{o.other("mate@example.com")} |
| 477 | mate.connect(o.base.Mint()) |
| 478 | mate.ask("Can we fix a bug in Tito? Login is broken") |
| 479 | request, cmd := mate.handoff("ot1", "Login is broken", "") |
| 480 | mate.in(cmd.TurnID, func() { |
| 481 | if res := mate.call("ot-rep", wire.ToolAddReport, map[string]string{"task": id, "text": "Login is broken too."}); res.IsError { |
| 482 | t.Fatalf("add_report %+v", res) |
| 483 | } |
| 484 | }) |
| 485 | if created, ok := o.linked(request)[id]; !ok || created { |
| 486 | t.Fatalf("the other hand-off does not follow the task: %v", o.linked(request)) |
| 487 | } |
| 488 | base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| 489 | o.in(mine, func() { |
| 490 | if res := o.call("ot-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}); res.IsError { |
| 491 | t.Fatalf("start %+v", res) |
| 492 | } |
| 493 | _, body := o.expect(wire.FrameDispatch) |
| 494 | d := body.(*wire.DispatchCommand) |
| 495 | o.step("ot-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "claude-a"}) |
| 496 | 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"}) |
| 497 | o.expect(wire.FrameWatchMerge) |
| 498 | c := o.dispatched(wire.SpecialistChecks, base, cand, 0) |
| 499 | o.checks("ot-c", c, wire.ChecksNone, nil, "", "") |
| 500 | o.verdict("ot-r", o.dispatched(wire.SpecialistReview, base, cand, 0), wire.VerdictApprove) |
| 501 | }) |
| 502 | o.until("the merge card", func() bool { return o.cardOf(id).ID != "" }) |
| 503 | if cards := o.assistantCards(); len(cards) != 0 { |
| 504 | t.Fatalf("the creator's Assistant cards %+v", cards) |
| 505 | } |
| 506 | // Their job card follows the work; no go-ahead is theirs. |
| 507 | if cards := mate.assistantCards(); len(cards) != 0 { |
| 508 | t.Fatalf("the other person's Assistant cards %+v", cards) |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | // TestContractOutcomeGoesStale: the outcome card's revision follows the |
| 513 | // team card's, so an answer from before the branch moved is refused with |
| 514 | // the card as it is now; a withdrawn team card resolves it. |
| 515 | func TestContractOutcomeGoesStale(t *testing.T) { |
| 516 | o := newTeamRig(t) |
| 517 | o.ask("Can we fix a bug in Tito? Login is broken") |
| 518 | _, cmd := o.handoff("os1", "Login is broken", "") |
| 519 | base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| 520 | var id string |
| 521 | o.in(cmd.TurnID, func() { id, _ = o.websiteReady("os", "Quick website", base, cand, false) }) |
| 522 | before := o.assistantCard("the merge outcome", isMergeOutcome) |
| 523 | team := o.cardOf(id) |
| 524 | if err := o.runner.Send(o.ctx, "os-moved", wire.FrameBranch, wire.BranchReport{TaskID: id, CandidateSHA: cand, Head: strings.Repeat("9", 40)}); err != nil { |
| 525 | t.Fatal(err) |
| 526 | } |
| 527 | o.wait("moved", func(c *Conversation) bool { return c.Tasks[id].NeedsYou == wire.NeedsBranchMoved }) |
| 528 | moved := o.cardOf(id) |
| 529 | after := o.assistantCard("the moved card", func(c wire.AssistantCard) bool { return c.ID == before.ID && c.Revision > before.Revision }) |
| 530 | if moved.Revision <= team.Revision || after.State != wire.CardOpen { |
| 531 | t.Fatalf("team %d to %d, outcome %+v", team.Revision, moved.Revision, after) |
| 532 | } |
| 533 | _, err := o.a.Answer(o.ctx, before.ID, wire.ChoiceMerge, before.Revision) |
| 534 | 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 { |
| 535 | t.Fatalf("stale answer %+v", c) |
| 536 | } |
| 537 | if n := o.rows("SELECT count(*) FROM chat_steps WHERE task_id = ? AND specialist = ?", id, wire.SpecialistMerge); n != 0 { |
| 538 | t.Fatal("merged on a stale answer") |
| 539 | } |
| 540 | if _, err := o.client.CancelTask(o.ctx, id); err != nil { |
| 541 | t.Fatal(err) |
| 542 | } |
| 543 | resolved := o.assistantCard("resolved", func(c wire.AssistantCard) bool { return c.ID == before.ID && c.State == wire.CardResolved }) |
| 544 | if resolved.Result != equipo.RunnerCopy("assistant.outcome.resolved") || resolved.Revision <= after.Revision { |
| 545 | t.Fatalf("resolved %+v", resolved) |
| 546 | } |
| 547 | 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 { |
| 548 | t.Fatalf("answer on a resolved card %+v", c) |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | // TestContractOutcomeOnlyOwnAnswer: only the person answers their |
| 553 | // outcome card: another member does not find it, no tool of the model's |
| 554 | // answers it, and the team card's own rule still holds (a person who is |
| 555 | // no longer an owner cannot merge). |
| 556 | func TestContractOutcomeOnlyOwnAnswer(t *testing.T) { |
| 557 | o := newTeamRig(t) |
| 558 | o.ask("Can we fix a bug in Tito? Login is broken") |
| 559 | _, cmd := o.handoff("oo1", "Login is broken", "") |
| 560 | base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| 561 | var id string |
| 562 | o.in(cmd.TurnID, func() { id, _ = o.websiteReady("oo", "Quick website", base, cand, false) }) |
| 563 | card := o.assistantCard("the merge outcome", isMergeOutcome) |
| 564 | |
| 565 | mate := &teamRig{o.other("mate@example.com")} |
| 566 | mate.connect(o.base.Mint()) |
| 567 | if _, err := mate.a.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision); Status(err) != http.StatusNotFound { |
| 568 | t.Fatalf("another member's answer: %v", err) |
| 569 | } |
| 570 | if snap, err := mate.a.Snapshot(o.ctx); err != nil || len(snap.Cards) != 0 { |
| 571 | t.Fatalf("another member sees %+v %v", snap.Cards, err) |
| 572 | } |
| 573 | // The model: no Assistant tool or operation answers a card, and the |
| 574 | // Coordinator has none either. |
| 575 | for _, name := range []string{"answer_card", "answer"} { |
| 576 | 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" { |
| 577 | t.Fatalf("Assistant tool %s %+v", name, res) |
| 578 | } |
| 579 | } |
| 580 | if res := o.use("oo-use", "answer_card", map[string]any{"card": card.ID, "choice": wire.ChoiceMerge}); !res.IsError { |
| 581 | t.Fatalf("use answer_card %+v", res) |
| 582 | } |
| 583 | o.in(cmd.TurnID, func() { |
| 584 | if res := o.call("oo-coord", "answer_card", map[string]any{"card": card.ID, "choice": wire.ChoiceMerge}); !res.IsError || res.Code != "unknown_tool" { |
| 585 | t.Fatalf("Coordinator tool %+v", res) |
| 586 | } |
| 587 | }) |
| 588 | if got := o.assistantCard("still open", func(c wire.AssistantCard) bool { return c.ID == card.ID }); got.State != wire.CardOpen || got.Revision != card.Revision { |
| 589 | t.Fatalf("after the model %+v", got) |
| 590 | } |
| 591 | if n := o.rows("SELECT count(*) FROM chat_steps WHERE task_id = ? AND specialist = ?", id, wire.SpecialistMerge); n != 0 { |
| 592 | t.Fatal("merged without the person") |
| 593 | } |
| 594 | // The person stops being an owner: the merge card's own rule refuses. |
| 595 | var revision int64 |
| 596 | if err := o.inst.DB.Writer().QueryRow("SELECT revision FROM members WHERE address = ?", Owner).Scan(&revision); err != nil { |
| 597 | t.Fatal(err) |
| 598 | } |
| 599 | if err := o.inst.Store.SetMember(context.Background(), equipo.Actor{Address: "mate@example.com"}, Owner, equipo.RoleMember, true, revision); err != nil { |
| 600 | t.Fatal(err) |
| 601 | } |
| 602 | if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision); Status(err) != http.StatusForbidden { |
| 603 | t.Fatalf("a member's merge: %v", err) |
| 604 | } |
| 605 | 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 { |
| 606 | t.Fatal("a member merged") |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | // TestContractNoMergeQuestionWhenGateMerges: work Equipo merges on its |
| 611 | // own raises no outcome card: the person is told it is done. |
| 612 | func TestContractNoMergeQuestionWhenGateMerges(t *testing.T) { |
| 613 | o := newTeamRigAt(t, wire.ProtocolCurrent) |
| 614 | o.ask("Can we fix a bug in Tito? Login is broken") |
| 615 | _, cmd := o.handoff("og1", "Login is broken", "") |
| 616 | base, cand, merged := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("e", 40) |
| 617 | var id string |
| 618 | o.in(cmd.TurnID, func() { id = o.judgedTask("og", "Fix the login", base, cand, wire.ChecksPassed, "") }) |
| 619 | m := o.dispatched(wire.SpecialistMerge, base, cand, 0) |
| 620 | o.mergedStep("og-m", m, merged) |
| 621 | o.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) |
| 622 | if cards := o.assistantCards(); len(cards) != 0 { |
| 623 | t.Fatalf("assistant cards %+v", cards) |
| 624 | } |
| 625 | if ids, notes, _ := o.updates(); len(ids) != 1 || !strings.Contains(notes[0], equipo.RunnerCopy("assistant.team.stage.done")) { |
| 626 | t.Fatalf("updates %v %q", ids, notes) |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | // TestContractOutcomeBlockedNotMirrored: a card in a job's thread that |
| 631 | // stops the work on something only the person can give (access) raises |
| 632 | // no Assistant card: the Assistant is told, in plain words, that only |
| 633 | // the person can move the job on, and not to nudge it. A task card and a |
| 634 | // merge receipt need nothing of the person and queue nothing. |
| 635 | func TestContractOutcomeBlockedNotMirrored(t *testing.T) { |
| 636 | o := newTeamRigAt(t, wire.ProtocolCurrent) |
| 637 | o.shipsNo(o.project()) |
| 638 | mine := o.own("Something of my own.") |
| 639 | var joined string |
| 640 | o.in(mine, func() { joined = o.record("ob-own", "Dark mode for settings") }) |
| 641 | o.reply(mine) |
| 642 | o.ask("Can we fix a bug in Tito? Login is broken") |
| 643 | request, cmd := o.handoff("ob1", "Login is broken", "") |
| 644 | o.in(cmd.TurnID, func() { |
| 645 | if res := o.call("ob-find", wire.ToolFind, map[string]string{"query": "moonbeam/app"}); res.Code != "none" { |
| 646 | t.Fatalf("find %+v", res) |
| 647 | } |
| 648 | }) |
| 649 | 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.") |
| 650 | if !strings.HasPrefix(note, jobLine("Login is broken", request, "Login is broken")) || strings.Contains(note, "Moonbeam") || strings.Contains(note, "team_nudge") { |
| 651 | t.Fatalf("note %q", note) |
| 652 | } |
| 653 | if o.threadCard(wire.CardAccess, cmd.TurnID).ID == "" { |
| 654 | t.Fatal("no access card in the thread") |
| 655 | } |
| 656 | if cards := o.assistantCards(); len(cards) != 0 { |
| 657 | t.Fatalf("assistant cards %+v", cards) |
| 658 | } |
| 659 | told, notes, _ := o.updates() |
| 660 | // A task card (add_report) and a merge receipt (Equipo merged on its |
| 661 | // own) need nothing of the person. |
| 662 | base, cand, merge := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("e", 40) |
| 663 | var id string |
| 664 | o.in(cmd.TurnID, func() { |
| 665 | if res := o.call("ob-rep", wire.ToolAddReport, map[string]string{"task": joined, "text": "Login is broken too."}); res.IsError { |
| 666 | t.Fatalf("add_report %+v", res) |
| 667 | } |
| 668 | id, _ = o.measured("ob", "Swipe back from the edge", base, cand, wire.ChecksCannotRun, "needs_macos", func(d *wire.DispatchCommand) *wire.ChangeFacts { return facts(d) }) |
| 669 | }) |
| 670 | if o.threadCard(wire.CardTask, cmd.TurnID).TaskID != joined { |
| 671 | t.Fatal("no task card") |
| 672 | } |
| 673 | m := o.dispatched(wire.SpecialistMerge, base, cand, 0) |
| 674 | if refused := o.lease(o.runner, "ob-lease", wire.LeaseCheck{StepID: m.StepID, Attempt: m.Attempt}); refused != "" { |
| 675 | t.Fatalf("start refused %q", refused) |
| 676 | } |
| 677 | if refused := o.lease(o.runner, "ob-confirm", wire.LeaseCheck{StepID: m.StepID, Attempt: m.Attempt, Purpose: wire.LeasePurposeMerge}); refused != "" { |
| 678 | t.Fatalf("confirmation refused %q", refused) |
| 679 | } |
| 680 | o.step("ob-m-run", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, CandidateSHA: cand}) |
| 681 | 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}}) |
| 682 | o.until("the receipt", func() bool { return len(o.coordinatorCards(wire.CardMergeReceipt, id)) == 1 }) |
| 683 | if cards := o.assistantCards(); len(cards) != 0 { |
| 684 | t.Fatalf("assistant cards %+v", cards) |
| 685 | } |
| 686 | if ids, after, _ := o.updates(); !slices.Equal(ids, told) || !slices.Equal(after, notes) { |
| 687 | t.Fatalf("updates after the task card and the receipt %v %q, before %v %q", ids, after, told, notes) |
| 688 | } |
| 689 | } |
| 690 | |
| 691 | // TestContractAssistantLaneLeaksNoMachinery: a hand-off through a |
| 692 | // question (answered in its thread), a merge card and its answer, then |
| 693 | // the publish card and its answer to a published site, leaves nothing of |
| 694 | // the team's machinery in the Assistant lane: no task id, repository, |
| 695 | // branch, SHA, link into Equipo's tasks or team keys, in the snapshot, |
| 696 | // any event or an answer; every card has exactly its eight keys, plus |
| 697 | // job on the go-ahead and the Publish card, plus detail and started_at |
| 698 | // on the job card. |
| 699 | func TestContractAssistantLaneLeaksNoMachinery(t *testing.T) { |
| 700 | o := newTeamRigAt(t, wire.ProtocolCurrent) |
| 701 | o.sitesOn(wire.ProtocolCurrent, true) |
| 702 | o.ask("Can we fix a bug in Tito? Login is broken") |
| 703 | request, cmd := o.handoff("ol1", "Login is broken", "") |
| 704 | base, cand, merged := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("e", 40) |
| 705 | var id string |
| 706 | o.in(cmd.TurnID, func() { |
| 707 | if res := o.call("ol-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" { |
| 708 | t.Fatalf("ask %+v", res) |
| 709 | } |
| 710 | id, _ = o.websiteReady("ol", "Quick website", base, cand, true) |
| 711 | }) |
| 712 | pv := o.previewDispatch(cand) |
| 713 | o.built("ol-pv-built", pv, digestA) |
| 714 | link := "https://eq-" + id + ".docs-t1.example.ts.net/" |
| 715 | o.previewDone("ol-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, Outcome: wire.PreviewDeployed}) |
| 716 | outcome := o.assistantCard("the merge outcome", func(c wire.AssistantCard) bool { |
| 717 | return isMergeOutcome(c) && slices.ContainsFunc(c.Links, func(l wire.CardLink) bool { return l.URL == link }) |
| 718 | }) |
| 719 | var answers [][]byte |
| 720 | answer := func(card wire.AssistantCard, choice string) { |
| 721 | body, _ := json.Marshal(wire.AnswerCard{Choice: choice, Revision: card.Revision}) |
| 722 | status, _, out := raw(t, "POST", o.inst.URL+"/api/v1/assistant/cards/"+card.ID+"/answer", o.client.Token, nil, string(body)) |
| 723 | if status != 200 { |
| 724 | t.Fatalf("answer %s: %d %s", card.ID, status, out) |
| 725 | } |
| 726 | answers = append(answers, out) |
| 727 | } |
| 728 | // The Assistant answers the thread's question itself (team_reply). |
| 729 | o.threadQuestion(request) |
| 730 | if res := o.use("ol-reply", "team_reply", map[string]any{"request": request, "answer": "Web"}); res.IsError { |
| 731 | t.Fatalf("team_reply %+v", res) |
| 732 | } |
| 733 | answer(outcome, wire.ChoiceMerge) |
| 734 | m := o.dispatched(wire.SpecialistMerge, base, cand, 0) |
| 735 | o.mergedStep("ol-m", m, merged) |
| 736 | o.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) |
| 737 | answer(o.assistantCard("the publish outcome", isPublishOutcome), wire.ChoicePublish) |
| 738 | d := o.publishDispatch() |
| 739 | if refused := o.lease(o.runner, "ol-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused != "" { |
| 740 | t.Fatalf("start refused %q", refused) |
| 741 | } |
| 742 | o.publishReport("ol-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40}) |
| 743 | 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 != "" { |
| 744 | t.Fatalf("deploy refused %q", refused) |
| 745 | } |
| 746 | site := "https://" + d.Publish.App + ".bds.oncarlos.com/" |
| 747 | 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}) |
| 748 | o.assistantCard("published", func(c wire.AssistantCard) bool { |
| 749 | return isPublishOutcome(c) && len(c.Links) == 1 && c.Links[0].URL == site |
| 750 | }) |
| 751 | k, err := o.client.Task(o.ctx, id) |
| 752 | if err != nil || k.Branch == "" { |
| 753 | t.Fatalf("task %+v %v", k, err) |
| 754 | } |
| 755 | |
| 756 | status, _, snap := raw(t, "GET", o.inst.URL+"/api/v1/assistant/snapshot", o.client.Token, nil, "") |
| 757 | if status != 200 { |
| 758 | t.Fatalf("snapshot %d %s", status, snap) |
| 759 | } |
| 760 | n := o.rows("SELECT count(*) FROM chat_events WHERE person = ? AND lane = ?", Owner, wire.LaneAssistant) |
| 761 | s, err := o.a.Open(o.ctx, 0) |
| 762 | if err != nil { |
| 763 | t.Fatal(err) |
| 764 | } |
| 765 | defer s.Close() |
| 766 | var events []wire.Event |
| 767 | assistEvents(t, s, "every Assistant event", &events, func(es []wire.Event) bool { return len(es) >= n }) |
| 768 | if !slices.ContainsFunc(events, func(e wire.Event) bool { return e.Type == wire.EventCard && e.ID == outcome.ID }) { |
| 769 | t.Fatal("no outcome card event") |
| 770 | } |
| 771 | |
| 772 | check := noMachinery(t, id, []string{"amadan.net/oficina/sample", "oficina/sample", k.Branch, "/tasks/"}) |
| 773 | decode := func(what string, b []byte) any { |
| 774 | var v any |
| 775 | if err := json.Unmarshal(b, &v); err != nil { |
| 776 | t.Fatalf("%s: %v", what, err) |
| 777 | } |
| 778 | return v |
| 779 | } |
| 780 | eight := func(what string, card any) { cardKeys(t, what, card) } |
| 781 | sv := decode("snapshot", snap) |
| 782 | check("the snapshot", sv, false) |
| 783 | cards := sv.(map[string]any)["cards"].([]any) |
| 784 | // The go-ahead, the publish card and the job's. |
| 785 | if len(cards) != 3 { |
| 786 | t.Fatalf("snapshot cards %s", snap) |
| 787 | } |
| 788 | for _, c := range cards { |
| 789 | eight("snapshot", c) |
| 790 | } |
| 791 | for _, e := range events { |
| 792 | b, _ := json.Marshal(e) |
| 793 | check("event "+e.Type, decode("event", b), false) |
| 794 | if e.Type == wire.EventCard { |
| 795 | eight("event", decode("card", e.Data)) |
| 796 | } |
| 797 | } |
| 798 | for _, b := range answers { |
| 799 | av := decode("answer", b) |
| 800 | check("an answer", av, false) |
| 801 | eight("answer", av.(map[string]any)["card"]) |
| 802 | } |
| 803 | // The preview was the one place the task's name could be. |
| 804 | if !strings.Contains(string(snap), link) && !slices.ContainsFunc(events, func(e wire.Event) bool { return strings.Contains(string(e.Data), link) }) { |
| 805 | t.Fatal("the preview was never shown") |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | // noMachinery fails t on the first piece of the team's machinery a |
| 810 | // decoded value from the Assistant lane carries (machineryIn). |
| 811 | func noMachinery(t *testing.T, task string, forbidden []string) func(what string, v any, link bool) { |
| 812 | return func(what string, v any, link bool) { |
| 813 | t.Helper() |
| 814 | if bad := machineryIn(task, forbidden, v, link); bad != "" { |
| 815 | t.Fatalf("%s %s", what, bad) |
| 816 | } |
| 817 | } |
| 818 | } |
| 819 | |
| 820 | var sha40 = regexp.MustCompile(`[0-9a-f]{40}`) |
| 821 | |
| 822 | // machineryIn is the first piece of the team's machinery a decoded value |
| 823 | // from the Assistant lane carries, said plainly ("" for none): forbidden |
| 824 | // text, a 40-hex SHA, the task id or one of the team's keys. A card |
| 825 | // link's url may be a preview, whose host is the devbox app Equipo |
| 826 | // names for the task (eq-<task>, tmp-<task>; ruling R9): only there the |
| 827 | // task id is not refused; every other rule holds for it too. |
| 828 | func machineryIn(task string, forbidden []string, v any, link bool) string { |
| 829 | keys := []string{"task_id", "project_id", "preview_url", "site", "runner"} |
| 830 | switch x := v.(type) { |
| 831 | case string: |
| 832 | for _, bad := range forbidden { |
| 833 | if strings.Contains(x, bad) { |
| 834 | return fmt.Sprintf("says %q: %q", bad, x) |
| 835 | } |
| 836 | } |
| 837 | rest := x |
| 838 | if link { |
| 839 | rest = previewHostless(x, task) |
| 840 | } |
| 841 | if sha40.MatchString(x) || strings.Contains(rest, task) { |
| 842 | return fmt.Sprintf("says the task or a SHA: %q", x) |
| 843 | } |
| 844 | case []any: |
| 845 | for _, e := range x { |
| 846 | if bad := machineryIn(task, forbidden, e, false); bad != "" { |
| 847 | return bad |
| 848 | } |
| 849 | } |
| 850 | case map[string]any: |
| 851 | for key, e := range x { |
| 852 | if slices.Contains(keys, key) { |
| 853 | return fmt.Sprintf("has the key %q", key) |
| 854 | } |
| 855 | if links, ok := e.([]any); ok && key == "links" { |
| 856 | for _, l := range links { |
| 857 | for lk, lv := range l.(map[string]any) { |
| 858 | if bad := machineryIn(task, forbidden, lv, lk == "url"); bad != "" { |
| 859 | return bad |
| 860 | } |
| 861 | } |
| 862 | } |
| 863 | continue |
| 864 | } |
| 865 | if bad := machineryIn(task, forbidden, e, false); bad != "" { |
| 866 | return bad |
| 867 | } |
| 868 | } |
| 869 | } |
| 870 | return "" |
| 871 | } |
| 872 | |
| 873 | // previewHostless is a link's url without its host's first label when |
| 874 | // that label is the devbox app named for the task (eq-<task>, |
| 875 | // tmp-<task>): the one place the task id may be (R9). Any other url, or |
| 876 | // one that does not parse as an absolute url, is as it is. |
| 877 | func previewHostless(raw, task string) string { |
| 878 | u, err := url.Parse(raw) |
| 879 | if err != nil || u.Host == "" { |
| 880 | return raw |
| 881 | } |
| 882 | label, after, _ := strings.Cut(u.Host, ".") |
| 883 | if label != "eq-"+task && label != "tmp-"+task { |
| 884 | return raw |
| 885 | } |
| 886 | u.Host = "." + after |
| 887 | return u.String() |
| 888 | } |
| 889 | |
| 890 | // TestContractAssistantLeakCheckLinks (ruling R20): the leak check lets |
| 891 | // the task id through only as a preview host's first label (eq-<task>, |
| 892 | // tmp-<task>); in a link's path or query, another host label, or the |
| 893 | // Equipo job link, it is machinery. |
| 894 | func TestContractAssistantLeakCheckLinks(t *testing.T) { |
| 895 | task := "k_7c4qhxw2" |
| 896 | link := func(url string) any { |
| 897 | return map[string]any{"links": []any{map[string]any{"label": "Try it", "url": url}}} |
| 898 | } |
| 899 | 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"} { |
| 900 | if bad := machineryIn(task, nil, link(ok), false); bad != "" { |
| 901 | t.Errorf("%s refused: %s", ok, bad) |
| 902 | } |
| 903 | } |
| 904 | 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} { |
| 905 | if bad := machineryIn(task, nil, link(leak), false); bad == "" { |
| 906 | t.Errorf("%s let through", leak) |
| 907 | } |
| 908 | } |
| 909 | } |
| 910 | |
| 911 | // cardKeys checks a decoded Assistant card has exactly its keys: the |
| 912 | // eight every card has, plus job on a go-ahead or Publish card that |
| 913 | // belongs to a job, plus detail and started_at on a job card. |
| 914 | func cardKeys(t *testing.T, what string, card any) { |
| 915 | t.Helper() |
| 916 | c := card.(map[string]any) |
| 917 | want := []string{"id", "revision", "kind", "state", "question", "options", "links", "result"} |
| 918 | switch c["kind"] { |
| 919 | case wire.CardOutcome: |
| 920 | want = append(want, "job") |
| 921 | case wire.CardJob: |
| 922 | want = append(want, "detail", "started_at") |
| 923 | } |
| 924 | got := []string{} |
| 925 | for key := range c { |
| 926 | got = append(got, key) |
| 927 | } |
| 928 | slices.Sort(got) |
| 929 | slices.Sort(want) |
| 930 | if !slices.Equal(got, want) { |
| 931 | t.Fatalf("%s card keys %v, want %v", what, got, want) |
| 932 | } |
| 933 | } |
| 934 | |
| 935 | // TestContractOutcomeAudited: an outcome answer is audited as the person |
| 936 | // in one row naming the card and the option's value, and nothing else. |
| 937 | func TestContractOutcomeAudited(t *testing.T) { |
| 938 | o := newTeamRig(t) |
| 939 | o.ask("Can we fix a bug in Tito? Login is broken") |
| 940 | _, cmd := o.handoff("oa1", "Login is broken", "") |
| 941 | base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| 942 | o.in(cmd.TurnID, func() { o.websiteReady("oa", "Quick website", base, cand, false) }) |
| 943 | card := o.assistantCard("the merge outcome", isMergeOutcome) |
| 944 | before := o.rows("SELECT count(*) FROM audit_events") |
| 945 | if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceWait, card.Revision); err != nil { |
| 946 | t.Fatal(err) |
| 947 | } |
| 948 | 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 { |
| 949 | t.Fatalf("%d outcome audits", n) |
| 950 | } |
| 951 | if after := o.rows("SELECT count(*) FROM audit_events"); after != before+1 { |
| 952 | t.Fatalf("%d audit rows for one answer", after-before) |
| 953 | } |
| 954 | // A refused answer is not audited. |
| 955 | if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision); Status(err) != http.StatusConflict { |
| 956 | t.Fatalf("a second answer %v", err) |
| 957 | } |
| 958 | time.Sleep(20 * time.Millisecond) |
| 959 | if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.outcome'"); n != 1 { |
| 960 | t.Fatalf("%d outcome audits after a refusal", n) |
| 961 | } |
| 962 | } |
| 963 | |
| 964 | // mergedWebsite hands a quick website to the team, brings its devbox |
| 965 | // preview up and merges it from the merge outcome card: Equipo asks to |
| 966 | // publish it when sites. It returns the task, its preview link, the |
| 967 | // merged SHA and the forget_task frame the task's end sent. |
| 968 | func (o *teamRig) mergedWebsite(key string, sites bool) (id, link, merged string, forget *wire.ForgetTaskCommand) { |
| 969 | o.t.Helper() |
| 970 | o.sitesOn(wire.ProtocolCurrent, sites) |
| 971 | o.ask("Build me a quick website") |
| 972 | _, cmd := o.handoff(key+"1", "Build me a quick website", "") |
| 973 | base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| 974 | merged = strings.Repeat("e", 40) |
| 975 | o.in(cmd.TurnID, func() { id, _ = o.websiteReady(key, "Quick website", base, cand, true) }) |
| 976 | pv := o.previewDispatch(cand) |
| 977 | o.built(key+"-pv-built", pv, digestA) |
| 978 | link = "https://eq-" + id + ".docs-t1.example.ts.net/" |
| 979 | o.previewDone(key+"-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, Outcome: wire.PreviewDeployed}) |
| 980 | ahead := o.assistantCard("the merge outcome", func(c wire.AssistantCard) bool { return isMergeOutcome(c) && len(c.Links) == 1 }) |
| 981 | if _, err := o.a.Answer(o.ctx, ahead.ID, wire.ChoiceMerge, ahead.Revision); err != nil { |
| 982 | o.t.Fatal(err) |
| 983 | } |
| 984 | o.mergedStep(key+"-m", o.dispatched(wire.SpecialistMerge, base, cand, 0), merged) |
| 985 | o.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) |
| 986 | if forget = o.forgetFrame(id, 5*time.Second); forget == nil { |
| 987 | o.t.Fatal("no forget_task at the merge") |
| 988 | } |
| 989 | return id, link, merged, forget |
| 990 | } |
| 991 | |
| 992 | // forgetFrame is the next forget_task for the task, acked, waiting up to |
| 993 | // wait for it (nil when none came); every other frame is held. |
| 994 | func (o *teamRig) forgetFrame(task string, wait time.Duration) *wire.ForgetTaskCommand { |
| 995 | o.t.Helper() |
| 996 | deadline := time.Now().Add(wait) |
| 997 | for { |
| 998 | for i, h := range o.held { |
| 999 | if f, ok := h.body.(*wire.ForgetTaskCommand); ok && f.TaskID == task { |
| 1000 | o.held = append(o.held[:i:i], o.held[i+1:]...) |
| 1001 | if err := o.runner.Send(o.ctx, "a-"+h.f.ID, wire.FrameAck, wire.Ack{ID: h.f.ID}); err != nil { |
| 1002 | o.t.Fatal(err) |
| 1003 | } |
| 1004 | return f |
| 1005 | } |
| 1006 | } |
| 1007 | if time.Now().After(deadline) { |
| 1008 | return nil |
| 1009 | } |
| 1010 | if refused := o.lease(o.runner, "fg-poll-"+itoa(int(time.Now().UnixNano()%1e9)), wire.LeaseCheck{}); refused != "" { |
| 1011 | o.t.Fatalf("poll lease refused %q", refused) |
| 1012 | } |
| 1013 | } |
| 1014 | } |
| 1015 | |
| 1016 | // publishOptions are a publish outcome card's options. |
| 1017 | func publishOptions() []wire.CardOption { |
| 1018 | return []wire.CardOption{{Value: wire.ChoicePublish, Label: equipo.RunnerCopy("assistant.outcome.publish_option")}, {Value: wire.ChoiceNotNow, Label: equipo.RunnerCopy("assistant.outcome.publish_not_now")}} |
| 1019 | } |
| 1020 | |
| 1021 | // previewOf is the card's preview link ("" when it shows none). |
| 1022 | func previewOf(c wire.AssistantCard) string { |
| 1023 | for _, l := range c.Links { |
| 1024 | if l.Label == equipo.RunnerCopy("assistant.outcome.preview") { |
| 1025 | return l.URL |
| 1026 | } |
| 1027 | } |
| 1028 | return "" |
| 1029 | } |
| 1030 | |
| 1031 | // TestContractOutcomePublish: a merged website on a hand-off's task |
| 1032 | // raises the publish outcome card, "Your site is ready. Publish it?" with |
| 1033 | // its preview. Publish there places the publish step as the publish |
| 1034 | // card's Publish does: the person's decision, for the project's app and |
| 1035 | // the merged SHA. Once the step reports it published, the card says so |
| 1036 | // with the site's address, and the person hears of it in a team_update |
| 1037 | // turn. Not now ends the card with no step. |
| 1038 | func TestContractOutcomePublish(t *testing.T) { |
| 1039 | o := newTeamRigAt(t, wire.ProtocolCurrent) |
| 1040 | id, link, merged, _ := o.mergedWebsite("op", true) |
| 1041 | card := o.assistantCard("the publish outcome", isPublishOutcome) |
| 1042 | 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 != "" { |
| 1043 | t.Fatalf("card %+v", card) |
| 1044 | } |
| 1045 | team, _ := o.publishCard(id) |
| 1046 | k, err := o.client.Task(o.ctx, id) |
| 1047 | if err != nil || k.Site == nil || team.State != wire.CardOpen { |
| 1048 | t.Fatalf("publish card %+v, site %+v %v", team, k.Site, err) |
| 1049 | } |
| 1050 | told, notes, _ := o.updates() |
| 1051 | ans, err := o.a.Answer(o.ctx, card.ID, wire.ChoicePublish, card.Revision) |
| 1052 | if err != nil || ans.Card.State != wire.CardAnswered || ans.Card.Result != equipo.RunnerCopy("assistant.outcome.publish_publishing") { |
| 1053 | t.Fatalf("answer %+v %v", ans, err) |
| 1054 | } |
| 1055 | if after, _ := o.publishCard(id); after.ID != team.ID || after.State != wire.CardAnswered || after.Choice != wire.ChoicePublish { |
| 1056 | t.Fatalf("publish card after %+v", after) |
| 1057 | } |
| 1058 | d := o.publishDispatch() |
| 1059 | if d.CandidateSHA != merged || d.Person != Owner || d.Publish == nil || d.Publish.App != k.Site.App { |
| 1060 | t.Fatalf("publish dispatch %+v %+v", d, d.Publish) |
| 1061 | } |
| 1062 | 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 { |
| 1063 | t.Fatal("the publish step is not the person's decision on the merged SHA") |
| 1064 | } |
| 1065 | if refused := o.lease(o.runner, "op-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused != "" { |
| 1066 | t.Fatalf("start refused %q", refused) |
| 1067 | } |
| 1068 | o.publishReport("op-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40}) |
| 1069 | // Publishing moves on its own: the Assistant hears nothing until it |
| 1070 | // is live. |
| 1071 | if ids, after, _ := o.updates(); !slices.Equal(ids, told) || !slices.Equal(after, notes) { |
| 1072 | t.Fatalf("updates while publishing %v %q, before %v %q", ids, after, told, notes) |
| 1073 | } |
| 1074 | 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 != "" { |
| 1075 | t.Fatalf("deploy refused %q", refused) |
| 1076 | } |
| 1077 | site := "https://" + k.Site.App + ".bds.oncarlos.com/" |
| 1078 | 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}) |
| 1079 | done := o.assistantCard("published", func(c wire.AssistantCard) bool { |
| 1080 | return c.ID == card.ID && c.Result == equipo.RunnerCopy("assistant.outcome.publish_published") |
| 1081 | }) |
| 1082 | if done.State != wire.CardAnswered || !slices.Equal(done.Links, []wire.CardLink{{Label: equipo.RunnerCopy("assistant.outcome.publish_site"), URL: site}}) { |
| 1083 | t.Fatalf("published card %+v", done) |
| 1084 | } |
| 1085 | // Done, though the project's ships question is still open: that is |
| 1086 | // not the job's stop. |
| 1087 | o.until("a team_update with the address", func() bool { |
| 1088 | _, notes, _ := o.updates() |
| 1089 | 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") |
| 1090 | }) |
| 1091 | |
| 1092 | // Not now: answered, and nothing published. |
| 1093 | n := newTeamRigAt(t, wire.ProtocolCurrent) |
| 1094 | id, _, _, _ = n.mergedWebsite("on", true) |
| 1095 | card = n.assistantCard("the publish outcome", isPublishOutcome) |
| 1096 | ans, err = n.a.Answer(n.ctx, card.ID, wire.ChoiceNotNow, card.Revision) |
| 1097 | if err != nil || ans.Card.State != wire.CardAnswered || ans.Card.Result != equipo.RunnerCopy("assistant.outcome.publish_declined") || len(ans.Card.Links) != 0 { |
| 1098 | t.Fatalf("not now %+v %v", ans, err) |
| 1099 | } |
| 1100 | if after, _ := n.publishCard(id); after.State != wire.CardAnswered || after.Choice != wire.ChoiceNotNow { |
| 1101 | t.Fatalf("publish card after not now %+v", after) |
| 1102 | } |
| 1103 | n.syncNow("on-sync") |
| 1104 | if c := n.rows("SELECT count(*) FROM chat_steps WHERE task_id = ? AND specialist = ?", id, wire.SpecialistPublish); c != 0 || n.audits("publish.declined") != 1 { |
| 1105 | t.Fatal("not now placed a publish step, or was not audited") |
| 1106 | } |
| 1107 | } |
| 1108 | |
| 1109 | // TestContractPreviewHeldUntilPublishAnswer: a merged website whose |
| 1110 | // Publish is asked keeps its devbox preview up: the forget_task at its |
| 1111 | // merge keeps the preview, and the cards show it though the task is |
| 1112 | // done. Either answer releases it with a second forget_task (the |
| 1113 | // sessions still kept), after which no card shows it. A publish asked |
| 1114 | // again after a failed one shows none; a merged task with nothing to |
| 1115 | // publish keeps nothing, in one forget_task as before. |
| 1116 | func TestContractPreviewHeldUntilPublishAnswer(t *testing.T) { |
| 1117 | for _, choice := range []string{wire.ChoicePublish, wire.ChoiceNotNow} { |
| 1118 | o := newTeamRigAt(t, wire.ProtocolCurrent) |
| 1119 | id, link, _, forget := o.mergedWebsite("ph"+choice[:1], true) |
| 1120 | if !forget.KeepPreview || forget.KeepUntil == nil { |
| 1121 | t.Fatalf("%s: the merge's forget_task %+v", choice, forget) |
| 1122 | } |
| 1123 | card := o.assistantCard("the publish outcome", isPublishOutcome) |
| 1124 | if previewOf(card) != link { |
| 1125 | t.Fatalf("%s: the publish outcome shows no preview: %+v", choice, card) |
| 1126 | } |
| 1127 | // The merge card itself is in the job's thread, read as the |
| 1128 | // thread's page reads it. |
| 1129 | request := o.requestOf(id) |
| 1130 | ahead := o.assistantCard("the merge outcome", isMergeOutcome) |
| 1131 | if previewOf(ahead) != link || o.jobCard(request, wire.CardMerge, id).PreviewURL != link { |
| 1132 | t.Fatalf("%s: the merge cards lost the held preview: %+v", choice, ahead) |
| 1133 | } |
| 1134 | if _, err := o.a.Answer(o.ctx, card.ID, choice, card.Revision); err != nil { |
| 1135 | t.Fatal(err) |
| 1136 | } |
| 1137 | release := o.forgetFrame(id, 5*time.Second) |
| 1138 | if release == nil || release.KeepPreview || release.KeepUntil == nil || release.Person != Owner || time.Until(*release.KeepUntil) < wire.KeepMergedSessions-time.Hour { |
| 1139 | t.Fatalf("%s: the releasing forget_task %+v", choice, release) |
| 1140 | } |
| 1141 | for _, c := range o.assistantCards() { |
| 1142 | if strings.Contains(fmt.Sprint(c.Links), link) { |
| 1143 | t.Fatalf("%s: a card shows the released preview: %+v", choice, c) |
| 1144 | } |
| 1145 | } |
| 1146 | if c := o.jobCard(request, wire.CardMerge, id); c.ID == "" || c.PreviewURL != "" { |
| 1147 | t.Fatalf("%s: the merge card shows the released preview: %+v", choice, c) |
| 1148 | } |
| 1149 | if choice != wire.ChoicePublish { |
| 1150 | continue |
| 1151 | } |
| 1152 | // The publish fails: asked again, with no preview, and nothing more |
| 1153 | // to release. |
| 1154 | d := o.publishDispatch() |
| 1155 | o.publishReport("ph-failed", d, wire.StepFailed, nil) |
| 1156 | again := o.assistantCard("asked again", func(c wire.AssistantCard) bool { |
| 1157 | return isPublishOutcome(c) && c.ID != card.ID && c.State == wire.CardOpen |
| 1158 | }) |
| 1159 | if len(again.Links) != 0 { |
| 1160 | t.Fatalf("asked again with a link %+v", again) |
| 1161 | } |
| 1162 | if f := o.forgetFrame(id, time.Second); f != nil { |
| 1163 | t.Fatalf("a forget_task after the failure %+v", f) |
| 1164 | } |
| 1165 | } |
| 1166 | o := newTeamRigAt(t, wire.ProtocolCurrent) |
| 1167 | id, _, _, forget := o.mergedWebsite("pn", false) |
| 1168 | if forget.KeepPreview || forget.KeepUntil == nil { |
| 1169 | t.Fatalf("the forget_task with nothing to publish %+v", forget) |
| 1170 | } |
| 1171 | if f := o.forgetFrame(id, time.Second); f != nil { |
| 1172 | t.Fatalf("a second forget_task %+v", f) |
| 1173 | } |
| 1174 | } |
| 1175 | |
| 1176 | // TestContractPublishNeedsOwnerAnswer: the gate is the publish card's |
| 1177 | // own. A publish step placed by the person's Publish on the outcome card |
| 1178 | // starts; the same step standing on anything but the person's answer is |
| 1179 | // refused by authorizePublish, the outcome card there all along: decided |
| 1180 | // by anyone else, or decided by the person with no answered Publish on |
| 1181 | // the task's publish card for the merged commit behind it. |
| 1182 | func TestContractPublishNeedsOwnerAnswer(t *testing.T) { |
| 1183 | o := newTeamRigAt(t, wire.ProtocolCurrent) |
| 1184 | id, _, merged, _ := o.mergedWebsite("pg", true) |
| 1185 | card := o.assistantCard("the publish outcome", isPublishOutcome) |
| 1186 | if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoicePublish, card.Revision); err != nil { |
| 1187 | t.Fatal(err) |
| 1188 | } |
| 1189 | d := o.publishDispatch() |
| 1190 | for _, by := range []string{"", "assistant:" + Owner, "policy", "person:mate@example.com"} { |
| 1191 | if _, err := o.inst.DB.Writer().Exec("UPDATE chat_steps SET decided_by = ? WHERE id = ?", by, d.StepID); err != nil { |
| 1192 | t.Fatal(err) |
| 1193 | } |
| 1194 | if refused := o.lease(o.runner, "pg-start-"+itoa(len(by)), wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused == "" { |
| 1195 | t.Fatalf("a publish standing on %q started", by) |
| 1196 | } |
| 1197 | } |
| 1198 | if _, err := o.inst.DB.Writer().Exec("UPDATE chat_steps SET decided_by = ? WHERE id = ?", "person:"+Owner, d.StepID); err != nil { |
| 1199 | t.Fatal(err) |
| 1200 | } |
| 1201 | team, _ := o.publishCard(id) |
| 1202 | for i, c := range []struct{ state, choice, asked string }{ |
| 1203 | {wire.CardOpen, "", merged}, |
| 1204 | {wire.CardAnswered, wire.ChoiceNotNow, merged}, |
| 1205 | {wire.CardResolved, "", merged}, |
| 1206 | {wire.CardAnswered, wire.ChoicePublish, strings.Repeat("9", 40)}, |
| 1207 | } { |
| 1208 | if _, err := o.inst.DB.Writer().Exec("UPDATE chat_cards SET state = ?, choice = ? WHERE id = ?", c.state, c.choice, team.ID); err != nil { |
| 1209 | t.Fatal(err) |
| 1210 | } |
| 1211 | if _, err := o.inst.DB.Writer().Exec("UPDATE chat_tasks SET publish_asked = ? WHERE id = ?", c.asked, id); err != nil { |
| 1212 | t.Fatal(err) |
| 1213 | } |
| 1214 | if refused := o.lease(o.runner, "pg-card-"+itoa(i), wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused == "" { |
| 1215 | t.Fatalf("a person's publish started with its card %+v", c) |
| 1216 | } |
| 1217 | } |
| 1218 | if _, err := o.inst.DB.Writer().Exec("UPDATE chat_cards SET state = ?, choice = ? WHERE id = ?", wire.CardAnswered, wire.ChoicePublish, team.ID); err != nil { |
| 1219 | t.Fatal(err) |
| 1220 | } |
| 1221 | if _, err := o.inst.DB.Writer().Exec("UPDATE chat_tasks SET publish_asked = ? WHERE id = ?", merged, id); err != nil { |
| 1222 | t.Fatal(err) |
| 1223 | } |
| 1224 | if refused := o.lease(o.runner, "pg-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused != "" { |
| 1225 | t.Fatalf("the person's publish refused %q", refused) |
| 1226 | } |
| 1227 | // The task has no publish card at all: the person's decision stands on |
| 1228 | // nothing, and the outcome card is still there. |
| 1229 | if _, err := o.inst.DB.Writer().Exec("DELETE FROM chat_cards WHERE id = ?", team.ID); err != nil { |
| 1230 | t.Fatal(err) |
| 1231 | } |
| 1232 | if n := o.rows("SELECT count(*) FROM chat_cards WHERE task_id = ? AND kind = ?", id, wire.CardPublish); n != 0 { |
| 1233 | t.Fatalf("%d publish cards left", n) |
| 1234 | } |
| 1235 | if n := o.rows("SELECT count(*) FROM chat_steps WHERE id = ? AND decided_by = ?", d.StepID, "person:"+Owner); n != 1 { |
| 1236 | t.Fatal("the step lost its decision") |
| 1237 | } |
| 1238 | if n := o.rows("SELECT count(*) FROM chat_cards WHERE id = ? AND lane = ?", card.ID, wire.LaneAssistant); n != 1 { |
| 1239 | t.Fatal("no outcome card") |
| 1240 | } |
| 1241 | if refused := o.lease(o.runner, "pg-no-card", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused == "" { |
| 1242 | t.Fatal("a person's publish started with no publish card behind it") |
| 1243 | } |
| 1244 | } |
| 1245 | |
| 1246 | // TestContractPreviewNotHeldBelow19: a runner below wire.ProtocolAssistant |
| 1247 | // cannot keep a preview past its task (Encode drops KeepPreview, and it |
| 1248 | // takes the link down), so a merged website it previewed holds nothing: |
| 1249 | // the forget_task asks for no retention and no card shows the link once |
| 1250 | // the task is done. Publish is not asked of it (places need protocol 31): |
| 1251 | // the task says why instead. |
| 1252 | func TestContractPreviewNotHeldBelow19(t *testing.T) { |
| 1253 | r := newToolRigAt(t, wire.ProtocolAssistant-1) |
| 1254 | r.sitesOn(wire.ProtocolAssistant-1, true) |
| 1255 | base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| 1256 | id, _ := r.websiteReady("p18", "Quick website", base, cand, true) |
| 1257 | if pv := r.previewDispatch(cand); pv != nil { |
| 1258 | t.Fatal("old runner received a preview without injection defences") |
| 1259 | } |
| 1260 | r.mergeFromCard("p18-m", id, base, cand, strings.Repeat("e", 40)) |
| 1261 | if _, ok := r.publishCard(id); ok || r.audits("publish.not_offered") != 1 { |
| 1262 | t.Fatal("Publish asked of a protocol 18 runner, or not said why") |
| 1263 | } |
| 1264 | if n := r.rows("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", wire.FrameForgetTask, `%"keep_preview":true%`); n != 0 { |
| 1265 | t.Fatalf("%d forget_task commands keep the preview on a protocol 18 runner", n) |
| 1266 | } |
| 1267 | if r.cardOf(id).PreviewURL != "" { |
| 1268 | t.Fatal("the merge card shows a preview the runner took down") |
| 1269 | } |
| 1270 | } |
| 1271 | |