| 1 | package plan3test |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/equipo" |
| 12 | "amadan.net/oficina/equipo/internal/equipo/conversation" |
| 13 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 14 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 15 | "gorm.io/gorm" |
| 16 | ) |
| 17 | |
| 18 | func TestCoordinatorContextLimitParked(t *testing.T) { |
| 19 | for _, action := range []string{"retry", "reset"} { |
| 20 | t.Run(action, func(t *testing.T) { |
| 21 | f, x, p, b := coordinatorFixture(t) |
| 22 | turn := queueCoordinator(t, f, strings.Repeat("\x00", 16000), "large") |
| 23 | if _, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision); err == nil { |
| 24 | t.Fatal("oversized request ran without its message") |
| 25 | } |
| 26 | for i := 0; i < 2; i++ { |
| 27 | turns, err := x.PollCoordinator(ctx, p) |
| 28 | must(t, err) |
| 29 | if len(turns) != 0 { |
| 30 | t.Fatal("context_limit turn re-offered") |
| 31 | } |
| 32 | } |
| 33 | if _, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision); err == nil { |
| 34 | t.Fatal("parked turn directly claimed") |
| 35 | } |
| 36 | page, err := f.Store.Conversation(ctx, owner, "", 50) |
| 37 | must(t, err) |
| 38 | found := false |
| 39 | for _, card := range page.Cards { |
| 40 | if card.Kind == "coordinator" && card.CopyKey == "coordinator.context_limit" && card.ResourceID == turn.ID && strings.Join(card.ActionKeys, ",") == "coordinator.reset,coordinator.retry" { |
| 41 | found = true |
| 42 | } |
| 43 | } |
| 44 | if !found { |
| 45 | t.Fatal("context_limit omitted person-visible card") |
| 46 | } |
| 47 | f.exec(t, "UPDATE conversation_messages SET body='smaller request',revision=revision+1 WHERE id=?", turn.MessageID) |
| 48 | var next equipo.CoordinatorTurn |
| 49 | if action == "retry" { |
| 50 | next, err = f.Store.RetryCoordinatorTurn(ctx, owner, turn.ID, equipo.Mutation{RequestID: "retry", Revision: turn.Revision}) |
| 51 | must(t, err) |
| 52 | } else { |
| 53 | _, err = f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| 54 | must(t, err) |
| 55 | turns, err := x.PollCoordinator(ctx, p) |
| 56 | must(t, err) |
| 57 | if len(turns) != 1 { |
| 58 | t.Fatal("reset did not release parked request", turns) |
| 59 | } |
| 60 | next = turns[0] |
| 61 | } |
| 62 | _, err = x.ClaimCoordinator(ctx, p, next.ID, next.Revision) |
| 63 | must(t, err) |
| 64 | page, err = f.Store.Conversation(ctx, owner, "", 50) |
| 65 | must(t, err) |
| 66 | for _, card := range page.Cards { |
| 67 | if card.CopyKey == "coordinator.context_limit" { |
| 68 | t.Fatal("resolved context_limit card survived") |
| 69 | } |
| 70 | } |
| 71 | }) |
| 72 | } |
| 73 | } |
| 74 | func TestCoordinatorContextFiftySmallMessages(t *testing.T) { |
| 75 | f, x, p, _ := coordinatorFixture(t) |
| 76 | for i := 0; i < 60; i++ { |
| 77 | _, err := f.Store.SendMessage(ctx, owner, "", fmt.Sprint("small-", i), equipo.Mutation{RequestID: fmt.Sprint(i)}) |
| 78 | must(t, err) |
| 79 | } |
| 80 | turn := queueCoordinator(t, f, "request", "request") |
| 81 | c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 82 | must(t, err) |
| 83 | if len(c.Context.Recent) != 50 || c.Context.Recent[0].Body != "small-11" || c.Context.Recent[49].ID != turn.MessageID { |
| 84 | t.Fatal("claim ignored 50-message limit") |
| 85 | } |
| 86 | checked := 0 |
| 87 | must(t, x.Write(ctx, func(tx *gorm.DB) error { |
| 88 | cs := conversation.New(tx, conversation.Dependencies{Authorize: func(*gorm.DB, kernel.Actor) (string, error) { return f.TeamID, nil }, ContextMessage: func(*gorm.DB, runnerproto.CoordinatorClaim, conversation.Message) (bool, error) { |
| 89 | checked++ |
| 90 | return true, nil |
| 91 | }}) |
| 92 | _, err := cs.CoordinatorContext(ctx, c) |
| 93 | return err |
| 94 | })) |
| 95 | if checked != 50 { |
| 96 | t.Fatal("instance fetched more than 50 messages", checked) |
| 97 | } |
| 98 | |
| 99 | } |
| 100 | func TestCoordinatorWaitingReset(t *testing.T) { |
| 101 | f, x, p, b := coordinatorFixture(t) |
| 102 | turn := queueCoordinator(t, f, "request", "request") |
| 103 | // Persist the same waiting state used while a specialist owns the home. |
| 104 | f.exec(t, "UPDATE coordinator_turns SET state='waiting_task' WHERE id=?", turn.ID) |
| 105 | f.exec(t, `INSERT INTO conversation_requests(principal,operation,resource,request_id,result) VALUES(?,'coordinator.waiting',?,'current','"blocking-task"')`, owner.Address, b.ID) |
| 106 | _, err := f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| 107 | must(t, err) |
| 108 | _ = x |
| 109 | _ = p |
| 110 | status, err := f.Store.Coordinator(ctx, owner) |
| 111 | must(t, err) |
| 112 | if status.WaitingTaskID != "" || f.count(t, "SELECT count(*) FROM conversation_requests WHERE operation='coordinator.waiting'") != 0 { |
| 113 | t.Fatal("reset retained waiting record/card") |
| 114 | } |
| 115 | } |
| 116 | func TestCoordinatorRecoveryInstanceRefusals(t *testing.T) { |
| 117 | for _, cause := range []string{"expired", "reset", "connection"} { |
| 118 | t.Run(cause, func(t *testing.T) { |
| 119 | f, x, p, b := coordinatorFixture(t) |
| 120 | old := queueCoordinator(t, f, "completed but unreported", "old") |
| 121 | c, err := x.ClaimCoordinator(ctx, p, old.ID, old.Revision) |
| 122 | must(t, err) |
| 123 | x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| 124 | change := func() (equipo.CoordinatorBinding, error) { |
| 125 | if cause == "connection" { |
| 126 | return f.Store.SaveCoordinatorBinding(ctx, owner, p.RunnerID, "codex", equipo.Mutation{RequestID: "change", Revision: b.Revision}) |
| 127 | } |
| 128 | return f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "change", Revision: b.Revision}) |
| 129 | } |
| 130 | if cause == "expired" { |
| 131 | f.exec(t, "UPDATE attempts SET lease_deadline=? WHERE id=?", time.Now().Add(-time.Hour).UTC(), c.Handle.Attempt) |
| 132 | } else { |
| 133 | if _, err = change(); err == nil { |
| 134 | t.Fatal("change skipped pending containment") |
| 135 | } |
| 136 | } |
| 137 | if err = x.CoordinatorEvent(ctx, p, c, coordinatorEvent(c, "turn.completed")); err == nil { |
| 138 | t.Fatal("stale completed turn accepted") |
| 139 | } |
| 140 | must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) |
| 141 | must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) |
| 142 | if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='uncertain'", old.ID) != 1 || f.count(t, "SELECT count(*) FROM reservations WHERE job_id=? AND state='settled' AND settled_by='unknown' AND s_calls=r_calls AND s_input=r_input AND s_output=r_output", c.Scope.Job) != 1 { |
| 143 | t.Fatal("refusal lost uncertainty or charge") |
| 144 | } |
| 145 | nextBinding, err := change() |
| 146 | must(t, err) |
| 147 | next := queueCoordinator(t, f, "new request", "new") |
| 148 | claim, err := x.ClaimCoordinator(ctx, p, next.ID, next.Revision) |
| 149 | must(t, err) |
| 150 | if claim.Binding.Generation != nextBinding.Generation || claim.Binding.Generation <= b.Generation { |
| 151 | t.Fatal("new generation stayed blocked") |
| 152 | } |
| 153 | }) |
| 154 | } |
| 155 | } |
| 156 | func TestCoordinatorRecoveryInvalidTool(t *testing.T) { |
| 157 | _, x, p, c := claimTools(t) |
| 158 | _, err := x.CoordinatorToolResult(ctx, p, c, runnerproto.CoordinatorToolCall{RequestID: "invalid", Name: "post_message", Arguments: json.RawMessage(`{"body":"","source_refs":[]}`)}) |
| 159 | if err == nil { |
| 160 | t.Fatal("invalid recovery tool arguments accepted") |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | func TestCoordinatorContextFinishedDecisionsOptional(t *testing.T) { |
| 165 | f, x, p, _ := coordinatorFixture(t) |
| 166 | var project int64 |
| 167 | must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&project)) |
| 168 | tx, err := f.DB.Writer().Begin() |
| 169 | must(t, err) |
| 170 | for i := 0; i < 1002; i++ { |
| 171 | id := fmt.Sprint("finished-", i) |
| 172 | state := "merged" |
| 173 | if i%2 == 0 { |
| 174 | state = "cancelled" |
| 175 | } |
| 176 | _, err = tx.Exec("INSERT INTO tasks(id,requester,request_id,project_id,team_id,state,kind,plan_revision,approval_revision,revision) VALUES(?,?,?,?,?,?,'bug',1,1,1)", id, owner.Address, id, project, f.TeamID, state) |
| 177 | must(t, err) |
| 178 | _, err = tx.Exec("INSERT INTO plan_revisions(task_id,revision,plan) VALUES(?,1,?)", id, strings.Repeat("finished decision ", 120)) |
| 179 | must(t, err) |
| 180 | _, err = tx.Exec(`INSERT INTO plan_requests(principal,operation,resource,request_id,result) VALUES(?,'plan.approve',?,'approved','{"ApprovalRevision":1,"PlanRevision":1}')`, owner.Address, id) |
| 181 | must(t, err) |
| 182 | } |
| 183 | must(t, tx.Commit()) |
| 184 | // One open approval must remain required even under pressure from history. |
| 185 | f.exec(t, "UPDATE tasks SET state='proposed' WHERE id='finished-0'") |
| 186 | f.exec(t, "UPDATE plan_revisions SET plan='keep open decision' WHERE task_id='finished-0'") |
| 187 | turn := queueCoordinator(t, f, "new request", "new") |
| 188 | c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 189 | if err != nil { |
| 190 | t.Fatal("finished work permanently blocked conversation", err) |
| 191 | } |
| 192 | if len(c.Context.ConfirmedDecisions) != 1 || c.Context.ConfirmedDecisions[0].Text != "keep open decision" { |
| 193 | t.Fatal("open-work decision lost or terminal decisions required", len(c.Context.ConfirmedDecisions)) |
| 194 | } |
| 195 | found := false |
| 196 | for _, ref := range c.Context.Retrieved { |
| 197 | if ref.Source.Kind == "plan_approval" { |
| 198 | found = true |
| 199 | } |
| 200 | } |
| 201 | if !found { |
| 202 | t.Fatal("finished decisions not available as optional retrieval") |
| 203 | } |
| 204 | if len(c.Context.Recent) != 1 || c.Context.Recent[0].ID != turn.MessageID { |
| 205 | t.Fatal("optional decisions displaced request") |
| 206 | } |
| 207 | } |
| 208 | func TestCoordinatorContextAnsweredWorkFinished(t *testing.T) { |
| 209 | f, x, p, c := claimTools(t) |
| 210 | question := toolCall(t, x, p, c, "question", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Choose a direction", "options": []any{}}) |
| 211 | must(t, f.Store.AnswerClarification(ctx, owner, question.ResourceID, "", "old finished answer", equipo.Mutation{RequestID: "answer", Revision: 1})) |
| 212 | // Both the original request and the answer's follow-up have finished. |
| 213 | f.exec(t, "UPDATE coordinator_turns SET state='delivered'") |
| 214 | f.exec(t, "UPDATE attempts SET containment='contained'") |
| 215 | turn := queueCoordinator(t, f, "next work", "next") |
| 216 | next, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 217 | must(t, err) |
| 218 | if len(next.Context.ConfirmedDecisions) != 0 { |
| 219 | t.Fatal("finished question retained as required decision") |
| 220 | } |
| 221 | found := false |
| 222 | for _, r := range next.Context.Retrieved { |
| 223 | if r.Text == "old finished answer" { |
| 224 | found = true |
| 225 | } |
| 226 | } |
| 227 | if !found { |
| 228 | t.Fatal("finished answer missing from optional retrieval") |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | func TestCoordinatorContextOwnProjectFirst(t *testing.T) { |
| 233 | f, x, p, _ := coordinatorFixture(t) |
| 234 | var own int64 |
| 235 | must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&own)) |
| 236 | for i := 0; i < 40; i++ { |
| 237 | project := equipo.Project{Name: strings.Repeat("label", 400), Repository: fmt.Sprint("amadan.net/test/", i), DefaultBranch: "main", Kind: equipo.ProjectRepository, Revision: 1, GrantVersion: 1} |
| 238 | must(t, f.DB.G.Create(&project).Error) |
| 239 | f.exec(t, `INSERT INTO connection_choices(person,project_id,revision,connection_ids_json,pinned_id) VALUES(?,?,1,'["claude"]','claude')`, owner.Address, project.ID) |
| 240 | } |
| 241 | msg, err := f.Store.SendMessage(ctx, owner, "", "own project request", equipo.Mutation{RequestID: "own"}) |
| 242 | must(t, err) |
| 243 | turn, err := f.Store.QueueCoordinatorTurn(ctx, owner, msg.ID, own, equipo.Mutation{RequestID: "own"}) |
| 244 | must(t, err) |
| 245 | c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 246 | must(t, err) |
| 247 | if len(c.Context.Retrieved) == 0 || c.Context.Retrieved[0].Source.Kind != "project" || c.Context.Retrieved[0].Source.ID != fmt.Sprint(own) { |
| 248 | t.Fatal("own project source trimmed before labels") |
| 249 | } |
| 250 | if len(c.Context.Retrieved) >= 42 { |
| 251 | t.Fatal("fixture did not exercise retrieval trimming") |
| 252 | } |
| 253 | } |
| 254 | func TestCoordinatorWaitingWritesOnlyOnChange(t *testing.T) { |
| 255 | f, x, p, _ := coordinatorFixture(t) |
| 256 | turn := queueCoordinator(t, f, "request", "request") |
| 257 | f.exec(t, "DELETE FROM connections WHERE id='claude'") |
| 258 | _, err := x.PollCoordinator(ctx, p) |
| 259 | must(t, err) |
| 260 | f.exec(t, "CREATE TRIGGER forbid_waiting_update BEFORE UPDATE ON conversation_requests WHEN OLD.operation='coordinator.waiting' BEGIN SELECT RAISE(ABORT,'unchanged waiting write'); END") |
| 261 | f.exec(t, "CREATE TRIGGER forbid_waiting_insert BEFORE INSERT ON conversation_requests WHEN NEW.operation='coordinator.waiting' BEGIN SELECT RAISE(ABORT,'unchanged waiting write'); END") |
| 262 | _, err = x.PollCoordinator(ctx, p) |
| 263 | if err != nil { |
| 264 | t.Fatal("unchanged waiting status wrote again", err) |
| 265 | } |
| 266 | if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='waiting_connection'", turn.ID) != 1 { |
| 267 | t.Fatal("waiting status missing") |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | func TestCoordinatorContextAnswerFollowsOpenWork(t *testing.T) { |
| 272 | for _, state := range []string{"proposed", "cancelled"} { |
| 273 | t.Run(state, func(t *testing.T) { |
| 274 | f, x, p, c := claimTools(t) |
| 275 | var task string |
| 276 | must(t, f.DB.Writer().QueryRow("SELECT id FROM tasks LIMIT 1").Scan(&task)) |
| 277 | question := toolCall(t, x, p, c, "question", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Choose a direction", "options": []any{}}) |
| 278 | toolCall(t, x, p, c, "route", "route_to_task", map[string]any{"message_id": c.Turn.MessageID, "task_id": task}) |
| 279 | must(t, f.Store.AnswerClarification(ctx, owner, question.ResourceID, "", "linked decision", equipo.Mutation{RequestID: "answer", Revision: 1})) |
| 280 | f.exec(t, "UPDATE coordinator_turns SET state='delivered'") |
| 281 | f.exec(t, "UPDATE attempts SET containment='contained'") |
| 282 | f.exec(t, "UPDATE tasks SET state=? WHERE id=?", state, task) |
| 283 | turn := queueCoordinator(t, f, "next work", "next") |
| 284 | next, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 285 | must(t, err) |
| 286 | found := false |
| 287 | for _, ref := range next.Context.ConfirmedDecisions { |
| 288 | if ref.Text == "linked decision" { |
| 289 | found = true |
| 290 | } |
| 291 | } |
| 292 | if found != (state == "proposed") { |
| 293 | t.Fatal("answer did not follow linked work state", state, found) |
| 294 | } |
| 295 | }) |
| 296 | } |
| 297 | } |
| 298 | |