package runner import ( "context" "encoding/json" "fmt" "net" "os" "path/filepath" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/runner/provider/codex" "amadan.net/oficina/equipo/internal/runnerproto" ) func TestCoordinatorToolAllowlist(t *testing.T) { profile, _ := provider.Profile("coordinate") for _, family := range []string{"claude", "codex"} { b := provider.Binding{Provider: family, CredentialHome: "/private/account", Home: "/private/run", RuntimeRoot: "/private/runtime"} in := provider.PolicyInputs{Action: "coordinate", Tools: profile.MCPTools()} var got provider.PolicyInputs var err error if family == "claude" { got, err = claude.PolicyInputs(b, in, profile.Specialist, "model") } else { got, err = codex.PolicyInputs(b, in, "model") } if err != nil { t.Fatal(err) } for _, tool := range got.Tools { if !strings.HasPrefix(tool, "mcp__equipo__") { t.Fatalf("coordinator exposes built-in tool %s", tool) } } if family == "claude" { if len(got.NativeTools) != 0 { t.Fatal("Claude native policy widened") } for i, arg := range got.Argv { if arg == "--tools" && got.Argv[i+1] != "" { t.Fatal("nonempty built-in inventory") } } } else { if !slices.Equal(got.NativeTools, []string{"list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"}) { t.Fatal("Codex native exception is not exact") } var cfg map[string]any json.Unmarshal(got.Settings, &cfg) servers := cfg["mcp_servers"].(map[string]any) if len(servers) != 1 || servers["equipo"] == nil { t.Fatal("additional MCP server configured") } var mcp struct { Servers map[string]any `json:"mcpServers"` } if json.Unmarshal(got.MCP, &mcp) != nil || len(mcp.Servers) != 1 || mcp.Servers["equipo"] == nil { t.Fatal("additional MCP server in manifest") } for _, key := range []string{"shell_tool", "view_image", "search_tool", "browser_use", "computer_use", "code_mode", "js_repl"} { if cfg["features"].(map[string]any)[key] != false { t.Fatal("Codex built-in enabled", key) } } var catalog struct { Models []struct { Shell string `json:"shell_type"` Patch any `json:"apply_patch_tool_type"` Tools []string `json:"experimental_supported_tools"` } } if json.Unmarshal(got.Catalog, &catalog) != nil || len(catalog.Models) != 1 || catalog.Models[0].Shell != "disabled" || catalog.Models[0].Patch != nil || len(catalog.Models[0].Tools) != 0 { t.Fatal("Codex model catalog enables native tools") } if cfg["web_search"] != "disabled" { t.Fatal("web search enabled") } } } } func TestCoordinatorToolJournal(t *testing.T) { ctx := context.Background() root := t.TempDir() mustJournal(t, os.Chmod(root, 0700)) j, err := OpenJournal(ctx, filepath.Join(root, "journal.db")) if err != nil { t.Fatal(err) } defer j.Close() c := runnerproto.CoordinatorClaim{} c.Scope.Account = "instance" c.Binding.ID = "binding" c.Binding.Generation = 1 c.Turn.ID = "turn" c.Handle.Attempt = 1 c.Handle.Fence = 2 session := provider.Session{ID: "session", AttemptKey: "attempt", Provider: "claude"} call := runnerproto.CoordinatorToolCall{RequestID: "r", Name: "post_message", Arguments: json.RawMessage(`{"body":"hi","source_refs":[]}`)} if err = j.reserveCoordinatorTool(ctx, c, session, call); err != nil { t.Fatal(err) } changed := call changed.Arguments = json.RawMessage(`{"body":"changed","source_refs":[]}`) if err = j.reserveCoordinatorTool(ctx, c, session, changed); err == nil { t.Fatal("approval request hash changed") } pending, err := j.CoordinatorToolSubmissions(ctx, 10) if err != nil || len(pending) != 0 { t.Fatal("approval queued execution", pending, err) } mustJournal(t, j.submitCoordinatorTool(ctx, c, session, call)) pending, err = j.CoordinatorToolSubmissions(ctx, 10) if err != nil || len(pending) != 1 { t.Fatal("missing durable submission", pending, err) } result := runnerproto.CoordinatorToolResult{ResourceID: "message", Revision: 1, Value: json.RawMessage(`{}`)} if err = j.ackCoordinatorTool(ctx, c, session, call, result); err != nil { t.Fatal(err) } if err = j.reserveCoordinatorTool(ctx, c, session, changed); err == nil { t.Fatal("acked request hash changed") } if err = j.reserveCoordinatorTool(ctx, c, session, call); err != nil { t.Fatal(err) } pending, err = j.CoordinatorToolSubmissions(ctx, 10) if err != nil || len(pending) != 0 { t.Fatal("ack not durable", pending, err) } } func TestCoordinatorToolBroker(t *testing.T) { for _, family := range []string{"claude", "codex"} { t.Run(family, func(t *testing.T) { ctx := context.Background() j, _, session, _ := directFixture(t, family) mustJournal(t, j.BeginTurn(ctx, session, directTurn())) mustJournal(t, j.consumeTurn(ctx, session.AttemptKey, session.ID, "hello")) c := runnerproto.CoordinatorClaim{} c.Scope.Account = "instance" c.Binding.ID = "binding" c.Binding.Generation = 1 c.Turn.ID = "turn" c.Turn.Generation = 1 c.Handle.Attempt = 1 c.Handle.Fence = 7 c.LeaseDeadline = time.Now().Add(time.Minute) c.AttemptDeadline = time.Now().Add(time.Hour) c.Brief.Selection.Provider = family c.Brief.Selection.AccountID = session.AccountID c.Brief.Selection.Model = session.Model c.Brief.Selection.Isolation.Status = "confined" c.ToolCopy = runnerproto.CoordinatorToolCopy{Accepted: "accepted", Rejected: "rejected"} current := true calls := 0 p, err := OpenCoordinatorToolProxy(ctx, CoordinatorToolBinding{Claim: c, Session: session, Journal: j, Current: func(context.Context) error { if !current { return runnerproto.ErrInvalid } return nil }, Call: func(_ context.Context, call runnerproto.CoordinatorToolCall) (runnerproto.CoordinatorToolResult, error) { calls++ return runnerproto.CoordinatorToolResult{ResourceID: "message", Revision: 1, Value: json.RawMessage(`{}`)}, nil }}) mustJournal(t, err) defer p.Close() call := runnerproto.CoordinatorToolCall{RequestID: "r", Name: "post_message", Arguments: json.RawMessage(`{"body":"hi","source_refs":[]}`)} mustJournal(t, p.ValidateCoordinatorApproval(ctx, call)) if calls != 0 { t.Fatal("approval executed tool") } changed := call changed.Arguments = json.RawMessage(`{"body":"different","source_refs":[]}`) if _, err = p.CallCoordinatorTool(ctx, changed); err == nil { t.Fatal("execution changed approved hash") } _, err = p.CallCoordinatorTool(ctx, call) mustJournal(t, err) if calls != 1 { t.Fatal("tool did not execute") } if family == "claude" { raw := json.RawMessage(`{"tool_name":"mcp__equipo__post_message","input":{"request_id":"r","body":"hi","source_refs":[]}}`) if _, err = p.coordinatorPermission(ctx, raw); err != nil { t.Fatal(err) } if _, err = p.coordinatorPermission(ctx, json.RawMessage(`{"tool_name":"Bash","input":{"command":"ls"}}`)); err == nil { t.Fatal("native permission granted") } } // Exercise the actual MCP transport and its coordinator schema selection. dir, err := os.Open(filepath.Dir(p.SocketPath)) mustJournal(t, err) defer dir.Close() conn, err := net.Dial("unix", fmt.Sprintf("/proc/self/fd/%d/equipo.sock", dir.Fd())) mustJournal(t, err) defer conn.Close() enc := json.NewEncoder(conn) dec := json.NewDecoder(conn) for i, method := range []string{"initialize", "tools/list", "resources/list", "resources/templates/list", "resources/read", "tools/call"} { var params any = map[string]any{} if method == "initialize" { params = map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{}, "clientInfo": map[string]any{}} } if method == "resources/read" { params = map[string]any{"uri": "file:///workspace/private"} } if method == "tools/call" { params = map[string]any{"name": "read_project", "arguments": map[string]any{"request_id": "read", "project_id": 1}} } mustJournal(t, enc.Encode(map[string]any{"jsonrpc": "2.0", "id": i, "method": method, "params": params})) var reply map[string]any mustJournal(t, dec.Decode(&reply)) if method == "resources/read" { if reply["error"] == nil || reply["result"] != nil { t.Fatal("resource read succeeded", reply) } continue } if reply["error"] != nil { t.Fatal(reply) } if method == "initialize" { caps := reply["result"].(map[string]any)["capabilities"].(map[string]any) if _, ok := caps["resources"]; !ok { t.Fatal("resources capability missing") } } if method == "resources/list" { entries := reply["result"].(map[string]any)["resources"].([]any) if len(entries) != 1 || entries[0].(map[string]any)["uri"] != "equipo://routing-check" { t.Fatal("unexpected resources", reply) } } if method == "resources/templates/list" && len(reply["result"].(map[string]any)["resourceTemplates"].([]any)) != 0 { t.Fatal("resource templates exposed", reply) } if method == "tools/list" { raw, _ := json.Marshal(reply) if !strings.Contains(string(raw), "source_message_ids") || strings.Contains(string(raw), "submit_candidate") { t.Fatal("task schema leaked", string(raw)) } } } current = false if _, err = p.CallCoordinatorTool(ctx, call); err == nil { t.Fatal("revoked authority replay") } if p.ValidateCoordinatorApproval(ctx, call) == nil { t.Fatal("revoked approval") } }) } } func TestCoordinatorToolJournalUpgrade(t *testing.T) { ctx := context.Background() path := filepath.Join(t.TempDir(), "private", "journal.db") j, err := OpenJournal(ctx, path) mustJournal(t, err) mustJournal(t, j.Append(ctx, journalEvent("retained", 1))) _, err = j.db.Exec("DROP TABLE coordinator_tools; DROP TABLE coordinator_tool_claims; DROP INDEX journal_coordinator_delivery; PRAGMA user_version=4") mustJournal(t, err) mustJournal(t, j.Close()) j, err = OpenJournal(ctx, path) mustJournal(t, err) defer j.Close() var version int mustJournal(t, j.db.QueryRow("PRAGMA user_version").Scan(&version)) if version != 6 { t.Fatal("ordered migration missing", version) } pending, err := j.Pending(ctx, 10) mustJournal(t, err) if len(pending) != 1 || pending[0].ID != "retained" { t.Fatal("old outbox lost") } rows, err := j.CoordinatorToolSubmissions(ctx, 10) mustJournal(t, err) if len(rows) != 0 { t.Fatal("invented coordinator submissions") } }