package mac import ( "bytes" "context" "errors" "os" "os/exec" "path/filepath" "slices" "strconv" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/wire" ) // Result is one gate run: the output's last lines, the exit code, why it // did not finish ("cancelled", "checks_timeout", "checks_unavailable"), // whether its end is proven, and how it was confined. type Result struct { Output, Reason string Code int Terminated bool // Sandbox is wire.SandboxSeatbelt when srt confined the gate, else // wire.SandboxNone. Sandbox string } // Gate runs a repository's checks in a process group of their own // (spec §5): a new session, EQUIPO_ATTEMPT= in the environment, an // environment from scratch. With SRT set the gate runs under srt with // the attempt's checks profile; without, it runs outside the sandbox // (the test build's fake worker, or a Mac whose P2 did not deny). type Gate struct { // SRT is the srt executable; "" runs the gate without a sandbox. SRT string // Settings writes the attempt's srt settings for a tree and scratch. Settings func(tree, attempt string) ([]byte, error) // Env is the gate's whole environment but TMPDIR, EQUIPO_ATTEMPT and // EQUIPO_GATE_STATUS (and under srt CLAUDE_CODE_TMPDIR and // XDG_CONFIG_HOME), which the run adds. Env []string // Caffeinate keeps the Mac awake while a gate runs // (/usr/bin/caffeinate); "" does not. Caffeinate string // Booted lists the simulators booted now; Shutdown shuts one down. // A run shuts down the simulators it booted. Booted func(context.Context) []string Shutdown func(context.Context, string) // Grace is SIGTERM to SIGKILL (10 s); Settle bounds the proof (30 s). Grace, Settle time.Duration // Lines bounds the output kept (the last 200 lines). Lines int // Sandbox labels the result: srt confines it (seatbelt) or not (none). Sandbox string // ScratchHome sets HOME to the attempt's scratch too (the test // build's fake worker; a Mac keeps the runner user's home, where // Xcode's caches are). ScratchHome bool // UserTemp is the runner user's DARWIN_USER_TEMP_DIR ("T", which a // checks profile lets the gate write): what appears in it and in // T/TemporaryItems while a run lasts is removed once the run's end // is proven. "" removes nothing. UserTemp string // QuietSimulators, when set, runs once a run with a UserTemp has // proven its end and before T is cleaned: on a Mac, every // simulator of the runner user shut down (bounded), and what is // left of them logged. QuietSimulators func(context.Context) // Turns, when set, lets one run at a time hold the Mac (shared by // every gate of the runner), so a cleanup of T sees only its own. Turns *Turns // Watch sees each line of output as it comes (probe P6 waits for a // test to start before it kills the group). Watch func(string) // procs and own stand in for the process table and the runner's own // processes (tests). procs Procs own *Own } // executor is the gate's share of the Mac's executor. func (g *Gate) executor() *Executor { return &Executor{Turns: g.Turns, Procs: g.procs, Own: g.own, Grace: g.Grace, Settle: g.Settle, UserTemp: g.UserTemp, QuietSimulators: g.QuietSimulators, Unsandboxed: g.SRT == "" || g.Sandbox != wire.SandboxSeatbelt} } // statusScript runs the gate and records its exit status in a file: srt // exits 0 when the command it wraps dies of SIGTERM or SIGINT // (cli.ts), so the exit code alone could turn a killed gate into a pass. const statusScript = `"$@"; s=$?; printf '%s\n' "$s" > "$EQUIPO_GATE_STATUS"; exit "$s"` // Run runs argv in dir as a check: in the Mac's turn (the one ctx holds, // else its own for the run's life), through the executor, so record // gets the attempt's marker before anything starts and its group once // the leader exists (spec §5). Nothing runs if the first record fails; // the group is stopped if the second does. func (g *Gate) Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(string) error) Result { res := Result{Code: -1, Sandbox: g.Sandbox} unavailable := func() Result { res.Reason, res.Terminated = "checks_unavailable", true; return res } if len(argv) == 0 || !validMarker(attempt) { return unavailable() } ctx, give, err := g.Turns.Hold(ctx, OpCheck) if err != nil { if ctx.Err() == nil { return unavailable() } res.Reason, res.Terminated = "cancelled", true return res } defer give() scratch, err := os.MkdirTemp(filepath.Dir(dir), "attempt-") if err != nil { return unavailable() } defer os.RemoveAll(scratch) status := filepath.Join(scratch, ".equipo-status") cmdline := append([]string{"/bin/sh", "-c", statusScript, "sh"}, argv...) if g.SRT != "" { raw, err := g.Settings(dir, scratch) if err != nil { return unavailable() } // Beside the tree and scratch, not in them: the gate cannot // rewrite its own profile (it is read once, at start, anyway). settings := filepath.Join(filepath.Dir(dir), "srt-settings-"+filepath.Base(scratch)+".json") if err := os.WriteFile(settings, raw, 0600); err != nil { return unavailable() } defer os.Remove(settings) cmdline = append([]string{g.SRT, "--settings", settings, "--"}, cmdline...) } env := append(append([]string{}, g.Env...), "TMPDIR="+scratch, "EQUIPO_ATTEMPT="+attempt, "EQUIPO_GATE_STATUS="+status) if g.SRT != "" { // srt 0.0.81 sets the command's TMPDIR to CLAUDE_CODE_TMPDIR, else // to its own /tmp/claude (generateProxyEnvVars in sandbox-utils), // a directory every srt user on the Mac shares and none cleans: // keep it this attempt's scratch, which the profile already lets // the gate write and the run removes. env = append(env, "CLAUDE_CODE_TMPDIR="+scratch) // SwiftPM keeps ~/.swiftpm (links to its security, configuration // and cache folders, and a lock it takes) at $XDG_CONFIG_HOME/ // swiftpm when that is set (dotSwiftPM in SwiftPM's Basics), and // removes and remakes the security link on every resolve: under // srt that is a write to the real home, which the profile // refuses. In the attempt's scratch it is the attempt's alone. env = append(env, "XDG_CONFIG_HOME="+filepath.Join(scratch, "config")) } if g.ScratchHome { env = append(env, "HOME="+scratch) } var before []string if g.Booted != nil { before = g.Booted(ctx) } out := &tail{max: max(g.Lines, 1), watch: g.Watch} // A cleanup of T an earlier attempt left is finished first, only by // its owner or after a restart; T that cannot be listed (or is no // longer this user's own folder) or cleaned runs nothing. run, err := g.executor().Start(ctx, Command{Argv: cmdline, Env: env, Dir: dir, Stdout: out, Stderr: out}, attempt, record) if err != nil { res.Output = out.String() if errors.Is(err, ErrUnproven) { res.Reason = "checks_unavailable" return res } return unavailable() } if g.Caffeinate != "" { // Outside the group, the runner's own: it ends by itself when the // gate's leader does. awake := exec.Command(g.Caffeinate, "-i", "-w", strconv.Itoa(run.pgid)) if StartOwn(awake) == nil { go func() { _ = awake.Wait() }() } } timer := time.NewTimer(limit) defer timer.Stop() select { case <-run.Exited(): res.Code = exitCode(run.ExitErr()) if res.Code == 0 { // Both must say 0: srt's own exit and the status the gate's // shell recorded. raw, rerr := os.ReadFile(status) if n, perr := strconv.Atoi(strings.TrimSpace(string(raw))); rerr != nil || perr != nil || n != 0 { res.Code = 1 if perr == nil && n > 0 { res.Code = n } } } case <-run.Aborted(): // Its turn's record could not be written: stopped, and its end // proven only once a write succeeds. res.Reason = "checks_unavailable" case <-ctx.Done(): res.Reason = "cancelled" case <-timer.C: res.Reason = "checks_timeout" } res.Terminated = run.Stop() if g.Booted != nil && g.Shutdown != nil { for _, udid := range g.Booted(context.WithoutCancel(ctx)) { if !slices.Contains(before, udid) { g.Shutdown(context.WithoutCancel(ctx), udid) } } } // Only once the run's end is proven: a process of it still alive // could be writing T as it is cleaned. Unproven, or not finished, // the cleanup waits for this attempt's proof (Verify) or a restart, // and the run is not terminated: its end is proven only with T clean. if !run.Finish(ctx) { res.Terminated = false } res.Output = out.String() return res } // Verify reports whether a recorded attempt has ended for sure, killing // what is left of it (Executor.Verify): after a crash this is what // kills every marked process before the runner reports runner_restarted. func (g *Gate) Verify(id string) bool { return g.executor().Verify(id) } // Acknowledge is Executor.Acknowledge. func (g *Gate) Acknowledge(id, consumer string) { g.executor().Acknowledge(id, consumer) } func exitCode(err error) int { if err == nil { return 0 } var exit *exec.ExitError if errors.As(err, &exit) { if code := exit.ExitCode(); code >= 0 { return code } } return -1 } // tail keeps the last max lines written to it, each at most // maxLineBytes (the rest of a longer line is dropped), so what it holds // is bounded however much a gate prints, with or without newlines. type tail struct { mu sync.Mutex max int watch func(string) lines []string partial []byte } const maxLineBytes = 4 << 10 func (t *tail) Write(p []byte) (int, error) { t.mu.Lock() defer t.mu.Unlock() n := len(p) for len(p) > 0 { i := bytes.IndexByte(p, '\n') chunk := p if i >= 0 { chunk = p[:i] } if room := maxLineBytes - len(t.partial); room > 0 { t.partial = append(t.partial, chunk[:min(len(chunk), room)]...) } if i < 0 { break } line := string(t.partial) t.partial = t.partial[:0] t.lines = append(t.lines, line) if len(t.lines) > t.max { t.lines = append(t.lines[:0:0], t.lines[len(t.lines)-t.max:]...) } if t.watch != nil { t.watch(line) } p = p[i+1:] } return n, nil } func (t *tail) String() string { t.mu.Lock() defer t.mu.Unlock() lines := t.lines if len(t.partial) > 0 { lines = append(append([]string{}, lines...), string(t.partial)) } if len(lines) > t.max { lines = lines[len(lines)-t.max:] } return strings.Join(lines, "\n") }