package thin import ( "context" "encoding/json" "fmt" "io" "os" "path/filepath" "strings" "testing" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" ) // The tool proxy transcript is the oracle for a Mac's MCP endpoint: the // requests a CLI sends through a tool proxy to a step's tool socket and // the replies it gets back, recorded from the Linux tool proxy // (TestLinuxToolProxyTranscript) and replayed through the Mac's // (TestDarwinToolProxySpeaksTheProtocol). Its header says when and where // it was recorded. const transcriptFile = "testdata/toolproxy-transcript.txt" // transcriptSession is one tool socket's conversation: the set it // serves, its tool caller and what the CLI sends. A request without an // id is a notification and gets no reply. type transcriptSession struct { name string set toolSet call ToolFunc requests []string } // transcriptSessions are Engineering's step (its permission callback, // submit_candidate, ask_person), the answer action's read-only git tools // with the read-only callback, and a set naming submit_answer. func transcriptSessions() []transcriptSession { initialize := func(version string) string { return `{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"` + version + `","capabilities":{},"clientInfo":{"name":"claude-code","version":"2.1.312"}}}` } initialized := `{"jsonrpc":"2.0","method":"notifications/initialized"}` permission := func(id, tool, input string) string { return `{"jsonrpc":"2.0","id":` + id + `,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"` + tool + `","tool_use_id":"toolu_` + id + `","input":` + input + `}}}` } call := func(id, name, args string) string { return `{"jsonrpc":"2.0","id":` + id + `,"method":"tools/call","params":{"name":"` + name + `","arguments":` + args + `,"_meta":{"claudecode/toolUseId":"toolu_` + id + `"}}}` } // An Engineering step's policy as far as its permission callback // reads it: the workspace on the host (absent, so nothing in it is a // link), a denied path, its native tools, and every command kept in // the CLI's sandbox. policy := provider.Policy{Manifest: json.RawMessage(`{"Workspace":"/nonexistent/equipo-transcript/workspace","DeniedPaths":["/workspace/.git"],"Tools":["Bash","Read","Write","Edit","Glob","Grep"],"Settings":{"sandbox":{"enabled":true,"failIfUnavailable":true,"allowUnsandboxedCommands":false,"excludedCommands":[]}}}`)} echo := func(_ context.Context, name, useID string, args json.RawMessage) (string, bool) { return name + " " + useID + " " + string(args), false } return []transcriptSession{ { name: "implement", set: toolSet{list: stepTools, names: []string{"submit_candidate", "ask_person", "submit_render"}, permission: func(raw json.RawMessage) string { return string(claude.StepPermission(raw, policy)) }}, call: func(context.Context, string, string, json.RawMessage) (string, bool) { return stepToolText, false }, requests: []string{ initialize("2025-06-18"), initialized, `{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}`, permission("2", "Read", `{"file_path":"/workspace/main.go"}`), permission("3", "Edit", `{"file_path":"/workspace/main.go","old_string":"hello","new_string":"hola"}`), permission("4", "Read", `{"file_path":"/etc/passwd"}`), permission("5", "Read", `{"file_path":"/workspace/../etc/passwd"}`), permission("5.5", "Read", `{"file_path":"/workspace/.git/config"}`), permission("6", "WebFetch", `{"url":"https://example.com/","prompt":"read it"}`), permission("7", "Bash", `{"command":"go test ./..."}`), permission("8", "Bash", `{"command":"ls","dangerouslyDisableSandbox":true}`), permission("9", "mcp__equipo__submit_candidate", `{}`), call("10", "submit_candidate", `{}`), call("11", "ask_person", `{"question":"Which colour?"}`), call("12", "submit_render", `null`), call("13", "submit_answer", `{"answer":"yes"}`), call("14", "read_file", `{"repo":"oficina/equipo","path":"/etc/passwd"}`), `{"jsonrpc":"2.0","id":15,"method":"ping"}`, `{"jsonrpc":"2.0","id":16,"method":"resources/list","params":{}}`, `{"jsonrpc":"2.0","id":"seventeen","method":"tools/call","params":{"name":"submit_candidate"}}`, }, }, { name: "answer", set: toolSet{list: answerTools, names: []string{"git_log", "git_diff", "git_show"}, permission: func(raw json.RawMessage) string { return string(claude.ReadPermission(raw, policy)) }}, call: echo, requests: []string{ initialize("2025-03-26"), initialized, `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`, permission("2", "Read", `{"file_path":"/workspace/README.md"}`), permission("3", "Grep", `{"pattern":"TODO","path":"/workspace"}`), permission("4", "Write", `{"file_path":"/workspace/README.md","content":"x"}`), permission("5", "Bash", `{"command":"git log"}`), call("6", "git_log", `{}`), call("7", "git_diff", `{"path":"main.go"}`), call("8", "git_show", `{"commit":"abc1234"}`), call("9", "submit_candidate", `{}`), }, }, { name: "submit", set: toolSet{list: []any{map[string]any{"name": "submit_answer", "description": "Submit the answer.", "inputSchema": toolSchema(map[string]any{"answer": str}, "answer")}}, names: []string{"submit_answer"}}, call: echo, requests: []string{ `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`, `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"submit_answer","arguments":{"answer":"before"}}}`, initialize("2024-11-05"), initialized, `{"jsonrpc":"2.0","id":3,"method":"tools/list"}`, call("4", "submit_answer", `{"answer":"The greeting is in main.go, line 12."}`), permission("5", "Read", `{"file_path":"/workspace/main.go"}`), }, }, } } // shortToolRoot is a private directory for tool sockets whose paths fit // a Mac's sun_path, without symbolic links (a Mac's TMPDIR is under /var). func shortToolRoot(t *testing.T) string { t.Helper() root, err := filepath.EvalSymlinks(os.TempDir()) if err != nil { t.Fatal(err) } dir, err := os.MkdirTemp(root, "t") if err != nil { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(dir) }) if err := os.Chmod(dir, 0700); err != nil { t.Fatal(err) } // The longest socket either layout makes under dir. if len(dir)+len("/coord-tool-4294967295/equipo.sock") > provider.MaxDarwinSocketPath { t.Fatalf("TMPDIR %s is too long for a Mac socket path; set a shorter TMPDIR", root) } return dir } // toolProxyServe is a tool proxy's stdio mode: the Linux tool proxy's // toolproxy.Serve or the Mac runner's runner.ServeDarwinToolProxy. type toolProxyServe func(ctx context.Context, input io.Reader, output io.Writer, path string) error // playTranscript plays every session through serve against a fresh tool // socket and returns the transcript body: per session a "== name" line, // then each request (">") followed by its reply ("<"), if it has one. func playTranscript(t *testing.T, serve toolProxyServe) string { t.Helper() root := shortToolRoot(t) var b strings.Builder for _, s := range transcriptSessions() { sock, err := openToolSet(context.Background(), root, s.set, s.call) if err != nil { t.Fatal(err) } var out strings.Builder err = serve(context.Background(), strings.NewReader(strings.Join(s.requests, "\n")+"\n"), &out, sock.Path) sock.Close() if err != nil { t.Fatalf("%s: %v", s.name, err) } replies := strings.SplitAfter(out.String(), "\n") if replies[len(replies)-1] == "" { replies = replies[:len(replies)-1] } b.WriteString("== " + s.name + "\n") for _, q := range s.requests { b.WriteString("> " + q + "\n") var id struct { ID json.RawMessage `json:"id"` } if json.Unmarshal([]byte(q), &id) != nil { t.Fatalf("%s: a request that is not JSON: %s", s.name, q) } if len(id.ID) == 0 { continue } if len(replies) == 0 { t.Fatalf("%s: no reply to %s", s.name, q) } b.WriteString("< " + replies[0]) replies = replies[1:] } if len(replies) != 0 { t.Fatalf("%s: replies nobody asked for: %q", s.name, replies) } } return b.String() } // readTranscript is the recorded transcript's header (its "#" lines) and // body. func readTranscript(t *testing.T) (header, body string) { t.Helper() raw, err := os.ReadFile(transcriptFile) if err != nil { t.Fatal(err) } text := string(raw) for strings.HasPrefix(text, "#") { line, rest, _ := strings.Cut(text, "\n") header += line + "\n" text = rest } return header, text } // fataler is what sameTranscript needs of a test, so its own test can // watch it fail. type fataler interface { Helper() Fatalf(format string, args ...any) } // sameTranscript fails t unless got is want byte for byte, naming the // first line that differs. func sameTranscript(t fataler, got, want string) { t.Helper() if got == want { return } g, w := strings.Split(got, "\n"), strings.Split(want, "\n") for i := 0; i < len(g) || i < len(w); i++ { var gl, wl string if i < len(g) { gl = g[i] } if i < len(w) { wl = w[i] } if gl != wl || i >= len(g) || i >= len(w) { t.Fatalf("transcript line %d differs\n got %q\nwant %q", i+1, gl, wl) return } } t.Fatalf("transcript differs (%d bytes, want %d)", len(got), len(want)) } // fatalRecorder records sameTranscript's verdict. type fatalRecorder struct{ failed []string } func (r *fatalRecorder) Helper() {} func (r *fatalRecorder) Fatalf(format string, args ...any) { r.failed = append(r.failed, fmt.Sprintf(format, args...)) } // A line-based MCP client reads a reply only at its newline, so a // transcript differing only in a final newline, or in an empty last // line, differs. func TestSameTranscriptIsExact(t *testing.T) { want := "== s\n> {\"id\":1}\n< {\"id\":1}\n" for name, got := range map[string]string{ "missing final newline": strings.TrimSuffix(want, "\n"), "extra empty line": want + "\n", "changed reply": strings.Replace(want, "< {\"id\":1}", "< {\"id\":2}", 1), "missing reply": "== s\n> {\"id\":1}\n", } { r := &fatalRecorder{} sameTranscript(r, got, want) if len(r.failed) == 0 { t.Fatalf("%s: %q passed as %q", name, got, want) } } r := &fatalRecorder{} if sameTranscript(r, want, want); len(r.failed) != 0 { t.Fatalf("an equal transcript failed: %v", r.failed) } }