package headless import ( "context" "crypto/rand" "crypto/sha256" "database/sql" "encoding/hex" "encoding/json" "fmt" "io" "log/slog" "os" "os/exec" "os/signal" "path/filepath" "strings" "sync" "syscall" "testing" "time" "amadan.net/oficina/equipo/internal/equipo/chat" "amadan.net/oficina/equipo/internal/fakeclaude" "amadan.net/oficina/equipo/internal/fakecodex" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/mac/proc" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/thin" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/testci" "amadan.net/oficina/equipo/internal/thintest" "amadan.net/oficina/equipo/internal/toolproxy" "amadan.net/oficina/equipo/internal/wire" "amadan.net/rastrillo/rastrillo/budget" gitleakscmd "github.com/zricethezav/gitleaks/v8/cmd" _ "modernc.org/sqlite" ) // TestMain also serves as the namespace helper, the fake claude and the // MCP stdio proxy: the suite runs them from copies of this binary. func TestMain(m *testing.M) { switch filepath.Base(os.Args[0]) { case "claude": os.Exit(fakeclaude.Main(os.Args[1:], os.Stdin, os.Stdout, os.Stderr)) case "xcodebuild": os.Exit(fakeXcodebuild()) case "codex": os.Exit(fakecodex.Main(os.Args[1:], os.Stdin, os.Stdout, os.Stderr)) case "codex-code-mode-host": os.Exit(0) case "scanner", "gitleaks": // The fake Mac worker's pinned gitleaks (the scan before anything // of a candidate made on the Mac leaves it). gitleakscmd.Execute() return case "equipo-tool-proxy": args := os.Args if len(args) == 4 && args[1] == provider.DarwinToolProxyCommand { // The darwin MCP config's command line (the fake Mac worker's // Engineering): equipo-runner tool-proxy --socket . args = append(args[:1:1], args[2:]...) } if len(args) != 3 || args[1] != "--socket" { os.Exit(2) } if toolproxy.Serve(context.Background(), os.Stdin, os.Stdout, args[2]) != nil { os.Exit(1) } os.Exit(0) } if len(os.Args) > 1 && os.Args[1] == "__namespace" { os.Exit(containment.NamespaceMain(os.Args[2:])) } if path := os.Getenv("EQUIPO_HEADLESS_RUNNER"); path != "" { os.Exit(runnerProcess(path)) } code := budget.Main(m) thintest.RemoveSchema() os.Exit(code) } // Env is what a scenario may touch: the person API and SSE through the // client, and the controls a person or an operator has (runner on and off, // instance restart). Local and staging environments implement the same. type Env struct { Client *thintest.Client // Live is true against the real CLI, where replies are not scripted. Live bool // Slow is a prompt that streams for a few seconds. Slow string StopRunner func(t *testing.T) // KillRunner kills the runner process outright (SIGKILL), with no // cleanup of its own. KillRunner func(t *testing.T) StartRunner func(t *testing.T) RestartRunner func(t *testing.T) RestartInst func(t *testing.T) AgeEvents func(t *testing.T) bool ResumeThreshold time.Duration // Project is the repository a live run works in (for example // oficina/equipo); local runs use the local forge's oficina/sample. Project string RunID string // Grant and Revoke change what the agent reaches (local forge only), // then restart the runner so its index refreshes. Grant, Revoke func(t *testing.T, repo string) // BreakDesk makes the desk record unwritable, then starts the runner. BreakDesk func(t *testing.T) // Witness is what the person says in the live Engineering scenario // (EQUIPO_STAGING_WITNESS); CrashWitness the same for scenario 4 and // CancelWitness for the step cancel. Each asks for a different change, // so no two of a run's tasks read alike. Witness, CrashWitness, CancelWitness string // ForgePath is a local forge repository's bare path (local only). ForgePath func(repo string) string // OfflineMac enrols a Mac worker that said hello once and is offline // (local only): checks that need a Mac wait for it (waiting_runner), // not for a Mac runner to be added. The func it returns removes it. // PastOfflineLimit runs placement with the clock past the offline // limit, so such checks end not run (runner_offline). OfflineMac func(t *testing.T) func() PastOfflineLimit func(t *testing.T) // GrantNow makes a repository reachable without restarting the // runner, like a grant on the hub (local only). GrantNow func(t *testing.T, repo string) // GrantEmpty makes a new repository with no commits reachable, then // restarts the runner (local only). GrantEmpty func(t *testing.T, repo string) // RebuildHead points a local repository's HEAD at branch, as the hub's // rebuild does to an empty repository whose only branch is a task's. RebuildHead func(t *testing.T, repo, branch string) // HubUpdate makes the local hub the one that makes the first merge // into an empty repository, then restarts the runner (local only). HubUpdate func(t *testing.T) // Indexed reports whether the instance's newest hello catalogues repo, // and whether as empty (local only). Indexed func(t *testing.T, repo string) (found, empty bool) // KeptSessions counts the step sessions the runner keeps on disk // (local only). KeptSessions func(t *testing.T) int // AskNamespace is the containment namespace the runner recorded for // a question's attempt (local only). AskNamespace func(t *testing.T, question string) string // AskUsage is the outcomes of a question's recorded usage rows, with // whether each carried figures (local only). AskUsage func(t *testing.T, question string) []string // AskPin is the Engineering attempt and session the instance froze on // a question, and the session the runner kept for that attempt // (local only). AskPin func(t *testing.T, question string) (attempt int64, session, kept string) // Usage is every usage row of a task and of one coordinator turn, as // role/round/turns=/cached=, by role and round (local only). Usage func(t *testing.T, task, turn string) []string // duringReplay makes something new reach the conversation while // scenario 7 reads its replay, as a runner's hello with fresh headroom // does on staging (local only). duringReplay func(t *testing.T, s *session) turns *int } // Turn counts model turns so staging stays inside its budget. func (e *Env) Turn(t *testing.T) { t.Helper() *e.turns++ if limit := os.Getenv("EQUIPO_STAGING_TURN_LIMIT"); e.Live && limit != "" { var n int json.Unmarshal([]byte(limit), &n) if *e.turns > n { t.Fatalf("staging turn budget %d exceeded", n) } } } // localRunner runs the real runner in this process against the fake CLI // inside real bubblewrap. type localRunner struct { cfg runner.Config opts thin.Options // subprocess runs the runner as its own process, so it can be killed. subprocess bool // runnerID scopes the connection wait to this runner (several runners // share one instance). runnerID string // binary runs the runner process from another build (M8: the slice 4 // test binary), not this one. binary string inst *thintest.Instance // scope, for the fake Mac worker, tags its process and everything it // starts (EQUIPO_TEST_SCOPE): its turns sweep only those, and a turn // a crash left incomplete is cleared by an idle read of them. scope string // instanceDB is the database of an instance in another process (an // older release's), read to see this runner connect when inst is nil. instanceDB string root string cmd *exec.Cmd mu sync.Mutex cancel context.CancelFunc done chan error connected chan bool } func (r *localRunner) start(t *testing.T) { t.Helper() if r.subprocess { r.startProcess(t) return } r.mu.Lock() defer r.mu.Unlock() ctx, cancel := context.WithCancel(context.Background()) r.cancel, r.done = cancel, make(chan error, 1) connected := make(chan bool, 16) r.connected = connected opts := r.opts opts.Connected = func(up bool) { select { case connected <- up: default: } } go func() { r.done <- thin.Run(ctx, r.cfg, opts) }() select { case up := <-connected: if !up { t.Fatal("runner did not connect") } case err := <-r.done: t.Fatalf("runner exited: %v", err) case <-time.After(15 * time.Second): t.Fatal("runner did not connect in time") } } func (r *localRunner) stop(t *testing.T) { t.Helper() if r.subprocess { r.endProcess(t, syscall.SIGTERM) return } r.mu.Lock() defer r.mu.Unlock() if r.cancel == nil { return } r.cancel() select { case err := <-r.done: if err != nil && err != context.Canceled { t.Logf("runner stopped: %v", err) } case <-time.After(45 * time.Second): t.Fatal("runner did not stop") } r.cancel = nil } func copyExecutable(t *testing.T, dst string) string { t.Helper() self, err := os.Executable() if err != nil { t.Fatal(err) } in, err := os.Open(self) if err != nil { t.Fatal(err) } defer in.Close() out, err := os.OpenFile(dst, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0755) if err != nil { t.Fatal(err) } h := sha256.New() if _, err = io.Copy(io.MultiWriter(out, h), in); err != nil { t.Fatal(err) } if err = out.Close(); err != nil { t.Fatal(err) } return hex.EncodeToString(h.Sum(nil)) } func private(t *testing.T, path string) string { t.Helper() if err := os.MkdirAll(path, 0700); err != nil { t.Fatal(err) } if err := os.Chmod(path, 0700); err != nil { t.Fatal(err) } return path } func writeJSON(t *testing.T, path string, v any) { t.Helper() raw, _ := json.Marshal(v) if err := os.WriteFile(path, raw, 0600); err != nil { t.Fatal(err) } } // localEnv starts an instance, signs a device in, enrols a runner and // gives it one dedicated fake Claude home for the owner. func localEnv(t *testing.T) (*Env, *thintest.Instance, *localRunner) { t.Helper() testci.Tools(t, "bwrap", "git", "tar") if _, err := exec.LookPath("/usr/bin/bwrap"); err != nil { t.Skip("bubblewrap is required") } inst := thintest.StartInstance(t) token := inst.DeviceToken(t) cred := inst.EnrolRunner(t) r, forge := runnerSetup(t, inst.URL, inst.TeamID, cred) r.inst = inst cfg, state, root := r.cfg, r.cfg.StateDir, r.root t.Cleanup(func() { r.stop(t) }) // Like carlos restart, the control returns before the instance cycles, // so scenario 8 has to wait for the restart itself. restartLater := func(t *testing.T) { done := make(chan struct{}) t.Cleanup(func() { <-done }) time.AfterFunc(time.Second, func() { defer close(done); inst.Restart(t) }) } turns := 0 env := &Env{ Client: thintest.NewClient(inst.URL, token), Slow: "Take your time with this one. sleep:1500", StartRunner: r.start, StopRunner: r.stop, KillRunner: r.kill, RestartRunner: func(t *testing.T) { r.stop(t); r.start(t) }, RestartInst: restartLater, ResumeThreshold: 5 * time.Second, turns: &turns, BreakDesk: func(t *testing.T) { r.stop(t) desk, err := thin.OpenDesk(thin.SessionRoot(cfg), thintest.Owner) if err != nil { t.Fatal(err) } if err := os.MkdirAll(filepath.Join(filepath.Dir(desk.Dir), "desk.json"), 0700); err != nil { t.Fatal(err) } r.start(t) }, ForgePath: forge.path, OfflineMac: func(t *testing.T) func() { cred := inst.EnrolRunner(t) w, err := thintest.DialRunnerHello(context.Background(), inst.URL, cred.Token, thintest.WorkerHello(0)) if err != nil { t.Fatal(err) } w.Close() return func() { if _, err := inst.DB.Writer().Exec("UPDATE runners SET revoked_at = ? WHERE id = ?", time.Now().UTC(), cred.RunnerID); err != nil { t.Error(err) } } }, PastOfflineLimit: func(t *testing.T) { later := time.Now().UTC().Add(chat.OfflineLimit + time.Minute) inst.Store.Chat().SetClock(func() time.Time { return later }) defer inst.Store.Chat().SetClock(func() time.Time { return time.Now().UTC() }) if err := inst.Store.Chat().Place(context.Background()); err != nil { t.Fatal(err) } }, AskNamespace: func(t *testing.T, question string) string { d, err := sql.Open("sqlite", "file:"+filepath.Join(state, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)") if err != nil { t.Fatal(err) } defer d.Close() var ns string if err := d.QueryRow("SELECT ns_id FROM asks WHERE question_id=?", question).Scan(&ns); err != nil { t.Fatal(err) } return ns }, AskPin: func(t *testing.T, question string) (attempt int64, session, kept string) { var step string if err := inst.DB.Writer().QueryRow("SELECT step_id, coalesce(eng_attempt, 0), coalesce(eng_session, '') FROM chat_questions WHERE id = ?", question).Scan(&step, &attempt, &session); err != nil { t.Fatal(err) } d, err := sql.Open("sqlite", "file:"+filepath.Join(state, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)") if err != nil { t.Fatal(err) } defer d.Close() _ = d.QueryRow("SELECT session_id FROM kept_sessions WHERE step_id=? AND attempt=?", step, attempt).Scan(&kept) return attempt, session, kept }, AskUsage: func(t *testing.T, question string) []string { rows, err := inst.DB.Writer().Query("SELECT outcome, input_tokens IS NOT NULL FROM chat_usage WHERE step_id = ? AND role = 'ask' ORDER BY attempt", question) if err != nil { t.Fatal(err) } defer rows.Close() var out []string for rows.Next() { var outcome string var figures bool if err := rows.Scan(&outcome, &figures); err != nil { t.Fatal(err) } out = append(out, fmt.Sprintf("%s/%v", outcome, figures)) } return out }, Usage: func(t *testing.T, task, turn string) []string { rows, err := inst.DB.Writer().Query("SELECT role, round, coalesce(turns, 0), coalesce(cached_input_tokens, 0), input_tokens IS NOT NULL FROM chat_usage WHERE (task_id = ? AND task_id <> '') OR (turn_id = ? AND turn_id <> '') ORDER BY role, round, attempt", task, turn) if err != nil { t.Fatal(err) } defer rows.Close() var out []string for rows.Next() { var role string var round int var turns, cached int64 var input bool if err := rows.Scan(&role, &round, &turns, &cached, &input); err != nil { t.Fatal(err) } if !input { role += "(no figures)" } out = append(out, fmt.Sprintf("%s/%d/turns=%v/cached=%v", role, round, turns > 0, cached > 0)) } return out }, KeptSessions: func(t *testing.T) int { dirs, _ := filepath.Glob(filepath.Join(thin.SessionRoot(cfg), "*", "steps", "*")) return len(dirs) }, GrantNow: func(t *testing.T, repo string) { forge.grant(t, root, repo) }, RebuildHead: func(t *testing.T, repo, branch string) { gitRun(t, forge.root, "--git-dir="+forge.path(repo), "symbolic-ref", "HEAD", "refs/heads/"+branch) }, HubUpdate: func(t *testing.T) { forge.mu.Lock() forge.hubUpdated = true forge.mu.Unlock() r.stop(t) r.start(t) }, GrantEmpty: func(t *testing.T, repo string) { forge.grantEmpty(t, repo) r.stop(t) r.start(t) }, Indexed: func(t *testing.T, repo string) (bool, bool) { rows, err := inst.DB.Writer().Query("SELECT hello FROM runner_sessions WHERE hello <> ''") if err != nil { t.Fatal(err) } defer rows.Close() for rows.Next() { var raw string var h wire.Hello if rows.Scan(&raw) != nil || json.Unmarshal([]byte(raw), &h) != nil { continue } for _, e := range h.Catalog { if e.Repo == repo { return true, e.Empty } } } return false, false }, Grant: func(t *testing.T, repo string) { forge.grant(t, root, repo); r.stop(t); r.start(t) }, Revoke: func(t *testing.T, repo string) { forge.revoke(repo); r.stop(t); r.start(t) }, AgeEvents: func(t *testing.T) bool { if _, err := inst.DB.Writer().Exec("UPDATE chat_events SET created_at = ?", time.Now().Add(-48*time.Hour)); err != nil { t.Fatal(err) } if err := inst.Store.Chat().Sweep(context.Background()); err != nil { t.Fatal(err) } return true }, } return env, inst, r } // stagingEnv drives a deployed staging instance and the staging runner // unit with the real CLI. Controls are shell commands from the gate script. func stagingEnv(t *testing.T) *Env { t.Helper() origin, token := os.Getenv("EQUIPO_STAGING_ORIGIN"), os.Getenv("EQUIPO_STAGING_TOKEN") if origin == "" || token == "" { t.Skip("set EQUIPO_STAGING_ORIGIN and EQUIPO_STAGING_TOKEN to run against staging") } run := func(variable string) func(t *testing.T) { return func(t *testing.T) { t.Helper() command := os.Getenv(variable) if command == "" { t.Skipf("%s is not set", variable) } cmd := exec.Command("/bin/sh", "-c", command) out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("%s: %v: %s", variable, err, strings.TrimSpace(string(out))) } } } turns := 0 client := thintest.NewClient(origin, token) client.HTTP.Timeout = 60 * time.Second return &Env{ Client: client, Live: true, RunID: os.Getenv("EQUIPO_STAGING_RUN_ID"), Slow: "Count from 1 to 150, one number per line, and nothing else.", StartRunner: run("EQUIPO_STAGING_RUNNER_START"), StopRunner: run("EQUIPO_STAGING_RUNNER_STOP"), KillRunner: run("EQUIPO_STAGING_RUNNER_KILL"), RestartRunner: run("EQUIPO_STAGING_RUNNER_RESTART"), RestartInst: run("EQUIPO_STAGING_INSTANCE_RESTART"), AgeEvents: func(*testing.T) bool { return false }, ResumeThreshold: 15 * time.Second, Project: os.Getenv("EQUIPO_STAGING_PROJECT"), Witness: os.Getenv("EQUIPO_STAGING_WITNESS"), CrashWitness: os.Getenv("EQUIPO_STAGING_CRASH_WITNESS"), CancelWitness: os.Getenv("EQUIPO_STAGING_CANCEL_WITNESS"), turns: &turns, } } // processConfig is what a runner subprocess needs; runner.Config holds a func. type processConfig struct { Origin, InstanceID, StateDir, AccountBindingsPath, AmadanCredentialPath string ClaudePath, CodexPath, CodexCodeModeHostPath, BwrapPath, GoRoot, ModuleCache string GoBinary, WorkspaceRoot, ScratchRoot, GitPath, AmadanPath, ToolProxy string Digest, MoveInNote string MachineLabel, FakePlatform, FakeBin, FakeSandbox string CodexDigest, CodexHostDigest, AccountsRoot string NoMoveIn bool Idle, LockWait, MaxTurn, Margin time.Duration // MaxStep bounds an Engineering step (thin.Options.MaxStep; 0 is the // default). The fake Mac worker's is a minute, so a step runs out of // time within a scenario. MaxStep time.Duration // Forge is the local forge's state, so a runner process works on the // same bare repositories as an in-process one. Forge *localForgeState } func runnerProcess(path string) int { raw, err := os.ReadFile(path) var p processConfig if err != nil || json.Unmarshal(raw, &p) != nil { return 2 } self, _ := os.Executable() cfg := runner.Config{MachineLabel: p.MachineLabel, Origin: p.Origin, InstanceID: p.InstanceID, StateDir: p.StateDir, AccountBindingsPath: p.AccountBindingsPath, AmadanCredentialPath: p.AmadanCredentialPath, ClaudePath: p.ClaudePath, CodexPath: p.CodexPath, CodexCodeModeHostPath: p.CodexCodeModeHostPath, BwrapPath: p.BwrapPath, GoRoot: p.GoRoot, ModuleCache: p.ModuleCache, GoBinary: p.GoBinary, WorkspaceRoot: p.WorkspaceRoot, ScratchRoot: p.ScratchRoot, GitPath: p.GitPath, AmadanPath: p.AmadanPath, ToolProxyPath: p.ToolProxy, Executable: self} ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt) defer stop() opts := thin.Options{Version: "test", Logger: slog.New(slog.NewTextHandler(os.Stderr, nil)), NoMoveIn: p.NoMoveIn, MergeEvery: time.Second, FakePlatform: p.FakePlatform, FakeBin: p.FakeBin, FakeSandbox: p.FakeSandbox, MaxStep: p.MaxStep} if p.Forge != nil { opts.Forge = p.Forge.forge() } opts.Claude = thin.ClaudeOptions{Digest: p.Digest, Idle: p.Idle, LockWait: p.LockWait, MaxTurn: p.MaxTurn, Margin: p.Margin, MoveInNote: p.MoveInNote} opts.Codex, opts.AccountsRoot = thin.CodexOptions{Digest: p.CodexDigest, HostDigest: p.CodexHostDigest}, p.AccountsRoot err = thin.Run(ctx, cfg, opts) if err != nil && ctx.Err() == nil { return 1 } return 0 } func (r *localRunner) generation() int64 { var g int64 if r.inst == nil { d, err := sql.Open("sqlite", "file:"+r.instanceDB+"?mode=ro&_pragma=busy_timeout(5000)") if err != nil { return 0 } defer d.Close() d.QueryRow("SELECT coalesce(max(generation),0) FROM runner_sessions WHERE connected = 1 AND runner_id = ?", r.runnerID).Scan(&g) return g } if r.runnerID != "" { r.inst.DB.Writer().QueryRow("SELECT coalesce(max(generation),0) FROM runner_sessions WHERE connected = 1 AND runner_id = ?", r.runnerID).Scan(&g) return g } r.inst.DB.Writer().QueryRow("SELECT coalesce(max(generation),0) FROM runner_sessions WHERE connected = 1").Scan(&g) return g } func (r *localRunner) startProcess(t *testing.T) { t.Helper() if r.cmd != nil { // A second process would orphan the first (cleanup stops only // the one it knows). t.Fatal("the runner process is already running") } c, o := r.cfg, r.opts.Claude var fs *localForgeState if lf, ok := r.opts.Forge.(*localForge); ok { fs = lf.state() } raw, _ := json.Marshal(processConfig{Forge: fs, Origin: c.Origin, InstanceID: c.InstanceID, StateDir: c.StateDir, AccountBindingsPath: c.AccountBindingsPath, AmadanCredentialPath: c.AmadanCredentialPath, ClaudePath: c.ClaudePath, CodexPath: c.CodexPath, CodexCodeModeHostPath: c.CodexCodeModeHostPath, BwrapPath: c.BwrapPath, GoRoot: c.GoRoot, ModuleCache: c.ModuleCache, GoBinary: c.GoBinary, WorkspaceRoot: c.WorkspaceRoot, ScratchRoot: c.ScratchRoot, GitPath: c.GitPath, AmadanPath: c.AmadanPath, ToolProxy: c.ToolProxyPath, Digest: o.Digest, MoveInNote: o.MoveInNote, CodexDigest: r.opts.Codex.Digest, CodexHostDigest: r.opts.Codex.HostDigest, MachineLabel: c.MachineLabel, FakePlatform: r.opts.FakePlatform, FakeBin: r.opts.FakeBin, FakeSandbox: r.opts.FakeSandbox, AccountsRoot: r.opts.AccountsRoot, NoMoveIn: r.opts.NoMoveIn, Idle: o.Idle, LockWait: o.LockWait, MaxTurn: o.MaxTurn, Margin: o.Margin, MaxStep: r.opts.MaxStep}) path := filepath.Join(r.root, "runner.json") if err := os.WriteFile(path, raw, 0600); err != nil { t.Fatal(err) } before := r.generation() log, err := os.OpenFile(filepath.Join(r.root, "runner.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) if err != nil { t.Fatal(err) } defer log.Close() self, _ := os.Executable() if r.binary != "" { self = r.binary } cmd := exec.Command(self) cmd.Env = append(os.Environ(), "EQUIPO_HEADLESS_RUNNER="+path) if r.scope != "" { cmd.Env = append(cmd.Env, proc.ScopeEnv+"="+r.scope) } cmd.Stdout, cmd.Stderr = log, log if err = cmd.Start(); err != nil { t.Fatal(err) } r.cmd = cmd deadline := time.Now().Add(20 * time.Second) for r.generation() <= before { if time.Now().After(deadline) { out, _ := os.ReadFile(filepath.Join(r.root, "runner.log")) t.Fatalf("runner process did not connect: %s", out) } time.Sleep(50 * time.Millisecond) } } func (r *localRunner) endProcess(t *testing.T, sig syscall.Signal) { t.Helper() if r.cmd == nil { return } _ = r.cmd.Process.Signal(sig) done := make(chan error, 1) go func() { done <- r.cmd.Wait() }() select { case <-done: case <-time.After(45 * time.Second): r.cmd.Process.Kill() t.Fatal("runner process did not exit") } r.cmd = nil } // kill is a real process death: SIGKILL, no deferred cleanup runs. func (r *localRunner) kill(t *testing.T) { t.Helper() if !r.subprocess { t.Fatal("kill needs a runner process") } r.endProcess(t, syscall.SIGKILL) } // runnerSetup makes a runner's files (fake Claude and Codex, account // homes, bindings, roots, a local forge) for an instance at origin, // enrolled as cred. func runnerSetup(t *testing.T, origin, teamID string, cred runnerproto.RunnerCredential) (*localRunner, *localForge) { t.Helper() root, err := os.MkdirTemp("", "eqh-") if err != nil { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(root) }) private(t, root) bin := private(t, filepath.Join(root, "bin")) digest := copyExecutable(t, filepath.Join(bin, "claude")) codexDigest := copyExecutable(t, filepath.Join(bin, "codex")) hostDigest := copyExecutable(t, filepath.Join(bin, "codex-code-mode-host")) copyExecutable(t, filepath.Join(bin, "equipo-tool-proxy")) state := private(t, filepath.Join(root, "state")) if err = thintest.WriteRunnerCredential(state, cred); err != nil { t.Fatal(err) } home := private(t, filepath.Join(root, "accounts", "claude-1")) identity := map[string]string{"account_id": thintest.Owner, "home_id": rand.Text(), "provider_version": fakeclaude.Version} writeJSON(t, filepath.Join(home, "equipo-identity.json"), identity) writeJSON(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]string{"emailAddress": thintest.Owner}}) if err = fakeclaude.WriteCredentials(home, time.Now().Add(8*time.Hour)); err != nil { t.Fatal(err) } config := private(t, filepath.Join(root, "config")) bindings := filepath.Join(config, "bindings.json") writeJSON(t, bindings, []map[string]any{{"id": "claude-1", "local_id": "claude-1", "label": "claude-1", "person_id": thintest.Owner, "provider": "claude", "family": "claude", "model": "claude-opus-5-5", "account_id": thintest.Owner, "provider_home": home, "kind": "subscription", "expected_identity": identity}}) self, _ := os.Executable() cfg := runner.Config{Origin: origin, InstanceID: teamID, StateDir: state, AccountBindingsPath: bindings, AmadanCredentialPath: filepath.Join(config, "amadan.json"), ClaudePath: filepath.Join(bin, "claude"), CodexPath: filepath.Join(bin, "codex"), CodexCodeModeHostPath: filepath.Join(bin, "codex-code-mode-host"), BwrapPath: "/usr/bin/bwrap", GoRoot: private(t, filepath.Join(root, "go")), ModuleCache: private(t, filepath.Join(root, "modules")), GoBinary: filepath.Join(root, "go", "bin", "go"), WorkspaceRoot: filepath.Join(root, "work"), ScratchRoot: filepath.Join(root, "scratch"), GitPath: "/usr/bin/git", AmadanPath: filepath.Join(bin, "claude"), ToolProxyPath: filepath.Join(bin, "equipo-tool-proxy"), Executable: self} logger := slog.New(slog.NewTextHandler(io.Discard, nil)) if testing.Verbose() { logger = slog.New(slog.NewTextHandler(os.Stderr, nil)) } forge := newLocalForge(t, root) // Moving in is on only for the scenarios about it (2b_*). r := &localRunner{root: root, cfg: cfg, opts: thin.Options{Version: "test", Logger: logger, Forge: forge, NoMoveIn: true, MergeEvery: time.Second, Claude: thin.ClaudeOptions{Digest: digest, Idle: time.Minute, LockWait: 5 * time.Second}, Codex: thin.CodexOptions{Digest: codexDigest, HostDigest: hostDigest}, AccountsRoot: filepath.Join(root, "accounts")}} return r, forge }