oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io"
8 "os"
9 "path/filepath"
10 "strings"
11 "testing"
12
13 "amadan.net/oficina/equipo/internal/runner/provider"
14 "amadan.net/oficina/equipo/internal/runner/provider/claude"
15)
16
17// The tool proxy transcript is the oracle for a Mac's MCP endpoint: the
18// requests a CLI sends through a tool proxy to a step's tool socket and
19// the replies it gets back, recorded from the Linux tool proxy
20// (TestLinuxToolProxyTranscript) and replayed through the Mac's
21// (TestDarwinToolProxySpeaksTheProtocol). Its header says when and where
22// it was recorded.
23const transcriptFile = "testdata/toolproxy-transcript.txt"
24
25// transcriptSession is one tool socket's conversation: the set it
26// serves, its tool caller and what the CLI sends. A request without an
27// id is a notification and gets no reply.
28type transcriptSession struct {
29 name string
30 set toolSet
31 call ToolFunc
32 requests []string
33}
34
35// transcriptSessions are Engineering's step (its permission callback,
36// submit_candidate, ask_person), the answer action's read-only git tools
37// with the read-only callback, and a set naming submit_answer.
38func transcriptSessions() []transcriptSession {
39 initialize := func(version string) string {
40 return `{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"` + version + `","capabilities":{},"clientInfo":{"name":"claude-code","version":"2.1.312"}}}`
41 }
42 initialized := `{"jsonrpc":"2.0","method":"notifications/initialized"}`
43 permission := func(id, tool, input string) string {
44 return `{"jsonrpc":"2.0","id":` + id + `,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"` + tool + `","tool_use_id":"toolu_` + id + `","input":` + input + `}}}`
45 }
46 call := func(id, name, args string) string {
47 return `{"jsonrpc":"2.0","id":` + id + `,"method":"tools/call","params":{"name":"` + name + `","arguments":` + args + `,"_meta":{"claudecode/toolUseId":"toolu_` + id + `"}}}`
48 }
49 // An Engineering step's policy as far as its permission callback
50 // reads it: the workspace on the host (absent, so nothing in it is a
51 // link), a denied path, its native tools, and every command kept in
52 // the CLI's sandbox.
53 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":[]}}}`)}
54 echo := func(_ context.Context, name, useID string, args json.RawMessage) (string, bool) {
55 return name + " " + useID + " " + string(args), false
56 }
57 return []transcriptSession{
58 {
59 name: "implement",
60 set: toolSet{list: stepTools, names: []string{"submit_candidate", "ask_person", "submit_render"}, permission: func(raw json.RawMessage) string {
61 return string(claude.StepPermission(raw, policy))
62 }},
63 call: func(context.Context, string, string, json.RawMessage) (string, bool) { return stepToolText, false },
64 requests: []string{
65 initialize("2025-06-18"),
66 initialized,
67 `{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}`,
68 permission("2", "Read", `{"file_path":"/workspace/main.go"}`),
69 permission("3", "Edit", `{"file_path":"/workspace/main.go","old_string":"hello","new_string":"hola"}`),
70 permission("4", "Read", `{"file_path":"/etc/passwd"}`),
71 permission("5", "Read", `{"file_path":"/workspace/../etc/passwd"}`),
72 permission("5.5", "Read", `{"file_path":"/workspace/.git/config"}`),
73 permission("6", "WebFetch", `{"url":"https://example.com/","prompt":"read it"}`),
74 permission("7", "Bash", `{"command":"go test ./..."}`),
75 permission("8", "Bash", `{"command":"ls","dangerouslyDisableSandbox":true}`),
76 permission("9", "mcp__equipo__submit_candidate", `{}`),
77 call("10", "submit_candidate", `{}`),
78 call("11", "ask_person", `{"question":"Which colour?"}`),
79 call("12", "submit_render", `null`),
80 call("13", "submit_answer", `{"answer":"yes"}`),
81 call("14", "read_file", `{"repo":"oficina/equipo","path":"/etc/passwd"}`),
82 `{"jsonrpc":"2.0","id":15,"method":"ping"}`,
83 `{"jsonrpc":"2.0","id":16,"method":"resources/list","params":{}}`,
84 `{"jsonrpc":"2.0","id":"seventeen","method":"tools/call","params":{"name":"submit_candidate"}}`,
85 },
86 },
87 {
88 name: "answer",
89 set: toolSet{list: answerTools, names: []string{"git_log", "git_diff", "git_show"}, permission: func(raw json.RawMessage) string {
90 return string(claude.ReadPermission(raw, policy))
91 }},
92 call: echo,
93 requests: []string{
94 initialize("2025-03-26"),
95 initialized,
96 `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`,
97 permission("2", "Read", `{"file_path":"/workspace/README.md"}`),
98 permission("3", "Grep", `{"pattern":"TODO","path":"/workspace"}`),
99 permission("4", "Write", `{"file_path":"/workspace/README.md","content":"x"}`),
100 permission("5", "Bash", `{"command":"git log"}`),
101 call("6", "git_log", `{}`),
102 call("7", "git_diff", `{"path":"main.go"}`),
103 call("8", "git_show", `{"commit":"abc1234"}`),
104 call("9", "submit_candidate", `{}`),
105 },
106 },
107 {
108 name: "submit",
109 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"}},
110 call: echo,
111 requests: []string{
112 `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`,
113 `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"submit_answer","arguments":{"answer":"before"}}}`,
114 initialize("2024-11-05"),
115 initialized,
116 `{"jsonrpc":"2.0","id":3,"method":"tools/list"}`,
117 call("4", "submit_answer", `{"answer":"The greeting is in main.go, line 12."}`),
118 permission("5", "Read", `{"file_path":"/workspace/main.go"}`),
119 },
120 },
121 }
122}
123
124// shortToolRoot is a private directory for tool sockets whose paths fit
125// a Mac's sun_path, without symbolic links (a Mac's TMPDIR is under /var).
126func shortToolRoot(t *testing.T) string {
127 t.Helper()
128 root, err := filepath.EvalSymlinks(os.TempDir())
129 if err != nil {
130 t.Fatal(err)
131 }
132 dir, err := os.MkdirTemp(root, "t")
133 if err != nil {
134 t.Fatal(err)
135 }
136 t.Cleanup(func() { os.RemoveAll(dir) })
137 if err := os.Chmod(dir, 0700); err != nil {
138 t.Fatal(err)
139 }
140 // The longest socket either layout makes under dir.
141 if len(dir)+len("/coord-tool-4294967295/equipo.sock") > provider.MaxDarwinSocketPath {
142 t.Fatalf("TMPDIR %s is too long for a Mac socket path; set a shorter TMPDIR", root)
143 }
144 return dir
145}
146
147// toolProxyServe is a tool proxy's stdio mode: the Linux tool proxy's
148// toolproxy.Serve or the Mac runner's runner.ServeDarwinToolProxy.
149type toolProxyServe func(ctx context.Context, input io.Reader, output io.Writer, path string) error
150
151// playTranscript plays every session through serve against a fresh tool
152// socket and returns the transcript body: per session a "== name" line,
153// then each request (">") followed by its reply ("<"), if it has one.
154func playTranscript(t *testing.T, serve toolProxyServe) string {
155 t.Helper()
156 root := shortToolRoot(t)
157 var b strings.Builder
158 for _, s := range transcriptSessions() {
159 sock, err := openToolSet(context.Background(), root, s.set, s.call)
160 if err != nil {
161 t.Fatal(err)
162 }
163 var out strings.Builder
164 err = serve(context.Background(), strings.NewReader(strings.Join(s.requests, "\n")+"\n"), &out, sock.Path)
165 sock.Close()
166 if err != nil {
167 t.Fatalf("%s: %v", s.name, err)
168 }
169 replies := strings.SplitAfter(out.String(), "\n")
170 if replies[len(replies)-1] == "" {
171 replies = replies[:len(replies)-1]
172 }
173 b.WriteString("== " + s.name + "\n")
174 for _, q := range s.requests {
175 b.WriteString("> " + q + "\n")
176 var id struct {
177 ID json.RawMessage `json:"id"`
178 }
179 if json.Unmarshal([]byte(q), &id) != nil {
180 t.Fatalf("%s: a request that is not JSON: %s", s.name, q)
181 }
182 if len(id.ID) == 0 {
183 continue
184 }
185 if len(replies) == 0 {
186 t.Fatalf("%s: no reply to %s", s.name, q)
187 }
188 b.WriteString("< " + replies[0])
189 replies = replies[1:]
190 }
191 if len(replies) != 0 {
192 t.Fatalf("%s: replies nobody asked for: %q", s.name, replies)
193 }
194 }
195 return b.String()
196}
197
198// readTranscript is the recorded transcript's header (its "#" lines) and
199// body.
200func readTranscript(t *testing.T) (header, body string) {
201 t.Helper()
202 raw, err := os.ReadFile(transcriptFile)
203 if err != nil {
204 t.Fatal(err)
205 }
206 text := string(raw)
207 for strings.HasPrefix(text, "#") {
208 line, rest, _ := strings.Cut(text, "\n")
209 header += line + "\n"
210 text = rest
211 }
212 return header, text
213}
214
215// fataler is what sameTranscript needs of a test, so its own test can
216// watch it fail.
217type fataler interface {
218 Helper()
219 Fatalf(format string, args ...any)
220}
221
222// sameTranscript fails t unless got is want byte for byte, naming the
223// first line that differs.
224func sameTranscript(t fataler, got, want string) {
225 t.Helper()
226 if got == want {
227 return
228 }
229 g, w := strings.Split(got, "\n"), strings.Split(want, "\n")
230 for i := 0; i < len(g) || i < len(w); i++ {
231 var gl, wl string
232 if i < len(g) {
233 gl = g[i]
234 }
235 if i < len(w) {
236 wl = w[i]
237 }
238 if gl != wl || i >= len(g) || i >= len(w) {
239 t.Fatalf("transcript line %d differs\n got %q\nwant %q", i+1, gl, wl)
240 return
241 }
242 }
243 t.Fatalf("transcript differs (%d bytes, want %d)", len(got), len(want))
244}
245
246// fatalRecorder records sameTranscript's verdict.
247type fatalRecorder struct{ failed []string }
248
249func (r *fatalRecorder) Helper() {}
250func (r *fatalRecorder) Fatalf(format string, args ...any) {
251 r.failed = append(r.failed, fmt.Sprintf(format, args...))
252}
253
254// A line-based MCP client reads a reply only at its newline, so a
255// transcript differing only in a final newline, or in an empty last
256// line, differs.
257func TestSameTranscriptIsExact(t *testing.T) {
258 want := "== s\n> {\"id\":1}\n< {\"id\":1}\n"
259 for name, got := range map[string]string{
260 "missing final newline": strings.TrimSuffix(want, "\n"),
261 "extra empty line": want + "\n",
262 "changed reply": strings.Replace(want, "< {\"id\":1}", "< {\"id\":2}", 1),
263 "missing reply": "== s\n> {\"id\":1}\n",
264 } {
265 r := &fatalRecorder{}
266 sameTranscript(r, got, want)
267 if len(r.failed) == 0 {
268 t.Fatalf("%s: %q passed as %q", name, got, want)
269 }
270 }
271 r := &fatalRecorder{}
272 if sameTranscript(r, want, want); len(r.failed) != 0 {
273 t.Fatalf("an equal transcript failed: %v", r.failed)
274 }
275}
276