| 1 | package plan3test |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo" |
| 5 | "amadan.net/oficina/equipo/internal/equipo/conversation" |
| 6 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 7 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 8 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 9 | "context" |
| 10 | "encoding/json" |
| 11 | "fmt" |
| 12 | "gorm.io/gorm" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | ) |
| 16 | |
| 17 | func TestCoordinatorConnectionWaiting(t *testing.T) { |
| 18 | f, x, p, b := coordinatorFixture(t) |
| 19 | first := queueCoordinator(t, f, "first", "first") |
| 20 | c, err := x.ClaimCoordinator(ctx, p, first.ID, first.Revision) |
| 21 | must(t, err) |
| 22 | // A claimed specialist holds the same home until its namespace is contained. |
| 23 | f.exec(t, "UPDATE coordinator_turns SET state='delivered' WHERE id=?", first.ID) |
| 24 | f.exec(t, `INSERT INTO runner_assignments(id,task_id,person,state,attempt_id,selection) VALUES('blocking','blocking-task',?,'claimed',?,?)`, owner.Address, c.Handle.Attempt, `{"ConnectionID":"claude"}`) |
| 25 | second := queueCoordinator(t, f, "second", "second") |
| 26 | // The first coordinator no longer owns pending containment; the specialist does. |
| 27 | f.exec(t, "UPDATE coordinator_turns SET attempt_id=0 WHERE id=?", first.ID) |
| 28 | turns, err := x.PollCoordinator(ctx, p) |
| 29 | must(t, err) |
| 30 | if len(turns) != 0 { |
| 31 | t.Fatal("coordinator overlapped shared home") |
| 32 | } |
| 33 | status, err := f.Store.Coordinator(ctx, owner) |
| 34 | must(t, err) |
| 35 | if status.WaitingTaskID != "blocking-task" || status.WaitingTaskURL != "/tasks/blocking-task" { |
| 36 | t.Fatal("waiting card omitted task link", status) |
| 37 | } |
| 38 | page, err := f.Store.Conversation(ctx, owner, "", 50) |
| 39 | must(t, err) |
| 40 | found := false |
| 41 | for _, card := range page.Cards { |
| 42 | if card.Kind == "coordinator" && card.Thinking && card.ConnectionLabel == "claude" { |
| 43 | found = true |
| 44 | } |
| 45 | } |
| 46 | if !found { |
| 47 | t.Fatal("conversation omitted live waiting bubble") |
| 48 | } |
| 49 | if f.count(t, "SELECT count(*) FROM admission_tickets") != 1 { |
| 50 | t.Fatal("waiting dispatched a provider") |
| 51 | } |
| 52 | if _, err = x.ClaimCoordinator(ctx, p, second.ID, second.Revision); err == nil { |
| 53 | t.Fatal("claim ignored occupied home") |
| 54 | } |
| 55 | f.exec(t, "UPDATE runner_assignments SET state='contained' WHERE id='blocking'") |
| 56 | f.exec(t, "UPDATE attempts SET containment='contained' WHERE id=?", c.Handle.Attempt) |
| 57 | turns, err = x.PollCoordinator(ctx, p) |
| 58 | must(t, err) |
| 59 | if len(turns) != 1 || turns[0].ID != second.ID { |
| 60 | t.Fatal("released home lost queued turn") |
| 61 | } |
| 62 | status, err = f.Store.Coordinator(ctx, owner) |
| 63 | must(t, err) |
| 64 | if status.WaitingTaskID != "" || f.count(t, "SELECT count(*) FROM conversation_requests WHERE operation='coordinator.waiting'") != 0 { |
| 65 | t.Fatal("released task retained waiting record before claim") |
| 66 | } |
| 67 | next, err := x.ClaimCoordinator(ctx, p, second.ID, second.Revision) |
| 68 | must(t, err) |
| 69 | if next.Handle.Attempt == c.Handle.Attempt || next.Binding.ID != b.ID { |
| 70 | t.Fatal("waiting redispatched old turn") |
| 71 | } |
| 72 | x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| 73 | must(t, x.ContainCoordinator(ctx, p, next, runnerproto.ContainmentProof{Scope: next.Scope, Handle: next.Handle})) |
| 74 | action, err := x.Core.GetAction(ctx, next.Scope, next.Admission.Dispatch.Action) |
| 75 | must(t, err) |
| 76 | if action.State != team.ActionUncertain { |
| 77 | t.Fatal("unknown charge lost") |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | func TestCoordinatorContextBounds(t *testing.T) { |
| 82 | f, x, p, _ := coordinatorFixture(t) |
| 83 | for i := 0; i < 60; i++ { |
| 84 | _, err := f.Store.SendMessage(ctx, owner, "", strings.Repeat("x", 16384), equipo.Mutation{RequestID: fmt.Sprint(i)}) |
| 85 | must(t, err) |
| 86 | } |
| 87 | turn := queueCoordinator(t, f, "latest request", "latest") |
| 88 | c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 89 | must(t, err) |
| 90 | if c.Context.Hash == "" || c.Context.Hash != c.Turn.ContextHash || c.Context.Hash != runnerproto.CoordinatorContextHash(c.Context) { |
| 91 | t.Fatal("claim snapshot hash mismatch") |
| 92 | } |
| 93 | if len(c.Context.Recent) != 2 || c.Context.Recent[1].ID != turn.MessageID { |
| 94 | t.Fatal("long history did not trim oldest first", len(c.Context.Recent)) |
| 95 | } |
| 96 | if len(c.Context.ConfirmedPreferences) != 0 || len(c.Context.ConfirmedDecisions) != 0 { |
| 97 | t.Fatal("history promoted to confirmed context") |
| 98 | } |
| 99 | _, err = runnerproto.CoordinatorPrompt(c.Context) |
| 100 | must(t, err) |
| 101 | again, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 102 | must(t, err) |
| 103 | if runnerproto.EventHash(c) != runnerproto.EventHash(again) { |
| 104 | t.Fatal("claim replay rebuilt snapshot") |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | func TestCoordinatorContextSourceRevocation(t *testing.T) { |
| 109 | f, x, p, _ := coordinatorFixture(t) |
| 110 | var project int64 |
| 111 | must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&project)) |
| 112 | msg, err := f.Store.SendMessage(ctx, owner, "", "restricted older message", equipo.Mutation{RequestID: "old"}) |
| 113 | must(t, err) |
| 114 | _, err = f.Store.QueueCoordinatorTurn(ctx, owner, msg.ID, project, equipo.Mutation{RequestID: "old"}) |
| 115 | must(t, err) |
| 116 | f.exec(t, "UPDATE coordinator_turns SET state='superseded'") |
| 117 | f.exec(t, `UPDATE connection_choices SET connection_ids_json='["codex"]',pinned_id='codex'`) |
| 118 | turn := queueCoordinator(t, f, "general request", "general") |
| 119 | c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 120 | must(t, err) |
| 121 | raw, err := runnerproto.CoordinatorPrompt(c.Context) |
| 122 | must(t, err) |
| 123 | if strings.Contains(raw, "restricted older message") || len(c.Context.Retrieved) != 0 { |
| 124 | t.Fatal("revoked source survived fresh snapshot") |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | func TestCoordinatorSessionTrustedReceipt(t *testing.T) { |
| 129 | f, x, p, c := claimTools(t) |
| 130 | validators := runnerproto.ReportValidators(runnerproto.ReportErrors{Invalid: equipo.ErrInvalid, Forbidden: equipo.ErrForbidden, Conflict: equipo.ErrConflict}, func(context.Context, string, []string) ([]json.RawMessage, error) { |
| 131 | t.Fatal("delivery used a remote or unbounded validator") |
| 132 | return nil, nil |
| 133 | }) |
| 134 | x.SetRunnerValidators(validators) |
| 135 | out := toolCall(t, x, p, c, "post", "post_message", map[string]any{"body": "delivered once", "source_refs": []team.SourceRef{}}) |
| 136 | event := coordinatorEvent(c, "coordinator.delivery") |
| 137 | event.SessionID = "fixture-session" |
| 138 | event.Payload = []byte(`{"request_id":"post","resource_id":"` + out.ResourceID + `"}`) |
| 139 | if err := x.CompleteCoordinator(ctx, p, c, event); err == nil { |
| 140 | t.Fatal("delivery accepted before receipt") |
| 141 | } |
| 142 | terminal := coordinatorEvent(c, "turn.completed") |
| 143 | terminal.SessionID = event.SessionID |
| 144 | terminal.Payload = []byte(`{"usage":{"calls":1,"input_tokens":11,"output_tokens":3,"cost_unavailable":true}}`) |
| 145 | raw, _ := runnerproto.Marshal(terminal) |
| 146 | q := runnerproto.RunnerRequest{Version: 2, AssignmentID: c.Turn.ID, Scope: c.Scope, Handle: c.Handle, ActionID: terminal.ActionID, Event: raw} |
| 147 | a := runnerproto.Assignment{ID: c.Turn.ID, Selection: c.Brief.Selection} |
| 148 | if err := validators.Events(ctx, a, q); err != nil { |
| 149 | t.Fatalf("event validator: %v; event %s", err, raw) |
| 150 | } |
| 151 | if _, err := validators.Receipt(ctx, a, q); err != nil { |
| 152 | t.Fatalf("receipt validator: %v", err) |
| 153 | } |
| 154 | must(t, x.CoordinatorEvent(ctx, p, c, terminal)) |
| 155 | must(t, x.CoordinatorEvent(ctx, p, c, terminal)) |
| 156 | must(t, x.CompleteCoordinator(ctx, p, c, event)) |
| 157 | must(t, x.CompleteCoordinator(ctx, p, c, event)) |
| 158 | action, err := x.Core.GetAction(ctx, c.Scope, c.Admission.Dispatch.Action) |
| 159 | must(t, err) |
| 160 | if action.Receipt == nil || action.Receipt.Usage == nil || action.Receipt.Usage.InputTokens != 11 { |
| 161 | t.Fatal("trusted receipt missing") |
| 162 | } |
| 163 | if f.count(t, "SELECT count(*) FROM conversation_messages WHERE body='delivered once'") != 1 { |
| 164 | t.Fatal("delivery duplicated tool effect") |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | func TestCoordinatorContextFixturePreferences(t *testing.T) { |
| 169 | f, x, p, _ := coordinatorFixture(t) |
| 170 | turn := queueCoordinator(t, f, "history", "prefs") |
| 171 | c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| 172 | must(t, err) |
| 173 | deleted := false |
| 174 | snapshot := func() runnerproto.CoordinatorContext { |
| 175 | var out runnerproto.CoordinatorContext |
| 176 | must(t, x.Write(ctx, func(tx *gorm.DB) error { |
| 177 | cs := conversation.New(tx, conversation.Dependencies{Authorize: func(tx *gorm.DB, a kernel.Actor) (string, error) { |
| 178 | var n int64 |
| 179 | err := tx.Table("members").Where("address=? AND active=1", a.Address).Count(&n).Error |
| 180 | if err != nil { |
| 181 | return "", err |
| 182 | } |
| 183 | if n != 1 { |
| 184 | return "", equipo.ErrForbidden |
| 185 | } |
| 186 | return f.TeamID, nil |
| 187 | }, ContextSource: func(context.Context, *gorm.DB, runnerproto.CoordinatorClaim) ([]runnerproto.ContextRef, []runnerproto.ContextRef, []runnerproto.ContextRef, []runnerproto.ContextRef, error) { |
| 188 | rule := runnerproto.ContextRef{Source: team.SourceRef{Kind: "team_rule", ID: "rule", Revision: 1, Hash: team.ContentDigest([]byte("required team rule"))}, Text: "required team rule"} |
| 189 | var prefs []runnerproto.ContextRef |
| 190 | if !deleted { |
| 191 | prefs = []runnerproto.ContextRef{{Source: team.SourceRef{Kind: "preference", ID: "confirmed", Revision: 2, Hash: team.ContentDigest([]byte("confirmed preference"))}, Text: "confirmed preference"}} |
| 192 | } |
| 193 | return []runnerproto.ContextRef{rule}, nil, prefs, nil, nil |
| 194 | }}) |
| 195 | var err error |
| 196 | out, err = cs.CoordinatorContext(ctx, c) |
| 197 | return err |
| 198 | })) |
| 199 | return out |
| 200 | } |
| 201 | before := snapshot() |
| 202 | deleted = true |
| 203 | after := snapshot() |
| 204 | if len(before.ConfirmedPreferences) != 1 || len(after.ConfirmedPreferences) != 0 || before.Hash == after.Hash || len(after.Instructions) != 1 { |
| 205 | t.Fatal("deleted preference survived or team rule disappeared") |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | func TestCoordinatorContextConfirmedAnswer(t *testing.T) { |
| 210 | f, x, p, c := claimTools(t) |
| 211 | question := toolCall(t, x, p, c, "question", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Choose a direction", "options": []any{}}) |
| 212 | toolCall(t, x, p, c, "suggestion", "suggest_preference", map[string]any{"source_message_id": c.Turn.MessageID, "text": "unconfirmed suggestion"}) |
| 213 | must(t, f.Store.AnswerClarification(ctx, owner, question.ResourceID, "", "explicit person decision", equipo.Mutation{RequestID: "answer", Revision: 1})) |
| 214 | must(t, x.Core.Record(ctx, c.Scope, c.Admission.Dispatch.Action, team.Receipt{ID: "receipt", Outcome: team.OutcomeSuccess})) |
| 215 | event := coordinatorEvent(c, "coordinator.delivery") |
| 216 | event.SessionID = "fixture-session" |
| 217 | event.Payload = []byte(`{"request_id":"question","resource_id":"` + question.ResourceID + `"}`) |
| 218 | must(t, x.CompleteCoordinator(ctx, p, c, event)) |
| 219 | x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| 220 | must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) |
| 221 | turns, err := x.PollCoordinator(ctx, p) |
| 222 | must(t, err) |
| 223 | if len(turns) != 1 { |
| 224 | t.Fatal(turns) |
| 225 | } |
| 226 | next, err := x.ClaimCoordinator(ctx, p, turns[0].ID, turns[0].Revision) |
| 227 | must(t, err) |
| 228 | if len(next.Context.ConfirmedDecisions) != 1 || next.Context.ConfirmedDecisions[0].Text != "explicit person decision" || len(next.Context.ConfirmedPreferences) != 0 { |
| 229 | t.Fatal("confirmed context inferred from assistant text", next.Context) |
| 230 | } |
| 231 | } |
| 232 | func TestCoordinatorSessionUnboundRunner(t *testing.T) { |
| 233 | f, x, p, _ := coordinatorFixture(t) |
| 234 | f.exec(t, "DELETE FROM coordinator_bindings") |
| 235 | turns, err := x.PollCoordinator(ctx, p) |
| 236 | must(t, err) |
| 237 | if len(turns) != 0 { |
| 238 | t.Fatal("unbound runner acquired coordinator work") |
| 239 | } |
| 240 | } |
| 241 | |