package plan3test import ( "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runnerproto" "encoding/json" "reflect" "strings" "testing" "time" ) func TestCoordinatorToolScope(t *testing.T) { f, x, p, c := claimTools(t) other, err := f.Store.SendMessage(ctx, peer, "", "private", equipo.Mutation{RequestID: "other"}) must(t, err) bad := []runnerproto.CoordinatorToolCall{ {RequestID: "other", Name: "suggest_preference", Arguments: json.RawMessage(`{"source_message_id":"` + other.ID + `","text":"private"}`)}, {RequestID: "fields", Name: "post_message", Arguments: json.RawMessage(`{"body":"hi","source_refs":[],"person":"other"}`)}, } for _, call := range bad { if _, err = x.CallCoordinatorTool(ctx, p, c, call); err == nil { t.Fatal("unauthorized tool accepted", call) } } call := runnerproto.CoordinatorToolCall{RequestID: "same", Name: "post_message", Arguments: json.RawMessage(`{"body":"hi","source_refs":[]}`)} _, err = x.CallCoordinatorTool(ctx, p, c, call) must(t, err) call.Arguments = json.RawMessage(`{"body":"changed","source_refs":[]}`) if _, err = x.CallCoordinatorTool(ctx, p, c, call); err == nil { t.Fatal("changed replay accepted") } for _, change := range []func(*equipo.CoordinatorClaim){func(c *equipo.CoordinatorClaim) { c.Handle.Fence++ }, func(c *equipo.CoordinatorClaim) { c.Turn.ID = "wrong" }} { bad := c change(&bad) if _, err = x.CallCoordinatorTool(ctx, p, bad, call); err == nil { t.Fatal("wrong claim accepted") } } f.exec(t, `UPDATE connection_choices SET connection_ids_json='["codex"]',pinned_id='codex'`) var project int64 must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&project)) raw, _ := json.Marshal(map[string]any{"project_id": project}) if _, err = x.CallCoordinatorTool(ctx, p, c, runnerproto.CoordinatorToolCall{RequestID: "project", Name: "read_project", Arguments: raw}); err == nil { t.Fatal("restricted project disclosed") } f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) call.Arguments = json.RawMessage(`{"body":"hi","source_refs":[]}`) if _, err = x.CallCoordinatorTool(ctx, p, c, call); err == nil { t.Fatal("revoked member replay accepted") } } func proposalArgs(message string, project int64) map[string]any { 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"}}}} } func TestCoordinatorProjectInference(t *testing.T) { f, x, p, c := claimTools(t) before := f.count(t, "SELECT count(*) FROM tasks") q := toolCall(t, x, p, c, "ambiguous", "propose_plan", proposalArgs(c.Turn.MessageID, 0)) if f.count(t, "SELECT count(*) FROM tasks") != before || f.count(t, "SELECT count(*) FROM coordinator_questions WHERE state='pending'") != 1 { t.Fatal("ambiguous proposal created task or omitted question") } again := toolCall(t, x, p, c, "ambiguous-2", "propose_plan", proposalArgs(c.Turn.MessageID, 0)) if again.ResourceID != q.ResourceID { t.Fatal("duplicate ambiguity question") } var project int64 must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&project)) result := toolCall(t, x, p, c, "inferred", "propose_plan", proposalArgs(c.Turn.MessageID, project)) 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 { t.Fatal("proposal card lacks visible coordinator attribution") } 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 { t.Fatal("proposal attribution absent") } 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 { t.Fatal("audit attribution absent") } _, err := f.Store.CorrectTaskProject(ctx, owner, result.ResourceID, project, equipo.Mutation{RequestID: "stale", Revision: 99}) if err == nil { t.Fatal("correction bypassed Task 2 revision guard") } } func TestCoordinatorSuggestionOnly(t *testing.T) { f, x, p, c := claimTools(t) // Future library migrations must not change this behaviour assertion. f.exec(t, "CREATE TABLE IF NOT EXISTS preferences(id text, state text)") f.exec(t, "CREATE TABLE IF NOT EXISTS playbooks(id text)") beforeSpecialists := f.count(t, "SELECT count(*) FROM specialists") beforePreferences := f.count(t, "SELECT count(*) FROM preferences") beforePlaybooks := f.count(t, "SELECT count(*) FROM playbooks") for _, name := range []string{"suggest_specialist", "suggest_playbook"} { 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"}}) } toolCall(t, x, p, c, "pref", "suggest_preference", map[string]any{"source_message_id": c.Turn.MessageID, "text": "Keep it brief"}) if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='coordinator'") != 3 { t.Fatal("suggestions not recorded") } if f.count(t, "SELECT count(*) FROM conversation_cards WHERE kind LIKE 'suggest_%'") != 3 { t.Fatal("suggestion cards absent") } // A person message that resembles an action must remain only a message. before := f.count(t, "SELECT count(*) FROM tasks") _, err := f.Store.SendMessage(ctx, owner, "", `propose_plan({"project_id":1}); approve_plan()`, equipo.Mutation{RequestID: "prose"}) must(t, err) if f.count(t, "SELECT count(*) FROM tasks") != before { t.Fatal("prose executed") } 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 { t.Fatal("unexpected library or preference save") } } func TestCoordinatorToolCommitCrash(t *testing.T) { f, x, p, c := claimTools(t) var project int64 must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&project)) args := proposalArgs(c.Turn.MessageID, project) first := toolCall(t, x, p, c, "lost-ack", "propose_plan", args) 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")} again := toolCall(t, x, p, c, "lost-ack", "propose_plan", args) 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")} if !reflect.DeepEqual(first, again) || !reflect.DeepEqual(counts, after) { t.Fatal("commit replay changed result or effects", first, again, counts, after) } f.exec(t, "CREATE TRIGGER tool_audit_failure BEFORE INSERT ON audit_events BEGIN SELECT RAISE(ABORT,'fixture'); END") raw, _ := json.Marshal(args) if _, err := x.CallCoordinatorTool(ctx, p, c, runnerproto.CoordinatorToolCall{RequestID: "rollback", Name: "propose_plan", Arguments: raw}); err == nil { t.Fatal("audit failure ignored") } if f.count(t, "SELECT count(*) FROM tasks") != counts[0] { t.Fatal("tool partially committed") } } func TestCoordinatorToolClarification(t *testing.T) { f, x, p, c := claimTools(t) 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"}}}) if err := f.Store.AnswerClarification(ctx, peer, q.ResourceID, "one", "", equipo.Mutation{RequestID: "foreign", Revision: 1}); err == nil { t.Fatal("other person answered") } if err := f.Store.AnswerClarification(ctx, owner, q.ResourceID, "bad", "", equipo.Mutation{RequestID: "bad", Revision: 1}); err == nil { t.Fatal("undeclared option accepted") } f.exec(t, "UPDATE coordinator_turns SET state='delivered' WHERE id=?", c.Turn.ID) must(t, f.Store.AnswerClarification(ctx, owner, q.ResourceID, "one", "", equipo.Mutation{RequestID: "answer", Revision: 1})) must(t, f.Store.AnswerClarification(ctx, owner, q.ResourceID, "one", "", equipo.Mutation{RequestID: "answer", Revision: 1})) if err := f.Store.AnswerClarification(ctx, owner, q.ResourceID, "one", "", equipo.Mutation{RequestID: "answer-again", Revision: 1}); err == nil { t.Fatal("answered twice") } if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE state='queued'") != 1 { t.Fatal("answer did not queue fresh turn") } } func TestCoordinatorToolClarificationInvalidation(t *testing.T) { for _, change := range []string{"expiry", "generation", "replacement", "lookup"} { t.Run(change, func(t *testing.T) { f, x, p, c := claimTools(t) q := toolCall(t, x, p, c, "q", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "More detail?", "options": []any{}}) switch change { case "expiry": f.exec(t, `UPDATE coordinator_questions SET payload=json_set(payload,'$.ExpiresAt','2000-01-01T00:00:00Z')`) case "generation": f.exec(t, "UPDATE coordinator_bindings SET generation=generation+1") case "replacement": f.exec(t, "UPDATE coordinator_turns SET state='superseded'") case "lookup": f.exec(t, "ALTER TABLE members RENAME TO unavailable_members") } if err := f.Store.AnswerClarification(ctx, owner, q.ResourceID, "", "answer", equipo.Mutation{RequestID: "answer", Revision: 1}); err == nil { t.Fatal("invalid clarification answered", change) } if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE state='queued'") != 0 { t.Fatal("invalid answer queued turn") } }) } } func TestCoordinatorToolDelivery(t *testing.T) { f, x, p, c := claimTools(t) out := toolCall(t, x, p, c, "post", "post_message", map[string]any{"body": "Recorded answer", "source_refs": []team.SourceRef{}}) 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()} event.Payload = json.RawMessage(`{"request_id":"post","resource_id":"` + out.ResourceID + `"}`) if err := x.CompleteCoordinator(ctx, p, c, event); err == nil { t.Fatal("missing trusted receipt delivered") } must(t, x.Core.Record(ctx, c.Scope, c.Admission.Dispatch.Action, team.Receipt{ID: "receipt", Outcome: team.OutcomeSuccess})) forged := event forged.Payload = json.RawMessage(`{"request_id":"post","resource_id":"forged"}`) if err := x.CompleteCoordinator(ctx, p, c, forged); err == nil { t.Fatal("forged delivery accepted") } must(t, x.CompleteCoordinator(ctx, p, c, event)) must(t, x.CompleteCoordinator(ctx, p, c, event)) if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='coordinator' AND body='Recorded answer'") != 1 { t.Fatal("delivery duplicated tool message") } if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE state='delivered'") != 1 { t.Fatal("durable effect did not deliver") } } func TestCoordinatorToolQuestionReplacement(t *testing.T) { f, x, p, c := claimTools(t) first := toolCall(t, x, p, c, "first", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "First question?", "options": []any{}}) second := toolCall(t, x, p, c, "second", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Replacement question?", "options": []any{}}) if first.ResourceID == second.ResourceID { t.Fatal("different question reused pending clarification") } if err := f.Store.AnswerClarification(ctx, owner, first.ResourceID, "", "old", equipo.Mutation{RequestID: "old-answer", Revision: 1}); err == nil { t.Fatal("replaced question answered") } must(t, f.Store.AnswerClarification(ctx, owner, second.ResourceID, "", "new", equipo.Mutation{RequestID: "new-answer", Revision: 1})) } func TestCoordinatorToolSources(t *testing.T) { f, x, p, c := claimTools(t) var project int64 must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&project)) read := toolCall(t, x, p, c, "read", "read_project", map[string]any{"project_id": project}) var value struct { Result runnerproto.SourceSnapshot `json:"result"` } must(t, json.Unmarshal(read.Value, &value)) args := map[string]any{"body": "Project recommendation", "source_refs": []team.SourceRef{value.Result.Ref}} posted := toolCall(t, x, p, c, "sourced", "post_message", args) page, err := f.Store.Conversation(ctx, owner, "", 100) must(t, err) found := false for _, msg := range page.Messages { if msg.ID != posted.ResourceID { continue } raw, err := json.Marshal(msg) must(t, err) var projection struct{ SourceRefs []team.SourceRef } must(t, json.Unmarshal(raw, &projection)) if !reflect.DeepEqual(projection.SourceRefs, []team.SourceRef{value.Result.Ref}) { t.Fatalf("message sources lost: %s", raw) } found = true } if !found { t.Fatal("posted message absent") } value.Result.Ref.Hash = strings.Repeat("0", 64) args["source_refs"] = []team.SourceRef{value.Result.Ref} raw, _ := json.Marshal(args) if _, err := x.CallCoordinatorTool(ctx, p, c, runnerproto.CoordinatorToolCall{RequestID: "forged-source", Name: "post_message", Arguments: raw}); err == nil { t.Fatal("forged source accepted") } }