//go:build linux package thin import ( "bufio" "context" "crypto/sha256" "encoding/hex" "encoding/json" "log/slog" "os" "path/filepath" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/fakeclaude" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/designstep" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/runner/renderpage" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/specialist" "amadan.net/oficina/equipo/internal/testci" "amadan.net/oficina/equipo/internal/wire" ) // claudeRig runs a real Claude launch: the fake CLI (this test binary // as "claude") in bubblewrap, on one subscription connection. type claudeRig struct { t *testing.T ctx context.Context e *Engineer conns *Conns root string } func newClaudeRig(t *testing.T) *claudeRig { t.Helper() testci.Tools(t, "bwrap", "git") if _, err := os.Stat("/usr/bin/bwrap"); err != nil { testci.Absent(t, "bubblewrap is absent") } // A short root: the tool socket's path must fit a socket address. root, err := os.MkdirTemp("", "ds-") if err != nil { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(root) }) for _, d := range []string{"state", "work", "scratch", "sessions", "bin"} { if err := os.MkdirAll(filepath.Join(root, d), 0700); err != nil { t.Fatal(err) } } state, err := OpenState(context.Background(), filepath.Join(root, "state")) if err != nil { t.Fatal(err) } t.Cleanup(func() { state.Close() }) home := filepath.Join(root, "accounts", "claude-a") os.MkdirAll(home, 0700) identity := map[string]string{"account_id": connPerson, "home_id": "h-a", "provider_version": fakeclaude.Version} raw, _ := json.Marshal(identity) os.WriteFile(filepath.Join(home, provider.IdentityFile), raw, 0600) raw, _ = json.Marshal(map[string]any{"oauthAccount": map[string]string{"emailAddress": connPerson}}) os.WriteFile(filepath.Join(home, ".claude.json"), raw, 0600) if err := fakeclaude.WriteCredentials(home, time.Now().Add(8*time.Hour)); err != nil { t.Fatal(err) } 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}}) bindings := filepath.Join(root, "bindings.json") os.WriteFile(bindings, raw, 0600) bin := filepath.Join(root, "bin") claudePath := copySelf(t, bin, "claude") cli, _ := os.ReadFile(claudePath) sum := sha256.Sum256(cli) self, _ := os.Executable() 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")} m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: self, ScratchRoot: cfg.ScratchRoot}) if err != nil { testci.Absent(t, "namespaces are unavailable: "+err.Error()) } conns := &Conns{Runner: cfg, State: state} conns.Validated("claude-a") ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) 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"} // The run's defaults, as Run sets them: Refresh runs the fake CLI's // auth status in the source home. e.O.defaults() return &claudeRig{t: t, ctx: ctx, e: e, conns: conns, root: root} } // binding is the rig's one Claude connection. func (r *claudeRig) binding() runner.AccountBinding { r.t.Helper() bs, err := runner.LoadBindings(r.e.O.Runner.AccountBindingsPath) if err != nil || len(bs) != 1 { r.t.Fatalf("bindings %v %v", bs, err) } return bs[0] } // initTools are the tools the CLI reported in the run's system/init. func (r *claudeRig) initTools(row stepRow) []string { r.t.Helper() f, err := os.Open(filepath.Join(r.e.root(), stepKey(row), "log.jsonl")) if err != nil { r.t.Fatal(err) } defer f.Close() scan := bufio.NewScanner(f) scan.Buffer(make([]byte, 0, 64<<10), 4<<20) for scan.Scan() { var v struct { Type, Subtype string Tools []string } if json.Unmarshal(scan.Bytes(), &v) == nil && v.Type == "system" && v.Subtype == "init" { return v.Tools } } r.t.Fatal("no system/init in the step log") return nil } // captureDir is a step's render directory as render_page leaves it: // the runner's, 0700, one capture in it. func captureDir(t *testing.T, root string) (string, []byte) { t.Helper() dir := filepath.Join(root, "render-tk1") if err := os.Mkdir(dir, 0700); err != nil { t.Fatal(err) } png := []byte("\x89PNG\r\n\x1a\nfixture capture") if err := os.WriteFile(filepath.Join(dir, "1-work-1.png"), png, 0600); err != nil { t.Fatal(err) } return dir, png } // TestDesignStepPolicyRealLaunch: a real Claude launch (the fake CLI in // bubblewrap) with the Design step's policy lists exactly Engineering's // native tools and render_page, submit_candidate and ask_person (no // submit_render); it reads a capture from /render and copies it into // the workspace; a write to /render is refused by the callback, and a // direct one by the read-only mount. func TestDesignStepPolicyRealLaunch(t *testing.T) { r := newClaudeRig(t) work := t.TempDir() render, png := captureDir(t, r.root) row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk1", StepID: "ds1", Attempt: 1, Specialist: wire.SpecialistEngineering, Profile: specialist.ProfileDesign}} 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) spec.render = render res := r.e.run(r.ctx, row, workspace.TaskTree{Dir: work}, spec) if res.reason != "" || !res.terminated { t.Fatalf("run %+v", res) } want := append([]string{"Bash", "Read", "Write", "Edit", "Glob", "Grep"}, "mcp__equipo__render_page", "mcp__equipo__submit_candidate", "mcp__equipo__ask_person") if got := r.initTools(row); !slices.Equal(got, want) { t.Fatalf("the CLI listed %q, want %q", got, want) } copied, err := os.ReadFile(filepath.Join(work, "mockups", "tk1", "capture.png")) if err != nil || string(copied) != string(png) { t.Fatalf("capture not read from /render: %q %v (%s)", copied, err, res.summary) } 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."} { if !strings.Contains(res.summary, said) { t.Fatalf("summary %q lacks %q", res.summary, said) } } entries, _ := os.ReadDir(render) if len(entries) != 1 || res.refused != 1 { t.Fatalf("render directory %v, %d refused", entries, res.refused) } } // TestEngineeringStepNoRender: Engineering's step, launched the same // way, lists its own tools (submit_render's stub, never render_page) // and cannot read /render: its callback refuses the path, and its // launch is refused a render directory outright. func TestEngineeringStepNoRender(t *testing.T) { r := newClaudeRig(t) work := t.TempDir() render, _ := captureDir(t, r.root) row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk1", StepID: "en1", Attempt: 1, Specialist: wire.SpecialistEngineering}} 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"} res := r.e.run(r.ctx, row, workspace.TaskTree{Dir: work}, spec) if res.reason != "" || !res.terminated { t.Fatalf("run %+v", res) } want := []string{"Bash", "Read", "Write", "Edit", "Glob", "Grep", "mcp__equipo__submit_candidate", "mcp__equipo__ask_person", "mcp__equipo__submit_render"} if got := r.initTools(row); !slices.Equal(got, want) { t.Fatalf("the CLI listed %q, want %q", got, want) } if !strings.Contains(res.summary, "Read of /render/1-work-1.png was denied.") { t.Fatalf("summary %q", res.summary) } spec.render = render row.StepID = "en2" if res = r.e.run(r.ctx, row, workspace.TaskTree{Dir: work}, spec); res.reason != "policy_rejected" { t.Fatalf("Engineering launched with /render: %+v", res) } } // TestDesignToolSurface: the Design step's MCP tools are design-v1's, // in its order, answered by the call the run is given (the step's // designstep.Attempt): submit_candidate takes the options, and // ask_person says nobody can answer. func TestDesignToolSurface(t *testing.T) { var names []string for _, tool := range designTools { names = append(names, tool.(map[string]any)["name"].(string)) } if !slices.Equal(names, provider.DesignTools()) || !slices.Equal(designToolNames, provider.DesignTools()) { t.Fatalf("tools %v names %v, design-v1 %v", names, designToolNames, provider.DesignTools()) } // render_page's tree is the spec's: base or work; compare renders // both, with either tree or none (renderpage.Parse). page := designTools[0].(map[string]any) props := page["inputSchema"].(map[string]any)["properties"].(map[string]any) 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") { t.Fatalf("render_page %v", page) } submit := designTools[1].(map[string]any) if schema := submit["inputSchema"].(map[string]any); !slices.Equal(schema["required"].([]string), []string{"options"}) || !strings.Contains(submit["description"].(string), "12 captures") { t.Fatalf("submit_candidate %v", submit) } if ask := designTools[2].(map[string]any)["description"].(string); !strings.HasPrefix(ask, "Nobody can answer") { t.Fatalf("ask_person %q", ask) } a := &designstep.Attempt{} spec := designRun(runner.AccountBinding{}, "p", a.Call) if spec.action != provider.DesignStepAction || !slices.Equal(spec.names, designToolNames) { t.Fatalf("run %+v", spec) } if text, isError := spec.call(context.Background(), "ask_person", "u", json.RawMessage(`{"question": "q"}`)); text != designstep.AskText || isError { t.Fatalf("ask_person: %q %v", text, isError) } }