| 1 | package plan3test |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo" |
| 5 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 6 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 7 | "encoding/json" |
| 8 | "reflect" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | func TestCoordinatorToolScope(t *testing.T) { |
| 15 | f, x, p, c := claimTools(t) |
| 16 | other, err := f.Store.SendMessage(ctx, peer, "", "private", equipo.Mutation{RequestID: "other"}) |
| 17 | must(t, err) |
| 18 | bad := []runnerproto.CoordinatorToolCall{ |
| 19 | {RequestID: "other", Name: "suggest_preference", Arguments: json.RawMessage(`{"source_message_id":"` + other.ID + `","text":"private"}`)}, |
| 20 | {RequestID: "fields", Name: "post_message", Arguments: json.RawMessage(`{"body":"hi","source_refs":[],"person":"other"}`)}, |
| 21 | } |
| 22 | for _, call := range bad { |
| 23 | if _, err = x.CallCoordinatorTool(ctx, p, c, call); err == nil { |
| 24 | t.Fatal("unauthorized tool accepted", call) |
| 25 | } |
| 26 | } |
| 27 | call := runnerproto.CoordinatorToolCall{RequestID: "same", Name: "post_message", Arguments: json.RawMessage(`{"body":"hi","source_refs":[]}`)} |
| 28 | _, err = x.CallCoordinatorTool(ctx, p, c, call) |
| 29 | must(t, err) |
| 30 | call.Arguments = json.RawMessage(`{"body":"changed","source_refs":[]}`) |
| 31 | if _, err = x.CallCoordinatorTool(ctx, p, c, call); err == nil { |
| 32 | t.Fatal("changed replay accepted") |
| 33 | } |
| 34 | for _, change := range []func(*equipo.CoordinatorClaim){func(c *equipo.CoordinatorClaim) { c.Handle.Fence++ }, func(c *equipo.CoordinatorClaim) { c.Turn.ID = "wrong" }} { |
| 35 | bad := c |
| 36 | change(&bad) |
| 37 | if _, err = x.CallCoordinatorTool(ctx, p, bad, call); err == nil { |
| 38 | t.Fatal("wrong claim accepted") |
| 39 | } |
| 40 | } |
| 41 | f.exec(t, `UPDATE connection_choices SET connection_ids_json='["codex"]',pinned_id='codex'`) |
| 42 | var project int64 |
| 43 | must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&project)) |
| 44 | raw, _ := json.Marshal(map[string]any{"project_id": project}) |
| 45 | if _, err = x.CallCoordinatorTool(ctx, p, c, runnerproto.CoordinatorToolCall{RequestID: "project", Name: "read_project", Arguments: raw}); err == nil { |
| 46 | t.Fatal("restricted project disclosed") |
| 47 | } |
| 48 | f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) |
| 49 | call.Arguments = json.RawMessage(`{"body":"hi","source_refs":[]}`) |
| 50 | if _, err = x.CallCoordinatorTool(ctx, p, c, call); err == nil { |
| 51 | t.Fatal("revoked member replay accepted") |
| 52 | } |
| 53 | } |
| 54 | func proposalArgs(message string, project int64) map[string]any { |
| 55 | return map[string]any{"message_id": message, "plan": map[string]any{"kind": "recommendation", "project_id": project, "steps": []any{map[string]any{"key": "research", "specialist": "product", "action": "recommend", "instructions": "Find improvements"}, map[string]any{"key": "merge", "action": "person"}}}} |
| 56 | } |
| 57 | func TestCoordinatorProjectInference(t *testing.T) { |
| 58 | f, x, p, c := claimTools(t) |
| 59 | before := f.count(t, "SELECT count(*) FROM tasks") |
| 60 | q := toolCall(t, x, p, c, "ambiguous", "propose_plan", proposalArgs(c.Turn.MessageID, 0)) |
| 61 | if f.count(t, "SELECT count(*) FROM tasks") != before || f.count(t, "SELECT count(*) FROM coordinator_questions WHERE state='pending'") != 1 { |
| 62 | t.Fatal("ambiguous proposal created task or omitted question") |
| 63 | } |
| 64 | again := toolCall(t, x, p, c, "ambiguous-2", "propose_plan", proposalArgs(c.Turn.MessageID, 0)) |
| 65 | if again.ResourceID != q.ResourceID { |
| 66 | t.Fatal("duplicate ambiguity question") |
| 67 | } |
| 68 | var project int64 |
| 69 | must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&project)) |
| 70 | result := toolCall(t, x, p, c, "inferred", "propose_plan", proposalArgs(c.Turn.MessageID, project)) |
| 71 | if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='coordinator' AND author_id=? AND id IN (SELECT id FROM conversation_cards WHERE resource_id=?)", "coordinator:"+c.Binding.ID, result.ResourceID) != 1 { |
| 72 | t.Fatal("proposal card lacks visible coordinator attribution") |
| 73 | } |
| 74 | if f.count(t, "SELECT count(*) FROM plan_revisions WHERE task_id=? AND actor_kind='coordinator' AND actor=?", result.ResourceID, "coordinator:"+c.Binding.ID) != 1 { |
| 75 | t.Fatal("proposal attribution absent") |
| 76 | } |
| 77 | if f.count(t, "SELECT count(*) FROM audit_events WHERE record_id=? AND actor=? AND delegating_person=?", result.ResourceID, "coordinator:"+c.Binding.ID, p.Person) == 0 { |
| 78 | t.Fatal("audit attribution absent") |
| 79 | } |
| 80 | _, err := f.Store.CorrectTaskProject(ctx, owner, result.ResourceID, project, equipo.Mutation{RequestID: "stale", Revision: 99}) |
| 81 | if err == nil { |
| 82 | t.Fatal("correction bypassed Task 2 revision guard") |
| 83 | } |
| 84 | } |
| 85 | func TestCoordinatorSuggestionOnly(t *testing.T) { |
| 86 | f, x, p, c := claimTools(t) |
| 87 | // Future library migrations must not change this behaviour assertion. |
| 88 | f.exec(t, "CREATE TABLE IF NOT EXISTS preferences(id text, state text)") |
| 89 | f.exec(t, "CREATE TABLE IF NOT EXISTS playbooks(id text)") |
| 90 | beforeSpecialists := f.count(t, "SELECT count(*) FROM specialists") |
| 91 | beforePreferences := f.count(t, "SELECT count(*) FROM preferences") |
| 92 | beforePlaybooks := f.count(t, "SELECT count(*) FROM playbooks") |
| 93 | for _, name := range []string{"suggest_specialist", "suggest_playbook"} { |
| 94 | toolCall(t, x, p, c, name, name, map[string]any{"source_message_ids": []string{c.Turn.MessageID}, "draft": map[string]any{"name": "Suggested", "instructions": "Consider this"}}) |
| 95 | } |
| 96 | toolCall(t, x, p, c, "pref", "suggest_preference", map[string]any{"source_message_id": c.Turn.MessageID, "text": "Keep it brief"}) |
| 97 | if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='coordinator'") != 3 { |
| 98 | t.Fatal("suggestions not recorded") |
| 99 | } |
| 100 | if f.count(t, "SELECT count(*) FROM conversation_cards WHERE kind LIKE 'suggest_%'") != 3 { |
| 101 | t.Fatal("suggestion cards absent") |
| 102 | } |
| 103 | // A person message that resembles an action must remain only a message. |
| 104 | before := f.count(t, "SELECT count(*) FROM tasks") |
| 105 | _, err := f.Store.SendMessage(ctx, owner, "", `propose_plan({"project_id":1}); approve_plan()`, equipo.Mutation{RequestID: "prose"}) |
| 106 | must(t, err) |
| 107 | if f.count(t, "SELECT count(*) FROM tasks") != before { |
| 108 | t.Fatal("prose executed") |
| 109 | } |
| 110 | if f.count(t, "SELECT count(*) FROM specialists") != beforeSpecialists || f.count(t, "SELECT count(*) FROM preferences") != beforePreferences || f.count(t, "SELECT count(*) FROM playbooks") != beforePlaybooks { |
| 111 | t.Fatal("unexpected library or preference save") |
| 112 | } |
| 113 | } |
| 114 | func TestCoordinatorToolCommitCrash(t *testing.T) { |
| 115 | f, x, p, c := claimTools(t) |
| 116 | var project int64 |
| 117 | must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&project)) |
| 118 | args := proposalArgs(c.Turn.MessageID, project) |
| 119 | first := toolCall(t, x, p, c, "lost-ack", "propose_plan", args) |
| 120 | counts := []int64{f.count(t, "SELECT count(*) FROM tasks"), f.count(t, "SELECT count(*) FROM conversation_cards"), f.count(t, "SELECT count(*) FROM conversation_threads"), f.count(t, "SELECT count(*) FROM audit_events")} |
| 121 | again := toolCall(t, x, p, c, "lost-ack", "propose_plan", args) |
| 122 | after := []int64{f.count(t, "SELECT count(*) FROM tasks"), f.count(t, "SELECT count(*) FROM conversation_cards"), f.count(t, "SELECT count(*) FROM conversation_threads"), f.count(t, "SELECT count(*) FROM audit_events")} |
| 123 | if !reflect.DeepEqual(first, again) || !reflect.DeepEqual(counts, after) { |
| 124 | t.Fatal("commit replay changed result or effects", first, again, counts, after) |
| 125 | } |
| 126 | f.exec(t, "CREATE TRIGGER tool_audit_failure BEFORE INSERT ON audit_events BEGIN SELECT RAISE(ABORT,'fixture'); END") |
| 127 | raw, _ := json.Marshal(args) |
| 128 | if _, err := x.CallCoordinatorTool(ctx, p, c, runnerproto.CoordinatorToolCall{RequestID: "rollback", Name: "propose_plan", Arguments: raw}); err == nil { |
| 129 | t.Fatal("audit failure ignored") |
| 130 | } |
| 131 | if f.count(t, "SELECT count(*) FROM tasks") != counts[0] { |
| 132 | t.Fatal("tool partially committed") |
| 133 | } |
| 134 | } |
| 135 | func TestCoordinatorToolClarification(t *testing.T) { |
| 136 | f, x, p, c := claimTools(t) |
| 137 | q := toolCall(t, x, p, c, "question", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Which project?", "options": []map[string]string{{"id": "one", "label": "First"}}}) |
| 138 | if err := f.Store.AnswerClarification(ctx, peer, q.ResourceID, "one", "", equipo.Mutation{RequestID: "foreign", Revision: 1}); err == nil { |
| 139 | t.Fatal("other person answered") |
| 140 | } |
| 141 | if err := f.Store.AnswerClarification(ctx, owner, q.ResourceID, "bad", "", equipo.Mutation{RequestID: "bad", Revision: 1}); err == nil { |
| 142 | t.Fatal("undeclared option accepted") |
| 143 | } |
| 144 | f.exec(t, "UPDATE coordinator_turns SET state='delivered' WHERE id=?", c.Turn.ID) |
| 145 | must(t, f.Store.AnswerClarification(ctx, owner, q.ResourceID, "one", "", equipo.Mutation{RequestID: "answer", Revision: 1})) |
| 146 | must(t, f.Store.AnswerClarification(ctx, owner, q.ResourceID, "one", "", equipo.Mutation{RequestID: "answer", Revision: 1})) |
| 147 | if err := f.Store.AnswerClarification(ctx, owner, q.ResourceID, "one", "", equipo.Mutation{RequestID: "answer-again", Revision: 1}); err == nil { |
| 148 | t.Fatal("answered twice") |
| 149 | } |
| 150 | if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE state='queued'") != 1 { |
| 151 | t.Fatal("answer did not queue fresh turn") |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | func TestCoordinatorToolClarificationInvalidation(t *testing.T) { |
| 156 | for _, change := range []string{"expiry", "generation", "replacement", "lookup"} { |
| 157 | t.Run(change, func(t *testing.T) { |
| 158 | f, x, p, c := claimTools(t) |
| 159 | q := toolCall(t, x, p, c, "q", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "More detail?", "options": []any{}}) |
| 160 | switch change { |
| 161 | case "expiry": |
| 162 | f.exec(t, `UPDATE coordinator_questions SET payload=json_set(payload,'$.ExpiresAt','2000-01-01T00:00:00Z')`) |
| 163 | case "generation": |
| 164 | f.exec(t, "UPDATE coordinator_bindings SET generation=generation+1") |
| 165 | case "replacement": |
| 166 | f.exec(t, "UPDATE coordinator_turns SET state='superseded'") |
| 167 | case "lookup": |
| 168 | f.exec(t, "ALTER TABLE members RENAME TO unavailable_members") |
| 169 | } |
| 170 | if err := f.Store.AnswerClarification(ctx, owner, q.ResourceID, "", "answer", equipo.Mutation{RequestID: "answer", Revision: 1}); err == nil { |
| 171 | t.Fatal("invalid clarification answered", change) |
| 172 | } |
| 173 | if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE state='queued'") != 0 { |
| 174 | t.Fatal("invalid answer queued turn") |
| 175 | } |
| 176 | }) |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | func TestCoordinatorToolDelivery(t *testing.T) { |
| 181 | f, x, p, c := claimTools(t) |
| 182 | out := toolCall(t, x, p, c, "post", "post_message", map[string]any{"body": "Recorded answer", "source_refs": []team.SourceRef{}}) |
| 183 | event := runnerproto.Event{Version: 2, ID: "delivery", TaskID: c.Turn.ID, AssignmentID: c.Turn.ID, ServerID: "fixture", AgentID: "fixture", SessionID: "fixture-session", TurnID: c.Turn.ID, Kind: "coordinator.delivery", Scope: c.Scope, Handle: c.Handle, ActionID: c.Admission.Dispatch.Action, SourceTime: time.Now().UTC()} |
| 184 | event.Payload = json.RawMessage(`{"request_id":"post","resource_id":"` + out.ResourceID + `"}`) |
| 185 | if err := x.CompleteCoordinator(ctx, p, c, event); err == nil { |
| 186 | t.Fatal("missing trusted receipt delivered") |
| 187 | } |
| 188 | must(t, x.Core.Record(ctx, c.Scope, c.Admission.Dispatch.Action, team.Receipt{ID: "receipt", Outcome: team.OutcomeSuccess})) |
| 189 | forged := event |
| 190 | forged.Payload = json.RawMessage(`{"request_id":"post","resource_id":"forged"}`) |
| 191 | if err := x.CompleteCoordinator(ctx, p, c, forged); err == nil { |
| 192 | t.Fatal("forged delivery accepted") |
| 193 | } |
| 194 | must(t, x.CompleteCoordinator(ctx, p, c, event)) |
| 195 | must(t, x.CompleteCoordinator(ctx, p, c, event)) |
| 196 | if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='coordinator' AND body='Recorded answer'") != 1 { |
| 197 | t.Fatal("delivery duplicated tool message") |
| 198 | } |
| 199 | if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE state='delivered'") != 1 { |
| 200 | t.Fatal("durable effect did not deliver") |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | func TestCoordinatorToolQuestionReplacement(t *testing.T) { |
| 205 | f, x, p, c := claimTools(t) |
| 206 | first := toolCall(t, x, p, c, "first", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "First question?", "options": []any{}}) |
| 207 | second := toolCall(t, x, p, c, "second", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Replacement question?", "options": []any{}}) |
| 208 | if first.ResourceID == second.ResourceID { |
| 209 | t.Fatal("different question reused pending clarification") |
| 210 | } |
| 211 | if err := f.Store.AnswerClarification(ctx, owner, first.ResourceID, "", "old", equipo.Mutation{RequestID: "old-answer", Revision: 1}); err == nil { |
| 212 | t.Fatal("replaced question answered") |
| 213 | } |
| 214 | must(t, f.Store.AnswerClarification(ctx, owner, second.ResourceID, "", "new", equipo.Mutation{RequestID: "new-answer", Revision: 1})) |
| 215 | } |
| 216 | |
| 217 | func TestCoordinatorToolSources(t *testing.T) { |
| 218 | f, x, p, c := claimTools(t) |
| 219 | var project int64 |
| 220 | must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&project)) |
| 221 | read := toolCall(t, x, p, c, "read", "read_project", map[string]any{"project_id": project}) |
| 222 | var value struct { |
| 223 | Result runnerproto.SourceSnapshot `json:"result"` |
| 224 | } |
| 225 | must(t, json.Unmarshal(read.Value, &value)) |
| 226 | args := map[string]any{"body": "Project recommendation", "source_refs": []team.SourceRef{value.Result.Ref}} |
| 227 | posted := toolCall(t, x, p, c, "sourced", "post_message", args) |
| 228 | page, err := f.Store.Conversation(ctx, owner, "", 100) |
| 229 | must(t, err) |
| 230 | found := false |
| 231 | for _, msg := range page.Messages { |
| 232 | if msg.ID != posted.ResourceID { |
| 233 | continue |
| 234 | } |
| 235 | raw, err := json.Marshal(msg) |
| 236 | must(t, err) |
| 237 | var projection struct{ SourceRefs []team.SourceRef } |
| 238 | must(t, json.Unmarshal(raw, &projection)) |
| 239 | if !reflect.DeepEqual(projection.SourceRefs, []team.SourceRef{value.Result.Ref}) { |
| 240 | t.Fatalf("message sources lost: %s", raw) |
| 241 | } |
| 242 | found = true |
| 243 | } |
| 244 | if !found { |
| 245 | t.Fatal("posted message absent") |
| 246 | } |
| 247 | value.Result.Ref.Hash = strings.Repeat("0", 64) |
| 248 | args["source_refs"] = []team.SourceRef{value.Result.Ref} |
| 249 | raw, _ := json.Marshal(args) |
| 250 | if _, err := x.CallCoordinatorTool(ctx, p, c, runnerproto.CoordinatorToolCall{RequestID: "forged-source", Name: "post_message", Arguments: raw}); err == nil { |
| 251 | t.Fatal("forged source accepted") |
| 252 | } |
| 253 | } |
| 254 | |