oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package headless
2
3import (
4 "context"
5 "crypto/rand"
6 "crypto/sha256"
7 "database/sql"
8 "encoding/hex"
9 "encoding/json"
10 "fmt"
11 "io"
12 "log/slog"
13 "os"
14 "os/exec"
15 "os/signal"
16 "path/filepath"
17 "strings"
18 "sync"
19 "syscall"
20 "testing"
21 "time"
22
23 "amadan.net/oficina/equipo/internal/equipo/chat"
24 "amadan.net/oficina/equipo/internal/fakeclaude"
25 "amadan.net/oficina/equipo/internal/fakecodex"
26 "amadan.net/oficina/equipo/internal/runner"
27 "amadan.net/oficina/equipo/internal/runner/containment"
28 "amadan.net/oficina/equipo/internal/runner/mac/proc"
29 "amadan.net/oficina/equipo/internal/runner/provider"
30 "amadan.net/oficina/equipo/internal/runner/thin"
31 "amadan.net/oficina/equipo/internal/runnerproto"
32 "amadan.net/oficina/equipo/internal/testci"
33 "amadan.net/oficina/equipo/internal/thintest"
34 "amadan.net/oficina/equipo/internal/toolproxy"
35 "amadan.net/oficina/equipo/internal/wire"
36 "amadan.net/rastrillo/rastrillo/budget"
37 gitleakscmd "github.com/zricethezav/gitleaks/v8/cmd"
38 _ "modernc.org/sqlite"
39)
40
41// TestMain also serves as the namespace helper, the fake claude and the
42// MCP stdio proxy: the suite runs them from copies of this binary.
43func TestMain(m *testing.M) {
44 switch filepath.Base(os.Args[0]) {
45 case "claude":
46 os.Exit(fakeclaude.Main(os.Args[1:], os.Stdin, os.Stdout, os.Stderr))
47 case "xcodebuild":
48 os.Exit(fakeXcodebuild())
49 case "codex":
50 os.Exit(fakecodex.Main(os.Args[1:], os.Stdin, os.Stdout, os.Stderr))
51 case "codex-code-mode-host":
52 os.Exit(0)
53 case "scanner", "gitleaks":
54 // The fake Mac worker's pinned gitleaks (the scan before anything
55 // of a candidate made on the Mac leaves it).
56 gitleakscmd.Execute()
57 return
58 case "equipo-tool-proxy":
59 args := os.Args
60 if len(args) == 4 && args[1] == provider.DarwinToolProxyCommand {
61 // The darwin MCP config's command line (the fake Mac worker's
62 // Engineering): equipo-runner tool-proxy --socket <path>.
63 args = append(args[:1:1], args[2:]...)
64 }
65 if len(args) != 3 || args[1] != "--socket" {
66 os.Exit(2)
67 }
68 if toolproxy.Serve(context.Background(), os.Stdin, os.Stdout, args[2]) != nil {
69 os.Exit(1)
70 }
71 os.Exit(0)
72 }
73 if len(os.Args) > 1 && os.Args[1] == "__namespace" {
74 os.Exit(containment.NamespaceMain(os.Args[2:]))
75 }
76 if path := os.Getenv("EQUIPO_HEADLESS_RUNNER"); path != "" {
77 os.Exit(runnerProcess(path))
78 }
79 code := budget.Main(m)
80 thintest.RemoveSchema()
81 os.Exit(code)
82}
83
84// Env is what a scenario may touch: the person API and SSE through the
85// client, and the controls a person or an operator has (runner on and off,
86// instance restart). Local and staging environments implement the same.
87type Env struct {
88 Client *thintest.Client
89 // Live is true against the real CLI, where replies are not scripted.
90 Live bool
91 // Slow is a prompt that streams for a few seconds.
92 Slow string
93 StopRunner func(t *testing.T)
94 // KillRunner kills the runner process outright (SIGKILL), with no
95 // cleanup of its own.
96 KillRunner func(t *testing.T)
97 StartRunner func(t *testing.T)
98 RestartRunner func(t *testing.T)
99 RestartInst func(t *testing.T)
100 AgeEvents func(t *testing.T) bool
101 ResumeThreshold time.Duration
102 // Project is the repository a live run works in (for example
103 // oficina/equipo); local runs use the local forge's oficina/sample.
104 Project string
105 RunID string
106 // Grant and Revoke change what the agent reaches (local forge only),
107 // then restart the runner so its index refreshes.
108 Grant, Revoke func(t *testing.T, repo string)
109 // BreakDesk makes the desk record unwritable, then starts the runner.
110 BreakDesk func(t *testing.T)
111 // Witness is what the person says in the live Engineering scenario
112 // (EQUIPO_STAGING_WITNESS); CrashWitness the same for scenario 4 and
113 // CancelWitness for the step cancel. Each asks for a different change,
114 // so no two of a run's tasks read alike.
115 Witness, CrashWitness, CancelWitness string
116 // ForgePath is a local forge repository's bare path (local only).
117 ForgePath func(repo string) string
118 // OfflineMac enrols a Mac worker that said hello once and is offline
119 // (local only): checks that need a Mac wait for it (waiting_runner),
120 // not for a Mac runner to be added. The func it returns removes it.
121 // PastOfflineLimit runs placement with the clock past the offline
122 // limit, so such checks end not run (runner_offline).
123 OfflineMac func(t *testing.T) func()
124 PastOfflineLimit func(t *testing.T)
125 // GrantNow makes a repository reachable without restarting the
126 // runner, like a grant on the hub (local only).
127 GrantNow func(t *testing.T, repo string)
128 // GrantEmpty makes a new repository with no commits reachable, then
129 // restarts the runner (local only).
130 GrantEmpty func(t *testing.T, repo string)
131 // RebuildHead points a local repository's HEAD at branch, as the hub's
132 // rebuild does to an empty repository whose only branch is a task's.
133 RebuildHead func(t *testing.T, repo, branch string)
134 // HubUpdate makes the local hub the one that makes the first merge
135 // into an empty repository, then restarts the runner (local only).
136 HubUpdate func(t *testing.T)
137 // Indexed reports whether the instance's newest hello catalogues repo,
138 // and whether as empty (local only).
139 Indexed func(t *testing.T, repo string) (found, empty bool)
140 // KeptSessions counts the step sessions the runner keeps on disk
141 // (local only).
142 KeptSessions func(t *testing.T) int
143 // AskNamespace is the containment namespace the runner recorded for
144 // a question's attempt (local only).
145 AskNamespace func(t *testing.T, question string) string
146 // AskUsage is the outcomes of a question's recorded usage rows, with
147 // whether each carried figures (local only).
148 AskUsage func(t *testing.T, question string) []string
149 // AskPin is the Engineering attempt and session the instance froze on
150 // a question, and the session the runner kept for that attempt
151 // (local only).
152 AskPin func(t *testing.T, question string) (attempt int64, session, kept string)
153 // Usage is every usage row of a task and of one coordinator turn, as
154 // role/round/turns=<known>/cached=<any>, by role and round (local only).
155 Usage func(t *testing.T, task, turn string) []string
156 // duringReplay makes something new reach the conversation while
157 // scenario 7 reads its replay, as a runner's hello with fresh headroom
158 // does on staging (local only).
159 duringReplay func(t *testing.T, s *session)
160 turns *int
161}
162
163// Turn counts model turns so staging stays inside its budget.
164func (e *Env) Turn(t *testing.T) {
165 t.Helper()
166 *e.turns++
167 if limit := os.Getenv("EQUIPO_STAGING_TURN_LIMIT"); e.Live && limit != "" {
168 var n int
169 json.Unmarshal([]byte(limit), &n)
170 if *e.turns > n {
171 t.Fatalf("staging turn budget %d exceeded", n)
172 }
173 }
174}
175
176// localRunner runs the real runner in this process against the fake CLI
177// inside real bubblewrap.
178type localRunner struct {
179 cfg runner.Config
180 opts thin.Options
181 // subprocess runs the runner as its own process, so it can be killed.
182 subprocess bool
183 // runnerID scopes the connection wait to this runner (several runners
184 // share one instance).
185 runnerID string
186 // binary runs the runner process from another build (M8: the slice 4
187 // test binary), not this one.
188 binary string
189 inst *thintest.Instance
190 // scope, for the fake Mac worker, tags its process and everything it
191 // starts (EQUIPO_TEST_SCOPE): its turns sweep only those, and a turn
192 // a crash left incomplete is cleared by an idle read of them.
193 scope string
194 // instanceDB is the database of an instance in another process (an
195 // older release's), read to see this runner connect when inst is nil.
196 instanceDB string
197 root string
198 cmd *exec.Cmd
199
200 mu sync.Mutex
201 cancel context.CancelFunc
202 done chan error
203 connected chan bool
204}
205
206func (r *localRunner) start(t *testing.T) {
207 t.Helper()
208 if r.subprocess {
209 r.startProcess(t)
210 return
211 }
212 r.mu.Lock()
213 defer r.mu.Unlock()
214 ctx, cancel := context.WithCancel(context.Background())
215 r.cancel, r.done = cancel, make(chan error, 1)
216 connected := make(chan bool, 16)
217 r.connected = connected
218 opts := r.opts
219 opts.Connected = func(up bool) {
220 select {
221 case connected <- up:
222 default:
223 }
224 }
225 go func() { r.done <- thin.Run(ctx, r.cfg, opts) }()
226 select {
227 case up := <-connected:
228 if !up {
229 t.Fatal("runner did not connect")
230 }
231 case err := <-r.done:
232 t.Fatalf("runner exited: %v", err)
233 case <-time.After(15 * time.Second):
234 t.Fatal("runner did not connect in time")
235 }
236}
237
238func (r *localRunner) stop(t *testing.T) {
239 t.Helper()
240 if r.subprocess {
241 r.endProcess(t, syscall.SIGTERM)
242 return
243 }
244 r.mu.Lock()
245 defer r.mu.Unlock()
246 if r.cancel == nil {
247 return
248 }
249 r.cancel()
250 select {
251 case err := <-r.done:
252 if err != nil && err != context.Canceled {
253 t.Logf("runner stopped: %v", err)
254 }
255 case <-time.After(45 * time.Second):
256 t.Fatal("runner did not stop")
257 }
258 r.cancel = nil
259}
260
261func copyExecutable(t *testing.T, dst string) string {
262 t.Helper()
263 self, err := os.Executable()
264 if err != nil {
265 t.Fatal(err)
266 }
267 in, err := os.Open(self)
268 if err != nil {
269 t.Fatal(err)
270 }
271 defer in.Close()
272 out, err := os.OpenFile(dst, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0755)
273 if err != nil {
274 t.Fatal(err)
275 }
276 h := sha256.New()
277 if _, err = io.Copy(io.MultiWriter(out, h), in); err != nil {
278 t.Fatal(err)
279 }
280 if err = out.Close(); err != nil {
281 t.Fatal(err)
282 }
283 return hex.EncodeToString(h.Sum(nil))
284}
285
286func private(t *testing.T, path string) string {
287 t.Helper()
288 if err := os.MkdirAll(path, 0700); err != nil {
289 t.Fatal(err)
290 }
291 if err := os.Chmod(path, 0700); err != nil {
292 t.Fatal(err)
293 }
294 return path
295}
296
297func writeJSON(t *testing.T, path string, v any) {
298 t.Helper()
299 raw, _ := json.Marshal(v)
300 if err := os.WriteFile(path, raw, 0600); err != nil {
301 t.Fatal(err)
302 }
303}
304
305// localEnv starts an instance, signs a device in, enrols a runner and
306// gives it one dedicated fake Claude home for the owner.
307func localEnv(t *testing.T) (*Env, *thintest.Instance, *localRunner) {
308 t.Helper()
309 testci.Tools(t, "bwrap", "git", "tar")
310 if _, err := exec.LookPath("/usr/bin/bwrap"); err != nil {
311 t.Skip("bubblewrap is required")
312 }
313 inst := thintest.StartInstance(t)
314 token := inst.DeviceToken(t)
315 cred := inst.EnrolRunner(t)
316 r, forge := runnerSetup(t, inst.URL, inst.TeamID, cred)
317 r.inst = inst
318 cfg, state, root := r.cfg, r.cfg.StateDir, r.root
319 t.Cleanup(func() { r.stop(t) })
320 // Like carlos restart, the control returns before the instance cycles,
321 // so scenario 8 has to wait for the restart itself.
322 restartLater := func(t *testing.T) {
323 done := make(chan struct{})
324 t.Cleanup(func() { <-done })
325 time.AfterFunc(time.Second, func() { defer close(done); inst.Restart(t) })
326 }
327 turns := 0
328 env := &Env{
329 Client: thintest.NewClient(inst.URL, token),
330 Slow: "Take your time with this one. sleep:1500",
331 StartRunner: r.start,
332 StopRunner: r.stop,
333 KillRunner: r.kill,
334 RestartRunner: func(t *testing.T) { r.stop(t); r.start(t) },
335 RestartInst: restartLater,
336 ResumeThreshold: 5 * time.Second,
337 turns: &turns,
338 BreakDesk: func(t *testing.T) {
339 r.stop(t)
340 desk, err := thin.OpenDesk(thin.SessionRoot(cfg), thintest.Owner)
341 if err != nil {
342 t.Fatal(err)
343 }
344 if err := os.MkdirAll(filepath.Join(filepath.Dir(desk.Dir), "desk.json"), 0700); err != nil {
345 t.Fatal(err)
346 }
347 r.start(t)
348 },
349 ForgePath: forge.path,
350 OfflineMac: func(t *testing.T) func() {
351 cred := inst.EnrolRunner(t)
352 w, err := thintest.DialRunnerHello(context.Background(), inst.URL, cred.Token, thintest.WorkerHello(0))
353 if err != nil {
354 t.Fatal(err)
355 }
356 w.Close()
357 return func() {
358 if _, err := inst.DB.Writer().Exec("UPDATE runners SET revoked_at = ? WHERE id = ?", time.Now().UTC(), cred.RunnerID); err != nil {
359 t.Error(err)
360 }
361 }
362 },
363 PastOfflineLimit: func(t *testing.T) {
364 later := time.Now().UTC().Add(chat.OfflineLimit + time.Minute)
365 inst.Store.Chat().SetClock(func() time.Time { return later })
366 defer inst.Store.Chat().SetClock(func() time.Time { return time.Now().UTC() })
367 if err := inst.Store.Chat().Place(context.Background()); err != nil {
368 t.Fatal(err)
369 }
370 },
371 AskNamespace: func(t *testing.T, question string) string {
372 d, err := sql.Open("sqlite", "file:"+filepath.Join(state, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)")
373 if err != nil {
374 t.Fatal(err)
375 }
376 defer d.Close()
377 var ns string
378 if err := d.QueryRow("SELECT ns_id FROM asks WHERE question_id=?", question).Scan(&ns); err != nil {
379 t.Fatal(err)
380 }
381 return ns
382 },
383 AskPin: func(t *testing.T, question string) (attempt int64, session, kept string) {
384 var step string
385 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 {
386 t.Fatal(err)
387 }
388 d, err := sql.Open("sqlite", "file:"+filepath.Join(state, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)")
389 if err != nil {
390 t.Fatal(err)
391 }
392 defer d.Close()
393 _ = d.QueryRow("SELECT session_id FROM kept_sessions WHERE step_id=? AND attempt=?", step, attempt).Scan(&kept)
394 return attempt, session, kept
395 },
396 AskUsage: func(t *testing.T, question string) []string {
397 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)
398 if err != nil {
399 t.Fatal(err)
400 }
401 defer rows.Close()
402 var out []string
403 for rows.Next() {
404 var outcome string
405 var figures bool
406 if err := rows.Scan(&outcome, &figures); err != nil {
407 t.Fatal(err)
408 }
409 out = append(out, fmt.Sprintf("%s/%v", outcome, figures))
410 }
411 return out
412 },
413 Usage: func(t *testing.T, task, turn string) []string {
414 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)
415 if err != nil {
416 t.Fatal(err)
417 }
418 defer rows.Close()
419 var out []string
420 for rows.Next() {
421 var role string
422 var round int
423 var turns, cached int64
424 var input bool
425 if err := rows.Scan(&role, &round, &turns, &cached, &input); err != nil {
426 t.Fatal(err)
427 }
428 if !input {
429 role += "(no figures)"
430 }
431 out = append(out, fmt.Sprintf("%s/%d/turns=%v/cached=%v", role, round, turns > 0, cached > 0))
432 }
433 return out
434 },
435 KeptSessions: func(t *testing.T) int {
436 dirs, _ := filepath.Glob(filepath.Join(thin.SessionRoot(cfg), "*", "steps", "*"))
437 return len(dirs)
438 },
439 GrantNow: func(t *testing.T, repo string) { forge.grant(t, root, repo) },
440 RebuildHead: func(t *testing.T, repo, branch string) {
441 gitRun(t, forge.root, "--git-dir="+forge.path(repo), "symbolic-ref", "HEAD", "refs/heads/"+branch)
442 },
443 HubUpdate: func(t *testing.T) {
444 forge.mu.Lock()
445 forge.hubUpdated = true
446 forge.mu.Unlock()
447 r.stop(t)
448 r.start(t)
449 },
450 GrantEmpty: func(t *testing.T, repo string) {
451 forge.grantEmpty(t, repo)
452 r.stop(t)
453 r.start(t)
454 },
455 Indexed: func(t *testing.T, repo string) (bool, bool) {
456 rows, err := inst.DB.Writer().Query("SELECT hello FROM runner_sessions WHERE hello <> ''")
457 if err != nil {
458 t.Fatal(err)
459 }
460 defer rows.Close()
461 for rows.Next() {
462 var raw string
463 var h wire.Hello
464 if rows.Scan(&raw) != nil || json.Unmarshal([]byte(raw), &h) != nil {
465 continue
466 }
467 for _, e := range h.Catalog {
468 if e.Repo == repo {
469 return true, e.Empty
470 }
471 }
472 }
473 return false, false
474 },
475 Grant: func(t *testing.T, repo string) { forge.grant(t, root, repo); r.stop(t); r.start(t) },
476 Revoke: func(t *testing.T, repo string) { forge.revoke(repo); r.stop(t); r.start(t) },
477 AgeEvents: func(t *testing.T) bool {
478 if _, err := inst.DB.Writer().Exec("UPDATE chat_events SET created_at = ?", time.Now().Add(-48*time.Hour)); err != nil {
479 t.Fatal(err)
480 }
481 if err := inst.Store.Chat().Sweep(context.Background()); err != nil {
482 t.Fatal(err)
483 }
484 return true
485 },
486 }
487 return env, inst, r
488}
489
490// stagingEnv drives a deployed staging instance and the staging runner
491// unit with the real CLI. Controls are shell commands from the gate script.
492func stagingEnv(t *testing.T) *Env {
493 t.Helper()
494 origin, token := os.Getenv("EQUIPO_STAGING_ORIGIN"), os.Getenv("EQUIPO_STAGING_TOKEN")
495 if origin == "" || token == "" {
496 t.Skip("set EQUIPO_STAGING_ORIGIN and EQUIPO_STAGING_TOKEN to run against staging")
497 }
498 run := func(variable string) func(t *testing.T) {
499 return func(t *testing.T) {
500 t.Helper()
501 command := os.Getenv(variable)
502 if command == "" {
503 t.Skipf("%s is not set", variable)
504 }
505 cmd := exec.Command("/bin/sh", "-c", command)
506 out, err := cmd.CombinedOutput()
507 if err != nil {
508 t.Fatalf("%s: %v: %s", variable, err, strings.TrimSpace(string(out)))
509 }
510 }
511 }
512 turns := 0
513 client := thintest.NewClient(origin, token)
514 client.HTTP.Timeout = 60 * time.Second
515 return &Env{
516 Client: client,
517 Live: true,
518 RunID: os.Getenv("EQUIPO_STAGING_RUN_ID"),
519 Slow: "Count from 1 to 150, one number per line, and nothing else.",
520 StartRunner: run("EQUIPO_STAGING_RUNNER_START"),
521 StopRunner: run("EQUIPO_STAGING_RUNNER_STOP"),
522 KillRunner: run("EQUIPO_STAGING_RUNNER_KILL"),
523 RestartRunner: run("EQUIPO_STAGING_RUNNER_RESTART"),
524 RestartInst: run("EQUIPO_STAGING_INSTANCE_RESTART"),
525 AgeEvents: func(*testing.T) bool { return false },
526 ResumeThreshold: 15 * time.Second,
527 Project: os.Getenv("EQUIPO_STAGING_PROJECT"),
528 Witness: os.Getenv("EQUIPO_STAGING_WITNESS"),
529 CrashWitness: os.Getenv("EQUIPO_STAGING_CRASH_WITNESS"),
530 CancelWitness: os.Getenv("EQUIPO_STAGING_CANCEL_WITNESS"),
531 turns: &turns,
532 }
533}
534
535// processConfig is what a runner subprocess needs; runner.Config holds a func.
536type processConfig struct {
537 Origin, InstanceID, StateDir, AccountBindingsPath, AmadanCredentialPath string
538 ClaudePath, CodexPath, CodexCodeModeHostPath, BwrapPath, GoRoot, ModuleCache string
539 GoBinary, WorkspaceRoot, ScratchRoot, GitPath, AmadanPath, ToolProxy string
540 Digest, MoveInNote string
541 MachineLabel, FakePlatform, FakeBin, FakeSandbox string
542 CodexDigest, CodexHostDigest, AccountsRoot string
543 NoMoveIn bool
544 Idle, LockWait, MaxTurn, Margin time.Duration
545 // MaxStep bounds an Engineering step (thin.Options.MaxStep; 0 is the
546 // default). The fake Mac worker's is a minute, so a step runs out of
547 // time within a scenario.
548 MaxStep time.Duration
549 // Forge is the local forge's state, so a runner process works on the
550 // same bare repositories as an in-process one.
551 Forge *localForgeState
552}
553
554func runnerProcess(path string) int {
555 raw, err := os.ReadFile(path)
556 var p processConfig
557 if err != nil || json.Unmarshal(raw, &p) != nil {
558 return 2
559 }
560 self, _ := os.Executable()
561 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}
562 ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
563 defer stop()
564 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}
565 if p.Forge != nil {
566 opts.Forge = p.Forge.forge()
567 }
568 opts.Claude = thin.ClaudeOptions{Digest: p.Digest, Idle: p.Idle, LockWait: p.LockWait, MaxTurn: p.MaxTurn, Margin: p.Margin, MoveInNote: p.MoveInNote}
569 opts.Codex, opts.AccountsRoot = thin.CodexOptions{Digest: p.CodexDigest, HostDigest: p.CodexHostDigest}, p.AccountsRoot
570 err = thin.Run(ctx, cfg, opts)
571 if err != nil && ctx.Err() == nil {
572 return 1
573 }
574 return 0
575}
576
577func (r *localRunner) generation() int64 {
578 var g int64
579 if r.inst == nil {
580 d, err := sql.Open("sqlite", "file:"+r.instanceDB+"?mode=ro&_pragma=busy_timeout(5000)")
581 if err != nil {
582 return 0
583 }
584 defer d.Close()
585 d.QueryRow("SELECT coalesce(max(generation),0) FROM runner_sessions WHERE connected = 1 AND runner_id = ?", r.runnerID).Scan(&g)
586 return g
587 }
588 if r.runnerID != "" {
589 r.inst.DB.Writer().QueryRow("SELECT coalesce(max(generation),0) FROM runner_sessions WHERE connected = 1 AND runner_id = ?", r.runnerID).Scan(&g)
590 return g
591 }
592 r.inst.DB.Writer().QueryRow("SELECT coalesce(max(generation),0) FROM runner_sessions WHERE connected = 1").Scan(&g)
593 return g
594}
595
596func (r *localRunner) startProcess(t *testing.T) {
597 t.Helper()
598 if r.cmd != nil {
599 // A second process would orphan the first (cleanup stops only
600 // the one it knows).
601 t.Fatal("the runner process is already running")
602 }
603 c, o := r.cfg, r.opts.Claude
604 var fs *localForgeState
605 if lf, ok := r.opts.Forge.(*localForge); ok {
606 fs = lf.state()
607 }
608 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})
609 path := filepath.Join(r.root, "runner.json")
610 if err := os.WriteFile(path, raw, 0600); err != nil {
611 t.Fatal(err)
612 }
613 before := r.generation()
614 log, err := os.OpenFile(filepath.Join(r.root, "runner.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
615 if err != nil {
616 t.Fatal(err)
617 }
618 defer log.Close()
619 self, _ := os.Executable()
620 if r.binary != "" {
621 self = r.binary
622 }
623 cmd := exec.Command(self)
624 cmd.Env = append(os.Environ(), "EQUIPO_HEADLESS_RUNNER="+path)
625 if r.scope != "" {
626 cmd.Env = append(cmd.Env, proc.ScopeEnv+"="+r.scope)
627 }
628 cmd.Stdout, cmd.Stderr = log, log
629 if err = cmd.Start(); err != nil {
630 t.Fatal(err)
631 }
632 r.cmd = cmd
633 deadline := time.Now().Add(20 * time.Second)
634 for r.generation() <= before {
635 if time.Now().After(deadline) {
636 out, _ := os.ReadFile(filepath.Join(r.root, "runner.log"))
637 t.Fatalf("runner process did not connect: %s", out)
638 }
639 time.Sleep(50 * time.Millisecond)
640 }
641}
642
643func (r *localRunner) endProcess(t *testing.T, sig syscall.Signal) {
644 t.Helper()
645 if r.cmd == nil {
646 return
647 }
648 _ = r.cmd.Process.Signal(sig)
649 done := make(chan error, 1)
650 go func() { done <- r.cmd.Wait() }()
651 select {
652 case <-done:
653 case <-time.After(45 * time.Second):
654 r.cmd.Process.Kill()
655 t.Fatal("runner process did not exit")
656 }
657 r.cmd = nil
658}
659
660// kill is a real process death: SIGKILL, no deferred cleanup runs.
661func (r *localRunner) kill(t *testing.T) {
662 t.Helper()
663 if !r.subprocess {
664 t.Fatal("kill needs a runner process")
665 }
666 r.endProcess(t, syscall.SIGKILL)
667}
668
669// runnerSetup makes a runner's files (fake Claude and Codex, account
670// homes, bindings, roots, a local forge) for an instance at origin,
671// enrolled as cred.
672func runnerSetup(t *testing.T, origin, teamID string, cred runnerproto.RunnerCredential) (*localRunner, *localForge) {
673 t.Helper()
674 root, err := os.MkdirTemp("", "eqh-")
675 if err != nil {
676 t.Fatal(err)
677 }
678 t.Cleanup(func() { os.RemoveAll(root) })
679 private(t, root)
680 bin := private(t, filepath.Join(root, "bin"))
681 digest := copyExecutable(t, filepath.Join(bin, "claude"))
682 codexDigest := copyExecutable(t, filepath.Join(bin, "codex"))
683 hostDigest := copyExecutable(t, filepath.Join(bin, "codex-code-mode-host"))
684 copyExecutable(t, filepath.Join(bin, "equipo-tool-proxy"))
685 state := private(t, filepath.Join(root, "state"))
686 if err = thintest.WriteRunnerCredential(state, cred); err != nil {
687 t.Fatal(err)
688 }
689 home := private(t, filepath.Join(root, "accounts", "claude-1"))
690 identity := map[string]string{"account_id": thintest.Owner, "home_id": rand.Text(), "provider_version": fakeclaude.Version}
691 writeJSON(t, filepath.Join(home, "equipo-identity.json"), identity)
692 writeJSON(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]string{"emailAddress": thintest.Owner}})
693 if err = fakeclaude.WriteCredentials(home, time.Now().Add(8*time.Hour)); err != nil {
694 t.Fatal(err)
695 }
696 config := private(t, filepath.Join(root, "config"))
697 bindings := filepath.Join(config, "bindings.json")
698 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}})
699 self, _ := os.Executable()
700 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}
701 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
702 if testing.Verbose() {
703 logger = slog.New(slog.NewTextHandler(os.Stderr, nil))
704 }
705 forge := newLocalForge(t, root)
706 // Moving in is on only for the scenarios about it (2b_*).
707 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")}}
708 return r, forge
709}
710