| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "slices" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/specialist" |
| 11 | "amadan.net/oficina/equipo/internal/wire" |
| 12 | ) |
| 13 | |
| 14 | // Task 17 (dynamic specialists slice 1): routing to Design (status, |
| 15 | // start_task's specialist, the task's maker), placement on a runner that |
| 16 | // can run Design, the three-attempt autonomy limit, and the recovery card |
| 17 | // after a revoke. |
| 18 | |
| 19 | const candidateSHA = "c0ffee0000000000000000000000000000000001" |
| 20 | |
| 21 | // designHello is the primary's hello: the team's repositories, its page |
| 22 | // renderer's health ("" none) and the connections it holds. |
| 23 | func designHello(renderer string, conns ...wire.HeldConnection) wire.Hello { |
| 24 | return wire.Hello{Repos: []string{repoPatrix, repoSuite, repoFresh}, Capabilities: &wire.Capabilities{Tools: &wire.ToolHealth{Scanner: wire.ToolHealthy, Renderer: renderer}}, Connections: conns} |
| 25 | } |
| 26 | |
| 27 | func (r *hkRig) setHello(protocol int, h wire.Hello) { |
| 28 | r.t.Helper() |
| 29 | raw, err := json.Marshal(h) |
| 30 | r.must(err) |
| 31 | r.exec("UPDATE runner_sessions SET protocol = ?, hello = ? WHERE runner_id = ?", protocol, string(raw), "RUNNER1") |
| 32 | } |
| 33 | |
| 34 | var claudeSub = wire.HeldConnection{LocalID: "claude-1", Person: paul, Provider: wire.ProviderClaude, Kind: wire.KindSubscription, State: wire.ConnHealthy} |
| 35 | |
| 36 | // active proposes design-v1 for project (a name, or "" for the team) and |
| 37 | // adds it. |
| 38 | func (r *hkRig) active(l Lease, project, scope string) specialistRecord { |
| 39 | r.t.Helper() |
| 40 | sp := r.propose(l, project, scope) |
| 41 | r.must(r.answer(paul, sp, wire.ChoiceAdd, 1)) |
| 42 | r.must(r.s.db.G.Where("id = ?", sp.ID).First(&sp).Error) |
| 43 | return sp |
| 44 | } |
| 45 | |
| 46 | // personTask records a task in repo in a new person turn of Paul's and |
| 47 | // returns the turn and the task. |
| 48 | func (r *hkRig) personTask(l Lease, repo, kind string) (turnRecord, string) { |
| 49 | r.t.Helper() |
| 50 | turn := r.asked(newID("t_"), wire.LaneCoordinator, "Please make it calmer.") |
| 51 | res := r.call(l, turn.ID, wire.ToolRecordTask, map[string]any{"repo": repo, "title": "Calmer " + newID(""), "brief": "Calmer.", "kind": kind, "separate": true}) |
| 52 | return turn, madeTask2(r.t, res) |
| 53 | } |
| 54 | |
| 55 | func (r *hkRig) stepsOf(task string) int64 { |
| 56 | return r.count("SELECT count(*) FROM chat_steps WHERE task_id = ?", task) |
| 57 | } |
| 58 | |
| 59 | // report sends the step's report from RUNNER1 at its current attempt. |
| 60 | func (r *hkRig) report(l Lease, s stepRecord, v wire.StepReport) { |
| 61 | r.t.Helper() |
| 62 | v.TaskID, v.StepID = s.TaskID, s.ID |
| 63 | if v.Attempt == 0 { |
| 64 | v.Attempt = s.Attempt |
| 65 | } |
| 66 | r.must(r.tx(func(tx *txn) error { return tx.stepReport(l, &v) })) |
| 67 | } |
| 68 | |
| 69 | // TestStartTaskRoutesToASpecialist: start_task's specialist must be an |
| 70 | // active specialist whose profile is a maker, scoped to the task's |
| 71 | // project or the team, whose grant grantFor finds for the task's project |
| 72 | // now. Each refusal starts nothing; the accepted start records the maker, |
| 73 | // and its dispatch carries the binding, the exploration flag and the |
| 74 | // specialist's brief. |
| 75 | func TestStartTaskRoutesToASpecialist(t *testing.T) { |
| 76 | r, l, _ := grantRig(t) |
| 77 | patrix := r.active(l, "Patrix", "p_patrix") |
| 78 | suite := r.active(l, "Suite", "p_suite") |
| 79 | team := r.active(l, "", "") |
| 80 | research := approvedResearch(r, paul) |
| 81 | turn, task := r.personTask(l, "Patrix", wire.KindChange) |
| 82 | start := func(id string) wire.ToolResult { |
| 83 | t.Helper() |
| 84 | return r.call(l, turn.ID, wire.ToolStartTask, map[string]any{"task": task, "brief": "Calmer type.", "specialist": id}) |
| 85 | } |
| 86 | for _, c := range []struct{ name, id, code string }{ |
| 87 | {"an unknown id", "sp_nobody", "specialist_unknown"}, |
| 88 | {"not a maker", research.ID, "specialist_not_maker"}, |
| 89 | {"another project's", suite.ID, "specialist_project"}, |
| 90 | {"the team's where the project has its own", team.ID, "specialist_no_grant"}, |
| 91 | } { |
| 92 | if res := start(c.id); !res.IsError || res.Code != c.code { |
| 93 | t.Fatalf("%s: %+v", c.name, res) |
| 94 | } |
| 95 | if n := r.stepsOf(task); n != 0 { |
| 96 | t.Fatalf("%s started %d steps", c.name, n) |
| 97 | } |
| 98 | } |
| 99 | // A grant that no longer holds, and a revoked specialist. |
| 100 | r.exec("UPDATE chat_capability_grants SET revoked_at = ? WHERE specialist_id = ? AND capability = ?", r.now, patrix.ID, specialist.CapabilityPageRender) |
| 101 | if res := start(patrix.ID); res.Code != "specialist_no_grant" || r.stepsOf(task) != 0 { |
| 102 | t.Fatalf("a grant that does not hold: %+v", res) |
| 103 | } |
| 104 | r.exec("UPDATE chat_capability_grants SET revoked_at = NULL WHERE specialist_id = ?", patrix.ID) |
| 105 | r.revoke(suite.ID) |
| 106 | _, suiteTask := r.personTask(l, "Suite", wire.KindChange) |
| 107 | if res := r.call(l, turn.ID, wire.ToolStartTask, map[string]any{"task": suiteTask, "brief": "b", "specialist": suite.ID}); res.Code != "specialist_unknown" || r.stepsOf(suiteTask) != 0 { |
| 108 | t.Fatalf("a revoked specialist: %+v", res) |
| 109 | } |
| 110 | |
| 111 | res := start(patrix.ID) |
| 112 | if res.IsError || res.Code != "started" || !strings.Contains(res.Text, "Design is working on it") { |
| 113 | t.Fatalf("start with Design: %+v", res) |
| 114 | } |
| 115 | k := r.load(task) |
| 116 | if k.MakerSpecialistID != patrix.ID || k.DesignRuns != 1 { |
| 117 | t.Fatalf("task %q runs %d", k.MakerSpecialistID, k.DesignRuns) |
| 118 | } |
| 119 | s := r.makerStep(task) |
| 120 | _, d := r.dispatched(s.ID) |
| 121 | if d.SpecialistID != patrix.ID || d.Profile != specialist.ProfileDesign || d.Explore || d.SpecialistBrief != "Overhaul the look." || !wire.ValidSpecialistBinding(&d) { |
| 122 | t.Fatalf("dispatch %+v", d) |
| 123 | } |
| 124 | if s.Specialist != wire.SpecialistEngineering { |
| 125 | t.Fatalf("step kind %q", s.Specialist) |
| 126 | } |
| 127 | // The team's Design works on a project with no row of its own, and an |
| 128 | // exploration says so to the runner. |
| 129 | r.must(r.s.db.G.Create(&projectRecord{ID: "p_fresh", Repo: repoFresh, Title: "Fresh", TitleSet: true, State: wire.ProjectActive, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}).Error) |
| 130 | turn2, fresh := r.personTask(l, "Fresh", wire.KindExplore) |
| 131 | if res := r.call(l, turn2.ID, wire.ToolStartTask, map[string]any{"task": fresh, "brief": "b", "specialist": team.ID}); res.IsError { |
| 132 | t.Fatalf("the team's Design on Fresh: %+v", res) |
| 133 | } |
| 134 | if _, d := r.dispatched(r.makerStep(fresh).ID); !d.Explore || d.SpecialistID != team.ID || d.SpecialistProject != "" { |
| 135 | t.Fatalf("an exploration's dispatch %+v", d) |
| 136 | } |
| 137 | // Without specialist it is Engineering, as before. |
| 138 | turn3, plain := r.personTask(l, "Patrix", wire.KindChange) |
| 139 | if res := r.call(l, turn3.ID, wire.ToolStartTask, map[string]any{"task": plain, "brief": "b"}); res.IsError || strings.Contains(res.Text, "Design") { |
| 140 | t.Fatalf("Engineering's start: %+v", res) |
| 141 | } |
| 142 | if k := r.load(plain); k.MakerSpecialistID != "" || k.DesignRuns != 0 { |
| 143 | t.Fatalf("Engineering's task %+v", k) |
| 144 | } |
| 145 | // A continuation bound to a specialist that is no maker (Research is |
| 146 | // team-only, so its card never queues one: a row written directly) |
| 147 | // starts nothing either. |
| 148 | r.must(r.s.db.G.Create(&turnRecord{ID: "t_bound", Person: paul, State: wire.TurnRunning, Attempt: 1, Kind: wire.TurnSpecialistAdded, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now, Lane: wire.LaneCoordinator}).Error) |
| 149 | r.must(r.s.db.G.Create(&specialistTurnRecord{CardID: "c_bound", TurnID: "t_bound", Person: paul, SpecialistID: research.ID, ProjectID: "p_patrix", CreatedAt: r.now}).Error) |
| 150 | bound := madeTask2(t, r.call(l, "t_bound", wire.ToolRecordTask, map[string]any{"repo": "Patrix", "title": "Look it up", "brief": "b"})) |
| 151 | if res := r.call(l, "t_bound", wire.ToolStartTask, map[string]any{"task": bound, "brief": "b", "specialist": research.ID}); res.Code != "specialist_not_maker" || r.stepsOf(bound) != 0 { |
| 152 | t.Fatalf("a bound start with no maker: %+v", res) |
| 153 | } |
| 154 | if specialist.MaxBrief != wire.MaxSpecialistBrief { |
| 155 | t.Fatalf("brief bounds %d and %d", specialist.MaxBrief, wire.MaxSpecialistBrief) |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | // TestStatusListsSpecialists: status lists the team's active specialists |
| 160 | // (id, profile, name, brief, scope) and the runner's renderer health. |
| 161 | func TestStatusListsSpecialists(t *testing.T) { |
| 162 | r, l, _ := grantRig(t) |
| 163 | patrix := r.active(l, "Patrix", "p_patrix") |
| 164 | gone := r.active(l, "Suite", "p_suite") |
| 165 | r.revoke(gone.ID) |
| 166 | research := approvedResearch(r, paul) |
| 167 | turn := r.asked(newID("t_"), wire.LaneCoordinator, "What can you do?") |
| 168 | res := r.call(l, turn.ID, wire.ToolStatus, map[string]any{}) |
| 169 | var out struct { |
| 170 | Runner struct { |
| 171 | Tools wire.ToolHealth `json:"tools"` |
| 172 | } `json:"runner"` |
| 173 | Specialists []specialistLine `json:"specialists"` |
| 174 | } |
| 175 | if err := json.Unmarshal([]byte(res.Text), &out); err != nil { |
| 176 | t.Fatal(err, res.Text) |
| 177 | } |
| 178 | if out.Runner.Tools.Renderer != wire.ToolHealthy { |
| 179 | t.Fatalf("renderer %q", out.Runner.Tools.Renderer) |
| 180 | } |
| 181 | want := []specialistLine{ |
| 182 | {ID: patrix.ID, Profile: specialist.ProfileDesign, Name: "Design", Brief: "Overhaul the look.", Scope: ProjectName(repoPatrix)}, |
| 183 | {ID: research.ID, Profile: specialist.ProfileResearch, Name: research.Name, Brief: research.Brief, Scope: "team"}, |
| 184 | } |
| 185 | if !slices.Equal(out.Specialists, want) { |
| 186 | t.Fatalf("specialists %+v", out.Specialists) |
| 187 | } |
| 188 | for _, key := range []string{`"id"`, `"profile"`, `"name"`, `"brief"`, `"scope"`} { |
| 189 | if !strings.Contains(res.Text, key) { |
| 190 | t.Fatalf("no %s in %s", key, res.Text) |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | // TestDesignPlacement: a Design step goes only to a runner at 38 whose |
| 196 | // renderer is ok and that holds a Claude connection of the person (not |
| 197 | // an API key's); otherwise it waits with design_runner, saying why, and |
| 198 | // nothing is sent. Placement sends it once the runner can. |
| 199 | func TestDesignPlacement(t *testing.T) { |
| 200 | r, l, _ := grantRig(t) |
| 201 | sp := r.active(l, "Patrix", "p_patrix") |
| 202 | r.setHello(wire.ProtocolMacEngineering, designHello(wire.ToolHealthy, claudeSub)) |
| 203 | turn, task := r.personTask(l, "Patrix", wire.KindChange) |
| 204 | if res := r.call(l, turn.ID, wire.ToolStartTask, map[string]any{"task": task, "brief": "b", "specialist": sp.ID}); res.IsError { |
| 205 | t.Fatal(res) |
| 206 | } |
| 207 | s := r.makerStep(task) |
| 208 | waits := func(what, reason string) { |
| 209 | t.Helper() |
| 210 | got := r.stepNow(s.ID) |
| 211 | if got.State != wire.StepQueued || got.Placement != wire.PlacementDesign || got.Reason != reason || got.RunnerID != "" || got.WaitingSince == nil { |
| 212 | t.Fatalf("%s: %+v", what, got) |
| 213 | } |
| 214 | if n := r.count("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", wire.FrameDispatch, `%"step_id":"`+s.ID+`"%`); n != 0 { |
| 215 | t.Fatalf("%s: %d dispatches", what, n) |
| 216 | } |
| 217 | if k := r.load(task); k.DesignRuns != 0 { |
| 218 | t.Fatalf("%s counted %d runs", what, k.DesignRuns) |
| 219 | } |
| 220 | } |
| 221 | place := func() { r.t.Helper(); r.must(r.tx(func(tx *txn) error { return tx.placeWaiting(paul) })) } |
| 222 | waits("a runner at 37", reasonDesignProtocol) |
| 223 | for _, c := range []struct { |
| 224 | what, renderer, reason string |
| 225 | conns []wire.HeldConnection |
| 226 | }{ |
| 227 | {"no renderer", "", reasonDesignRenderer, []wire.HeldConnection{claudeSub}}, |
| 228 | {"a renderer that does not match", wire.ToolMismatch, reasonDesignRenderer, []wire.HeldConnection{claudeSub}}, |
| 229 | {"no connection", wire.ToolHealthy, reasonDesignClaude, nil}, |
| 230 | {"Codex only", wire.ToolHealthy, reasonDesignClaude, []wire.HeldConnection{{LocalID: "codex-1", Person: paul, Provider: wire.ProviderCodex, Kind: wire.KindSubscription}}}, |
| 231 | {"a Claude API key only", wire.ToolHealthy, reasonDesignClaude, []wire.HeldConnection{{LocalID: "key-1", Person: paul, Provider: wire.ProviderClaude, Kind: wire.KindAPIKey}}}, |
| 232 | {"someone else's Claude", wire.ToolHealthy, reasonDesignClaude, []wire.HeldConnection{{LocalID: "claude-2", Person: "nora@tito.io", Provider: wire.ProviderClaude, Kind: wire.KindSubscription}}}, |
| 233 | } { |
| 234 | r.setHello(wire.ProtocolDesign, designHello(c.renderer, c.conns...)) |
| 235 | place() |
| 236 | waits(c.what, c.reason) |
| 237 | } |
| 238 | r.setHello(wire.ProtocolDesign, designHello(wire.ToolHealthy, claudeSub)) |
| 239 | place() |
| 240 | got := r.stepNow(s.ID) |
| 241 | if got.Placement != "" || got.Reason != "" || got.RunnerID != "RUNNER1" { |
| 242 | t.Fatalf("placed %+v", got) |
| 243 | } |
| 244 | if _, d := r.dispatched(s.ID); d.SpecialistID != sp.ID { |
| 245 | t.Fatalf("dispatch %+v", d) |
| 246 | } |
| 247 | if k := r.load(task); k.DesignRuns != 1 { |
| 248 | t.Fatalf("runs %d", k.DesignRuns) |
| 249 | } |
| 250 | // Engineering's own step is placed as before on that old runner. |
| 251 | r.setHello(wire.ProtocolMacEngineering, designHello("")) |
| 252 | plain := r.plainTask(l, "tk_plain") |
| 253 | if plain.Placement != "" || plain.RunnerID != "RUNNER1" { |
| 254 | t.Fatalf("Engineering waited %+v", plain) |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | // failAndRetry ends the task's maker step failed (its end proven) and |
| 259 | // retries it as Paul. |
| 260 | func (r *hkRig) failAndRetry(l Lease, task string) stepRecord { |
| 261 | r.t.Helper() |
| 262 | s := r.makerStep(task) |
| 263 | r.report(l, s, wire.StepReport{State: wire.StepFailed, Reason: "provider_failed", Termination: true}) |
| 264 | if _, err := r.s.RetryTask(r.ctx, paul, task); err != nil { |
| 265 | r.t.Fatal(err) |
| 266 | } |
| 267 | return r.makerStep(task) |
| 268 | } |
| 269 | |
| 270 | // heldCards are the task's held cards. |
| 271 | func (r *hkRig) heldCards(task string) []cardRecord { |
| 272 | r.t.Helper() |
| 273 | var cs []cardRecord |
| 274 | r.must(r.s.db.G.Where("task_id = ? AND kind = ?", task, wire.CardHeld).Order("created_at, id").Find(&cs).Error) |
| 275 | return cs |
| 276 | } |
| 277 | |
| 278 | // attemptSent reports whether a dispatch of the step's attempt was sent. |
| 279 | func (r *hkRig) attemptSent(s stepRecord) bool { |
| 280 | return r.count("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", wire.FrameDispatch, `%"step_id":"`+s.ID+`","attempt":`+itoa64(s.Attempt)+`,%`) > 0 |
| 281 | } |
| 282 | |
| 283 | // designTask starts a Patrix change with Design in a person turn. |
| 284 | func (r *hkRig) designTask(l Lease, sp specialistRecord, kind string) string { |
| 285 | r.t.Helper() |
| 286 | turn, task := r.personTask(l, "Patrix", kind) |
| 287 | if res := r.call(l, turn.ID, wire.ToolStartTask, map[string]any{"task": task, "brief": "b", "specialist": sp.ID}); res.IsError { |
| 288 | r.t.Fatal(res) |
| 289 | } |
| 290 | return task |
| 291 | } |
| 292 | |
| 293 | // TestDesignLimitHoldsTheFourth: three Design attempts (the first run and |
| 294 | // two retries) go; the fourth is not dispatched and is held for the |
| 295 | // person through the held-step card, which offers only Run it now; the |
| 296 | // tap sends it and counts again from there. |
| 297 | func TestDesignLimitHoldsTheFourth(t *testing.T) { |
| 298 | r, l, _ := grantRig(t) |
| 299 | sp := r.active(l, "Patrix", "p_patrix") |
| 300 | task := r.designTask(l, sp, wire.KindChange) |
| 301 | r.failAndRetry(l, task) |
| 302 | third := r.failAndRetry(l, task) |
| 303 | if !r.attemptSent(third) || r.load(task).DesignRuns != 3 { |
| 304 | t.Fatalf("third attempt %+v runs %d", third, r.load(task).DesignRuns) |
| 305 | } |
| 306 | fourth := r.failAndRetry(l, task) |
| 307 | if r.attemptSent(fourth) || fourth.State != wire.StepQueued || fourth.Placement != wire.PlacementDesignLimit || fourth.Reason != reasonDesignLimit || fourth.RunnerID != "" { |
| 308 | t.Fatalf("fourth attempt %+v", fourth) |
| 309 | } |
| 310 | if h := stepHold(fourth); h == nil || h.Reason != wire.HoldDesignLimit || h.NeedsPerson != wire.HoldDesignLimit || h.StepRevision != fourth.Attempt { |
| 311 | t.Fatalf("hold %+v", h) |
| 312 | } |
| 313 | if k := r.load(task); k.DesignRuns != 3 { |
| 314 | t.Fatalf("runs %d", k.DesignRuns) |
| 315 | } |
| 316 | cards := r.heldCards(task) |
| 317 | if len(cards) != 1 || cards[0].State != wire.CardOpen || cards[0].Options != `["run_now"]` || cards[0].Person != paul || cards[0].Question != "Design has tried this 3 times since you last responded, so I’ve paused it. Run it again?" { |
| 318 | t.Fatalf("held cards %+v", cards) |
| 319 | } |
| 320 | var v wire.Task |
| 321 | r.must(r.tx(func(tx *txn) error { |
| 322 | var err error |
| 323 | v, err = tx.taskView(r.load(task)) |
| 324 | return err |
| 325 | })) |
| 326 | if v.NeedsYou != wire.NeedsHeld { |
| 327 | t.Fatalf("needs you %q", v.NeedsYou) |
| 328 | } |
| 329 | // Placement passes leave it held, with its one card. |
| 330 | r.must(r.tx(func(tx *txn) error { return tx.placeWaiting(paul) })) |
| 331 | if got := r.stepNow(fourth.ID); r.attemptSent(got) || got.Placement != wire.PlacementDesignLimit || len(r.heldCards(task)) != 1 { |
| 332 | t.Fatalf("after placement %+v", got) |
| 333 | } |
| 334 | // Wait is not offered. |
| 335 | if _, _, err := r.s.Answer(r.ctx, paul, cards[0].ID, wire.AnswerCard{Choice: ChoiceWait, Revision: cards[0].Revision}); !errors.Is(err, ErrInvalid) { |
| 336 | t.Fatalf("wait: %v", err) |
| 337 | } |
| 338 | if _, _, err := r.s.Answer(r.ctx, paul, cards[0].ID, wire.AnswerCard{Choice: ChoiceRunNow, Revision: cards[0].Revision}); err != nil { |
| 339 | t.Fatal(err) |
| 340 | } |
| 341 | got := r.stepNow(fourth.ID) |
| 342 | if !r.attemptSent(got) || got.Placement != "" || got.Reason != "" || got.Hold != "" || got.RunnerID != "RUNNER1" { |
| 343 | t.Fatalf("after Run it now %+v", got) |
| 344 | } |
| 345 | if c := r.heldCards(task); len(c) != 1 || c[0].State != wire.CardAnswered || c[0].Choice != ChoiceRunNow { |
| 346 | t.Fatalf("held card after the tap %+v", c) |
| 347 | } |
| 348 | if k := r.load(task); k.DesignRuns != 1 { |
| 349 | t.Fatalf("runs after the tap %d", k.DesignRuns) |
| 350 | } |
| 351 | // Run it now on the task page (the run-now route) is the same act. |
| 352 | r.failAndRetry(l, task) |
| 353 | r.failAndRetry(l, task) |
| 354 | held := r.failAndRetry(l, task) |
| 355 | h := stepHold(held) |
| 356 | if r.attemptSent(held) || h == nil { |
| 357 | t.Fatalf("not held again %+v", held) |
| 358 | } |
| 359 | if _, err := r.s.RunNow(r.ctx, paul, task, wire.RunNow{Step: held.ID, StepRevision: h.StepRevision}); err != nil { |
| 360 | t.Fatal(err) |
| 361 | } |
| 362 | if got := r.stepNow(held.ID); !r.attemptSent(got) || r.load(task).DesignRuns != 1 { |
| 363 | t.Fatalf("after the run-now route %+v, runs %d", got, r.load(task).DesignRuns) |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | // TestDesignLimitResetByAMessage: a message in the task's thread is its |
| 368 | // person acting: the count starts again, and a step the limit held goes |
| 369 | // at once, its card resolved. |
| 370 | func TestDesignLimitResetByAMessage(t *testing.T) { |
| 371 | r, l, _ := grantRig(t) |
| 372 | sp := r.active(l, "Patrix", "p_patrix") |
| 373 | task := r.designTask(l, sp, wire.KindChange) |
| 374 | r.failAndRetry(l, task) |
| 375 | post := func(text string) { |
| 376 | t.Helper() |
| 377 | if _, err := r.s.PostThread(r.ctx, paul, task, wire.PostThread{Text: text, IdempotencyKey: newID("k")}); err != nil { |
| 378 | t.Fatal(err) |
| 379 | } |
| 380 | } |
| 381 | post("Keep the logo.") |
| 382 | if k := r.load(task); k.DesignRuns != 0 { |
| 383 | t.Fatalf("runs after a message %d", k.DesignRuns) |
| 384 | } |
| 385 | for i := 0; i < 3; i++ { |
| 386 | if s := r.failAndRetry(l, task); !r.attemptSent(s) { |
| 387 | t.Fatalf("attempt %d after the message held %+v", i+1, s) |
| 388 | } |
| 389 | } |
| 390 | held := r.failAndRetry(l, task) |
| 391 | if r.attemptSent(held) || held.Placement != wire.PlacementDesignLimit { |
| 392 | t.Fatalf("not held %+v", held) |
| 393 | } |
| 394 | // An answer on one of its cards is the person acting too. |
| 395 | q := cardRecord{ID: "c_q", Person: paul, Kind: wire.CardQuestion, State: wire.CardOpen, TaskID: task, Question: "Which logo?", Options: `["The old one"]`, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now, Lane: wire.LaneCoordinator} |
| 396 | r.must(r.s.db.G.Create(&q).Error) |
| 397 | if _, _, err := r.s.Answer(r.ctx, paul, q.ID, wire.AnswerCard{Choice: "The old one", Revision: 1}); err != nil { |
| 398 | t.Fatal(err) |
| 399 | } |
| 400 | if got := r.stepNow(held.ID); !r.attemptSent(got) || got.Placement != "" || r.load(task).DesignRuns != 1 { |
| 401 | t.Fatalf("after an answer on its card %+v", got) |
| 402 | } |
| 403 | r.failAndRetry(l, task) |
| 404 | r.failAndRetry(l, task) |
| 405 | held = r.failAndRetry(l, task) |
| 406 | if r.attemptSent(held) || held.Placement != wire.PlacementDesignLimit { |
| 407 | t.Fatalf("not held again %+v", held) |
| 408 | } |
| 409 | post("Go on.") |
| 410 | got := r.stepNow(held.ID) |
| 411 | if !r.attemptSent(got) || got.Placement != "" || got.Hold != "" { |
| 412 | t.Fatalf("after a message %+v", got) |
| 413 | } |
| 414 | if c := r.heldCards(task); len(c) != 2 || c[1].State != wire.CardResolved { |
| 415 | t.Fatalf("held card after a message %+v", c) |
| 416 | } |
| 417 | if k := r.load(task); k.DesignRuns != 1 { |
| 418 | t.Fatalf("runs %d", k.DesignRuns) |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | // directionCard takes the exploration's maker step to done with a |
| 423 | // candidate, and its review to approve: the direction card is open. |
| 424 | func (r *hkRig) directionCard(l Lease, task string, verdict string) cardRecord { |
| 425 | r.t.Helper() |
| 426 | s := r.makerStep(task) |
| 427 | r.pushed(l, s) |
| 428 | var review stepRecord |
| 429 | r.must(r.s.db.G.Where("task_id = ? AND specialist = ?", task, wire.SpecialistReview).Order("idx DESC").First(&review).Error) |
| 430 | r.report(l, review, wire.StepReport{State: wire.StepDone, CandidateSHA: candidateSHA, Verdict: verdict, ReviewLabel: wire.ReviewOtherFamily, Termination: true, Findings: []wire.Finding{}}) |
| 431 | var c cardRecord |
| 432 | if verdict == wire.VerdictApprove { |
| 433 | r.must(r.s.db.G.Where("task_id = ? AND kind = ? AND state = ?", task, wire.CardDirection, wire.CardOpen).First(&c).Error) |
| 434 | } |
| 435 | return c |
| 436 | } |
| 437 | |
| 438 | // pushed reports the maker step's candidate, then its done and pushed |
| 439 | // end, proven. |
| 440 | func (r *hkRig) pushed(l Lease, s stepRecord) { |
| 441 | r.t.Helper() |
| 442 | r.report(l, s, wire.StepReport{State: wire.StepRunning, BaseSHA: strings.Repeat("b", 40), CandidateSHA: candidateSHA}) |
| 443 | r.report(l, s, wire.StepReport{State: wire.StepDone, BaseSHA: strings.Repeat("b", 40), CandidateSHA: candidateSHA, Pushed: true, Termination: true}) |
| 444 | } |
| 445 | |
| 446 | // TestDesignKeepsTheTask: a fix round, Try again and the task Build this |
| 447 | // makes all run as the task's Design, bound and dispatched as Design (the |
| 448 | // step kind stays engineering); an answer on the direction card is the |
| 449 | // person acting. |
| 450 | func TestDesignKeepsTheTask(t *testing.T) { |
| 451 | r, l, _ := grantRig(t) |
| 452 | // The direction card reads the person's runners (previews). |
| 453 | r.exec("CREATE TABLE IF NOT EXISTS runners (id text PRIMARY KEY, person text, role text, label text, removing_at datetime, tainted_at datetime, revoked_at datetime)") |
| 454 | r.exec("INSERT INTO runners(id, person, role) VALUES ('RUNNER1', ?, ?)", paul, wire.RolePrimary) |
| 455 | sp := r.active(l, "Patrix", "p_patrix") |
| 456 | task := r.designTask(l, sp, wire.KindExplore) |
| 457 | r.directionCard(l, task, wire.VerdictChanges) |
| 458 | fix := r.makerStep(task) |
| 459 | if fix.Round != 1 || fix.SpecialistID != sp.ID || fix.Specialist != wire.SpecialistEngineering { |
| 460 | t.Fatalf("fix round %+v", fix) |
| 461 | } |
| 462 | if _, d := r.dispatched(fix.ID); d.SpecialistID != sp.ID || !d.Explore { |
| 463 | t.Fatalf("fix round's dispatch %+v", d) |
| 464 | } |
| 465 | c := r.directionCard(l, task, wire.VerdictApprove) |
| 466 | if k := r.load(task); k.DesignRuns != 2 { |
| 467 | t.Fatalf("runs before Try again %d", k.DesignRuns) |
| 468 | } |
| 469 | if _, _, err := r.s.Answer(r.ctx, paul, c.ID, wire.AnswerCard{Choice: wire.ChoiceAgain, Note: "Warmer.", Revision: c.Revision}); err != nil { |
| 470 | t.Fatal(err) |
| 471 | } |
| 472 | again := r.makerStep(task) |
| 473 | if again.ID == fix.ID || again.SpecialistID != sp.ID || again.Specialist != wire.SpecialistEngineering { |
| 474 | t.Fatalf("Try again %+v", again) |
| 475 | } |
| 476 | if _, d := r.dispatched(again.ID); d.SpecialistID != sp.ID || d.Profile != specialist.ProfileDesign { |
| 477 | t.Fatalf("Try again's dispatch %+v", d) |
| 478 | } |
| 479 | if k := r.load(task); k.DesignRuns != 1 { |
| 480 | t.Fatalf("runs after Try again %d (the answer is the person acting)", k.DesignRuns) |
| 481 | } |
| 482 | c = r.directionCard(l, task, wire.VerdictApprove) |
| 483 | if _, _, err := r.s.Answer(r.ctx, paul, c.ID, wire.AnswerCard{Choice: wire.ChoiceBuild, Revision: c.Revision}); err != nil { |
| 484 | t.Fatal(err) |
| 485 | } |
| 486 | built := r.load(task).BuiltAs |
| 487 | n := r.load(built) |
| 488 | if n.MakerSpecialistID != sp.ID || n.Kind != wire.KindChange || n.DesignRuns != 1 { |
| 489 | t.Fatalf("Build's task %+v", n) |
| 490 | } |
| 491 | b := r.makerStep(built) |
| 492 | if _, d := r.dispatched(b.ID); b.SpecialistID != sp.ID || d.SpecialistID != sp.ID || d.Explore { |
| 493 | t.Fatalf("Build's dispatch %+v %+v", b, d) |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | // recoveryCards are the task's recovery cards. |
| 498 | func (r *hkRig) recoveryCards(task string) []cardRecord { |
| 499 | r.t.Helper() |
| 500 | var cs []cardRecord |
| 501 | r.must(r.s.db.G.Where("task_id = ? AND kind = ?", task, wire.CardMakerRemoved).Find(&cs).Error) |
| 502 | return cs |
| 503 | } |
| 504 | |
| 505 | // runningDesign is a Design task in Patrix of kind whose attempt its |
| 506 | // runner took and started. |
| 507 | func (r *hkRig) runningDesign(l Lease, sp specialistRecord, kind string) (string, stepRecord) { |
| 508 | r.t.Helper() |
| 509 | task := r.designTask(l, sp, kind) |
| 510 | s := r.makerStep(task) |
| 511 | r.ackDispatches(s.ID) |
| 512 | if refused := r.authorize(l, s, ""); refused != "" { |
| 513 | r.t.Fatalf("start %q", refused) |
| 514 | } |
| 515 | return task, r.stepNow(s.ID) |
| 516 | } |
| 517 | |
| 518 | // TestDesignRecoveryWaitsForTheProof: after a revoke the recovery card |
| 519 | // waits until every attempt of the task's Design steps has ended with |
| 520 | // its termination proof, cancelled or done: a terminal report without |
| 521 | // the proof raises nothing, even with nothing else at work; the proof |
| 522 | // raises one card, once. |
| 523 | func TestDesignRecoveryWaitsForTheProof(t *testing.T) { |
| 524 | for _, state := range []string{wire.StepCancelled, wire.StepDone} { |
| 525 | t.Run(state, func(t *testing.T) { |
| 526 | r, l, _ := grantRig(t) |
| 527 | sp := r.active(l, "Patrix", "p_patrix") |
| 528 | task, s := r.runningDesign(l, sp, wire.KindExplore) |
| 529 | end := wire.StepReport{State: wire.StepCancelled, Reason: "cancelled"} |
| 530 | if state == wire.StepDone { |
| 531 | r.report(l, s, wire.StepReport{State: wire.StepRunning, BaseSHA: strings.Repeat("b", 40), CandidateSHA: candidateSHA}) |
| 532 | end = wire.StepReport{State: wire.StepDone, BaseSHA: strings.Repeat("b", 40), CandidateSHA: candidateSHA, Pushed: true} |
| 533 | } |
| 534 | r.revoke(sp.ID) |
| 535 | if n := len(r.recoveryCards(task)); n != 0 || r.cancels(s.ID) != 1 { |
| 536 | t.Fatalf("a running step: %d cards, %d cancels", n, r.cancels(s.ID)) |
| 537 | } |
| 538 | r.report(l, s, end) |
| 539 | if got := r.stepNow(s.ID); got.State != state || got.Terminated { |
| 540 | t.Fatalf("its end %+v", got) |
| 541 | } |
| 542 | // Nothing else at work (a Review of the candidate ended too). |
| 543 | r.exec("UPDATE chat_steps SET state = ?, terminated = 1 WHERE task_id = ? AND specialist <> ?", wire.StepDone, task, wire.SpecialistEngineering) |
| 544 | r.must(r.tx(func(tx *txn) error { return tx.offerRecovery(task) })) |
| 545 | if n := len(r.recoveryCards(task)); n != 0 { |
| 546 | t.Fatalf("%d cards before the proof", n) |
| 547 | } |
| 548 | proof := end |
| 549 | proof.Termination = true |
| 550 | r.report(l, s, proof) |
| 551 | if got := r.stepNow(s.ID); !got.Terminated { |
| 552 | t.Fatalf("proof %+v", got) |
| 553 | } |
| 554 | cards := r.recoveryCards(task) |
| 555 | if len(cards) != 1 || cards[0].State != wire.CardOpen || cards[0].Person != paul || cards[0].Options != `["to_engineering"]` || cards[0].Lane != r.load(task).Lane || cards[0].Question != "Design was removed. Hand this task to Engineering?" { |
| 556 | t.Fatalf("cards after the proof %+v", cards) |
| 557 | } |
| 558 | r.report(l, s, proof) |
| 559 | r.must(r.tx(func(tx *txn) error { return tx.offerRecovery(task) })) |
| 560 | if n := len(r.recoveryCards(task)); n != 1 { |
| 561 | t.Fatalf("%d cards, once was enough", n) |
| 562 | } |
| 563 | }) |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | // TestDesignRecoveryAtRevoke: a task whose Design steps had all ended, |
| 568 | // proven, is asked about in the revoke itself; one whose maker is still |
| 569 | // on the team is never asked. |
| 570 | func TestDesignRecoveryAtRevoke(t *testing.T) { |
| 571 | r, l, _ := grantRig(t) |
| 572 | sp := r.active(l, "Patrix", "p_patrix") |
| 573 | task, s := r.runningDesign(l, sp, wire.KindChange) |
| 574 | r.report(l, s, wire.StepReport{State: wire.StepFailed, Reason: "provider_failed", Termination: true}) |
| 575 | r.must(r.tx(func(tx *txn) error { return tx.offerRecovery(task) })) |
| 576 | if n := len(r.recoveryCards(task)); n != 0 { |
| 577 | t.Fatalf("%d cards while Design is on the team", n) |
| 578 | } |
| 579 | // A task cancelled meanwhile is not asked about. |
| 580 | cancelled, c := r.runningDesign(l, sp, wire.KindChange) |
| 581 | r.report(l, c, wire.StepReport{State: wire.StepFailed, Reason: "provider_failed", Termination: true}) |
| 582 | if _, err := r.s.CancelTask(r.ctx, paul, cancelled); err != nil { |
| 583 | t.Fatal(err) |
| 584 | } |
| 585 | // A running one whose runner's sync proves it ended (interrupted). |
| 586 | synced, y := r.runningDesign(l, sp, wire.KindChange) |
| 587 | r.revoke(sp.ID) |
| 588 | if n := len(r.recoveryCards(task)); n != 1 { |
| 589 | t.Fatalf("%d cards at the revoke", n) |
| 590 | } |
| 591 | if n := len(r.recoveryCards(cancelled)); n != 0 || !wire.FinalStage(r.load(cancelled).Stage) { |
| 592 | t.Fatalf("%d cards for a cancelled task", n) |
| 593 | } |
| 594 | if n := len(r.recoveryCards(synced)); n != 0 { |
| 595 | t.Fatalf("%d cards for a running step", n) |
| 596 | } |
| 597 | r.must(r.tx(func(tx *txn) error { return tx.syncSteps(l, nil) })) |
| 598 | if got := r.stepNow(y.ID); !got.Terminated || len(r.recoveryCards(synced)) != 1 { |
| 599 | t.Fatalf("after the sync %+v, %d cards", got, len(r.recoveryCards(synced))) |
| 600 | } |
| 601 | } |
| 602 | |
| 603 | // TestDesignRecoveryTap: the creator's tap is checked again in its |
| 604 | // transaction (every attempt ended with its proof, nothing at work); it |
| 605 | // then clears the maker and queues Engineering, unbound. |
| 606 | func TestDesignRecoveryTap(t *testing.T) { |
| 607 | r, l, _ := grantRig(t) |
| 608 | sp := r.active(l, "Patrix", "p_patrix") |
| 609 | task, s := r.runningDesign(l, sp, wire.KindChange) |
| 610 | r.revoke(sp.ID) |
| 611 | r.report(l, s, wire.StepReport{State: wire.StepCancelled, Reason: "cancelled", Termination: true}) |
| 612 | cards := r.recoveryCards(task) |
| 613 | if len(cards) != 1 { |
| 614 | t.Fatalf("cards %+v", cards) |
| 615 | } |
| 616 | c := cards[0] |
| 617 | tap := func() error { |
| 618 | _, _, err := r.s.Answer(r.ctx, paul, c.ID, wire.AnswerCard{Choice: wire.ChoiceToEngineering, Revision: c.Revision}) |
| 619 | return err |
| 620 | } |
| 621 | unchanged := func(what string) { |
| 622 | t.Helper() |
| 623 | if k := r.load(task); k.MakerSpecialistID != sp.ID || r.count("SELECT count(*) FROM chat_steps WHERE task_id = ? AND specialist = ?", task, wire.SpecialistEngineering) != 1 { |
| 624 | t.Fatalf("%s changed the task %+v", what, k) |
| 625 | } |
| 626 | if got := r.recoveryCards(task); got[0].State != wire.CardOpen { |
| 627 | t.Fatalf("%s answered the card", what) |
| 628 | } |
| 629 | } |
| 630 | // An attempt that ended without its proof (done or cancelled). |
| 631 | for _, state := range []string{wire.StepCancelled, wire.StepDone} { |
| 632 | r.exec("UPDATE chat_steps SET state = ?, terminated = 0 WHERE id = ?", state, s.ID) |
| 633 | if err := tap(); !errors.Is(err, ErrCardConflict) { |
| 634 | t.Fatalf("a %s attempt without its proof: %v", state, err) |
| 635 | } |
| 636 | unchanged("an unproven " + state) |
| 637 | } |
| 638 | // Then its proof arrives. |
| 639 | r.report(l, s, wire.StepReport{State: wire.StepDone, Termination: true}) |
| 640 | if got := r.stepNow(s.ID); !got.Terminated { |
| 641 | t.Fatalf("proof %+v", got) |
| 642 | } |
| 643 | // Something else at work on the task. |
| 644 | r.must(r.s.db.G.Create(&stepRecord{ID: "s_review", TaskID: task, Idx: s.Idx + 1, Specialist: wire.SpecialistReview, Person: paul, State: wire.StepQueued, Attempt: 1, RunnerID: "RUNNER1", CreatedAt: r.now, UpdatedAt: r.now}).Error) |
| 645 | if err := tap(); !errors.Is(err, ErrCardConflict) { |
| 646 | t.Fatalf("with a step at work: %v", err) |
| 647 | } |
| 648 | r.exec("UPDATE chat_steps SET state = ?, terminated = 1 WHERE id = ?", wire.StepDone, "s_review") |
| 649 | // Not the creator's card: not found for another person; nor theirs |
| 650 | // to answer even when it reaches them. |
| 651 | if _, _, err := r.s.Answer(r.ctx, "nora@tito.io", c.ID, wire.AnswerCard{Choice: wire.ChoiceToEngineering, Revision: c.Revision}); err == nil { |
| 652 | t.Fatal("another person tapped it") |
| 653 | } |
| 654 | r.exec("INSERT INTO members(address, active, role) VALUES (?, 1, 'owner')", "nora@tito.io") |
| 655 | if err := r.tx(func(tx *txn) error { |
| 656 | other := c |
| 657 | other.Person = "nora@tito.io" |
| 658 | _, _, err := tx.answerMakerRemoved("nora@tito.io", other, wire.AnswerCard{Choice: wire.ChoiceToEngineering, Revision: c.Revision}) |
| 659 | return err |
| 660 | }); !errors.Is(err, ErrForbidden) { |
| 661 | t.Fatalf("another owner: %v", err) |
| 662 | } |
| 663 | // The creator is no longer an owner. |
| 664 | r.exec("UPDATE members SET role = 'member' WHERE address = ?", paul) |
| 665 | if err := tap(); err == nil { |
| 666 | t.Fatal("a member tapped it") |
| 667 | } |
| 668 | r.exec("UPDATE members SET role = 'owner' WHERE address = ?", paul) |
| 669 | unchanged("a member's tap") |
| 670 | // A stale revision. |
| 671 | if _, _, err := r.s.Answer(r.ctx, paul, c.ID, wire.AnswerCard{Choice: wire.ChoiceToEngineering, Revision: c.Revision + 1}); !errors.Is(err, ErrCardConflict) { |
| 672 | t.Fatalf("a stale revision: %v", err) |
| 673 | } |
| 674 | unchanged("a stale revision") |
| 675 | if err := tap(); err != nil { |
| 676 | t.Fatal(err) |
| 677 | } |
| 678 | k := r.load(task) |
| 679 | if k.MakerSpecialistID != "" || k.DesignRuns != 0 || k.Stage != wire.StageInProgress { |
| 680 | t.Fatalf("task after the tap %+v", k) |
| 681 | } |
| 682 | eng := r.makerStep(task) |
| 683 | if eng.ID == s.ID || eng.SpecialistID != "" || eng.State != wire.StepQueued || eng.RunnerID != "RUNNER1" { |
| 684 | t.Fatalf("Engineering %+v", eng) |
| 685 | } |
| 686 | if _, d := r.dispatched(eng.ID); d.SpecialistID != "" || d.Profile != "" || d.Explore || d.SpecialistBrief != "" { |
| 687 | t.Fatalf("Engineering's dispatch is bound %+v", d) |
| 688 | } |
| 689 | if got := r.recoveryCards(task); got[0].State != wire.CardAnswered || got[0].Choice != wire.ChoiceToEngineering { |
| 690 | t.Fatalf("card %+v", got[0]) |
| 691 | } |
| 692 | if err := tap(); !errors.Is(err, ErrCardConflict) { |
| 693 | t.Fatalf("a second tap: %v", err) |
| 694 | } |
| 695 | } |
| 696 | |
| 697 | // liveMakerStep is the task's newest Engineering step that is not retired |
| 698 | // (a move retires the old ones and numbers anew). |
| 699 | func (r *hkRig) liveMakerStep(task string) stepRecord { |
| 700 | r.t.Helper() |
| 701 | var s stepRecord |
| 702 | r.must(r.s.db.G.Where("task_id = ? AND specialist = ? AND coalesce(retired, 0) = 0", task, wire.SpecialistEngineering).Order("idx DESC, created_at DESC").First(&s).Error) |
| 703 | return s |
| 704 | } |
| 705 | |
| 706 | // TestDesignRecoveryAfterAMove: the card comes whenever the task's maker |
| 707 | // no longer acts for its project, not only after a revoke. A Design task |
| 708 | // moved to a project its Design does not cover is asked about once its |
| 709 | // attempt ended with its proof (its restarted step ended at dispatch); |
| 710 | // one whose maker still resolves after the move (the team's Design) is |
| 711 | // not, and its restarted step runs as that maker. |
| 712 | func TestDesignRecoveryAfterAMove(t *testing.T) { |
| 713 | r, l, _ := grantRig(t) |
| 714 | r.exec("CREATE TABLE IF NOT EXISTS runners (id text PRIMARY KEY, person text, role text, label text, removing_at datetime, tainted_at datetime, revoked_at datetime)") |
| 715 | r.exec("INSERT INTO runners(id, person, role) VALUES ('RUNNER1', ?, ?)", paul, wire.RolePrimary) |
| 716 | patrix := r.active(l, "Patrix", "p_patrix") |
| 717 | task, s := r.runningDesign(l, patrix, wire.KindChange) |
| 718 | k := r.load(task) |
| 719 | if err := r.s.MoveTask(r.ctx, paul, task, wire.MoveTask{Repo: repoSuite, Revision: k.Revision}); err != nil { |
| 720 | t.Fatal(err) |
| 721 | } |
| 722 | if n := len(r.recoveryCards(task)); n != 0 { |
| 723 | t.Fatalf("%d cards while the attempt runs", n) |
| 724 | } |
| 725 | r.report(l, s, wire.StepReport{State: wire.StepCancelled, Reason: "cancelled"}) |
| 726 | if n := len(r.recoveryCards(task)); n != 0 { |
| 727 | t.Fatalf("%d cards before the proof", n) |
| 728 | } |
| 729 | r.report(l, s, wire.StepReport{State: wire.StepCancelled, Reason: "cancelled", Termination: true}) |
| 730 | k = r.load(task) |
| 731 | if k.ProjectID != "p_suite" || k.MakerSpecialistID != patrix.ID { |
| 732 | t.Fatalf("after the move %+v", k) |
| 733 | } |
| 734 | if got := r.liveMakerStep(task); got.ID == s.ID || got.State != wire.StepCancelled || got.Reason != reasonSpecialistNoGrant || !got.Terminated { |
| 735 | t.Fatalf("the restarted step %+v", got) |
| 736 | } |
| 737 | cards := r.recoveryCards(task) |
| 738 | if len(cards) != 1 || cards[0].State != wire.CardOpen { |
| 739 | t.Fatalf("cards after the move %+v", cards) |
| 740 | } |
| 741 | c := cards[0] |
| 742 | if _, _, err := r.s.Answer(r.ctx, paul, c.ID, wire.AnswerCard{Choice: wire.ChoiceToEngineering, Revision: c.Revision}); err != nil { |
| 743 | t.Fatal(err) |
| 744 | } |
| 745 | if k := r.load(task); k.MakerSpecialistID != "" { |
| 746 | t.Fatalf("after the tap %+v", k) |
| 747 | } |
| 748 | |
| 749 | // The team's Design still covers Suite's task moved to Fresh. |
| 750 | team := r.active(l, "", "") |
| 751 | r.must(r.s.db.G.Create(&projectRecord{ID: "p_fresh", Repo: repoFresh, Title: "Fresh", TitleSet: true, State: wire.ProjectActive, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}).Error) |
| 752 | turn, kept := r.personTask(l, "Suite", wire.KindChange) |
| 753 | if res := r.call(l, turn.ID, wire.ToolStartTask, map[string]any{"task": kept, "brief": "b", "specialist": team.ID}); res.IsError { |
| 754 | t.Fatal(res) |
| 755 | } |
| 756 | ks := r.makerStep(kept) |
| 757 | r.ackDispatches(ks.ID) |
| 758 | if refused := r.authorize(l, ks, ""); refused != "" { |
| 759 | t.Fatalf("start %q", refused) |
| 760 | } |
| 761 | kk := r.load(kept) |
| 762 | if err := r.s.MoveTask(r.ctx, paul, kept, wire.MoveTask{Repo: repoFresh, Revision: kk.Revision}); err != nil { |
| 763 | t.Fatal(err) |
| 764 | } |
| 765 | r.report(l, r.stepNow(ks.ID), wire.StepReport{State: wire.StepCancelled, Reason: "cancelled", Termination: true}) |
| 766 | if n := len(r.recoveryCards(kept)); n != 0 { |
| 767 | t.Fatalf("%d cards for a maker that still resolves", n) |
| 768 | } |
| 769 | if got := r.liveMakerStep(kept); got.ID == ks.ID || got.SpecialistID != team.ID || got.State != wire.StepQueued { |
| 770 | t.Fatalf("the restarted step %+v", got) |
| 771 | } |
| 772 | |
| 773 | // The team's Design does not stand in where a project has its own: |
| 774 | // moved to Patrix, the team-made task is asked about. |
| 775 | turn2, toPatrix := r.personTask(l, "Suite", wire.KindChange) |
| 776 | if res := r.call(l, turn2.ID, wire.ToolStartTask, map[string]any{"task": toPatrix, "brief": "b", "specialist": team.ID}); res.IsError { |
| 777 | t.Fatal(res) |
| 778 | } |
| 779 | ps := r.makerStep(toPatrix) |
| 780 | r.ackDispatches(ps.ID) |
| 781 | if refused := r.authorize(l, ps, ""); refused != "" { |
| 782 | t.Fatalf("start %q", refused) |
| 783 | } |
| 784 | if err := r.s.MoveTask(r.ctx, paul, toPatrix, wire.MoveTask{Repo: repoPatrix, Revision: r.load(toPatrix).Revision}); err != nil { |
| 785 | t.Fatal(err) |
| 786 | } |
| 787 | r.report(l, r.stepNow(ps.ID), wire.StepReport{State: wire.StepCancelled, Reason: "cancelled", Termination: true}) |
| 788 | if n := len(r.recoveryCards(toPatrix)); n != 1 { |
| 789 | t.Fatalf("%d cards for the team's Design moved to Patrix", n) |
| 790 | } |
| 791 | } |
| 792 | |
| 793 | // TestDesignRecoverySweep: a maker that stops resolving with no step |
| 794 | // event (its grant no longer holds) is found by the placement pass; a |
| 795 | // task whose maker resolves is not. |
| 796 | func TestDesignRecoverySweep(t *testing.T) { |
| 797 | r, l, _ := grantRig(t) |
| 798 | r.exec("CREATE TABLE IF NOT EXISTS runners (id text PRIMARY KEY, person text, role text, label text, removing_at datetime, tainted_at datetime, revoked_at datetime)") |
| 799 | sp := r.active(l, "Patrix", "p_patrix") |
| 800 | task, s := r.runningDesign(l, sp, wire.KindChange) |
| 801 | r.report(l, s, wire.StepReport{State: wire.StepFailed, Reason: "provider_failed", Termination: true}) |
| 802 | r.must(r.s.Place(r.ctx)) |
| 803 | if n := len(r.recoveryCards(task)); n != 0 { |
| 804 | t.Fatalf("%d cards while the maker resolves", n) |
| 805 | } |
| 806 | r.exec("UPDATE chat_capability_grants SET revoked_at = ? WHERE specialist_id = ? AND capability = ?", r.now, sp.ID, specialist.CapabilityPageRender) |
| 807 | r.must(r.s.Place(r.ctx)) |
| 808 | r.must(r.s.Place(r.ctx)) |
| 809 | if n := len(r.recoveryCards(task)); n != 1 { |
| 810 | t.Fatalf("%d cards after the grant stopped holding", n) |
| 811 | } |
| 812 | // The Assistant hears of it as a card that stops the work: a job |
| 813 | // whose thread holds one is blocked by it. |
| 814 | if !blocksWork(wire.CardMakerRemoved, wire.CardOpen) || blocksWork(wire.CardMakerRemoved, wire.CardAnswered) { |
| 815 | t.Fatal("the recovery card does not stop the work") |
| 816 | } |
| 817 | h := handoffRecord{ID: "h_design1", Person: paul, LedgerKey: "k_design1", State: handoffOpen, Lane: wire.JobLane("h_design1"), CreatedAt: r.now, UpdatedAt: r.now} |
| 818 | r.must(r.s.db.G.Create(&h).Error) |
| 819 | r.must(r.s.db.G.Create(&cardRecord{ID: "c_job_maker", Person: paul, Kind: wire.CardMakerRemoved, State: wire.CardOpen, TaskID: task, Name: "maker:x", Options: `["to_engineering"]`, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now, Lane: h.Lane}).Error) |
| 820 | r.must(r.tx(func(tx *txn) error { |
| 821 | kind, err := tx.blockingCard(h) |
| 822 | if err == nil && kind != wire.CardMakerRemoved { |
| 823 | t.Fatalf("the job's blocking card %q", kind) |
| 824 | } |
| 825 | return err |
| 826 | })) |
| 827 | } |
| 828 | |
| 829 | // TestDesignLimitHoldsAFailover: a failover the runner makes (the |
| 830 | // provider refused an attempt, so it moves the step to its next one) is a |
| 831 | // new Design attempt. Under the limit it counts once, however often its |
| 832 | // report arrives; at the limit it is not launched: the step is held for |
| 833 | // the person through the held-step card, and the runner's start of the |
| 834 | // failover attempt is refused. |
| 835 | func TestDesignLimitHoldsAFailover(t *testing.T) { |
| 836 | r, l, _ := grantRig(t) |
| 837 | sp := r.active(l, "Patrix", "p_patrix") |
| 838 | task, s := r.runningDesign(l, sp, wire.KindChange) |
| 839 | if k := r.load(task); k.DesignRuns != 1 { |
| 840 | t.Fatalf("runs %d", k.DesignRuns) |
| 841 | } |
| 842 | failover := wire.StepReport{Attempt: s.Attempt + 1, State: wire.StepRunning} |
| 843 | r.report(l, s, failover) |
| 844 | r.report(l, s, failover) |
| 845 | moved := r.stepNow(s.ID) |
| 846 | if moved.Attempt != s.Attempt+1 || moved.State != wire.StepRunning || moved.RunnerID != "RUNNER1" || r.load(task).DesignRuns != 2 { |
| 847 | t.Fatalf("a failover under the limit %+v, runs %d", moved, r.load(task).DesignRuns) |
| 848 | } |
| 849 | if refused := r.authorize(l, moved, ""); refused != "" { |
| 850 | t.Fatalf("its start %q", refused) |
| 851 | } |
| 852 | third := r.failAndRetry(l, task) |
| 853 | if !r.attemptSent(third) || r.load(task).DesignRuns != 3 { |
| 854 | t.Fatalf("third attempt %+v runs %d", third, r.load(task).DesignRuns) |
| 855 | } |
| 856 | r.ackDispatches(third.ID) |
| 857 | if refused := r.authorize(l, third, ""); refused != "" { |
| 858 | t.Fatalf("third start %q", refused) |
| 859 | } |
| 860 | third = r.stepNow(third.ID) |
| 861 | r.report(l, third, wire.StepReport{Attempt: third.Attempt + 1, State: wire.StepRunning}) |
| 862 | held := r.stepNow(third.ID) |
| 863 | if held.Attempt <= third.Attempt+1 || held.State != wire.StepQueued || held.RunnerID != "" || held.Placement != wire.PlacementDesignLimit || held.Reason != reasonDesignLimit || held.StartedAt != nil || r.attemptSent(held) { |
| 864 | t.Fatalf("a failover at the limit %+v", held) |
| 865 | } |
| 866 | if h := stepHold(held); h == nil || h.Reason != wire.HoldDesignLimit || h.StepRevision != held.Attempt { |
| 867 | t.Fatalf("hold %+v", h) |
| 868 | } |
| 869 | if k := r.load(task); k.DesignRuns != 3 { |
| 870 | t.Fatalf("runs at the limit %d", k.DesignRuns) |
| 871 | } |
| 872 | cards := r.heldCards(task) |
| 873 | if len(cards) != 1 || cards[0].State != wire.CardOpen || cards[0].Options != `["run_now"]` { |
| 874 | t.Fatalf("held cards %+v", cards) |
| 875 | } |
| 876 | // The runner's start of the failover attempt is refused, and its end |
| 877 | // changes nothing. |
| 878 | refused, err := r.s.Authorize(r.ctx, l, held.ID, third.Attempt+1, "", "", "") |
| 879 | if err != nil || refused != "withdrawn" { |
| 880 | t.Fatalf("the failover's start %q %v", refused, err) |
| 881 | } |
| 882 | end := wire.StepReport{TaskID: task, StepID: held.ID, Attempt: third.Attempt + 1, State: wire.StepCancelled, Reason: "withdrawn", Termination: true} |
| 883 | if err := r.tx(func(tx *txn) error { return tx.stepReport(l, &end) }); err != nil && !errors.Is(err, ErrRefused) { |
| 884 | t.Fatal(err) |
| 885 | } |
| 886 | if got := r.stepNow(held.ID); got.State != wire.StepQueued || got.Placement != wire.PlacementDesignLimit || got.Attempt != held.Attempt { |
| 887 | t.Fatalf("after the failover's end %+v", got) |
| 888 | } |
| 889 | // Run it now sends it, counted from there. |
| 890 | if _, _, err := r.s.Answer(r.ctx, paul, cards[0].ID, wire.AnswerCard{Choice: ChoiceRunNow, Revision: cards[0].Revision}); err != nil { |
| 891 | t.Fatal(err) |
| 892 | } |
| 893 | if got := r.stepNow(held.ID); !r.attemptSent(got) || got.RunnerID != "RUNNER1" || r.load(task).DesignRuns != 1 { |
| 894 | t.Fatalf("after Run it now %+v, runs %d", got, r.load(task).DesignRuns) |
| 895 | } |
| 896 | // Engineering's own failovers are not Design's: never counted, never |
| 897 | // held. |
| 898 | turn, plain := r.personTask(l, "Patrix", wire.KindChange) |
| 899 | if res := r.call(l, turn.ID, wire.ToolStartTask, map[string]any{"task": plain, "brief": "b"}); res.IsError { |
| 900 | t.Fatal(res) |
| 901 | } |
| 902 | e := r.makerStep(plain) |
| 903 | r.ackDispatches(e.ID) |
| 904 | if refused := r.authorize(l, e, ""); refused != "" { |
| 905 | t.Fatalf("Engineering's start %q", refused) |
| 906 | } |
| 907 | for i := int64(1); i <= wire.DesignRunLimit+1; i++ { |
| 908 | r.report(l, e, wire.StepReport{Attempt: e.Attempt + i, State: wire.StepRunning}) |
| 909 | } |
| 910 | if got := r.stepNow(e.ID); got.Attempt != e.Attempt+wire.DesignRunLimit+1 || got.State != wire.StepRunning || got.RunnerID != "RUNNER1" || got.Hold != "" || r.load(plain).DesignRuns != 0 { |
| 911 | t.Fatalf("Engineering's failovers %+v, runs %d", got, r.load(plain).DesignRuns) |
| 912 | } |
| 913 | } |
| 914 | |
| 915 | // TestDesignLimitOnlyTheCreatorActs: only the task's creator, an owner |
| 916 | // now, resets Design's count and releases a held attempt. Another |
| 917 | // member's message in the thread, or their answer on a card of the |
| 918 | // task, does neither; nor does the creator's once they are no longer an |
| 919 | // owner. |
| 920 | func TestDesignLimitOnlyTheCreatorActs(t *testing.T) { |
| 921 | r, l, _ := grantRig(t) |
| 922 | const nora = "nora@tito.io" |
| 923 | r.exec("INSERT INTO members(address, active, role) VALUES (?, 1, 'owner')", nora) |
| 924 | sp := r.active(l, "Patrix", "p_patrix") |
| 925 | task := r.designTask(l, sp, wire.KindChange) |
| 926 | r.failAndRetry(l, task) |
| 927 | r.failAndRetry(l, task) |
| 928 | held := r.failAndRetry(l, task) |
| 929 | still := func(what string) { |
| 930 | t.Helper() |
| 931 | got := r.stepNow(held.ID) |
| 932 | if r.attemptSent(got) || got.State != wire.StepQueued || got.Placement != wire.PlacementDesignLimit || r.load(task).DesignRuns != 3 { |
| 933 | t.Fatalf("%s: step %+v, runs %d", what, got, r.load(task).DesignRuns) |
| 934 | } |
| 935 | if c := r.heldCards(task); len(c) != 1 || c[0].State != wire.CardOpen { |
| 936 | t.Fatalf("%s: held cards %+v", what, c) |
| 937 | } |
| 938 | } |
| 939 | still("the fourth attempt") |
| 940 | post := func(who, text string) { |
| 941 | t.Helper() |
| 942 | if _, err := r.s.PostThread(r.ctx, who, task, wire.PostThread{Text: text, IdempotencyKey: newID("k")}); err != nil { |
| 943 | t.Fatal(err) |
| 944 | } |
| 945 | } |
| 946 | post(nora, "Following this.") |
| 947 | still("another member's message") |
| 948 | q := cardRecord{ID: "c_nora", Person: nora, Kind: wire.CardQuestion, State: wire.CardOpen, TaskID: task, Question: "Which logo?", Options: `["The old one"]`, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now, Lane: wire.LaneCoordinator} |
| 949 | r.must(r.s.db.G.Create(&q).Error) |
| 950 | if _, _, err := r.s.Answer(r.ctx, nora, q.ID, wire.AnswerCard{Choice: "The old one", Revision: 1}); err != nil { |
| 951 | t.Fatal(err) |
| 952 | } |
| 953 | still("another member's answer on the task's card") |
| 954 | r.exec("UPDATE members SET role = 'member' WHERE address = ?", paul) |
| 955 | post(paul, "Go on.") |
| 956 | still("the creator's message, no longer an owner") |
| 957 | r.exec("UPDATE members SET role = 'owner' WHERE address = ?", paul) |
| 958 | post(paul, "Go on now.") |
| 959 | if got := r.stepNow(held.ID); !r.attemptSent(got) || got.Placement != "" || r.load(task).DesignRuns != 1 { |
| 960 | t.Fatalf("the creator's message %+v, runs %d", got, r.load(task).DesignRuns) |
| 961 | } |
| 962 | } |
| 963 | |
| 964 | // TestDesignRecoveryHeldAfterDemotion: a fourth attempt the limit held |
| 965 | // was never given to a runner. When the task's maker stops resolving |
| 966 | // (its approver demoted), the placement pass settles it as never started |
| 967 | // (no proof is owed: nothing ran), closes its hold, and offers the |
| 968 | // recovery card, which the creator can tap. An attempt its runner holds |
| 969 | // still waits for its proof. |
| 970 | func TestDesignRecoveryHeldAfterDemotion(t *testing.T) { |
| 971 | r, l, _ := grantRig(t) |
| 972 | r.exec("CREATE TABLE IF NOT EXISTS runners (id text PRIMARY KEY, person text, role text, label text, removing_at datetime, tainted_at datetime, revoked_at datetime)") |
| 973 | r.exec("INSERT OR IGNORE INTO members(address, active, role) VALUES (?, 1, 'owner')", hkOwner) |
| 974 | r.exec("UPDATE members SET active = 1, role = 'owner' WHERE address = ?", hkOwner) |
| 975 | sp := r.active(l, "Patrix", "p_patrix") |
| 976 | r.exec("UPDATE chat_specialists SET approver = ? WHERE id = ?", hkOwner, sp.ID) |
| 977 | r.exec("UPDATE chat_capability_grants SET granted_by = ? WHERE specialist_id = ?", hkOwner, sp.ID) |
| 978 | task := r.designTask(l, sp, wire.KindChange) |
| 979 | r.failAndRetry(l, task) |
| 980 | r.failAndRetry(l, task) |
| 981 | held := r.failAndRetry(l, task) |
| 982 | if r.attemptSent(held) || held.Placement != wire.PlacementDesignLimit || held.RunnerID != "" { |
| 983 | t.Fatalf("not held %+v", held) |
| 984 | } |
| 985 | other, o := r.runningDesign(l, sp, wire.KindChange) |
| 986 | // And one whose dispatch went to its runner, not yet started. |
| 987 | sent := r.designTask(l, sp, wire.KindChange) |
| 988 | d := r.makerStep(sent) |
| 989 | if !r.attemptSent(d) || d.RunnerID != "RUNNER1" || d.StartedAt != nil || d.State != wire.StepQueued { |
| 990 | t.Fatalf("a dispatched attempt %+v", d) |
| 991 | } |
| 992 | r.must(r.s.Place(r.ctx)) |
| 993 | if n := len(r.recoveryCards(task)) + len(r.recoveryCards(other)); n != 0 { |
| 994 | t.Fatalf("%d cards while the maker resolves", n) |
| 995 | } |
| 996 | if got := r.stepNow(held.ID); got.State != wire.StepQueued || got.Placement != wire.PlacementDesignLimit { |
| 997 | t.Fatalf("settled while the maker resolves %+v", got) |
| 998 | } |
| 999 | r.exec("UPDATE members SET role = 'member' WHERE address = ?", hkOwner) |
| 1000 | r.must(r.s.Place(r.ctx)) |
| 1001 | r.must(r.s.Place(r.ctx)) |
| 1002 | got := r.stepNow(held.ID) |
| 1003 | if got.State != wire.StepCancelled || !got.Terminated || got.Reason != reasonSpecialistNoGrant || got.Hold != "" || got.Placement != "" || got.RunnerID != "" || r.attemptSent(got) { |
| 1004 | t.Fatalf("the held attempt %+v", got) |
| 1005 | } |
| 1006 | if c := r.heldCards(task); len(c) != 1 || c[0].State != wire.CardResolved { |
| 1007 | t.Fatalf("held cards %+v", c) |
| 1008 | } |
| 1009 | cards := r.recoveryCards(task) |
| 1010 | if len(cards) != 1 || cards[0].State != wire.CardOpen || cards[0].Person != paul { |
| 1011 | t.Fatalf("recovery cards %+v", cards) |
| 1012 | } |
| 1013 | // The attempts their runner holds, started or only sent, keep |
| 1014 | // waiting for their proof. |
| 1015 | for task, id := range map[string]string{other: o.ID, sent: d.ID} { |
| 1016 | if got := r.stepNow(id); got.Terminated || wire.StepTerminal(got.State) || len(r.recoveryCards(task)) != 0 { |
| 1017 | t.Fatalf("an attempt that could have run %+v, %d cards", got, len(r.recoveryCards(task))) |
| 1018 | } |
| 1019 | } |
| 1020 | if _, _, err := r.s.Answer(r.ctx, paul, cards[0].ID, wire.AnswerCard{Choice: wire.ChoiceToEngineering, Revision: cards[0].Revision}); err != nil { |
| 1021 | t.Fatal(err) |
| 1022 | } |
| 1023 | if k := r.load(task); k.MakerSpecialistID != "" { |
| 1024 | t.Fatalf("after the tap %+v", k) |
| 1025 | } |
| 1026 | } |
| 1027 | |