oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build linux
2
3package thin
4
5import (
6 "bufio"
7 "context"
8 "crypto/sha256"
9 "encoding/hex"
10 "encoding/json"
11 "log/slog"
12 "os"
13 "path/filepath"
14 "slices"
15 "strings"
16 "testing"
17 "time"
18
19 "amadan.net/oficina/equipo/internal/fakeclaude"
20 "amadan.net/oficina/equipo/internal/runner"
21 "amadan.net/oficina/equipo/internal/runner/containment"
22 "amadan.net/oficina/equipo/internal/runner/designstep"
23 "amadan.net/oficina/equipo/internal/runner/provider"
24 "amadan.net/oficina/equipo/internal/runner/provider/claude"
25 "amadan.net/oficina/equipo/internal/runner/renderpage"
26 "amadan.net/oficina/equipo/internal/runner/workspace"
27 "amadan.net/oficina/equipo/internal/specialist"
28 "amadan.net/oficina/equipo/internal/testci"
29 "amadan.net/oficina/equipo/internal/wire"
30)
31
32// claudeRig runs a real Claude launch: the fake CLI (this test binary
33// as "claude") in bubblewrap, on one subscription connection.
34type claudeRig struct {
35 t *testing.T
36 ctx context.Context
37 e *Engineer
38 conns *Conns
39 root string
40}
41
42func newClaudeRig(t *testing.T) *claudeRig {
43 t.Helper()
44 testci.Tools(t, "bwrap", "git")
45 if _, err := os.Stat("/usr/bin/bwrap"); err != nil {
46 testci.Absent(t, "bubblewrap is absent")
47 }
48 // A short root: the tool socket's path must fit a socket address.
49 root, err := os.MkdirTemp("", "ds-")
50 if err != nil {
51 t.Fatal(err)
52 }
53 t.Cleanup(func() { os.RemoveAll(root) })
54 for _, d := range []string{"state", "work", "scratch", "sessions", "bin"} {
55 if err := os.MkdirAll(filepath.Join(root, d), 0700); err != nil {
56 t.Fatal(err)
57 }
58 }
59 state, err := OpenState(context.Background(), filepath.Join(root, "state"))
60 if err != nil {
61 t.Fatal(err)
62 }
63 t.Cleanup(func() { state.Close() })
64 home := filepath.Join(root, "accounts", "claude-a")
65 os.MkdirAll(home, 0700)
66 identity := map[string]string{"account_id": connPerson, "home_id": "h-a", "provider_version": fakeclaude.Version}
67 raw, _ := json.Marshal(identity)
68 os.WriteFile(filepath.Join(home, provider.IdentityFile), raw, 0600)
69 raw, _ = json.Marshal(map[string]any{"oauthAccount": map[string]string{"emailAddress": connPerson}})
70 os.WriteFile(filepath.Join(home, ".claude.json"), raw, 0600)
71 if err := fakeclaude.WriteCredentials(home, time.Now().Add(8*time.Hour)); err != nil {
72 t.Fatal(err)
73 }
74 raw, _ = json.Marshal([]map[string]any{{"id": "claude-a", "local_id": "claude-a", "label": "claude-a", "person_id": connPerson, "provider": "claude", "family": "claude", "model": "claude-opus-5-5", "account_id": connPerson, "provider_home": home, "kind": "subscription", "expected_identity": identity}})
75 bindings := filepath.Join(root, "bindings.json")
76 os.WriteFile(bindings, raw, 0600)
77 bin := filepath.Join(root, "bin")
78 claudePath := copySelf(t, bin, "claude")
79 cli, _ := os.ReadFile(claudePath)
80 sum := sha256.Sum256(cli)
81 self, _ := os.Executable()
82 cfg := runner.Config{AccountBindingsPath: bindings, AmadanCredentialPath: filepath.Join(root, "amadan.json"), ClaudePath: claudePath, CodexPath: "/bin/true", StateDir: filepath.Join(root, "state"), WorkspaceRoot: filepath.Join(root, "work"), ScratchRoot: filepath.Join(root, "scratch"), GitPath: "/usr/bin/git", BwrapPath: "/usr/bin/bwrap", ToolProxyPath: copySelf(t, bin, "equipo-tool-proxy")}
83 m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: self, ScratchRoot: cfg.ScratchRoot})
84 if err != nil {
85 testci.Absent(t, "namespaces are unavailable: "+err.Error())
86 }
87 conns := &Conns{Runner: cfg, State: state}
88 conns.Validated("claude-a")
89 ctx, cancel := context.WithCancel(context.Background())
90 t.Cleanup(cancel)
91 e := &Engineer{O: ClaudeOptions{Runner: cfg, Manager: m, State: state, SessionRoot: filepath.Join(root, "sessions"), Digest: hex.EncodeToString(sum[:]), LockWait: 5 * time.Second, Logger: slog.New(slog.NewTextHandler(testWriter{t}, nil))}, Owners: []string{connPerson}, MaxStep: 2 * time.Minute, Conns: conns, Host: "test"}
92 // The run's defaults, as Run sets them: Refresh runs the fake CLI's
93 // auth status in the source home.
94 e.O.defaults()
95 return &claudeRig{t: t, ctx: ctx, e: e, conns: conns, root: root}
96}
97
98// binding is the rig's one Claude connection.
99func (r *claudeRig) binding() runner.AccountBinding {
100 r.t.Helper()
101 bs, err := runner.LoadBindings(r.e.O.Runner.AccountBindingsPath)
102 if err != nil || len(bs) != 1 {
103 r.t.Fatalf("bindings %v %v", bs, err)
104 }
105 return bs[0]
106}
107
108// initTools are the tools the CLI reported in the run's system/init.
109func (r *claudeRig) initTools(row stepRow) []string {
110 r.t.Helper()
111 f, err := os.Open(filepath.Join(r.e.root(), stepKey(row), "log.jsonl"))
112 if err != nil {
113 r.t.Fatal(err)
114 }
115 defer f.Close()
116 scan := bufio.NewScanner(f)
117 scan.Buffer(make([]byte, 0, 64<<10), 4<<20)
118 for scan.Scan() {
119 var v struct {
120 Type, Subtype string
121 Tools []string
122 }
123 if json.Unmarshal(scan.Bytes(), &v) == nil && v.Type == "system" && v.Subtype == "init" {
124 return v.Tools
125 }
126 }
127 r.t.Fatal("no system/init in the step log")
128 return nil
129}
130
131// captureDir is a step's render directory as render_page leaves it:
132// the runner's, 0700, one capture in it.
133func captureDir(t *testing.T, root string) (string, []byte) {
134 t.Helper()
135 dir := filepath.Join(root, "render-tk1")
136 if err := os.Mkdir(dir, 0700); err != nil {
137 t.Fatal(err)
138 }
139 png := []byte("\x89PNG\r\n\x1a\nfixture capture")
140 if err := os.WriteFile(filepath.Join(dir, "1-work-1.png"), png, 0600); err != nil {
141 t.Fatal(err)
142 }
143 return dir, png
144}
145
146// TestDesignStepPolicyRealLaunch: a real Claude launch (the fake CLI in
147// bubblewrap) with the Design step's policy lists exactly Engineering's
148// native tools and render_page, submit_candidate and ask_person (no
149// submit_render); it reads a capture from /render and copies it into
150// the workspace; a write to /render is refused by the callback, and a
151// direct one by the read-only mount.
152func TestDesignStepPolicyRealLaunch(t *testing.T) {
153 r := newClaudeRig(t)
154 work := t.TempDir()
155 render, png := captureDir(t, r.root)
156 row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk1", StepID: "ds1", Attempt: 1, Specialist: wire.SpecialistEngineering, Profile: specialist.ProfileDesign}}
157 spec := designRun(r.binding(), "[Equipo: engineering] copy:/render/1-work-1.png|mockups/tk1/capture.png escape:/render/planted.png rowrite:/render/forced.png", (&designstep.Attempt{}).Call)
158 spec.render = render
159 res := r.e.run(r.ctx, row, workspace.TaskTree{Dir: work}, spec)
160 if res.reason != "" || !res.terminated {
161 t.Fatalf("run %+v", res)
162 }
163 want := append([]string{"Bash", "Read", "Write", "Edit", "Glob", "Grep"}, "mcp__equipo__render_page", "mcp__equipo__submit_candidate", "mcp__equipo__ask_person")
164 if got := r.initTools(row); !slices.Equal(got, want) {
165 t.Fatalf("the CLI listed %q, want %q", got, want)
166 }
167 copied, err := os.ReadFile(filepath.Join(work, "mockups", "tk1", "capture.png"))
168 if err != nil || string(copied) != string(png) {
169 t.Fatalf("capture not read from /render: %q %v (%s)", copied, err, res.summary)
170 }
171 for _, said := range []string{"Copied /render/1-work-1.png to mockups/tk1/capture.png.", "Writing /render/forced.png failed (errno 30).", "Write to /render/planted.png was denied."} {
172 if !strings.Contains(res.summary, said) {
173 t.Fatalf("summary %q lacks %q", res.summary, said)
174 }
175 }
176 entries, _ := os.ReadDir(render)
177 if len(entries) != 1 || res.refused != 1 {
178 t.Fatalf("render directory %v, %d refused", entries, res.refused)
179 }
180}
181
182// TestEngineeringStepNoRender: Engineering's step, launched the same
183// way, lists its own tools (submit_render's stub, never render_page)
184// and cannot read /render: its callback refuses the path, and its
185// launch is refused a render directory outright.
186func TestEngineeringStepNoRender(t *testing.T) {
187 r := newClaudeRig(t)
188 work := t.TempDir()
189 render, _ := captureDir(t, r.root)
190 row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk1", StepID: "en1", Attempt: 1, Specialist: wire.SpecialistEngineering}}
191 spec := specialistRun{action: "implement", binding: r.binding(), tools: stepTools, names: []string{"submit_candidate", "ask_person", "submit_render"}, permission: claude.StepPermission, call: func(context.Context, string, string, json.RawMessage) (string, bool) { return stepToolText, false }, prompt: "[Equipo: engineering] copy:/render/1-work-1.png|capture.png"}
192 res := r.e.run(r.ctx, row, workspace.TaskTree{Dir: work}, spec)
193 if res.reason != "" || !res.terminated {
194 t.Fatalf("run %+v", res)
195 }
196 want := []string{"Bash", "Read", "Write", "Edit", "Glob", "Grep", "mcp__equipo__submit_candidate", "mcp__equipo__ask_person", "mcp__equipo__submit_render"}
197 if got := r.initTools(row); !slices.Equal(got, want) {
198 t.Fatalf("the CLI listed %q, want %q", got, want)
199 }
200 if !strings.Contains(res.summary, "Read of /render/1-work-1.png was denied.") {
201 t.Fatalf("summary %q", res.summary)
202 }
203 spec.render = render
204 row.StepID = "en2"
205 if res = r.e.run(r.ctx, row, workspace.TaskTree{Dir: work}, spec); res.reason != "policy_rejected" {
206 t.Fatalf("Engineering launched with /render: %+v", res)
207 }
208}
209
210// TestDesignToolSurface: the Design step's MCP tools are design-v1's,
211// in its order, answered by the call the run is given (the step's
212// designstep.Attempt): submit_candidate takes the options, and
213// ask_person says nobody can answer.
214func TestDesignToolSurface(t *testing.T) {
215 var names []string
216 for _, tool := range designTools {
217 names = append(names, tool.(map[string]any)["name"].(string))
218 }
219 if !slices.Equal(names, provider.DesignTools()) || !slices.Equal(designToolNames, provider.DesignTools()) {
220 t.Fatalf("tools %v names %v, design-v1 %v", names, designToolNames, provider.DesignTools())
221 }
222 // render_page's tree is the spec's: base or work; compare renders
223 // both, with either tree or none (renderpage.Parse).
224 page := designTools[0].(map[string]any)
225 props := page["inputSchema"].(map[string]any)["properties"].(map[string]any)
226 if tree := props["tree"].(map[string]any)["enum"].([]string); !slices.Equal(tree, []string{renderpage.TreeBase, renderpage.TreeWork}) || !strings.Contains(page["description"].(string), "compare true renders both trees, whichever tree you name or none") {
227 t.Fatalf("render_page %v", page)
228 }
229 submit := designTools[1].(map[string]any)
230 if schema := submit["inputSchema"].(map[string]any); !slices.Equal(schema["required"].([]string), []string{"options"}) || !strings.Contains(submit["description"].(string), "12 captures") {
231 t.Fatalf("submit_candidate %v", submit)
232 }
233 if ask := designTools[2].(map[string]any)["description"].(string); !strings.HasPrefix(ask, "Nobody can answer") {
234 t.Fatalf("ask_person %q", ask)
235 }
236 a := &designstep.Attempt{}
237 spec := designRun(runner.AccountBinding{}, "p", a.Call)
238 if spec.action != provider.DesignStepAction || !slices.Equal(spec.names, designToolNames) {
239 t.Fatalf("run %+v", spec)
240 }
241 if text, isError := spec.call(context.Background(), "ask_person", "u", json.RawMessage(`{"question": "q"}`)); text != designstep.AskText || isError {
242 t.Fatalf("ask_person: %q %v", text, isError)
243 }
244}
245