oficina / equipo Public

Mac slice F task 9: executor, sweep and proof, one turn per operation

One executor for every Mac launch (the gate and the pinned CLI): the
marker on record before anything starts, the group once the leader
exists, a session of its own. Bash commands run setsid and macOS 27.2
hides platform binaries' environment, so the end is found by identity
(pid and kernel start time), never by name: (a) the tree under the
leader and the groups and sessions it makes, polled while it runs;
(b) every runner-user process not there when the turn began, except
the runner's own helpers (StartOwn) and launchd's system agents by the
kernel's path; (c) the marker. Each signal follows a fresh read of the
process; other users' processes are never targets. Proven only when
nothing of (a) to (c) is left, the leader is reaped and every group it
made is gone, within 30 s.

Turns per operation (check, Engineering, ask, probe run, token check,
sign-in, token store, warm) with a durable turn record; a later turn
settles an unproven one first. The restart path no longer proves an
attempt whose recorded group is alive without a marked process. A
pending user-temp cleanup is finished only by its owner or a restart.

The process table moves into internal/runner/mac/proc (mac budget).
Spec section 8.8 records the findings, the sweep and the narrowed limit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 4cc9a164f23a14563377f35849d5dc816fcaf681 parent 758bc5c
24 files changed, +3,360 −496
  • .rastrillo/budgets.txt +1 −1
  • docs/superpowers/specs/2026-11-07-equipo-mac-runners.md +115 −0
  • internal/runner/mac/engineering_test.go +4 −2
  • internal/runner/mac/gate.go +56 −214
  • internal/runner/mac/gate_test.go +6 −5
  • internal/runner/mac/launch.go +631 −0
  • internal/runner/mac/launch_test.go +653 −0
  • internal/runner/mac/marked_darwin.go +0 −20
  • internal/runner/mac/marked_linux.go +0 −42
  • internal/runner/mac/probe.go +14 −0
  • internal/runner/mac/probe_test.go +1 −1
  • internal/runner/mac/proc/proc.go +362 −0
  • internal/runner/mac/proc/proc_darwin.go +122 −0
  • internal/runner/mac/proc/proc_linux.go +169 −0
  • internal/runner/mac/proc/proc_test.go +34 −0
  • internal/runner/mac/{ => proc}/ps.go +4 −1
  • internal/runner/mac/proc_alias.go +43 −0
  • internal/runner/mac/procs_test.go +205 −0
  • internal/runner/mac/sweep_test.go +226 −0
  • internal/runner/mac/turns.go +647 −0
  • internal/runner/mac/usertemp.go +0 −176
  • internal/runner/mac/usertemp_test.go +33 −23
  • internal/runner/thin/mac.go +31 −9
  • internal/runner/thin/mac_test.go +3 −2
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 372a24f2..e886e136 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 30702 26575 Protocol 31 facts, 35 diffs, merge credential, publication guards, kept work, CI units, places publish, token scans, Mac pin, paths, bases, endpoint; measured 30702/26575.
+size internal/runner/thin 30724 26576 Protocol 31 facts, 35 diffs, merge credential, publication guards, kept work, CI units, places publish, token scans, Mac pin, paths, bases, endpoint, Mac turns; measured 30724/26576.
time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes.
time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
diff --git a/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md b/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md
index f757c6c5..8879ca03 100644
--- a/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md
+++ b/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md
@@ -923,3 +923,118 @@ build's fake worker and fake CLI.
in slice F; the findings text is, and the prompt says the images are on
the main runner. `simctl shutdown all` before a temp cleanup stays (the
mac-user-temp ruling): the runner user's simulators are all its own.
+
+### 8.8 Addendum to §5, 2026-11-28: finding what an attempt left
+
+Written for plan task 9, from task 1's findings
+(`docs/superpowers/plans/MAC-SLICE-F-TASK1-FINDINGS.md`, R4 and S5) and
+the sweep the coordinating session approved on 2026-11-28. Where it
+disagrees with §5, this section is current.
+
+**What task 1 found.**
+
+- Claude Code 2.1.312 starts every Bash tool command with
+ `detached: true`, so each command runs in a new session and process
+ group (setsid), outside the attempt's group. Signals to the
+ attempt's group never reach them.
+- On macOS 27.2 the kernel hides the environment of platform binaries
+ (`/bin/bash`, `/bin/zsh`, `/bin/sleep`, `/usr/bin/env`,
+ `/usr/bin/sandbox-exec`) even from their own user. `ps -E` and
+ `KERN_PROCARGS2` show `EQUIPO_ATTEMPT` only on other binaries (Xcode's
+ tools, built test binaries, Homebrew tools).
+- Together: §5's group-plus-marker sweep misses exactly the processes
+ Bash commands are made of. A sandboxed `sleep 1000 &` would outlive a
+ cancel, unseen.
+
+**The sweep.** Every process is named by its identity: its pid and the
+kernel's start time (microseconds, from `kern.proc`). A pid used again
+later is another identity. Nothing is matched by name. Three nets:
+
+- (a) While the operation runs, the runner reads the process table
+ (`kern.proc.ruid` for the runner user, `getsid` for sessions) about
+ every 250 ms. It records every process under the operation's leader,
+ and every group and session those processes make, on the operation's
+ scope and on the turn's durable record.
+- (b) When a turn begins, the runner records the identities of every
+ process the runner user has. At the operation's end, every process of
+ the runner user that was not there then is the operation's. Two
+ exceptions:
+ - the runner itself, and every helper it started for itself (capability
+ queries, `ps`, `caffeinate`, git, gitleaks, packing), registered by
+ identity when started (`mac.StartOwn`), and what those helpers start;
+ - launchd's system agents: parent pid 1 and an executable under
+ `/System` (not `/System/Volumes`) or `/usr/libexec`. The path is the
+ kernel's (`proc_pidpath`, the file it runs), never `argv[0]`, which a
+ process can set.
+
+ A process in a group or session the operation made, or one carrying
+ its marker, is the operation's whatever its parent or path.
+- (c) The marker, wherever the kernel shows it, as before.
+
+**The stop.** Close stdin and wait for a graceful end. Then send SIGTERM
+to everything in (a), (b) and (c), wait the 10 s grace, and send
+SIGKILL. Before each signal the runner reads that process again and
+signals it only if it is the same identity and still the runner user's.
+A group is signalled whole only while a re-checked member is in it (a
+group id cannot be used again while it has a member). Another user's
+process is never a target. Then the user-temp protocol, as before:
+`simctl shutdown all`, then the cleanup of what the attempt created.
+
+**The proof.** Termination is proven only when, within 30 s of the
+stop's start, all of these hold:
+
+- nothing from (a), (b) or (c) remains;
+- the leader is reaped;
+- every group the operation made returns ESRCH to `kill(-pgid, 0)`. A
+ group id now held by someone else keeps the proof waiting; it is never
+ killed.
+
+Otherwise the step stays unterminated (no Retry). Its turn's record
+stays too. The next turn, in any runner process, settles that record
+before it begins: it applies the same sweep with the earlier turn's
+"before" table. If anything is still left, the next turn does not begin.
+
+**After a restart.** The new runner settles the dead runner's turn
+record first. Then, for each recorded attempt, it kills every process
+carrying the marker, and the recorded group only while a marked process
+is in it. A recorded group that is alive with no marked process in it is
+either the attempt's child that scrubbed its environment or the group id
+used again by someone else. It is not killed, and the attempt is not
+proven over until the group is gone. A user-temp cleanup left pending
+belongs to the attempt, in the runner process that wrote it. Only that
+attempt (its run, or its later proof) or a restart may finish it.
+
+**One turn per operation.** `mac.Turns` is taken for each operation's
+life and no longer: a check, an Engineering attempt, an ask, a probe run
+(P1 to P7 as one turn; F1 to F7 likewise), a token check, a sign-in pty
+and a token store. What the operation starts itself belongs to it. Every
+Mac launch refuses to start outside a held turn. The credential flag
+(task 11) is separate: it holds no turn.
+
+**The honest limit, narrowed.** The sweep cannot tell a process launchd
+starts on the attempt's behalf from a system path from a system agent.
+Precisely, it spares any process that meets all of these:
+
+- its parent is launchd;
+- its kernel path is under `/System` or `/usr/libexec`;
+- it never showed in the attempt's tree, groups or sessions while the
+ table was read, and shows no marker.
+
+That includes a step that double-forks between two reads, starts a
+session of its own, and runs a system binary (a script interpreter under
+`/System`, for example). Such a process still runs under the attempt's
+Seatbelt profile, which it inherited. Also not covered:
+
+- a process that changes its real uid (a setuid program that calls
+ `setuid`), which leaves the runner user's table;
+- the moment between a fresh read of a process and its signal, in which
+ a pid could in theory be used again (macOS allocates pids in sequence,
+ so this needs a full wrap of the pid space within that moment);
+- after a restart, a group the attempt made whose members all changed
+ uid (the live proof sees it, the restart does not).
+
+Since the runner user is dedicated and turns are serialized, the sweep
+also ends anything else of the runner user's that started during the
+turn: a person signed in as that user, or launchd agents outside
+`/System` and `/usr/libexec` (such as `cfprefsd` in `/usr/sbin`), which
+launchd starts again on demand.
diff --git a/internal/runner/mac/engineering_test.go b/internal/runner/mac/engineering_test.go
index 77360090..a3c1f0fd 100644
--- a/internal/runner/mac/engineering_test.go
+++ b/internal/runner/mac/engineering_test.go
@@ -400,7 +400,10 @@ type engRig struct {
read [][]byte
}
-func newEngRig(t *testing.T) *engRig {
+func newEngRig(t *testing.T) *engRig { t.Helper(); return newEngRigWith(t, fakeClaude()) }
+
+// newEngRigWith is the rig with body as the pinned CLI.
+func newEngRigWith(t *testing.T, body []byte) *engRig {
t.Helper()
home, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
@@ -427,7 +430,6 @@ func newEngRig(t *testing.T) *engRig {
t.Fatal(err)
}
}
- body := fakeClaude()
cli := homeCLI(home, install, body)
if err := cli.Provision(context.Background(), serve(body, nil)); err != nil {
t.Fatal(err)
diff --git a/internal/runner/mac/gate.go b/internal/runner/mac/gate.go
index 9107130a..d5cb2d00 100644
--- a/internal/runner/mac/gate.go
+++ b/internal/runner/mac/gate.go
@@ -10,7 +10,6 @@ import (
"strconv"
"strings"
"sync"
- "syscall"
"time"
)
@@ -73,8 +72,15 @@ type Gate struct {
// 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)
- // find lists marked processes (Marked; tests stand in).
- find func(string) ([]Proc, error)
+ // 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}
}
// statusScript runs the gate and records its exit status in a file: srt
@@ -82,26 +88,26 @@ type Gate struct {
// (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. record persists the attempt's process record:
-// its marker before anything starts (a restarted runner then sweeps by
-// the marker alone), and its group once the leader exists. Nothing runs
-// if the first record fails; the group is killed if the second does.
+// 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 || strings.ContainsAny(attempt, " \n\x00") {
+ if len(argv) == 0 || !validMarker(attempt) {
return unavailable()
}
- if g.Turns != nil {
- if err := g.Turns.take(ctx); err != nil {
- if ctx.Err() == nil {
- return unavailable()
- }
- res.Reason, res.Terminated = "cancelled", true
- return res
+ ctx, give, err := g.Turns.Hold(ctx, OpCheck)
+ if err != nil {
+ if ctx.Err() == nil {
+ return unavailable()
}
- defer g.Turns.give()
+ res.Reason, res.Terminated = "cancelled", true
+ return res
}
+ defer give()
scratch, err := os.MkdirTemp(filepath.Dir(dir), "attempt-")
if err != nil {
return unavailable()
@@ -123,127 +129,55 @@ func (g *Gate) Run(ctx context.Context, attempt, dir string, argv []string, limi
defer os.Remove(settings)
cmdline = append([]string{g.SRT, "--settings", settings, "--"}, cmdline...)
}
- // What T holds before anything of the run starts, by handle: the
- // cleanup keeps exactly that. A cleanup an earlier attempt left is
- // finished first; a T that cannot be listed (or is no longer this
- // user's own folder) or cleaned runs nothing.
- var temp *tempState
- if g.UserTemp != "" {
- if err := g.finishPending(ctx); err != nil {
- return unavailable()
- }
- if temp, err = openTemp(g.UserTemp, nil); err != nil {
- return unavailable()
- }
- defer temp.close()
- // On record before anything starts: a runner killed from here
- // on leaves the cleanup to the next gate, not to nobody.
- if err := g.Turns.writePending(pendingRecord{Attempt: attempt, Before: temp.before}); err != nil {
- return unavailable()
- }
- }
- // 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 is left for the next gate, which runs nothing until
- // it is done.
- cleanUp := func() {
- if temp == nil {
- return
- }
- if !res.Terminated {
- // The record stays: the next gate proves this attempt's
- // end before it cleans.
- return
- }
- // Simulator processes are CoreSimulator's, outside the group
- // and outside srt, and may still write T: they go first
- // (bounded by the hook; it never fails the run).
- if g.QuietSimulators != nil {
- g.QuietSimulators(context.WithoutCancel(ctx))
- }
- if temp.clean() == nil {
- _ = g.Turns.dropPending()
- }
- }
- if err := record(RecordID(0, attempt)); err != nil {
- return unavailable()
- }
- var before []string
- if g.Booted != nil {
- before = g.Booted(ctx)
- }
- cmd := exec.Command(cmdline[0], cmdline[1:]...)
- cmd.Dir = dir
- cmd.Env = append(append([]string{}, g.Env...), "TMPDIR="+scratch, "EQUIPO_ATTEMPT="+attempt, "EQUIPO_GATE_STATUS="+status)
+ 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.
- cmd.Env = append(cmd.Env, "CLAUDE_CODE_TMPDIR="+scratch)
+ 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.
- cmd.Env = append(cmd.Env, "XDG_CONFIG_HOME="+filepath.Join(scratch, "config"))
+ env = append(env, "XDG_CONFIG_HOME="+filepath.Join(scratch, "config"))
}
if g.ScratchHome {
- cmd.Env = append(cmd.Env, "HOME="+scratch)
+ 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}
- cmd.Stdout, cmd.Stderr = out, out
- cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
- // A child that keeps the output open must not hold the run: once the
- // leader has gone, the pipes close after a second and the sweep
- // below kills what is left.
- cmd.WaitDelay = time.Second
- if err := cmd.Start(); err != nil {
+ // 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()
}
- pgid := cmd.Process.Pid
- if temp != nil {
- // With its group, so the next gate can prove that end too. Best
- // effort: the record before the start has the marker.
- _ = g.Turns.writePending(pendingRecord{Attempt: attempt, PGID: pgid, Before: temp.before})
- }
- exited := make(chan error, 1)
- go func() { exited <- cmd.Wait() }()
- if err := record(RecordID(pgid, attempt)); err != nil {
- _ = syscall.Kill(-pgid, syscall.SIGKILL)
- <-exited
- res.Reason, res.Terminated, res.Output = "checks_unavailable", g.settle(pgid, attempt, true), out.String()
- cleanUp()
- return res
- }
if g.Caffeinate != "" {
- // Outside the group: it ends by itself when the gate's leader does.
- awake := exec.Command(g.Caffeinate, "-i", "-w", strconv.Itoa(pgid))
- if awake.Start() == nil {
+ // 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() }()
}
}
- grace := g.Grace
- if grace <= 0 {
- grace = 10 * time.Second
- }
- stop := func(reason string) {
- res.Reason = reason
- _ = syscall.Kill(-pgid, syscall.SIGTERM)
- select {
- case <-exited:
- case <-time.After(grace):
- _ = syscall.Kill(-pgid, syscall.SIGKILL)
- <-exited
- }
- }
timer := time.NewTimer(limit)
defer timer.Stop()
select {
- case err := <-exited:
- res.Code = exitCode(err)
+ 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.
@@ -256,11 +190,11 @@ func (g *Gate) Run(ctx context.Context, attempt, dir string, argv []string, limi
}
}
case <-ctx.Done():
- stop("cancelled")
+ res.Reason = "cancelled"
case <-timer.C:
- stop("checks_timeout")
+ res.Reason = "checks_timeout"
}
- res.Terminated = g.settle(pgid, attempt, true)
+ res.Terminated = run.Stop()
if g.Booted != nil && g.Shutdown != nil {
for _, udid := range g.Booted(context.WithoutCancel(ctx)) {
if !contains(before, udid) {
@@ -268,110 +202,18 @@ func (g *Gate) Run(ctx context.Context, attempt, dir string, argv []string, limi
}
}
}
- cleanUp()
+ // 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.
+ run.Finish(ctx)
res.Output = out.String()
return res
}
-// finishPending finishes the T cleanup an earlier attempt (in this
-// process or another, perhaps killed) left: that attempt's end proven
-// first (its group and every process with its marker gone, killed if
-// need be, as Verify does), its simulators shut down, then T cleaned
-// against what it held before that attempt. Holding the turn.
-func (g *Gate) finishPending(ctx context.Context) error {
- r, ok, err := g.Turns.readPending()
- if err != nil || !ok {
- return err
- }
- if !g.settle(r.PGID, r.Attempt, false) {
- return errors.New("mac: an earlier attempt's end is not proven")
- }
- if g.QuietSimulators != nil {
- g.QuietSimulators(context.WithoutCancel(ctx))
- }
- s, err := openTemp(g.UserTemp, r.Before)
- if err != nil {
- return err
- }
- defer s.close()
- if err := s.clean(); err != nil {
- return err
- }
- return g.Turns.dropPending()
-}
-
-// RecordID is the process record of an attempt: its group and marker.
-func RecordID(pgid int, attempt string) string { return "pg:" + strconv.Itoa(pgid) + ":" + attempt }
-
// Verify reports whether a recorded attempt has ended for sure, killing
-// what is left of it: after a crash this is what kills every marked
-// process before the runner reports runner_restarted.
-func (g *Gate) Verify(id string) bool {
- rest, ok := strings.CutPrefix(id, "pg:")
- if !ok {
- return false
- }
- num, attempt, _ := strings.Cut(rest, ":")
- pgid, err := strconv.Atoi(num)
- if err != nil || pgid < 0 || pgid == 1 || attempt == "" {
- return false
- }
- // pgid 0: the marker was recorded, the group not yet; the marker
- // alone settles it.
- return g.settle(pgid, attempt, false)
-}
-
-// settle kills what is left of the group and of the marked processes
-// and reports whether, within Settle, none remains: kill(-pgid, 0) says
-// ESRCH and no process carries the marker. own is true while this
-// process started the group; after a restart the group id may have been
-// reused, so it is killed only while a marked process is in it.
-func (g *Gate) settle(pgid int, attempt string, own bool) bool {
- limit := g.Settle
- if limit <= 0 {
- limit = 30 * time.Second
- }
- deadline := time.Now().Add(limit)
- find := g.find
- if find == nil {
- find = Marked
- }
- for {
- marked, err := find(attempt)
- if err != nil {
- return false
- }
- ours := own && pgid > 1
- for _, p := range marked {
- ours = ours || pgid > 1 && p.PGID == pgid
- _ = syscall.Kill(p.PID, syscall.SIGKILL)
- }
- if ours {
- _ = syscall.Kill(-pgid, syscall.SIGKILL)
- }
- gone := !ours || syscall.Kill(-pgid, 0) == syscall.ESRCH
- if gone && len(marked) == 0 {
- return true
- }
- if time.Now().After(deadline) {
- return false
- }
- time.Sleep(100 * time.Millisecond)
- }
-}
-
-// Proc is a process carrying an attempt's marker.
-type Proc struct{ PID, PGID int }
-
-// Marked lists this user's processes whose environment carries
-// EQUIPO_ATTEMPT=<attempt> (marked_linux.go reads /proc; on a Mac,
-// ps -E). Never this process.
-func Marked(attempt string) ([]Proc, error) {
- if attempt == "" {
- return nil, errors.New("mac: no attempt marker")
- }
- return marked(attempt)
-}
+// 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) }
func exitCode(err error) int {
if err == nil {
diff --git a/internal/runner/mac/gate_test.go b/internal/runner/mac/gate_test.go
index f528c1d4..421d2c2e 100644
--- a/internal/runner/mac/gate_test.go
+++ b/internal/runner/mac/gate_test.go
@@ -193,7 +193,7 @@ func TestGateShutsDownWhatItBooted(t *testing.T) {
// After a restart a recorded attempt is settled: its marked processes
// are killed. A group id since reused by an unmarked process is left
-// alone.
+// alone, and not taken as over while it lives.
func TestGateVerifyAfterRestart(t *testing.T) {
g, _ := gateFixture(t, false)
marked := exec.Command("/bin/sleep", "60")
@@ -217,8 +217,9 @@ func TestGateVerifyAfterRestart(t *testing.T) {
case <-time.After(5 * time.Second):
t.Fatal("marked process still running")
}
- if !g.Verify(RecordID(other.Process.Pid, "checks-f-2")) {
- t.Fatal("an attempt with nothing marked is not over")
+ g.Settle = 300 * time.Millisecond
+ if g.Verify(RecordID(other.Process.Pid, "checks-f-2")) {
+ t.Fatal("proven over while its recorded group is alive")
}
if syscall.Kill(other.Process.Pid, 0) != nil {
t.Fatal("an unmarked group with a reused id was killed")
@@ -237,7 +238,7 @@ func TestParseMarked(t *testing.T) {
" 555 555 equipo-runner run EQUIPO_ATTEMPT=checks/a-1\n" +
"garbage\n"
got := ParseMarked(out, "checks/a-1", 555)
- if !slices.Equal(got, []Proc{{101, 101}, {103, 103}}) {
+ if !slices.Equal(got, []Proc{{PID: 101, PGID: 101}, {PID: 103, PGID: 103}}) {
t.Fatalf("%v", got)
}
}
@@ -259,7 +260,7 @@ func TestTailKeepsTheLastLines(t *testing.T) {
func TestGateUnprovenWhileMarkedRemain(t *testing.T) {
g, dir := gateFixture(t, false)
g.Settle = 500 * time.Millisecond
- g.find = func(string) ([]Proc, error) { return []Proc{{PID: 1 << 30, PGID: 1 << 30}}, nil }
+ g.procs = withPhantom()
if res, _ := run(g, dir, "checks-g-1", time.Minute, "true"); res.Terminated {
t.Fatalf("proven with a marked process left: %+v", res)
}
diff --git a/internal/runner/mac/launch.go b/internal/runner/mac/launch.go
new file mode 100644
index 00000000..42ccfb9e
--- /dev/null
+++ b/internal/runner/mac/launch.go
@@ -0,0 +1,631 @@
+package mac
+
+import (
+ "context"
+ "errors"
+ "io"
+ "os"
+ "os/exec"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/provider/claude"
+)
+
+// The Mac's executor (spec §5 and §8.8): what a check, an Engineering
+// attempt, an ask, a token check, a sign-in or a probe launch starts,
+// and how its end is proven. The gate and the CLI launches share it.
+
+// ErrRecord says a process record could not be written: when it was the
+// marker, nothing started.
+var ErrRecord = errors.New("mac: the process record could not be written")
+
+// ErrUnproven says a process was started and stopped but its end is not
+// proven: the attempt stays unterminated (no Retry).
+var ErrUnproven = errors.New("mac: the end is not proven")
+
+// Executor starts an operation's processes and proves their end.
+type Executor struct {
+ // Turns is the Mac's turns: Start refuses unless ctx holds one
+ // (ErrNoTurn). nil holds no machine lock (the test build's fake
+ // worker on Linux).
+ Turns *Turns
+ // Procs is the process table; nil: the turns' sweep table, else the
+ // platform's.
+ Procs Procs
+ // Own is the runner's own processes; nil: this process's.
+ Own *Own
+ // Grace is SIGTERM to SIGKILL (10 s); Settle bounds the whole stop
+ // and its proof (30 s); Poll is how often the tree under the leader
+ // is read while it runs (250 ms).
+ Grace, Settle, Poll time.Duration
+ // UserTemp is the runner user's T when the attempt may write it (a
+ // sandboxed check, Engineering with sandboxed Xcode access): what
+ // appears there while it runs is removed once its end is proven.
+ UserTemp string
+ // QuietSimulators runs once the end is proven, before T is cleaned
+ // (simctl shutdown all: every simulator of the runner user is its).
+ QuietSimulators func(context.Context)
+}
+
+// Command is what to start: Argv with Env as its whole environment, in
+// Dir, Files as descriptors 3 and on. With Pipes the run offers its
+// stdin, stdout and stderr; otherwise Stdout and Stderr receive the
+// output and stdin is empty.
+type Command struct {
+ Argv, Env []string
+ Dir string
+ Files []*os.File
+ Pipes bool
+ Stdout, Stderr io.Writer
+}
+
+func (x *Executor) procs() Procs {
+ switch {
+ case x.Procs != nil:
+ return x.Procs
+ case x.Turns != nil && x.Turns.sweep != nil:
+ return x.Turns.sweep
+ }
+ return platformProcs
+}
+
+func (x *Executor) own() *Own {
+ if x.Own != nil {
+ return x.Own
+ }
+ return x.Turns.owned()
+}
+
+func (x *Executor) settleLimit() time.Duration {
+ if x.Settle > 0 {
+ return x.Settle
+ }
+ return 30 * time.Second
+}
+
+// validMarker: a marker fits a record ("pg:<pgid>:<marker>") and a
+// ps -E word.
+func validMarker(m string) bool {
+ return m != "" && len(m) <= 128 && !strings.ContainsAny(m, " \t\n\r\x00:=")
+}
+
+// Start starts c as attempt marker, recorded in this order (record is
+// the step's or question's row): the marker on the turn's record and on
+// the row before anything starts (if either cannot be written nothing
+// starts: ErrRecord); the group once the leader exists (if that cannot
+// be written the group is stopped at once and Start fails, ErrUnproven
+// when that end is not proven either). The leader starts in a session
+// and group of its own.
+func (x *Executor) Start(ctx context.Context, c Command, marker string, record func(string) error) (*Run, error) {
+ var turn *Turn
+ if x.Turns != nil {
+ if turn = HeldTurn(ctx, x.Turns); turn == nil {
+ return nil, ErrNoTurn
+ }
+ }
+ if len(c.Argv) == 0 || !validMarker(marker) {
+ return nil, provider.ErrPolicy
+ }
+ r := &Run{x: x, turn: turn, marker: marker, procs: x.procs(), own: x.own(), exited: make(chan struct{}), stopPoll: make(chan struct{}), polled: make(chan struct{})}
+ var before []ProcID
+ if turn != nil {
+ // A sweeping turn's table is the run's: the identities it read
+ // when the turn began are compared with the same clock.
+ if before = turn.before(); before != nil {
+ r.procs = x.Turns.sweep
+ }
+ }
+ r.scope = newScope(r.procs, []string{marker}, before)
+ // What T holds before anything of the attempt starts, and the
+ // cleanup on record: a runner killed from here on leaves it to the
+ // next process (a restart), never to another turn of this one.
+ if x.UserTemp != "" {
+ if err := x.finishPending(ctx, turn); err != nil {
+ return nil, err
+ }
+ temp, err := openTemp(x.UserTemp, nil)
+ if err != nil {
+ return nil, err
+ }
+ r.temp = temp
+ if err := x.Turns.writePending(pendingRecord{Attempt: marker, Before: temp.before, Runner: selfID()}); err != nil {
+ temp.close()
+ return nil, errors.Join(ErrRecord, err)
+ }
+ }
+ fail := func(err error) (*Run, error) {
+ if r.temp != nil {
+ r.temp.close()
+ }
+ return nil, err
+ }
+ if turn != nil {
+ if err := turn.launch(marker); err != nil {
+ return fail(errors.Join(ErrRecord, err))
+ }
+ }
+ if err := record(RecordID(0, marker)); err != nil {
+ return fail(errors.Join(ErrRecord, err))
+ }
+ cmd := exec.Command(c.Argv[0], c.Argv[1:]...)
+ cmd.Dir, cmd.Env, cmd.ExtraFiles = c.Dir, slices.Clone(c.Env), c.Files
+ if cmd.Env == nil {
+ cmd.Env = []string{}
+ }
+ if c.Pipes {
+ var err error
+ if r.stdin, err = cmd.StdinPipe(); err != nil {
+ return fail(err)
+ }
+ if r.stdout, err = cmd.StdoutPipe(); err != nil {
+ return fail(err)
+ }
+ if r.stderr, err = cmd.StderrPipe(); err != nil {
+ return fail(err)
+ }
+ } else {
+ cmd.Stdout, cmd.Stderr = c.Stdout, c.Stderr
+ // A child that keeps the output open must not hold the run: once
+ // the leader has gone the pipes close after a second, and the
+ // stop kills what is left.
+ cmd.WaitDelay = time.Second
+ }
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
+ if err := cmd.Start(); err != nil {
+ return fail(err)
+ }
+ r.cmd, r.pgid = cmd, cmd.Process.Pid
+ go func() {
+ r.waitErr = cmd.Wait()
+ close(r.exited)
+ }()
+ // The leader, its group and its session are the attempt's from now:
+ // what has that id and started later is someone else's.
+ r.scope.Groups[r.pgid], r.scope.Sessions[r.pgid] = 0, 0
+ r.leaderPending = true
+ if leader, ok := r.procs.Lookup(r.pgid); ok {
+ r.adopt([]ProcInfo{leader})
+ }
+ if r.temp != nil {
+ _ = x.Turns.writePending(pendingRecord{Attempt: marker, PGID: r.pgid, Before: r.temp.before, Runner: selfID()})
+ }
+ if turn != nil {
+ turn.note(r.scope.Groups, r.scope.Sessions)
+ }
+ if err := record(RecordID(r.pgid, marker)); err != nil {
+ r.pollOnce.Do(func() { close(r.stopPoll) })
+ close(r.polled)
+ proven := r.stopWith(0)
+ r.stopOnce.Do(func() { r.proven = proven })
+ if !proven && turn != nil {
+ turn.unprovenEnd()
+ }
+ r.Finish(context.WithoutCancel(ctx))
+ if !proven {
+ return nil, errors.Join(ErrRecord, ErrUnproven, err)
+ }
+ return nil, errors.Join(ErrRecord, err)
+ }
+ go r.poll()
+ return r, nil
+}
+
+// Run is one started attempt.
+type Run struct {
+ x *Executor
+ turn *Turn
+ marker string
+ cmd *exec.Cmd
+ pgid int
+ procs Procs
+ own *Own
+
+ mu sync.Mutex
+ scope *scope
+ // leaderPending: the leader's identity is not read yet (the kernel
+ // may show it a moment after the exec).
+ leaderPending bool
+
+ exited chan struct{}
+ waitErr error
+
+ stopPoll, polled chan struct{}
+ pollOnce sync.Once
+ stopOnce sync.Once
+ proven bool
+
+ temp *tempState
+ finishOnce sync.Once
+
+ stdin io.WriteCloser
+ stdout, stderr io.ReadCloser
+}
+
+// ID is the attempt's process record.
+func (r *Run) ID() string { return RecordID(r.pgid, r.marker) }
+
+// Exited is closed once the leader has exited (and been reaped).
+func (r *Run) Exited() <-chan struct{} { return r.exited }
+
+// ExitErr is the leader's exit (after Exited).
+func (r *Run) ExitErr() error { return r.waitErr }
+
+// adopt takes the leader's identity from list the first time it shows
+// (still unreaped: the pid is still the leader's), with its group and
+// session from its start. Under r.mu, or before the run is shared.
+func (r *Run) adopt(list []ProcInfo) {
+ if !r.leaderPending {
+ return
+ }
+ select {
+ case <-r.exited:
+ r.leaderPending = false
+ return
+ default:
+ }
+ for _, q := range list {
+ if q.PID == r.pgid {
+ r.scope.Seen[q.ID] = true
+ r.scope.Groups[r.pgid], r.scope.Sessions[r.pgid] = q.Start, q.Start
+ r.leaderPending = false
+ return
+ }
+ }
+}
+
+// poll is (a): while the attempt runs, the tree under its leader, and
+// every group and session it makes, onto the scope and the turn's record.
+func (r *Run) poll() {
+ defer close(r.polled)
+ every := r.x.Poll
+ if every <= 0 {
+ every = 250 * time.Millisecond
+ }
+ tick := time.NewTicker(every)
+ defer tick.Stop()
+ for {
+ list, own, err := r.own.Snapshot(r.procs, nil)
+ if err == nil {
+ r.mu.Lock()
+ r.adopt(list)
+ grew := r.scope.Track(list, own)
+ groups, sessions := cloneSpan(r.scope.Groups), cloneSpan(r.scope.Sessions)
+ r.mu.Unlock()
+ if grew && r.turn != nil {
+ r.turn.note(groups, sessions)
+ }
+ }
+ select {
+ case <-r.stopPoll:
+ return
+ case <-tick.C:
+ }
+ }
+}
+
+// Stop ends the attempt and reports whether its end is proven (once;
+// later calls report the same): SIGTERM to everything in its scope
+// (its group, the groups and sessions it made, what descends from it,
+// what carries its marker and, on a Mac, every process of the runner
+// user started since the turn began but the runner's own and launchd's
+// system agents), Grace, then SIGKILL, each signal after the process's
+// identity is read again. Proven only when, within Settle, none of that
+// is left, the leader is reaped and every group it made is gone
+// (kill(-pgid, 0) is ESRCH). Unproven, the turn's record stays.
+func (r *Run) Stop() bool {
+ r.stopOnce.Do(func() {
+ r.pollOnce.Do(func() { close(r.stopPoll) })
+ <-r.polled
+ grace := r.x.Grace
+ if grace <= 0 {
+ grace = 10 * time.Second
+ }
+ r.proven = r.stopWith(grace)
+ if !r.proven && r.turn != nil {
+ r.turn.unprovenEnd()
+ }
+ })
+ return r.proven
+}
+
+func (r *Run) stopWith(grace time.Duration) bool {
+ start := time.Now()
+ deadline := start.Add(r.x.settleLimit())
+ for {
+ list, own, err := r.own.Snapshot(r.procs, []string{r.marker})
+ if err == nil {
+ r.mu.Lock()
+ r.adopt(list)
+ left := r.scope.Targets(list, own)
+ reaped := false
+ select {
+ case <-r.exited:
+ reaped = true
+ default:
+ }
+ if len(left) == 0 && reaped && r.scope.GroupsGone() {
+ r.mu.Unlock()
+ if r.turn != nil {
+ r.turn.note(r.scope.Groups, r.scope.Sessions)
+ }
+ return true
+ }
+ sig := syscall.SIGKILL
+ if time.Since(start) < grace {
+ sig = syscall.SIGTERM
+ }
+ r.scope.Kill(left, sig)
+ r.mu.Unlock()
+ }
+ if time.Now().After(deadline) {
+ r.mu.Lock()
+ groups, sessions := cloneSpan(r.scope.Groups), cloneSpan(r.scope.Sessions)
+ r.mu.Unlock()
+ if r.turn != nil {
+ r.turn.note(groups, sessions)
+ r.turn.unprovenEnd()
+ }
+ return false
+ }
+ select {
+ case <-r.exited:
+ time.Sleep(20 * time.Millisecond)
+ case <-time.After(100 * time.Millisecond):
+ }
+ }
+}
+
+// Finish is the user-temp cleanup once the end is proven (the
+// attempt's own, in its turn): simulators quieted, then what appeared in
+// T removed, then the record. Unproven or not cleaned, the record stays
+// for this attempt's proof later, or a restart.
+func (r *Run) Finish(ctx context.Context) {
+ r.finishOnce.Do(func() {
+ if r.temp == nil {
+ return
+ }
+ defer r.temp.close()
+ if !r.proven {
+ return
+ }
+ if r.x.QuietSimulators != nil {
+ r.x.QuietSimulators(context.WithoutCancel(ctx))
+ }
+ if r.temp.clean() == nil {
+ _ = r.x.Turns.dropPending()
+ }
+ })
+}
+
+// finishPending finishes the user-temp cleanup an earlier attempt left,
+// only when it is turn's to finish (Turns.mayFinish: its owner, or a
+// restart): that attempt's end proven (settleRecord), its simulators
+// shut down, then T cleaned against what it held before. Another live
+// owner's: ErrPendingCleanup, nothing touched.
+func (x *Executor) finishPending(ctx context.Context, turn *Turn) error {
+ r, ok, err := x.Turns.readPending()
+ if err != nil || !ok {
+ return err
+ }
+ if !x.Turns.mayFinish(turn, r) {
+ return ErrPendingCleanup
+ }
+ if !x.settleRecord(r.PGID, r.Attempt) {
+ // That attempt's end, not this one's: nothing of this one ran.
+ return errors.Join(ErrPendingCleanup, errors.New("mac: its end is not proven"))
+ }
+ if x.QuietSimulators != nil {
+ x.QuietSimulators(context.WithoutCancel(ctx))
+ }
+ s, err := openTemp(x.UserTemp, r.Before)
+ if err != nil {
+ return err
+ }
+ defer s.close()
+ if err := s.clean(); err != nil {
+ return err
+ }
+ return x.Turns.dropPending()
+}
+
+// RecordID is the process record of an attempt: its group and marker.
+func RecordID(pgid int, attempt string) string { return "pg:" + strconv.Itoa(pgid) + ":" + attempt }
+
+func parseRecord(id string) (int, string, bool) {
+ rest, ok := strings.CutPrefix(id, "pg:")
+ if !ok {
+ return 0, "", false
+ }
+ num, attempt, _ := strings.Cut(rest, ":")
+ pgid, err := strconv.Atoi(num)
+ if err != nil || pgid < 0 || pgid == 1 || attempt == "" {
+ return 0, "", false
+ }
+ return pgid, attempt, true
+}
+
+// Verify reports whether a recorded attempt has ended for sure (after a
+// restart, or for a step whose end was not proven when it stopped):
+// - if its turn's record is still unsettled, a turn is taken (only
+// if free now) and settles it first: everything that turn left, by
+// its sweep;
+// - every process carrying its marker is killed, and its recorded
+// group only while a marked process is in it. A group alive with no
+// marked process (a child that scrubbed its environment, or the id
+// used again by someone else) is never killed and never proven over;
+// - a user-temp cleanup the attempt owns is finished in that turn.
+//
+// Ended only when the group is gone (kill(-pgid, 0) is ESRCH), nothing
+// carries the marker, its turn is settled and its cleanup is done.
+func (x *Executor) Verify(id string) bool {
+ pgid, attempt, ok := parseRecord(id)
+ if !ok {
+ return false
+ }
+ var held *Turn
+ if x.Turns != nil {
+ r, pending, err := x.Turns.readPending()
+ owned := x.UserTemp != "" && (err != nil || pending && r.Attempt == attempt)
+ if x.Turns.unsettledFor(attempt) || owned {
+ u, ok := x.Turns.TryTake(OpRecover)
+ if !ok {
+ return false
+ }
+ defer u.Give()
+ u.adopt(attempt)
+ held = u
+ }
+ }
+ if !x.settleRecord(pgid, attempt) {
+ return false
+ }
+ if held != nil && x.UserTemp != "" {
+ r, pending, err := x.Turns.readPending()
+ if err != nil {
+ return false
+ }
+ if pending && r.Attempt == attempt && x.finishPending(context.Background(), held) != nil {
+ return false
+ }
+ }
+ return true
+}
+
+// settleRecord kills what carries the marker (and the recorded group
+// while a marked process is in it) and reports whether, within Settle,
+// the group is gone and nothing marked is left. pgid 0: the marker
+// alone settles it.
+func (x *Executor) settleRecord(pgid int, attempt string) bool {
+ procs, own := x.procs(), x.own()
+ deadline := time.Now().Add(x.settleLimit())
+ me := os.Getpid()
+ for {
+ list, mine, err := own.Snapshot(procs, []string{attempt})
+ if err != nil {
+ return false
+ }
+ var marked []ProcInfo
+ inGroup := false
+ for _, q := range list {
+ if q.Marker != attempt || q.PID == me || q.PID <= 1 || mine[q.ID] {
+ continue
+ }
+ marked = append(marked, q)
+ inGroup = inGroup || pgid > 1 && q.PGID == pgid
+ }
+ s := newScope(procs, nil, nil)
+ if inGroup {
+ for _, q := range marked {
+ if q.PGID == pgid && s.Still(q) {
+ _ = procs.Signal(-pgid, syscall.SIGKILL)
+ break
+ }
+ }
+ }
+ for _, q := range marked {
+ if s.Still(q) {
+ _ = procs.Signal(q.PID, syscall.SIGKILL)
+ }
+ }
+ gone := pgid == 0 || procs.Signal(-pgid, 0) == syscall.ESRCH
+ if gone && len(marked) == 0 {
+ return true
+ }
+ if time.Now().After(deadline) {
+ return false
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+}
+
+// Marked lists this user's processes whose environment carries
+// EQUIPO_ATTEMPT=<attempt> where the kernel shows it (/proc on Linux;
+// ps -E on a Mac, which cannot see platform binaries'). Never this
+// process.
+func Marked(attempt string) ([]Proc, error) {
+ if attempt == "" {
+ return nil, errors.New("mac: no attempt marker")
+ }
+ list, _, err := runnerOwn.Snapshot(platformProcs, []string{attempt})
+ if err != nil {
+ return nil, err
+ }
+ var out []Proc
+ for _, q := range list {
+ if q.Marker == attempt && q.PID != os.Getpid() {
+ out = append(out, Proc{PID: q.PID, PGID: q.PGID})
+ }
+ }
+ return out, nil
+}
+
+// Starter is thin's starter (containment.Manager's StartRecorded) for
+// one Mac launch of the pinned CLI: Engineering, an ask or a token
+// check. It runs LaunchEngineering with Exec as its executor, so the
+// marker is on record before the CLI starts and its group once it
+// exists. ctx must hold the Mac's turn (Turns.Take with the
+// operation's Op). Cancelling ctx stops the launch.
+type Starter struct {
+ Exec *Executor
+ CLI ClaudeCLI
+ Input EngineeringInput
+ // Token is the connection's token, cleared once handed over.
+ Token []byte
+}
+
+// StartRecorded starts the policy's CLI: argv must be the policy's own.
+func (s *Starter) StartRecorded(ctx context.Context, l provider.Launch, argv []string, record func(context.Context, containment.Record) error) (provider.Process, error) {
+ defer clear(s.Token)
+ if want := claude.DarwinArgv(l.Policy); want == nil || !slices.Equal(argv, want) {
+ return nil, provider.ErrPolicy
+ }
+ var run *Run
+ err := LaunchEngineering(ctx, s.CLI, s.Input, l.Policy, s.Token, func(ctx context.Context, c EngineeringCommand) error {
+ r, err := s.Exec.Start(ctx, Command{Argv: c.Argv, Env: c.Env, Dir: c.Dir, Files: c.Files, Pipes: true}, s.Input.Attempt, func(id string) error {
+ return record(context.WithoutCancel(ctx), containment.Record{ID: id})
+ })
+ run = r
+ return err
+ })
+ if err != nil {
+ return nil, err
+ }
+ p := &process{run: run}
+ p.stop = context.AfterFunc(ctx, func() { run.Stop() })
+ return p, nil
+}
+
+// process is a Run as thin's provider.Process: Wait returns once the
+// leader has exited or the launch's ctx was cancelled, and the end is
+// proven (nil) or not (ErrUnproven), with the user-temp cleanup done.
+type process struct {
+ run *Run
+ stop func() bool
+}
+
+func (p *process) Stdin() io.WriteCloser { return p.run.stdin }
+func (p *process) Stdout() io.ReadCloser { return p.run.stdout }
+func (p *process) Stderr() io.ReadCloser { return p.run.stderr }
+func (p *process) ID() string { return p.run.ID() }
+func (p *process) Wait(ctx context.Context) (provider.Exit, error) {
+ select {
+ case <-p.run.exited:
+ case <-p.run.stopPoll:
+ case <-ctx.Done():
+ }
+ proven := p.run.Stop()
+ p.stop()
+ p.run.Finish(ctx)
+ exit := provider.Exit{Code: exitCode(p.run.waitErr), ObservedAt: time.Now()}
+ if !proven {
+ return exit, ErrUnproven
+ }
+ return exit, nil
+}
diff --git a/internal/runner/mac/launch_test.go b/internal/runner/mac/launch_test.go
new file mode 100644
index 00000000..edd38319
--- /dev/null
+++ b/internal/runner/mac/launch_test.go
@@ -0,0 +1,653 @@
+//go:build linux
+
+package mac
+
+import (
+ "context"
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+
+ "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/provider/claude"
+)
+
+// These tests run real processes on Linux through the /pr table. The
+// machine is shared, so every table here is scoped: it lists, and
+// signals, only processes whose environment carries this test's
+// EQUIPO_TEST_SCOPE nonce (or its own unique marker). The runner-user
+// sweep therefore sees the test's processes as a Mac's turn sees the
+// runner user's, and can never reach anyone else's.
+
+type launchRig struct {
+ t *testing.T
+ nonce string
+ procs Procs
+ turns *Turns
+ x *Executor
+}
+
+func newLaunchRig(t *testing.T, extra ...string) *launchRig {
+ t.Helper()
+ nonce := token()[:12]
+ procs := proc.Scoped(append([]string{proc.ScopeEnv + "=" + nonce}, extra...)...)
+ turns := NewTurns(filepath.Join(t.TempDir(), "lock")).Sweep(procs)
+ turns.Settle = 3 * time.Second
+ r := &launchRig{t: t, nonce: nonce, procs: procs, turns: turns, x: &Executor{Turns: turns, Grace: 300 * time.Millisecond, Settle: 3 * time.Second, Poll: 50 * time.Millisecond}}
+ t.Cleanup(func() {
+ // Whatever of the test's own is left (a failed test): by scope.
+ if list, err := procs.List(nil); err == nil {
+ for _, q := range list {
+ _ = procs.Signal(q.PID, syscall.SIGKILL)
+ }
+ }
+ })
+ return r
+}
+
+func (r *launchRig) env(more ...string) []string {
+ return append([]string{"PATH=/usr/bin:/bin", proc.ScopeEnv + "=" + r.nonce}, more...)
+}
+
+func (r *launchRig) take(op Op) (context.Context, *Turn) {
+ r.t.Helper()
+ u, err := r.turns.Take(context.Background(), op)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ return u.Context(context.Background()), u
+}
+
+// start runs argv in a session of its own with env (reaped when it
+// ends, so a dead one is not a zombie in a group).
+func (r *launchRig) start(env []string, argv ...string) *exec.Cmd {
+ r.t.Helper()
+ c := exec.Command(argv[0], argv[1:]...)
+ c.Env = env
+ c.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
+ if err := c.Start(); err != nil {
+ r.t.Fatal(err)
+ }
+ go func() { _ = c.Wait() }()
+ r.waitListed(c.Process.Pid)
+ return c
+}
+
+// waitListed waits until the table shows pid (the kernel shows a new
+// environment a moment after the exec).
+func (r *launchRig) waitListed(pid int) ProcInfo {
+ r.t.Helper()
+ for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) {
+ if q, ok := r.procs.Lookup(pid); ok {
+ return q
+ }
+ }
+ r.t.Fatalf("pid %d never listed", pid)
+ return ProcInfo{}
+}
+
+func gone(pid int) bool { return syscall.Kill(pid, 0) == syscall.ESRCH }
+
+func hasKey(m span, k int) bool { _, ok := m[k]; return ok }
+
+// waitPID reads a pid a script wrote to file.
+func waitPID(t *testing.T, file string) int {
+ t.Helper()
+ for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) {
+ raw, _ := os.ReadFile(file)
+ if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil && pid > 0 {
+ return pid
+ }
+ }
+ t.Fatalf("no pid in %s", file)
+ return 0
+}
+
+// engLaunch is the Engineering launch rig with body as the pinned CLI,
+// a unique marker, and a scoped table that sees what carries it.
+func engLaunch(t *testing.T, body string) (*engRig, *launchRig) {
+ t.Helper()
+ er := newEngRigWith(t, []byte(body))
+ er.in.Attempt = "attempt-" + token()[:12]
+ return er, newLaunchRig(t, "EQUIPO_ATTEMPT="+er.in.Attempt)
+}
+
+// The marker is on the step row (and the turn's record) before the CLI
+// starts; the group once it exists. A marker that cannot be written
+// starts nothing; a group that cannot be stops the CLI at once, proven.
+func TestEngineeringLaunchRecordsMarkerThenGroup(t *testing.T) {
+ er, r := engLaunch(t, "#!/bin/sh\ntouch \"$TMPDIR/started\"\ncat <&3 >/dev/null\nread line\n")
+ p := er.policy()
+ argv := claude.DarwinArgv(p)
+ started := filepath.Join(er.in.Scratch, "started")
+ marker := er.in.Attempt
+ ctx, turn := r.take(OpEngineering)
+ defer turn.Give()
+ launch := func(fail int) (provider.Process, []string, error) {
+ var ids []string
+ pctx, kill := context.WithCancel(ctx)
+ t.Cleanup(kill)
+ s := &Starter{Exec: r.x, CLI: er.cli, Input: er.in, Token: slices.Clone(er.token)}
+ pr, err := s.StartRecorded(pctx, provider.Launch{Policy: p}, argv, func(_ context.Context, rec containment.Record) error {
+ ids = append(ids, rec.ID)
+ if len(ids) == 1 {
+ if exists(started) {
+ t.Error("the CLI started before its marker was on record")
+ }
+ if rec, ok, _ := r.turns.loadTurn(); !ok || !slices.Contains(rec.Markers, marker) {
+ t.Error("the turn's record lacks the marker at the first write")
+ }
+ }
+ if len(ids) == 2 {
+ pgid, _, _ := parseRecord(rec.ID)
+ if pgid <= 1 || syscall.Kill(-pgid, 0) != nil {
+ t.Errorf("group %d recorded before it existed", pgid)
+ }
+ }
+ if len(ids) == fail {
+ return errors.New("disk full")
+ }
+ return nil
+ })
+ return pr, ids, err
+ }
+ pr, ids, err := launch(0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(ids) != 2 || ids[0] != RecordID(0, marker) || !strings.HasPrefix(ids[1], "pg:") || !strings.HasSuffix(ids[1], ":"+marker) || ids[1] == ids[0] || pr.ID() != ids[1] {
+ t.Fatalf("records %v, process %s", ids, pr.ID())
+ }
+ pgid, _, _ := parseRecord(ids[1])
+ if rec, ok, _ := r.turns.loadTurn(); !ok || !hasKey(rec.Groups, pgid) {
+ t.Fatalf("the turn's record lacks the group: %+v", rec)
+ }
+ pr.Stdin().Close()
+ if _, err := pr.Wait(context.Background()); err != nil || !gone(pgid) {
+ t.Fatalf("a CLI that ended by itself: %v", err)
+ }
+ // The marker cannot be written: nothing starts.
+ _ = os.Remove(started)
+ if _, ids, err = launch(1); !errors.Is(err, ErrRecord) || len(ids) != 1 || ids[0] != RecordID(0, marker) {
+ t.Fatalf("first write failed: %v %v", err, ids)
+ }
+ time.Sleep(200 * time.Millisecond)
+ if exists(started) {
+ t.Fatal("the CLI ran without its marker on record")
+ }
+ // The group cannot be written: stopped at once, and proven.
+ if _, ids, err = launch(2); !errors.Is(err, ErrRecord) || errors.Is(err, ErrUnproven) || len(ids) != 2 {
+ t.Fatalf("second write failed: %v %v", err, ids)
+ }
+ if pgid, _, _ := parseRecord(ids[1]); !gone(pgid) {
+ t.Fatal("the CLI outlived its failed group record")
+ }
+}
+
+// A fake CLI starts two Bash-like commands in sessions of their own, as
+// Claude Code does (setsid): one keeps the marker, one scrubbed it. Both
+// ignore SIGTERM. Cancelling the launch ends them (SIGKILL after the
+// grace), and the proof waits for that: nothing of the attempt is alive
+// when Wait says it ended.
+func TestEngineeringTerminationGroupAndMarker(t *testing.T) {
+ scope := token()[:12]
+ body := "#!/bin/bash\ncat <&3 >/dev/null\nexport " + proc.ScopeEnv + "=" + scope + "\n" +
+ "setsid bash -c 'trap \"\" TERM; echo $$ > \"$TMPDIR/marked\"; exec sleep 60' &\n" +
+ "setsid env -u EQUIPO_ATTEMPT bash -c 'trap \"\" TERM; echo $$ > \"$TMPDIR/scrubbed\"; exec sleep 60' &\n" +
+ "read line\n"
+ er, r := engLaunch(t, body)
+ r.procs = proc.Scoped(proc.ScopeEnv+"="+scope, "EQUIPO_ATTEMPT="+er.in.Attempt)
+ r.turns.Sweep(r.procs)
+ p := er.policy()
+ ctx, turn := r.take(OpEngineering)
+ defer turn.Give()
+ pctx, kill := context.WithCancel(ctx)
+ defer kill()
+ s := &Starter{Exec: r.x, CLI: er.cli, Input: er.in, Token: slices.Clone(er.token)}
+ pr, err := s.StartRecorded(pctx, provider.Launch{Policy: p}, claude.DarwinArgv(p), func(context.Context, containment.Record) error { return nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ marked, scrubbed := waitPID(t, filepath.Join(er.in.Scratch, "marked")), waitPID(t, filepath.Join(er.in.Scratch, "scrubbed"))
+ for _, pid := range []int{marked, scrubbed} {
+ if q := r.waitListed(pid); q.SID != pid || q.PGID != pid {
+ t.Fatalf("%d is not in a session of its own: %+v", pid, q)
+ }
+ }
+ waited := make(chan error, 1)
+ go func() { _, err := pr.Wait(context.Background()); waited <- err }()
+ stopped := time.Now()
+ kill()
+ if err := <-waited; err != nil {
+ t.Fatalf("end not proven: %v", err)
+ }
+ if !gone(marked) || !gone(scrubbed) {
+ t.Fatal("proven over with a command still running")
+ }
+ if took := time.Since(stopped); took < r.x.Grace {
+ t.Fatalf("proven in %s, before the grace ended what ignores SIGTERM", took)
+ }
+ if rec, ok, _ := r.turns.loadTurn(); !ok || len(rec.Groups) < 3 || len(rec.Sessions) < 3 {
+ t.Fatalf("the turn's record lacks the commands' groups and sessions: %+v", rec)
+ }
+}
+
+// After a restart: a recorded group alive with no marked process in it
+// (a child that scrubbed its environment, or the id used again) is never
+// killed, and the attempt is not proven over while it lives.
+func TestRestartUnmarkedSurvivorWithholdsProof(t *testing.T) {
+ r := newLaunchRig(t)
+ r.x.Settle = 500 * time.Millisecond
+ survivor := r.start(r.env(), "/bin/sleep", "60")
+ id := RecordID(survivor.Process.Pid, "attempt-u-"+r.nonce)
+ if r.x.Verify(id) {
+ t.Fatal("proven over while its recorded group is alive")
+ }
+ if gone(survivor.Process.Pid) {
+ t.Fatal("an unmarked group was killed")
+ }
+ // The same through a gate (the worker's Verify).
+ g := &Gate{Turns: r.turns, Settle: 500 * time.Millisecond}
+ if g.Verify(id) || gone(survivor.Process.Pid) {
+ t.Fatal("the gate proved or killed it")
+ }
+ _ = survivor.Process.Kill()
+ for deadline := time.Now().Add(5 * time.Second); !gone(survivor.Process.Pid) && time.Now().Before(deadline); {
+ time.Sleep(10 * time.Millisecond)
+ }
+ if !r.x.Verify(id) {
+ t.Fatal("not proven once the group is gone")
+ }
+}
+
+// After a restart, the dead runner's turn is settled first: what it
+// started (marked or not) is swept, what was there before it began is
+// not, and a group id since used by a process from before is neither
+// killed nor proven over until it is gone.
+func TestRestartReusedGroupNotKilled(t *testing.T) {
+ r := newLaunchRig(t)
+ r.x.Settle = 500 * time.Millisecond
+ marker := "attempt-r-" + r.nonce
+ unrelated := r.start(r.env(), "/bin/sleep", "60")
+ before, err := r.procs.List(nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var ids []ProcID
+ for _, q := range before {
+ ids = append(ids, q.ID)
+ }
+ dead := r.start(r.env(), "/bin/sleep", "0.2")
+ deadID := r.waitListed(dead.Process.Pid).ID
+ for !gone(dead.Process.Pid) {
+ time.Sleep(10 * time.Millisecond)
+ }
+ left := r.start(r.env("EQUIPO_ATTEMPT="+marker), "/bin/sleep", "60")
+ scrubbed := r.start(r.env(), "/bin/sleep", "60")
+ if err := r.turns.saveTurn(turnRecord{ID: "dead-turn", Op: OpEngineering, Runner: deadID, Sweep: true, Before: ids, Markers: []string{marker}}); err != nil {
+ t.Fatal(err)
+ }
+ if r.x.Verify(RecordID(unrelated.Process.Pid, marker)) {
+ t.Fatal("proven over while the reused group lives")
+ }
+ if gone(unrelated.Process.Pid) {
+ t.Fatal("a process from before the turn was killed")
+ }
+ for name, c := range map[string]*exec.Cmd{"marked": left, "unmarked": scrubbed} {
+ for deadline := time.Now().Add(5 * time.Second); !gone(c.Process.Pid) && time.Now().Before(deadline); {
+ time.Sleep(10 * time.Millisecond)
+ }
+ if !gone(c.Process.Pid) {
+ t.Fatalf("the dead turn's %s leftover survived", name)
+ }
+ }
+ if _, ok, _ := r.turns.loadTurn(); ok {
+ t.Fatal("the dead turn's record was not settled")
+ }
+ _ = unrelated.Process.Kill()
+ for deadline := time.Now().Add(5 * time.Second); !gone(unrelated.Process.Pid) && time.Now().Before(deadline); {
+ time.Sleep(10 * time.Millisecond)
+ }
+ if !r.x.Verify(RecordID(unrelated.Process.Pid, marker)) {
+ t.Fatal("not proven once it is gone")
+ }
+}
+
+// After a restart every marked process is killed, the recorded group
+// with it, and a marked grandchild that double-forked out of it too;
+// then the attempt is over. A marker-only record settles the same way.
+func TestRestartKillsMarked(t *testing.T) {
+ r := newLaunchRig(t)
+ marker := "attempt-k-" + r.nonce
+ pidFile := filepath.Join(t.TempDir(), "grandchild")
+ leader := r.start(r.env("EQUIPO_ATTEMPT="+marker), "/bin/bash", "-c", "(setsid sleep 60 & echo $! > "+quote(pidFile)+"); exec sleep 60")
+ grandchild := waitPID(t, pidFile)
+ r.waitListed(grandchild)
+ if !r.x.Verify(RecordID(leader.Process.Pid, marker)) {
+ t.Fatal("not settled")
+ }
+ if !gone(leader.Process.Pid) || !gone(grandchild) {
+ t.Fatal("a marked process survived")
+ }
+ alone := r.start(r.env("EQUIPO_ATTEMPT="+marker+"-0"), "/bin/sleep", "60")
+ if !r.x.Verify(RecordID(0, marker+"-0")) || !gone(alone.Process.Pid) {
+ t.Fatal("a marker-only record not settled")
+ }
+}
+
+// The sweep spares the runner and every helper it started for itself,
+// by identity: a helper started during the turn and still running at
+// its end lives on, a step's process running the very same program
+// with the same arguments does not.
+func TestSweepSparesTheRunnerAndItsHelpers(t *testing.T) {
+ r := newLaunchRig(t)
+ ctx, turn := r.take(OpEngineering)
+ defer turn.Give()
+ run, err := r.x.Start(ctx, Command{Argv: []string{"/bin/bash", "-c", "sleep 60 & exec sleep 60"}, Env: r.env("EQUIPO_ATTEMPT=attempt-o-" + r.nonce)}, "attempt-o-"+r.nonce, func(string) error { return nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ helper := exec.Command("/bin/sleep", "60")
+ helper.Env = r.env()
+ if err := StartOwn(helper); err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = helper.Process.Kill(); _ = helper.Wait() }()
+ // The same program, arguments and environment, but the step's: its
+ // own session, after the turn began, not the runner's.
+ impostor := r.start(r.env(), "/bin/sleep", "60")
+ if !run.Stop() {
+ t.Fatal("end not proven")
+ }
+ if gone(helper.Process.Pid) {
+ t.Fatal("the runner's own helper was killed")
+ }
+ if !gone(impostor.Process.Pid) {
+ t.Fatal("a process like the helper's but not the runner's survived")
+ }
+}
+
+// A step that double-forks to escape (its parent gone, a session of its
+// own, no marker) is found by the runner-user sweep alone: the tree poll
+// never saw it.
+func TestSweepCatchesDoubleForkToLaunchd(t *testing.T) {
+ r := newLaunchRig(t)
+ r.x.Poll = time.Hour
+ ctx, turn := r.take(OpEngineering)
+ defer turn.Give()
+ pidFile := filepath.Join(t.TempDir(), "escaped")
+ script := "sleep 0.3; (setsid env -u EQUIPO_ATTEMPT sleep 60 & echo $! > " + quote(pidFile) + ")"
+ run, err := r.x.Start(ctx, Command{Argv: []string{"/bin/bash", "-c", script}, Env: r.env("EQUIPO_ATTEMPT=attempt-d-" + r.nonce)}, "attempt-d-"+r.nonce, func(string) error { return nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ escaped := waitPID(t, pidFile)
+ <-run.Exited()
+ q := r.waitListed(escaped)
+ if q.Marker != "" || q.SID != escaped {
+ t.Fatalf("not an escape: %+v", q)
+ }
+ if !run.Stop() || !gone(escaped) {
+ t.Fatal("a double-forked step outlived the turn's end")
+ }
+}
+
+// Proof only when nothing is left: a process only the runner-user sweep
+// finds (it double-forked out unseen: no marker, no recorded group or
+// session) that will not die keeps the end unproven within its bound,
+// the turn's record stays past Give, and the next turn cannot begin
+// until that process is gone.
+func TestProofOnlyWhenNothingRemains(t *testing.T) {
+ r := newLaunchRig(t)
+ r.x.Settle, r.turns.Settle, r.x.Poll = 600*time.Millisecond, 600*time.Millisecond, time.Hour
+ stuck := &stuckProcs{Procs: r.procs}
+ r.turns.Sweep(stuck)
+ ctx, turn := r.take(OpEngineering)
+ pidFile := filepath.Join(t.TempDir(), "p")
+ script := "sleep 0.3; (setsid env -u EQUIPO_ATTEMPT sleep 60 & echo $! > " + quote(pidFile) + ")"
+ run, err := r.x.Start(ctx, Command{Argv: []string{"/bin/bash", "-c", script}, Env: r.env("EQUIPO_ATTEMPT=attempt-p-" + r.nonce)}, "attempt-p-"+r.nonce, func(string) error { return nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ <-run.Exited()
+ r.waitListed(waitPID(t, pidFile))
+ stuck.hold()
+ start := time.Now()
+ if run.Stop() {
+ t.Fatal("proven over with a process of the turn alive")
+ }
+ if took := time.Since(start); took > r.x.Settle+time.Second {
+ t.Fatalf("the proof took %s, past its bound", took)
+ }
+ turn.Give()
+ if _, ok, _ := r.turns.loadTurn(); !ok {
+ t.Fatal("an unproven turn's record went")
+ }
+ if _, err := r.turns.Take(context.Background(), OpCheck); !errors.Is(err, ErrUnsettled) {
+ t.Fatalf("a turn began beside an unproven one: %v", err)
+ }
+ stuck.release()
+ next, err := r.turns.Take(context.Background(), OpCheck)
+ if err != nil {
+ t.Fatalf("not settled once it could be: %v", err)
+ }
+ next.Give()
+}
+
+// stuckProcs drops every signal while held: a process that will not die.
+type stuckProcs struct {
+ Procs
+ held bool
+}
+
+func (s *stuckProcs) hold() { s.held = true }
+func (s *stuckProcs) release() { s.held = false }
+func (s *stuckProcs) Signal(pid int, sig syscall.Signal) error {
+ if s.held && sig != 0 {
+ return nil
+ }
+ return s.Procs.Signal(pid, sig)
+}
+
+// Every operation that has a model token in a process, runs Xcode or
+// repository code holds the Mac's one turn: an Engineering launch, a
+// token check and a probe run never overlap, a launch outside a turn
+// starts nothing, and a check waits while a sign-in holds its pty.
+func TestTurnsCoverEveryTokenOperation(t *testing.T) {
+ er, r := engLaunch(t, "#!/bin/sh\ncat <&3 >/dev/null\nread line\n")
+ er.in.Action = claude.DarwinCheck
+ check := er.policy()
+ // A token check outside any turn: refused, nothing on record.
+ recorded := 0
+ s := &Starter{Exec: r.x, CLI: er.cli, Input: er.in, Token: slices.Clone(er.token)}
+ if _, err := s.StartRecorded(context.Background(), provider.Launch{Policy: check}, claude.DarwinArgv(check), func(context.Context, containment.Record) error { recorded++; return nil }); !errors.Is(err, ErrNoTurn) || recorded != 0 {
+ t.Fatalf("a token check ran outside the turn: %v (%d records)", err, recorded)
+ }
+ // While Engineering holds the turn, a token check and a probe run wait.
+ _, eng := r.take(OpEngineering)
+ short, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
+ if _, err := r.turns.Take(short, OpTokenCheck); err == nil {
+ t.Fatal("a token check took the turn beside Engineering")
+ }
+ cancel()
+ f := newProbeFixture(t, allLines("denied"))
+ f.h.Turns, f.h.Limit = r.turns, 300*time.Millisecond
+ if rep := RunProbes(context.Background(), f.h); len(rep.Unfinished) != len(rep.Probes) || slices.ContainsFunc(f.execLog, func(k string) bool { return strings.Contains(k, "simctl") }) {
+ t.Fatalf("probes ran beside Engineering: %+v", rep)
+ }
+ eng.Give()
+ // The token check in its own turn runs, and ends proven.
+ ctx, tc := r.take(OpTokenCheck)
+ s.Token = slices.Clone(er.token)
+ pr, err := s.StartRecorded(ctx, provider.Launch{Policy: check}, claude.DarwinArgv(check), func(context.Context, containment.Record) error { return nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ pr.Stdin().Close()
+ if _, err := pr.Wait(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ tc.Give()
+ // A sign-in's pty holds the turn: a check waits for it.
+ _, signIn := r.take(OpSignIn)
+ g, dir := gateFixture(t, false)
+ g.Turns = r.turns
+ g.Env = append(g.Env, proc.ScopeEnv+"="+r.nonce)
+ ran := make(chan Result, 1)
+ var at time.Time
+ go func() {
+ res := g.Run(context.Background(), "checks-w-"+r.nonce, dir, []string{"/bin/sh", "-c", "true"}, time.Minute, func(string) error {
+ if at.IsZero() {
+ at = time.Now()
+ }
+ return nil
+ })
+ ran <- res
+ }()
+ time.Sleep(300 * time.Millisecond)
+ select {
+ case res := <-ran:
+ t.Fatalf("a check ran while a sign-in held the turn: %+v", res)
+ default:
+ }
+ gave := time.Now()
+ signIn.Give()
+ if res := <-ran; res.Code != 0 || !res.Terminated || at.Before(gave) {
+ t.Fatalf("the check after the sign-in: %+v", res)
+ }
+}
+
+// A stored connection holds no turn: once the token is stored, an
+// Engineering launch, a sandboxed check and an ask take turns one after
+// another, each proven over, and nothing is left on record.
+func TestStoredConnectionAllowsSerialTurns(t *testing.T) {
+ er, r := engLaunch(t, "#!/bin/sh\ncat <&3 >/dev/null\nread line\n")
+ store, err := r.turns.Take(context.Background(), OpTokenStore)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(er.in.CredentialHome, ".oauth-token"), er.token, 0600); err != nil {
+ t.Fatal(err)
+ }
+ store.Give()
+ ask := newEngRigWith(t, []byte("#!/bin/sh\ncat <&3 >/dev/null\nread line\n"))
+ ask.in.Attempt, ask.in.Action = er.in.Attempt, claude.DarwinAnswer
+ cli := func(op Op, rig *engRig) error {
+ p, err := EngineeringPolicy(rig.cli, rig.in)
+ if err != nil {
+ return err
+ }
+ u, err := r.turns.Take(context.Background(), op)
+ if err != nil {
+ return err
+ }
+ defer u.Give()
+ s := &Starter{Exec: r.x, CLI: rig.cli, Input: rig.in, Token: slices.Clone(rig.token)}
+ pr, err := s.StartRecorded(u.Context(context.Background()), provider.Launch{Policy: p}, claude.DarwinArgv(p), func(context.Context, containment.Record) error { return nil })
+ if err != nil {
+ return err
+ }
+ pr.Stdin().Close()
+ _, err = pr.Wait(context.Background())
+ return err
+ }
+ g, dir := gateFixture(t, true)
+ _, temp := userTempFixture(t)
+ g.Turns, g.UserTemp = r.turns, temp
+ g.Env = append(g.Env, proc.ScopeEnv+"="+r.nonce)
+ done := make(chan []string)
+ go func() {
+ var errs []string
+ if err := cli(OpEngineering, er); err != nil {
+ errs = append(errs, "engineering: "+err.Error())
+ }
+ if res, _ := run(g, dir, "checks-s-"+r.nonce, time.Minute, "true"); res.Code != 0 || !res.Terminated {
+ errs = append(errs, "sandboxed check did not pass")
+ }
+ if err := cli(OpAsk, ask); err != nil {
+ errs = append(errs, "ask: "+err.Error())
+ }
+ done <- errs
+ }()
+ select {
+ case errs := <-done:
+ if len(errs) > 0 {
+ t.Fatal(errs)
+ }
+ case <-time.After(30 * time.Second):
+ t.Fatal("a turn waited on the stored connection")
+ }
+ if _, ok, _ := r.turns.loadTurn(); ok || r.turns.Pending() {
+ t.Fatal("a turn or a cleanup was left on record")
+ }
+}
+
+// An interrupted cleanup (its attempt's end not proven) is finished
+// only by its owner (that attempt's proof, in the runner process that
+// wrote it) or by a restart (that process gone), never by another turn.
+func TestCleanupOwnedByItsTurn(t *testing.T) {
+ g, dir := gateFixture(t, true)
+ _, temp := userTempFixture(t)
+ g.UserTemp, g.Settle, g.Turns = temp, 500*time.Millisecond, NewTurns(filepath.Join(t.TempDir(), "lock"))
+ g.procs = withPhantom()
+ res, id := run(g, dir, "checks-o-1", time.Minute, `touch `+quote(filepath.Join(temp, "left-by-1")))
+ if res.Terminated || !g.Turns.Pending() {
+ t.Fatalf("not interrupted: %+v", res)
+ }
+ g.procs = nil
+ // Another turn of this runner: it neither finishes it nor runs.
+ if res, _ := run(g, dir, "checks-o-2", time.Minute, `touch `+quote(filepath.Join(temp, "ran-2"))); res.Reason != "checks_unavailable" || exists(filepath.Join(temp, "ran-2")) {
+ t.Fatalf("another turn ran: %+v", res)
+ }
+ if !exists(filepath.Join(temp, "left-by-1")) || !g.Turns.Pending() {
+ t.Fatal("another turn finished the cleanup")
+ }
+ // Nor does a recovery for another attempt.
+ if g.Verify(RecordID(0, "checks-o-other")) && (!exists(filepath.Join(temp, "left-by-1")) || !g.Turns.Pending()) {
+ t.Fatal("another attempt's proof finished the cleanup")
+ }
+ // Its owner does.
+ if !g.Verify(id) || exists(filepath.Join(temp, "left-by-1")) || g.Turns.Pending() {
+ t.Fatal("the owner did not finish its cleanup")
+ }
+ // A restart: the record of a runner process that is gone.
+ dead := exec.Command("/bin/true")
+ if err := dead.Start(); err != nil {
+ t.Fatal(err)
+ }
+ deadID, ok := platformProcs.Lookup(dead.Process.Pid)
+ _ = dead.Wait()
+ if !ok {
+ deadID.ID = ProcID{PID: dead.Process.Pid, Start: 1}
+ }
+ s, err := openTemp(temp, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := g.Turns.writePending(pendingRecord{Attempt: "checks-o-dead", Before: s.before, Runner: deadID.ID}); err != nil {
+ t.Fatal(err)
+ }
+ s.close()
+ if err := os.WriteFile(filepath.Join(temp, "left-by-dead"), nil, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if res, _ := run(g, dir, "checks-o-3", time.Minute, `ls `+quote(temp)); res.Code != 0 || strings.Contains(res.Output, "left-by-dead") || g.Turns.Pending() {
+ t.Fatalf("a restart did not finish the dead runner's cleanup: %+v", res)
+ }
+ // This live runner's record for an attempt of another turn: never.
+ if err := g.Turns.writePending(pendingRecord{Attempt: "checks-o-live", Before: tempListing{}, Runner: selfID()}); err != nil {
+ t.Fatal(err)
+ }
+ if res, _ := run(g, dir, "checks-o-4", time.Minute, `true`); res.Reason != "checks_unavailable" || !g.Turns.Pending() {
+ t.Fatalf("a live owner's cleanup taken by another turn: %+v", res)
+ }
+}
diff --git a/internal/runner/mac/marked_darwin.go b/internal/runner/mac/marked_darwin.go
deleted file mode 100644
index 54db3dbc..00000000
--- a/internal/runner/mac/marked_darwin.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package mac
-
-import (
- "context"
- "os"
- "os/exec"
- "time"
-)
-
-// marked asks ps for this user's processes with their environment
-// (-E shows it for one's own processes only, which is all we may kill).
-func marked(attempt string) ([]Proc, error) {
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
- defer cancel()
- raw, err := exec.CommandContext(ctx, "/bin/ps", "-E", "-ww", "-x", "-o", "pid=,pgid=,command=").Output()
- if err != nil {
- return nil, err
- }
- return ParseMarked(string(raw), attempt, os.Getpid()), nil
-}
diff --git a/internal/runner/mac/marked_linux.go b/internal/runner/mac/marked_linux.go
deleted file mode 100644
index c431e2b0..00000000
--- a/internal/runner/mac/marked_linux.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package mac
-
-import (
- "bytes"
- "os"
- "path/filepath"
- "strconv"
- "strings"
-)
-
-// marked reads /proc: every process of this user whose environment
-// carries the attempt's marker, with its process group.
-func marked(attempt string) ([]Proc, error) {
- want := []byte("EQUIPO_ATTEMPT=" + attempt + "\x00")
- entries, err := os.ReadDir("/proc")
- if err != nil {
- return nil, err
- }
- var out []Proc
- for _, e := range entries {
- pid, err := strconv.Atoi(e.Name())
- if err != nil || pid == os.Getpid() {
- continue
- }
- env, err := os.ReadFile(filepath.Join("/proc", e.Name(), "environ"))
- if err != nil || !bytes.Contains(append(env, 0), want) {
- continue
- }
- stat, err := os.ReadFile(filepath.Join("/proc", e.Name(), "stat"))
- if err != nil {
- continue
- }
- // pid (comm) state ppid pgrp ...; comm may hold spaces.
- fields := strings.Fields(string(stat[bytes.LastIndexByte(stat, ')')+1:]))
- pgid := 0
- if len(fields) > 2 {
- pgid, _ = strconv.Atoi(fields[2])
- }
- out = append(out, Proc{PID: pid, PGID: pgid})
- }
- return out, nil
-}
diff --git a/internal/runner/mac/probe.go b/internal/runner/mac/probe.go
index 932471fc..fb7ad11c 100644
--- a/internal/runner/mac/probe.go
+++ b/internal/runner/mac/probe.go
@@ -45,6 +45,9 @@ type ProbeHost struct {
// Gate is the gate the fixture runs under: sandboxed, srt with the
// checks profile; or bare.
Gate func(sandboxed bool) *Gate
+ // Turns is the Mac's turns: the whole run is one turn (OpProbe), and
+ // its gates run in it. nil takes none (tests).
+ Turns *Turns
// Resolve and Exposed are the same attempts made outside the
// sandbox, so a denial can be told from a failure; Listen opens a
// loopback port whose accepts are ground truth for "tcp".
@@ -147,6 +150,17 @@ func RunProbes(ctx context.Context, h ProbeHost) Report {
run, cancel := context.WithTimeout(ctx, limit)
defer cancel()
r := Report{Version: h.Version, Profile: ProfileDigest(), At: time.Now().UTC()}
+ // One turn for the run's life: no check, Engineering or token
+ // operation runs between its gates.
+ run, give, err := h.Turns.Hold(run, OpProbe)
+ if err != nil {
+ for _, id := range wire.ProbeIDs {
+ r.Probes = append(r.Probes, wire.Probe{ID: id, Verdict: wire.ProbeUnavailable, Detail: "not proven: the Mac's turn was not free"})
+ r.Unfinished = append(r.Unfinished, id)
+ }
+ return r
+ }
+ defer give()
h.late = &queries{run: run, exec: h.Exec, late: map[string]bool{}}
h.Exec = h.late.do
var mu sync.Mutex
diff --git a/internal/runner/mac/probe_test.go b/internal/runner/mac/probe_test.go
index 0424ebbe..05a4a871 100644
--- a/internal/runner/mac/probe_test.go
+++ b/internal/runner/mac/probe_test.go
@@ -341,7 +341,7 @@ func TestP2NeedsTheSimulatorAndAProvenEnd(t *testing.T) {
f.h.Gate = func(sandboxed bool) *Gate {
g := gate(sandboxed)
g.Settle = 300 * time.Millisecond
- g.find = func(string) ([]Proc, error) { return []Proc{{PID: 1 << 30, PGID: 1 << 30}}, nil }
+ g.procs = withPhantom()
return g
}
if p, _, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "end not proven") {
diff --git a/internal/runner/mac/proc/proc.go b/internal/runner/mac/proc/proc.go
new file mode 100644
index 00000000..1b40fc21
--- /dev/null
+++ b/internal/runner/mac/proc/proc.go
@@ -0,0 +1,362 @@
+// Package proc is the Mac runner's view of its user's processes (spec
+// §5 and its 2026-11-28 addendum, §8.8): identities that survive pid
+// reuse, the kernel's table behind a seam, the runner's own helpers, and
+// what one operation may have left.
+package proc
+
+import (
+ "errors"
+ "os"
+ "os/exec"
+ "slices"
+ "strings"
+ "sync"
+ "syscall"
+)
+
+// How the runner finds what an operation left (spec §5 and its
+// 2026-11-28 addendum, §8.8). Claude Code starts every Bash command in a
+// session of its own (setsid), and macOS 27.2 hides the environment of
+// platform binaries (bash, zsh, sleep, env, sandbox-exec) even from
+// their own user, so neither the attempt's group nor its marker finds
+// them all. Three nets, all keyed by process identity (pid and kernel
+// start time), never by name:
+//
+// (a) while the operation runs, the processes under its leader and
+// every group and session they make;
+// (b) at its end, every process of the runner user that did not exist
+// when the turn began, except the runner and what it started for
+// itself (Own), and launchd's own system agents (ppid 1, executable
+// under /System or /usr/libexec, by the kernel's path);
+// (c) the marker, wherever the kernel shows it.
+
+// ID names one process for its whole life: its pid and the kernel's
+// start time (on a Mac microseconds since the epoch, on Linux clock
+// ticks since boot). A pid used again later has another start: another
+// ID.
+type ID struct {
+ PID int `json:"pid"`
+ Start int64 `json:"start"`
+}
+
+// Info is one process of the runner user as the kernel reports it.
+type Info struct {
+ ID
+ PPID, PGID, SID, UID int
+ // Marker is the EQUIPO_ATTEMPT value it carries, of those asked for
+ // ("" for none, or when the kernel does not show it).
+ Marker string
+}
+
+// Table is the process table (the seam: sysctl on a Mac, /proc on
+// Linux, recorded tables in tests).
+type Table interface {
+ // List is every process whose user is the runner's, each with
+ // which of markers its environment carries.
+ List(markers []string) ([]Info, error)
+ // Lookup is pid as it is now; ok is false once it is gone (or is
+ // another user's).
+ Lookup(pid int) (Info, bool)
+ // Path is the executable the kernel runs as pid (its file, not its
+ // argv[0], which the process may set), "" when unknown.
+ Path(pid int) string
+ // Sweeps reports whether this table may drive the runner-user sweep
+ // (b): on a Mac, where the runner user is dedicated; on Linux only a
+ // table scoped to a test's own processes.
+ Sweeps() bool
+ // Signal sends sig to pid (a negative pid: that group).
+ Signal(pid int, sig syscall.Signal) error
+}
+
+// ErrNoSweep refuses a runner-user sweep on a table that may not drive
+// one (Linux outside a test's scope: other people's processes).
+var ErrNoSweep = errors.New("mac: this process table cannot sweep the runner user")
+
+// Own is the runner's own processes: the runner itself and every helper
+// it starts for itself (simctl and ps queries, caffeinate, git, the
+// gitleaks scan, packing), each by ID. A sweep never signals them,
+// nor, in the runner-user sweep, what they started. Its lock is held for
+// reading across a helper's start and registration and for writing
+// across a sweep's listing, so a helper is never listed unregistered.
+type Own struct {
+ mu sync.RWMutex
+ ids map[ID]bool
+}
+
+// Runner is this process's registry; every helper the runner starts
+// for itself goes through StartOwn.
+var Runner = &Own{}
+
+// Start starts cmd as the runner's own helper (cmd.Start, then its
+// identity on record). A helper whose identity cannot be read while it
+// runs is killed and not started: unrecorded, a sweep would take it for
+// the operation's.
+func Start(cmd *exec.Cmd) error { return Runner.Start(cmd, Platform) }
+
+// Start starts cmd and records it as own, reading its identity from p.
+func (o *Own) Start(cmd *exec.Cmd, p Table) error {
+ o.mu.RLock()
+ defer o.mu.RUnlock()
+ if err := cmd.Start(); err != nil {
+ return err
+ }
+ pid := cmd.Process.Pid
+ if info, ok := p.Lookup(pid); ok && info.PID == pid {
+ o.add(info.ID)
+ return nil
+ }
+ if syscall.Kill(pid, 0) == syscall.ESRCH {
+ // Already gone (or a zombie Wait will reap): nothing to spare.
+ return nil
+ }
+ _ = cmd.Process.Kill()
+ _ = cmd.Wait()
+ return errors.New("mac: a helper's identity could not be read")
+}
+
+// Add records id as own (a helper started some other way).
+func (o *Own) Add(id ID) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ o.add(id)
+}
+
+func (o *Own) add(id ID) {
+ if o.ids == nil {
+ o.ids = map[ID]bool{}
+ }
+ o.ids[id] = true
+}
+
+// Snapshot lists p with no helper half-started, and forgets the helpers
+// that are gone (their identity cannot come back).
+func (o *Own) Snapshot(p Table, markers []string) ([]Info, map[ID]bool, error) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ list, err := p.List(markers)
+ if err != nil {
+ return nil, nil, err
+ }
+ live := map[ID]bool{}
+ for _, q := range list {
+ live[q.ID] = true
+ }
+ own := map[ID]bool{}
+ for id := range o.ids {
+ if live[id] {
+ own[id] = true
+ } else {
+ delete(o.ids, id)
+ }
+ }
+ return list, own, nil
+}
+
+// SystemPath reports whether the kernel's path of an executable is one
+// only the system can write: under /System (but not its volumes, where
+// /System/Volumes/Data holds every user's files) or /usr/libexec. Exact
+// case: anything else is not a system agent, and is swept.
+func SystemPath(p string) bool {
+ if p == "" || strings.Contains(p, "/../") || strings.Contains(p, "/./") || strings.HasSuffix(p, "/..") {
+ return false
+ }
+ switch {
+ case strings.HasPrefix(p, "/System/Volumes/"):
+ return false
+ case strings.HasPrefix(p, "/System/"), strings.HasPrefix(p, "/usr/libexec/"):
+ return true
+ }
+ return false
+}
+
+// Span is a group or session id an operation made, and the latest start
+// in the table it was first seen in: a leader with that pid started
+// after it is the id used again by someone else.
+type Span map[int]int64
+
+// scope is what one operation (or a turn's operations) may have left:
+// its processes seen, their groups and sessions, its markers, and, for
+// the runner-user sweep, what existed when the turn began.
+type Scope struct {
+ uid, self int
+ markers []string
+ Seen map[ID]bool
+ Groups Span
+ Sessions Span
+ // before is the turn's table at its start; nil: no runner-user sweep.
+ before map[ID]bool
+ procs Table
+}
+
+func NewScope(p Table, markers []string, before []ID) *Scope {
+ s := &Scope{uid: os.Getuid(), self: os.Getpid(), markers: markers, Seen: map[ID]bool{}, Groups: Span{}, Sessions: Span{}, procs: p}
+ if before != nil {
+ s.before = map[ID]bool{}
+ for _, id := range before {
+ s.before[id] = true
+ }
+ }
+ return s
+}
+
+// Track adds to the scope what list shows of it: children of what it
+// has seen (a true child started no earlier than its parent), members
+// of its groups and sessions (not of an id used again), and marked
+// processes; with each, its group and session. It reports whether a new
+// group or session was found.
+func (s *Scope) Track(list []Info, own map[ID]bool) bool {
+ sorted := slices.Clone(list)
+ slices.SortFunc(sorted, func(a, b Info) int {
+ if a.Start != b.Start {
+ if a.Start < b.Start {
+ return -1
+ }
+ return 1
+ }
+ return a.PID - b.PID
+ })
+ by := Index(list)
+ top := int64(0)
+ for _, q := range list {
+ top = max(top, q.Start)
+ }
+ grew := false
+ for _, q := range sorted {
+ if q.UID != s.uid || q.PID == s.self || own[q.ID] {
+ continue
+ }
+ parent, ok := by[q.PPID]
+ child := ok && parent.Start <= q.Start && s.Seen[parent.ID]
+ if !(child || s.Seen[q.ID] || s.member(q, by) || s.marked(q)) {
+ continue
+ }
+ s.Seen[q.ID] = true
+ for _, m := range []struct {
+ ids Span
+ id int
+ }{{s.Groups, q.PGID}, {s.Sessions, q.SID}} {
+ if _, ok := m.ids[m.id]; !ok && m.id > 1 {
+ m.ids[m.id] = top
+ grew = true
+ }
+ }
+ }
+ return grew
+}
+
+// member: q is in one of the scope's groups or sessions, and that id has
+// not been used again since (its leader, if alive, was there then).
+func (s *Scope) member(q Info, by map[int]Info) bool {
+ in := func(ids Span, id int) bool {
+ at, ok := ids[id]
+ if !ok || id <= 1 {
+ return false
+ }
+ leader, alive := by[id]
+ return !alive || leader.Start <= at || s.Seen[leader.ID]
+ }
+ return in(s.Groups, q.PGID) || in(s.Sessions, q.SID)
+}
+
+func (s *Scope) marked(q Info) bool {
+ return q.Marker != "" && slices.Contains(s.markers, q.Marker)
+}
+
+// Targets is what of list the stop must end: the scope's own processes
+// and, with a runner-user sweep, every process of the runner user that
+// was not there when the turn began, except the runner, its own helpers
+// and what they started, and launchd's system agents. Never another
+// user's process, never the runner's own.
+func (s *Scope) Targets(list []Info, own map[ID]bool) []Info {
+ s.Track(list, own)
+ by := Index(list)
+ var out []Info
+ for _, q := range list {
+ if q.UID != s.uid || q.PID == s.self || q.PID <= 1 || own[q.ID] {
+ continue
+ }
+ switch {
+ case s.Seen[q.ID] || s.member(q, by) || s.marked(q):
+ out = append(out, q)
+ case s.before != nil && !s.before[q.ID] && !ownChild(q, by, own) && !s.agent(q):
+ out = append(out, q)
+ }
+ }
+ return out
+}
+
+// ownChild: q descends from one of the runner's own helpers (through
+// live parents, each started no later than its child).
+func ownChild(q Info, by map[int]Info, own map[ID]bool) bool {
+ for range 64 {
+ parent, ok := by[q.PPID]
+ if !ok || parent.Start > q.Start || parent.PID == q.PID {
+ return false
+ }
+ if own[parent.ID] {
+ return true
+ }
+ q = parent
+ }
+ return false
+}
+
+// agent: launchd started q from the system (ppid 1, the kernel's path
+// under /System or /usr/libexec), read for the same process (its
+// identity again after the path).
+func (s *Scope) agent(q Info) bool {
+ if q.PPID != 1 || !SystemPath(s.procs.Path(q.PID)) {
+ return false
+ }
+ now, ok := s.procs.Lookup(q.PID)
+ return ok && now.ID == q.ID
+}
+
+func Index(list []Info) map[int]Info {
+ by := make(map[int]Info, len(list))
+ for _, q := range list {
+ by[q.PID] = q
+ }
+ return by
+}
+
+// Kill sends sig to each target, each checked again just before
+// (same pid, same start, still the runner user's): a pid used again
+// since the table was read is never signalled. A group is signalled
+// whole only while a checked target is in it (a group id cannot be used
+// again while it has a member).
+func (s *Scope) Kill(targets []Info, sig syscall.Signal) {
+ done := map[int]bool{}
+ for _, q := range targets {
+ if q.PGID <= 1 || done[q.PGID] {
+ continue
+ }
+ if _, ours := s.Groups[q.PGID]; !ours || !s.Still(q) {
+ continue
+ }
+ done[q.PGID] = true
+ _ = s.procs.Signal(-q.PGID, sig)
+ }
+ for _, q := range targets {
+ if s.Still(q) {
+ _ = s.procs.Signal(q.PID, sig)
+ }
+ }
+}
+
+func (s *Scope) Still(q Info) bool {
+ now, ok := s.procs.Lookup(q.PID)
+ return ok && now.ID == q.ID && now.UID == s.uid
+}
+
+// GroupsGone reports whether every group the scope made is gone:
+// kill(-pgid, 0) says ESRCH. A group id used again by someone else
+// keeps it false until that group ends too.
+func (s *Scope) GroupsGone() bool {
+ for g := range s.Groups {
+ if s.procs.Signal(-g, 0) != syscall.ESRCH {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/runner/mac/proc/proc_darwin.go b/internal/runner/mac/proc/proc_darwin.go
new file mode 100644
index 00000000..2407e425
--- /dev/null
+++ b/internal/runner/mac/proc/proc_darwin.go
@@ -0,0 +1,122 @@
+package proc
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "syscall"
+ "time"
+ "unsafe"
+
+ "golang.org/x/sys/unix"
+)
+
+// sysctlProcs is the Mac's process table: kern.proc.ruid (pid, parent,
+// group, the kernel's start time to the microsecond, real uid, so a
+// setuid program the attempt ran is still listed), getsid for the
+// session, proc_pidpath for the executable, and ps -E for the marker
+// (which it shows only for non-platform binaries on macOS 27.2).
+type sysctlProcs struct{ uid int }
+
+var Platform Table = sysctlProcs{uid: os.Getuid()}
+
+// Machine is the table a Mac's turns sweep with; nil off a Mac.
+func Machine() Table { return Platform }
+
+func (p sysctlProcs) table() ([]Info, error) {
+ kps, err := unix.SysctlKinfoProcSlice("kern.proc.ruid", p.uid)
+ if err != nil {
+ return nil, err
+ }
+ out := make([]Info, 0, len(kps))
+ for i := range kps {
+ if q, ok := fromKinfo(&kps[i]); ok && q.UID == p.uid {
+ out = append(out, q)
+ }
+ }
+ return out, nil
+}
+
+func fromKinfo(k *unix.KinfoProc) (Info, bool) {
+ pid := int(k.Proc.P_pid)
+ if pid <= 0 {
+ return Info{}, false
+ }
+ start := k.Proc.P_starttime.Sec*1_000_000 + int64(k.Proc.P_starttime.Usec)
+ sid, err := unix.Getsid(pid)
+ if err != nil {
+ sid = -1
+ }
+ return Info{ID: ID{PID: pid, Start: start}, PPID: int(k.Eproc.Ppid), PGID: int(k.Eproc.Pgid), SID: sid, UID: int(k.Eproc.Pcred.P_ruid)}, true
+}
+
+// List reads the table, then ps -E, then the table again: a process is
+// marked only when ps named its pid and that pid was the same process
+// both times (so a pid used again meanwhile is never taken as marked).
+func (p sysctlProcs) List(markers []string) ([]Info, error) {
+ first, err := p.table()
+ if err != nil || len(markers) == 0 {
+ return first, err
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ // Not StartOwn: List runs under Own's write lock, and ps is started
+ // after the first table and reaped before the second, so neither
+ // lists it.
+ raw, err := exec.CommandContext(ctx, "/bin/ps", "-E", "-ww", "-x", "-o", "pid=,pgid=,command=").Output()
+ if err != nil {
+ return nil, err
+ }
+ second, err := p.table()
+ if err != nil {
+ return nil, err
+ }
+ was := Index(first)
+ for _, m := range markers {
+ for _, hit := range ParseMarked(string(raw), m, os.Getpid()) {
+ for i := range second {
+ if second[i].PID == hit.PID && was[hit.PID].ID == second[i].ID {
+ second[i].Marker = m
+ }
+ }
+ }
+ }
+ return second, nil
+}
+
+func (p sysctlProcs) Lookup(pid int) (Info, bool) {
+ if pid <= 0 {
+ return Info{}, false
+ }
+ k, err := unix.SysctlKinfoProc("kern.proc.pid", pid)
+ if err != nil {
+ return Info{}, false
+ }
+ q, ok := fromKinfo(k)
+ if !ok || q.PID != pid || q.UID != p.uid {
+ return Info{}, false
+ }
+ return q, true
+}
+
+// Path is proc_pidpath: __proc_info(PROC_INFO_CALL_PIDINFO,
+// pid, PROC_PIDPATHINFO, 0, buf, PROC_PIDPATHINFO_MAXSIZE), the path of
+// the vnode the kernel runs, which the process cannot set.
+func (sysctlProcs) Path(pid int) string {
+ const callPIDInfo, pidPathInfo, maxSize = 2, 11, 4096
+ buf := make([]byte, maxSize)
+ n, _, errno := unix.Syscall6(unix.SYS_PROC_INFO, callPIDInfo, uintptr(pid), pidPathInfo, 0, uintptr(unsafe.Pointer(&buf[0])), maxSize)
+ if errno != 0 || n == 0 || n > maxSize {
+ return ""
+ }
+ for i := 0; i < int(n); i++ {
+ if buf[i] == 0 {
+ return string(buf[:i])
+ }
+ }
+ return string(buf[:n])
+}
+
+func (sysctlProcs) Sweeps() bool { return true }
+
+func (sysctlProcs) Signal(pid int, sig syscall.Signal) error { return syscall.Kill(pid, sig) }
diff --git a/internal/runner/mac/proc/proc_linux.go b/internal/runner/mac/proc/proc_linux.go
new file mode 100644
index 00000000..776c467e
--- /dev/null
+++ b/internal/runner/mac/proc/proc_linux.go
@@ -0,0 +1,169 @@
+package proc
+
+import (
+ "bytes"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+)
+
+// procfs is the process table on Linux, where a Mac's runner is only
+// ever tested (the test build's fake worker, and this package's tests):
+// /proc/<pid>/stat for parent, group, session and start, the directory's
+// owner for the user, environ for the marker, exe for the path.
+//
+// Linux machines are shared, so it never drives a runner-user sweep
+// unless scoped: then it lists only processes whose environment carries
+// EQUIPO_TEST_SCOPE=<scope>, a test's own.
+type procfs struct {
+ uid int
+ // scope is the environment entries (any one) that tag a test's own
+ // processes, NUL-joined so the table stays comparable; "" lists all.
+ scope string
+}
+
+var Platform Table = procfs{uid: os.Getuid()}
+
+// Machine is the table a Mac's turns sweep with; nil off a Mac.
+func Machine() Table { return nil }
+
+// ScopeEnv tags a test's own processes for a scoped table.
+const ScopeEnv = "EQUIPO_TEST_SCOPE"
+
+func (p procfs) read(pid int, markers []string) (Info, bool) {
+ dir := filepath.Join("/proc", strconv.Itoa(pid))
+ fi, err := os.Stat(dir)
+ if err != nil {
+ return Info{}, false
+ }
+ if st, ok := fi.Sys().(*syscall.Stat_t); !ok || int(st.Uid) != p.uid {
+ return Info{}, false
+ }
+ stat, err := os.ReadFile(filepath.Join(dir, "stat"))
+ if err != nil {
+ return Info{}, false
+ }
+ end := bytes.LastIndexByte(stat, ')')
+ if end < 0 {
+ return Info{}, false
+ }
+ // pid (comm) state ppid pgrp session tty tpgid flags minflt cminflt
+ // majflt cmajflt utime stime cutime cstime priority nice threads
+ // itrealvalue starttime ...
+ f := strings.Fields(string(stat[end+1:]))
+ if len(f) < 20 {
+ return Info{}, false
+ }
+ num := func(s string) int { n, _ := strconv.Atoi(s); return n }
+ start, _ := strconv.ParseInt(f[19], 10, 64)
+ q := Info{ID: ID{PID: pid, Start: start}, PPID: num(f[1]), PGID: num(f[2]), SID: num(f[3]), UID: p.uid}
+ if p.scope == "" && len(markers) == 0 {
+ return q, true
+ }
+ env, err := os.ReadFile(filepath.Join(dir, "environ"))
+ if err != nil {
+ // Unreadable (gone, or not dumpable): unmarked, and outside any
+ // scope.
+ return q, p.scope == ""
+ }
+ vars := bytes.Split(env, []byte{0})
+ has := func(kv string) bool {
+ for _, v := range vars {
+ if string(v) == kv {
+ return true
+ }
+ }
+ return false
+ }
+ if p.scope != "" {
+ in := false
+ for _, kv := range strings.Split(p.scope, "\x00") {
+ in = in || has(kv)
+ }
+ if !in {
+ return Info{}, false
+ }
+ }
+ for _, m := range markers {
+ if has("EQUIPO_ATTEMPT=" + m) {
+ q.Marker = m
+ break
+ }
+ }
+ return q, true
+}
+
+func (p procfs) List(markers []string) ([]Info, error) {
+ entries, err := os.ReadDir("/proc")
+ if err != nil {
+ return nil, err
+ }
+ var out []Info
+ for _, e := range entries {
+ pid, err := strconv.Atoi(e.Name())
+ if err != nil {
+ continue
+ }
+ if q, ok := p.read(pid, markers); ok {
+ out = append(out, q)
+ }
+ }
+ return out, nil
+}
+
+func (p procfs) Lookup(pid int) (Info, bool) {
+ if pid <= 0 {
+ return Info{}, false
+ }
+ return p.read(pid, nil)
+}
+
+func (p procfs) Path(pid int) string {
+ if _, ok := p.Lookup(pid); !ok {
+ return ""
+ }
+ path, err := os.Readlink(filepath.Join("/proc", strconv.Itoa(pid), "exe"))
+ if err != nil {
+ return ""
+ }
+ return path
+}
+
+func (p procfs) Sweeps() bool { return p.scope != "" }
+
+// Signal refuses to signal outside the scope: a scoped table's signals
+// reach only the test's own processes (a group only while a member of
+// it is the test's).
+func (p procfs) Signal(pid int, sig syscall.Signal) error {
+ if p.scope != "" && sig != 0 {
+ target := pid
+ if pid < 0 {
+ target = -pid
+ if _, ok := p.Lookup(target); !ok {
+ list, err := p.List(nil)
+ if err != nil {
+ return err
+ }
+ found := false
+ for _, q := range list {
+ found = found || q.PGID == target
+ }
+ if !found {
+ return syscall.ESRCH
+ }
+ }
+ } else if _, ok := p.Lookup(target); !ok {
+ return syscall.ESRCH
+ }
+ }
+ return syscall.Kill(pid, sig)
+}
+
+// Scoped is a table of only the processes whose environment holds
+// one of entries (tests: EQUIPO_TEST_SCOPE=<nonce>, or a test's own
+// EQUIPO_ATTEMPT=<unique marker>).
+func Scoped(entries ...string) Table {
+ return procfs{uid: os.Getuid(), scope: strings.Join(entries, "\x00")}
+}
diff --git a/internal/runner/mac/proc/proc_test.go b/internal/runner/mac/proc/proc_test.go
new file mode 100644
index 00000000..2009b676
--- /dev/null
+++ b/internal/runner/mac/proc/proc_test.go
@@ -0,0 +1,34 @@
+package proc
+
+import (
+ "os"
+ "testing"
+
+ "amadan.net/rastrillo/rastrillo/budget"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
+
+// Only a path the system alone can write is a launchd agent's: under
+// /System (not its volumes: /System/Volumes/Data is every user's data)
+// or /usr/libexec, exactly, with no climbing out.
+func TestSystemPath(t *testing.T) {
+ for p, want := range map[string]bool{
+ "/System/Library/PrivateFrameworks/X.framework/XPCServices/Y.xpc/Contents/MacOS/Y": true,
+ "/usr/libexec/trustd": true,
+ "/System/Volumes/Data/Users/paulequipo/x": false,
+ "/System/Volumes/Preboot/Cryptexes/OS/x": false,
+ "/System/Library/../../Users/paulequipo/x": false,
+ "/usr/libexec/./x": false,
+ "/usr/libexec/..": false,
+ "/system/Library/x": false,
+ "/usr/sbin/cfprefsd": false,
+ "/Users/paulequipo/.local/lib/equipo-runner/x": false,
+ "/System": false,
+ "": false,
+ } {
+ if SystemPath(p) != want {
+ t.Errorf("%q: %v", p, !want)
+ }
+ }
+}
diff --git a/internal/runner/mac/ps.go b/internal/runner/mac/proc/ps.go
similarity index 89%
rename from internal/runner/mac/ps.go
rename to internal/runner/mac/proc/ps.go
index 82508e36..0bd58fa0 100644
--- a/internal/runner/mac/ps.go
+++ b/internal/runner/mac/proc/ps.go
@@ -1,10 +1,13 @@
-package mac
+package proc
import (
"strconv"
"strings"
)
+// Proc is a process carrying an attempt's marker.
+type Proc struct{ PID, PGID int }
+
// ParseMarked reads `ps -E -ww -x -o pid=,pgid=,command=` output: each
// line is the pid, the group, then the command and, separated by spaces,
// the environment. A process is marked when one of those words is
diff --git a/internal/runner/mac/proc_alias.go b/internal/runner/mac/proc_alias.go
new file mode 100644
index 00000000..acdfe919
--- /dev/null
+++ b/internal/runner/mac/proc_alias.go
@@ -0,0 +1,43 @@
+package mac
+
+import (
+ "os/exec"
+
+ "amadan.net/oficina/equipo/internal/runner/mac/proc"
+)
+
+// The runner user's process table, the runner's own helpers and what an
+// operation may have left live in package proc; these names keep the
+// Mac runner's callers on this package.
+type (
+ ProcID = proc.ID
+ ProcInfo = proc.Info
+ Procs = proc.Table
+ Own = proc.Own
+ Proc = proc.Proc
+ span = proc.Span
+ scope = proc.Scope
+)
+
+// ErrNoSweep refuses a runner-user sweep on a table that may not drive
+// one.
+var ErrNoSweep = proc.ErrNoSweep
+
+var (
+ platformProcs = proc.Platform
+ runnerOwn = proc.Runner
+)
+
+// StartOwn starts cmd as the runner's own helper: a turn's sweep spares
+// it, by identity (proc.Start).
+func StartOwn(cmd *exec.Cmd) error { return proc.Start(cmd) }
+
+// MachineProcs is the table a Mac's turns sweep with; nil off a Mac.
+func MachineProcs() Procs { return proc.Machine() }
+
+// ParseMarked reads ps -E output for attempt's marker (proc.ParseMarked).
+func ParseMarked(out, attempt string, self int) []Proc { return proc.ParseMarked(out, attempt, self) }
+
+func newScope(p Procs, markers []string, before []ProcID) *scope {
+ return proc.NewScope(p, markers, before)
+}
diff --git a/internal/runner/mac/procs_test.go b/internal/runner/mac/procs_test.go
new file mode 100644
index 00000000..e18ea3eb
--- /dev/null
+++ b/internal/runner/mac/procs_test.go
@@ -0,0 +1,205 @@
+package mac
+
+import (
+ "os"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+)
+
+// phantomPID is a process the table shows carrying a marker that no
+// signal ends: an end that is never proven.
+const phantomPID = 1 << 30
+
+// phantom is the platform's table plus that process, for the markers in
+// only (any marker when only is empty).
+type phantom struct {
+ Procs
+ only []string
+}
+
+func withPhantom(only ...string) *phantom { return &phantom{Procs: platformProcs, only: only} }
+
+func (p *phantom) ghost(m string) ProcInfo {
+ return ProcInfo{ID: ProcID{PID: phantomPID, Start: 1}, PPID: 1, PGID: phantomPID, SID: phantomPID, UID: os.Getuid(), Marker: m}
+}
+
+func (p *phantom) List(markers []string) ([]ProcInfo, error) {
+ list, err := p.Procs.List(markers)
+ if err != nil {
+ return nil, err
+ }
+ for _, m := range markers {
+ if len(p.only) == 0 || slices.Contains(p.only, m) {
+ return append(list, p.ghost(m)), nil
+ }
+ }
+ return list, nil
+}
+
+func (p *phantom) Lookup(pid int) (ProcInfo, bool) {
+ if pid == phantomPID {
+ return p.ghost(""), true
+ }
+ return p.Procs.Lookup(pid)
+}
+
+func (p *phantom) Signal(pid int, sig syscall.Signal) error {
+ if pid == phantomPID || pid == -phantomPID {
+ return nil
+ }
+ return p.Procs.Signal(pid, sig)
+}
+
+// table is a synthetic process table. Signals are recorded; a process
+// signalled with SIGKILL (or SIGTERM, unless stubborn) leaves it.
+type table struct {
+ mu sync.Mutex
+ procs map[int]ProcInfo
+ paths map[int]string
+ stubborn map[int]bool
+ sent []sent
+ // lookup, when set, runs before each Lookup (a race between the
+ // listing and the re-check).
+ lookup func(t *table, pid int)
+}
+
+type sent struct {
+ PID int
+ Sig syscall.Signal
+}
+
+// parseTable reads rows shaped like
+// `ps -axo pid,ppid,pgid,sess,lstart,uid,comm` as the darwin table
+// reports them (lstart as the kernel's microseconds), one per line, and
+// a trailing marker=<m> where the environment shows one. "me" in the
+// uid column is this test's uid, "self" in the pid column this process.
+func parseTable(t *testing.T, rows string) *table {
+ t.Helper()
+ tb := &table{procs: map[int]ProcInfo{}, paths: map[int]string{}, stubborn: map[int]bool{}}
+ for _, line := range strings.Split(rows, "\n") {
+ f := strings.Fields(line)
+ if len(f) == 0 || strings.HasPrefix(f[0], "#") {
+ continue
+ }
+ if len(f) < 7 {
+ t.Fatalf("row %q", line)
+ }
+ n := func(s string) int {
+ switch s {
+ case "me":
+ return os.Getuid()
+ case "self":
+ return os.Getpid()
+ }
+ v, err := strconv.Atoi(s)
+ if err != nil {
+ t.Fatalf("row %q: %v", line, err)
+ }
+ return v
+ }
+ q := ProcInfo{ID: ProcID{PID: n(f[0]), Start: int64(n(f[4]))}, PPID: n(f[1]), PGID: n(f[2]), SID: n(f[3]), UID: n(f[5])}
+ if len(f) > 7 {
+ q.Marker = strings.TrimPrefix(f[7], "marker=")
+ }
+ if q.PID == os.Getpid() && f[0] != "self" {
+ t.Skip("a synthetic pid is this test's own")
+ }
+ tb.procs[q.PID] = q
+ tb.paths[q.PID] = f[6]
+ }
+ return tb
+}
+
+func (tb *table) List(markers []string) ([]ProcInfo, error) {
+ tb.mu.Lock()
+ defer tb.mu.Unlock()
+ var out []ProcInfo
+ for _, q := range tb.procs {
+ if !slices.Contains(markers, q.Marker) {
+ q.Marker = ""
+ }
+ out = append(out, q)
+ }
+ slices.SortFunc(out, func(a, b ProcInfo) int { return a.PID - b.PID })
+ return out, nil
+}
+
+func (tb *table) Lookup(pid int) (ProcInfo, bool) {
+ if tb.lookup != nil {
+ tb.lookup(tb, pid)
+ }
+ tb.mu.Lock()
+ defer tb.mu.Unlock()
+ // Every user's: the scope checks the user itself, whatever the
+ // table does.
+ q, ok := tb.procs[pid]
+ if !ok {
+ return ProcInfo{}, false
+ }
+ q.Marker = ""
+ return q, true
+}
+
+func (tb *table) Path(pid int) string {
+ tb.mu.Lock()
+ defer tb.mu.Unlock()
+ return tb.paths[pid]
+}
+
+func (tb *table) Sweeps() bool { return true }
+
+func (tb *table) Signal(pid int, sig syscall.Signal) error {
+ tb.mu.Lock()
+ defer tb.mu.Unlock()
+ var hit []int
+ for p, q := range tb.procs {
+ if p == pid || pid < 0 && q.PGID == -pid {
+ hit = append(hit, p)
+ }
+ }
+ if len(hit) == 0 {
+ return syscall.ESRCH
+ }
+ if sig == 0 {
+ return nil
+ }
+ tb.sent = append(tb.sent, sent{pid, sig})
+ for _, p := range hit {
+ if sig == syscall.SIGKILL || !tb.stubborn[p] {
+ delete(tb.procs, p)
+ delete(tb.paths, p)
+ }
+ }
+ return nil
+}
+
+// signalled is every pid (negative: a group) the table was signalled at.
+func (tb *table) signalled() []int {
+ tb.mu.Lock()
+ defer tb.mu.Unlock()
+ var out []int
+ for _, s := range tb.sent {
+ if !slices.Contains(out, s.PID) {
+ out = append(out, s.PID)
+ }
+ }
+ return out
+}
+
+func (tb *table) add(q ProcInfo, path string) {
+ tb.mu.Lock()
+ defer tb.mu.Unlock()
+ tb.procs[q.PID] = q
+ tb.paths[q.PID] = path
+}
+
+func (tb *table) has(pid int) bool {
+ tb.mu.Lock()
+ defer tb.mu.Unlock()
+ _, ok := tb.procs[pid]
+ return ok
+}
diff --git a/internal/runner/mac/sweep_test.go b/internal/runner/mac/sweep_test.go
new file mode 100644
index 00000000..307d5219
--- /dev/null
+++ b/internal/runner/mac/sweep_test.go
@@ -0,0 +1,226 @@
+package mac
+
+import (
+ "context"
+ "os"
+ "slices"
+ "testing"
+ "time"
+)
+
+// Synthetic process tables. No table of the Studio's processes was
+// recorded (task 1 recorded no ps output, only that Bash commands run in
+// sessions of their own and that macOS 27.2 hides platform binaries'
+// environment), so these rows are made up, 2026-11-28, in the shape the
+// darwin table reports: ps -axo pid,ppid,pgid,sess,lstart,uid,comm, with
+// lstart as the kernel's start in microseconds and comm as the kernel's
+// path (proc_pidpath), not argv[0].
+
+// turnBegan is the runner user's table when the turn begins: the runner,
+// two launchd agents and another user's shell.
+const turnBegan = `
+# pid ppid pgid sess start uid path
+self 1 self self 1000 me /Users/paulequipo/.local/lib/equipo-runner/equipo-runner
+40100 1 40100 40100 900 me /usr/sbin/cfprefsd
+40200 1 40200 40200 950 me /usr/libexec/trustd
+40300 1 40300 40300 960 501 /bin/zsh
+`
+
+// sweepTurn begins a turn on tb (its table read as before), lets during
+// add what the turn starts, and leaves the turn unproven, so the next
+// take settles it with the sweep. It returns the signals sent.
+func sweepTurn(t *testing.T, tb *table, own *Own, during func(*Turn)) []int {
+ t.Helper()
+ turns := NewTurns("").Sweep(tb)
+ turns.own, turns.Settle = own, 300*time.Millisecond
+ u, err := turns.Take(context.Background(), OpEngineering)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := u.launch("attempt-s"); err != nil {
+ t.Fatal(err)
+ }
+ during(u)
+ u.unprovenEnd()
+ u.Give()
+ _ = turns.settle()
+ return tb.signalled()
+}
+
+func row(pid, ppid, pgid, sid int, start int64, uid int, marker string) ProcInfo {
+ return ProcInfo{ID: ProcID{PID: pid, Start: start}, PPID: ppid, PGID: pgid, SID: sid, UID: uid, Marker: marker}
+}
+
+// The runner and its own helpers are spared by identity (pid and start),
+// with what they start; a step's process running the same program is
+// not, nor a process that has a helper's pid but another start.
+func TestSweepSparesOwnByIdentityNotName(t *testing.T) {
+ me, self := os.Getuid(), os.Getpid()
+ tb := parseTable(t, turnBegan)
+ own := &Own{}
+ sig := sweepTurn(t, tb, own, func(*Turn) {
+ tb.add(row(50100, self, self, self, 2000, me, ""), "/usr/bin/git")
+ own.Add(ProcID{PID: 50100, Start: 2000})
+ tb.add(row(50101, 50100, self, self, 2001, me, ""), "/usr/libexec/git-core/git-remote-http")
+ tb.add(row(50200, 1, 50200, 50200, 2100, me, ""), "/usr/bin/git")
+ tb.add(row(50300, self, self, self, 2200, me, ""), "/usr/bin/xcrun")
+ })
+ for _, pid := range []int{self, 50100, 50101, 40100, 40200, 40300} {
+ if slices.Contains(sig, pid) || slices.Contains(sig, -pid) {
+ t.Fatalf("signalled %d, the runner's or from before the turn: %v", pid, sig)
+ }
+ }
+ for _, pid := range []int{50200, 50300} {
+ if !slices.Contains(sig, pid) {
+ t.Fatalf("%d (not the runner's, whatever its name) was spared: %v", pid, sig)
+ }
+ }
+ // A helper's pid used again by a step's process: another identity.
+ tb = parseTable(t, turnBegan)
+ own = &Own{}
+ sig = sweepTurn(t, tb, own, func(*Turn) {
+ own.Add(ProcID{PID: 50100, Start: 2000})
+ tb.add(row(50100, 1, 50100, 50100, 2500, me, ""), "/usr/bin/git")
+ })
+ if !slices.Contains(sig, 50100) {
+ t.Fatalf("a reused helper pid was spared: %v", sig)
+ }
+}
+
+// Each signal follows a fresh read of that process: a pid used again
+// between the table and the signal (here by another user's process with
+// a later start, or the same process that changed user) is never
+// signalled, nor its group.
+func TestSweepRechecksIdentityBeforeEachSignal(t *testing.T) {
+ me := os.Getuid()
+ tb := parseTable(t, turnBegan)
+ sig := sweepTurn(t, tb, &Own{}, func(u *Turn) {
+ tb.add(row(60100, 1, 60100, 60100, 3000, me, ""), "/Users/paulequipo/w/escape")
+ tb.add(row(60200, 1, 60200, 60200, 3010, me, "attempt-s"), "/Users/paulequipo/w/marked")
+ u.note(span{60200: 3010}, nil)
+ tb.add(row(60300, 1, 60300, 60300, 3020, me, ""), "/Users/paulequipo/w/setuid")
+ reused := map[int]bool{}
+ tb.lookup = func(tb *table, pid int) {
+ tb.mu.Lock()
+ defer tb.mu.Unlock()
+ if reused[pid] {
+ return
+ }
+ switch pid {
+ case 60100, 60200:
+ reused[pid] = true
+ tb.procs[pid] = row(pid, 1, pid, pid, 9000, 501, "")
+ tb.paths[pid] = "/bin/zsh"
+ case 60300:
+ reused[pid] = true
+ q := tb.procs[pid]
+ q.UID = 0
+ tb.procs[pid] = q
+ }
+ }
+ })
+ for _, pid := range []int{60100, -60100, 60200, -60200, 60300} {
+ if slices.Contains(sig, pid) {
+ t.Fatalf("signalled %d after it stopped being the process listed: %v", pid, sig)
+ }
+ }
+}
+
+// Another user's processes are never signalled, even started during the
+// turn, holding an id the attempt's group had, or showing its marker; a
+// group id of the attempt's now used by another user keeps the proof
+// waiting.
+func TestSweepNeverTouchesOtherUsers(t *testing.T) {
+ tb := parseTable(t, turnBegan)
+ var left []ProcInfo
+ sig := sweepTurn(t, tb, &Own{}, func(u *Turn) {
+ u.note(span{70300: 3900}, span{70300: 3900})
+ tb.add(row(70100, 1, 70100, 70100, 4000, 501, ""), "/Users/other/evil")
+ tb.add(row(70300, 1, 70300, 70300, 4100, 501, ""), "/bin/zsh")
+ tb.add(row(70400, 70300, 70300, 70300, 4200, 0, "attempt-s"), "/usr/bin/login")
+ s := newScope(tb, []string{"attempt-s"}, u.before())
+ s.Groups[70300] = 3900
+ list, _ := tb.List([]string{"attempt-s"})
+ left = s.Targets(list, nil)
+ if s.GroupsGone() {
+ t.Error("proof given while another user holds a group id the attempt made")
+ }
+ })
+ if len(left) != 0 || len(sig) != 0 {
+ t.Fatalf("another user's process was a target %v or signalled %v", left, sig)
+ }
+}
+
+// launchd's own agents (ppid 1, the kernel's path under /System or
+// /usr/libexec) are spared. A step that double-forked to launchd from
+// anywhere else is not: its own tree, a /System/Volumes path (every
+// user's data), a path that climbs out, an unknown path, a system path
+// whose parent is not launchd, or one in a session the attempt made.
+func TestSweepSystemAgentsByKernelPath(t *testing.T) {
+ me := os.Getuid()
+ tb := parseTable(t, turnBegan)
+ sig := sweepTurn(t, tb, &Own{}, func(u *Turn) {
+ u.note(nil, span{81000: 5000})
+ tb.add(row(80100, 1, 80100, 80100, 5100, me, ""), "/System/Library/PrivateFrameworks/X.framework/XPCServices/Y.xpc/Contents/MacOS/Y")
+ tb.add(row(80200, 1, 80200, 80200, 5200, me, ""), "/usr/libexec/xpcproxy")
+ tb.add(row(80300, 1, 80300, 80300, 5300, me, ""), "/Users/paulequipo/w/tree/.build/escape")
+ tb.add(row(80400, 1, 80400, 80400, 5400, me, ""), "/System/Volumes/Data/Users/paulequipo/escape")
+ tb.add(row(80500, 1, 80500, 80500, 5500, me, ""), "/System/Library/../../Users/paulequipo/escape")
+ tb.add(row(80600, 80300, 80600, 80600, 5600, me, ""), "/usr/libexec/xpcproxy")
+ tb.add(row(80700, 1, 80700, 80700, 5700, me, ""), "")
+ tb.add(row(80800, 1, 80800, 81000, 5800, me, ""), "/usr/libexec/xpcproxy")
+ tb.add(row(80900, 1, 80900, 80900, 5900, me, ""), "/system/Library/escape")
+ })
+ for _, pid := range []int{80100, 80200} {
+ if slices.Contains(sig, pid) {
+ t.Fatalf("a launchd system agent was signalled: %d in %v", pid, sig)
+ }
+ }
+ for _, pid := range []int{80300, 80400, 80500, 80600, 80700, 80800, 80900} {
+ // 80800 is in a session the attempt made: ended with its group.
+ if !slices.Contains(sig, pid) && !slices.Contains(sig, -pid) {
+ t.Fatalf("%d escaped the sweep: %v", pid, sig)
+ }
+ }
+}
+
+// The live proof waits for every group the attempt made: one its
+// process made (and that is gone) but whose id another user now holds
+// keeps the end unproven until that group ends too.
+func TestStopWaitsForEveryGroupItMade(t *testing.T) {
+ me := os.Getuid()
+ tb := parseTable(t, turnBegan)
+ x := &Executor{Procs: tb, Own: &Own{}, Grace: 50 * time.Millisecond, Settle: 400 * time.Millisecond, Poll: 10 * time.Millisecond}
+ var leader int
+ run, err := x.Start(context.Background(), Command{Argv: []string{"/bin/sleep", "0.3"}}, "attempt-g", func(id string) error {
+ if pgid, _, _ := parseRecord(id); pgid > 0 {
+ leader = pgid
+ tb.add(row(pgid, os.Getpid(), pgid, pgid, 6000, me, ""), "/bin/sleep")
+ tb.add(row(90000, pgid, 90000, pgid, 6001, me, ""), "/bin/bash")
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) {
+ run.mu.Lock()
+ _, made := run.scope.Groups[90000]
+ run.mu.Unlock()
+ if made {
+ break
+ }
+ }
+ <-run.Exited()
+ tb.mu.Lock()
+ delete(tb.procs, leader)
+ delete(tb.procs, 90000)
+ tb.procs[90000] = row(90000, 1, 90000, 90000, 7000, 501, "")
+ tb.mu.Unlock()
+ if run.Stop() {
+ t.Fatal("proven while a group the attempt made is held by another user")
+ }
+ if slices.Contains(tb.signalled(), 90000) || slices.Contains(tb.signalled(), -90000) {
+ t.Fatal("the other user's group was signalled")
+ }
+}
diff --git a/internal/runner/mac/turns.go b/internal/runner/mac/turns.go
new file mode 100644
index 00000000..48596480
--- /dev/null
+++ b/internal/runner/mac/turns.go
@@ -0,0 +1,647 @@
+package mac
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "io/fs"
+ "os"
+ "slices"
+ "sync"
+ "syscall"
+ "time"
+)
+
+// Op is what a turn is for. Every operation that runs repository code,
+// runs Xcode or has a model token in a process takes the Mac's one turn
+// for its own life and no longer (spec §8.3 item 4); what it starts
+// itself (Xcode under Engineering, a simulator under a check) is its.
+type Op string
+
+const (
+ OpCheck Op = "check"
+ OpEngineering Op = "engineering"
+ OpAsk Op = "ask"
+ OpProbe Op = "probe"
+ OpTokenCheck Op = "token_check"
+ OpSignIn Op = "sign_in"
+ OpTokenStore Op = "token_store"
+ OpWarm Op = "warm"
+ // OpRecover settles what an earlier operation left (Verify).
+ OpRecover Op = "recover"
+)
+
+// ErrNoTurn refuses a start outside a turn of the Mac's Turns.
+var ErrNoTurn = errors.New("mac: no turn held")
+
+// ErrUnsettled refuses a turn while an earlier one's processes may
+// still be running (its end not proven), or while another live runner
+// process left a turn record.
+var ErrUnsettled = errors.New("mac: an earlier turn is not settled")
+
+// ErrPendingCleanup refuses a sandboxed run while another attempt's
+// user-temp cleanup is unfinished and not this turn's to finish.
+var ErrPendingCleanup = errors.New("mac: another attempt's cleanup is pending")
+
+// Turns is the Mac's one machine lock, across the runner's processes (a
+// channel within a process, an flock on a file in the state dir, which
+// no profile lets a sandboxed command reach, between them). Beside the
+// lock it keeps two durable records:
+//
+// - lock+".turn": the turn now (or the last one whose end was not
+// proven): its operation, the runner process that took it, the
+// runner user's processes when it began (the sweep's "before"), and
+// the markers, groups and sessions of what it started. A later turn
+// settles it before it begins; a restart does the same.
+// - lock+".pending": a sandboxed attempt's user-temp cleanup not yet
+// done, owned by the turn that wrote it: only that attempt (its run,
+// or its proof later in the same runner) or a restart may finish it.
+type Turns struct {
+ ch chan struct{}
+ lock string
+ f *os.File
+ // sweep is the table every turn sweeps the runner user with at its
+ // end (MachineProcs on a Mac); nil: no runner-user sweep.
+ sweep Procs
+ // own is the runner's own processes (runnerOwn; tests stand in).
+ own *Own
+ // Settle bounds settling an earlier turn (30 s).
+ Settle time.Duration
+ // mem is the turn record without a lock file (one process).
+ mu sync.Mutex
+ mem *turnRecord
+}
+
+// NewTurns makes the runner's one turn; lock is its file in the state
+// dir ("" keeps the turn, and its record, within this process).
+func NewTurns(lock string) *Turns { return &Turns{ch: make(chan struct{}, 1), lock: lock} }
+
+// Sweep makes every turn sweep the runner user with p at its end: a
+// Mac's turns (MachineProcs). A table that may not sweep (Linux outside
+// a test's scope) makes every turn fail to begin; nil sweeps nothing.
+func (t *Turns) Sweep(p Procs) *Turns {
+ t.sweep = p
+ return t
+}
+
+func (t *Turns) owned() *Own {
+ if t != nil && t.own != nil {
+ return t.own
+ }
+ return runnerOwn
+}
+
+// table is the process table the turns' records are read with.
+func (t *Turns) table() Procs {
+ if t != nil && t.sweep != nil {
+ return t.sweep
+ }
+ return platformProcs
+}
+
+// Turn is one operation's hold on the Mac.
+type Turn struct {
+ t *Turns
+ ID string
+ Op Op
+
+ mu sync.Mutex
+ rec turnRecord
+ adopted []string
+ unproven bool
+ gave sync.Once
+ given bool
+}
+
+// turnRecord is a turn on disk (lock+".turn").
+type turnRecord struct {
+ ID string `json:"id"`
+ Op Op `json:"op"`
+ Runner ProcID `json:"runner"`
+ // Sweep: Before is the runner user's table when the turn began.
+ Sweep bool `json:"sweep"`
+ Before []ProcID `json:"before,omitempty"`
+ Markers []string `json:"markers,omitempty"`
+ Groups span `json:"groups,omitempty"`
+ Sessions span `json:"sessions,omitempty"`
+}
+
+// Take waits for the turn and begins op: an earlier turn left unsettled
+// is settled first (or the take fails: ErrUnsettled), the runner user's
+// table is read for the sweep, and the record is written before Take
+// returns. Give it back with Give.
+func (t *Turns) Take(ctx context.Context, op Op) (*Turn, error) {
+ if err := t.acquire(ctx); err != nil {
+ return nil, err
+ }
+ u, err := t.begin(op)
+ if err != nil {
+ t.release()
+ return nil, err
+ }
+ return u, nil
+}
+
+// TryTake takes the turn for op only if it is free now (in this process
+// and the others) and begins; ok is false otherwise.
+func (t *Turns) TryTake(op Op) (*Turn, bool) {
+ if !t.tryAcquire() {
+ return nil, false
+ }
+ u, err := t.begin(op)
+ if err != nil {
+ t.release()
+ return nil, false
+ }
+ return u, true
+}
+
+// Hold is op's turn in ctx: the one ctx already holds (what an
+// operation starts itself is its own: the probe run's gates), else a
+// new one, waited for, given back by give. On a nil Turns it holds
+// nothing (the test build's fake worker).
+func (t *Turns) Hold(ctx context.Context, op Op) (context.Context, func(), error) {
+ if t == nil {
+ return ctx, func() {}, nil
+ }
+ if HeldTurn(ctx, t) != nil {
+ return ctx, func() {}, nil
+ }
+ u, err := t.Take(ctx, op)
+ if err != nil {
+ return ctx, func() {}, err
+ }
+ return u.Context(ctx), u.Give, nil
+}
+
+type turnKey struct{ t *Turns }
+
+// Context carries the turn to what the operation starts.
+func (u *Turn) Context(ctx context.Context) context.Context {
+ return context.WithValue(ctx, turnKey{u.t}, u)
+}
+
+// HeldTurn is the turn of t that ctx holds, nil when none (or given).
+func HeldTurn(ctx context.Context, t *Turns) *Turn {
+ if t == nil || ctx == nil {
+ return nil
+ }
+ u, _ := ctx.Value(turnKey{t}).(*Turn)
+ if u == nil {
+ return nil
+ }
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ if u.given {
+ return nil
+ }
+ return u
+}
+
+// Give ends the turn. Its record goes only when every launch in it was
+// proven ended; otherwise it stays, and the next turn (in any runner
+// process) settles it before it begins.
+func (u *Turn) Give() {
+ u.gave.Do(func() {
+ u.mu.Lock()
+ u.given = true
+ keep := u.unproven
+ u.mu.Unlock()
+ if !keep {
+ _ = u.t.dropTurn(u.ID)
+ }
+ u.t.release()
+ })
+}
+
+// Before is the runner user's table when the turn began (nil: no sweep).
+func (u *Turn) before() []ProcID {
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ if !u.rec.Sweep {
+ return nil
+ }
+ return slices.Clone(u.rec.Before)
+}
+
+// launch puts an attempt's marker on the turn's record before anything
+// of it starts.
+func (u *Turn) launch(marker string) error {
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ if !slices.Contains(u.rec.Markers, marker) {
+ u.rec.Markers = append(u.rec.Markers, marker)
+ }
+ return u.t.saveTurn(u.rec)
+}
+
+// note adds groups and sessions an attempt made to the record (best
+// effort: the record before the start has the marker and the table).
+func (u *Turn) note(groups, sessions span) {
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ grew := false
+ for _, m := range []struct {
+ to *span
+ from span
+ }{{&u.rec.Groups, groups}, {&u.rec.Sessions, sessions}} {
+ if *m.to == nil {
+ *m.to = span{}
+ }
+ for id, at := range m.from {
+ if _, ok := (*m.to)[id]; !ok {
+ (*m.to)[id] = at
+ grew = true
+ }
+ }
+ }
+ if grew {
+ _ = u.t.saveTurn(u.rec)
+ }
+}
+
+// unprovenEnd keeps the record past Give: a launch's end is not proven.
+func (u *Turn) unprovenEnd() {
+ u.mu.Lock()
+ u.unproven = true
+ u.mu.Unlock()
+}
+
+// owns: the attempt was launched in this turn, or the turn settles it
+// (Verify's recovery turn).
+func (u *Turn) owns(attempt string) bool {
+ if u == nil {
+ return false
+ }
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ return slices.Contains(u.rec.Markers, attempt) || slices.Contains(u.adopted, attempt)
+}
+
+func (u *Turn) adopt(attempt string) {
+ u.mu.Lock()
+ u.adopted = append(u.adopted, attempt)
+ u.mu.Unlock()
+}
+
+func (t *Turns) begin(op Op) (*Turn, error) {
+ if err := t.settle(); err != nil {
+ return nil, err
+ }
+ var raw [8]byte
+ _, _ = rand.Read(raw[:])
+ rec := turnRecord{ID: hex.EncodeToString(raw[:]), Op: op, Runner: selfID()}
+ if t.sweep != nil {
+ if !t.sweep.Sweeps() {
+ return nil, ErrNoSweep
+ }
+ list, _, err := t.owned().Snapshot(t.sweep, nil)
+ if err != nil {
+ return nil, err
+ }
+ rec.Sweep = true
+ rec.Before = make([]ProcID, 0, len(list))
+ for _, q := range list {
+ rec.Before = append(rec.Before, q.ID)
+ }
+ }
+ if err := t.saveTurn(rec); err != nil {
+ return nil, err
+ }
+ return &Turn{t: t, ID: rec.ID, Op: op, rec: rec}, nil
+}
+
+// settle ends what an earlier turn left: every process of its scope
+// (its seen groups and sessions, its markers and, if it swept, every
+// process of the runner user that did not exist when it began, but for
+// this runner's own and launchd's system agents) killed, checked again
+// before each signal, until none is left within Settle. A record of
+// another live runner process is never settled from here.
+func (t *Turns) settle() error {
+ rec, ok, err := t.loadTurn()
+ if err != nil || !ok {
+ return err
+ }
+ if rec.Runner != selfID() && alive(rec.Runner) {
+ return ErrUnsettled
+ }
+ procs := t.table()
+ if rec.Sweep && (t.sweep == nil || !t.sweep.Sweeps()) {
+ return ErrUnsettled
+ }
+ var before []ProcID
+ if rec.Sweep {
+ before = rec.Before
+ if before == nil {
+ before = []ProcID{}
+ }
+ }
+ s := newScope(procs, rec.Markers, before)
+ for id, at := range rec.Groups {
+ s.Groups[id] = at
+ }
+ for id, at := range rec.Sessions {
+ s.Sessions[id] = at
+ }
+ limit := t.Settle
+ if limit <= 0 {
+ limit = 30 * time.Second
+ }
+ deadline := time.Now().Add(limit)
+ for {
+ list, own, err := t.owned().Snapshot(procs, rec.Markers)
+ if err == nil {
+ left := s.Targets(list, own)
+ if len(left) == 0 {
+ return t.dropTurn(rec.ID)
+ }
+ s.Kill(left, syscall.SIGKILL)
+ }
+ if time.Now().After(deadline) {
+ return ErrUnsettled
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+}
+
+// unsettledFor: the stored turn record names attempt (its leftovers are
+// not settled yet).
+func (t *Turns) unsettledFor(attempt string) bool {
+ rec, ok, err := t.loadTurn()
+ return err != nil || ok && slices.Contains(rec.Markers, attempt)
+}
+
+func (t *Turns) acquire(ctx context.Context) error {
+ select {
+ case t.ch <- struct{}{}:
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ if t.lock == "" {
+ return nil
+ }
+ f, err := os.OpenFile(t.lock, os.O_CREATE|os.O_RDWR, 0600)
+ if err != nil {
+ <-t.ch
+ return err
+ }
+ for {
+ err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
+ if err == nil {
+ t.f = f
+ return nil
+ }
+ if !errors.Is(err, syscall.EWOULDBLOCK) {
+ f.Close()
+ <-t.ch
+ return err
+ }
+ select {
+ case <-ctx.Done():
+ f.Close()
+ <-t.ch
+ return ctx.Err()
+ case <-time.After(250 * time.Millisecond):
+ }
+ }
+}
+
+func (t *Turns) tryAcquire() bool {
+ select {
+ case t.ch <- struct{}{}:
+ default:
+ return false
+ }
+ if t.lock == "" {
+ return true
+ }
+ f, err := os.OpenFile(t.lock, os.O_CREATE|os.O_RDWR, 0600)
+ if err == nil {
+ if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err == nil {
+ t.f = f
+ return true
+ }
+ f.Close()
+ }
+ <-t.ch
+ return false
+}
+
+func (t *Turns) release() {
+ if t.f != nil {
+ _ = syscall.Flock(int(t.f.Fd()), syscall.LOCK_UN)
+ t.f.Close()
+ t.f = nil
+ }
+ <-t.ch
+}
+
+func (t *Turns) turnFile() string {
+ if t.lock == "" {
+ return ""
+ }
+ return t.lock + ".turn"
+}
+
+func (t *Turns) saveTurn(rec turnRecord) error {
+ p := t.turnFile()
+ if p == "" {
+ t.mu.Lock()
+ c := rec
+ c.Before, c.Markers = slices.Clone(rec.Before), slices.Clone(rec.Markers)
+ c.Groups, c.Sessions = cloneSpan(rec.Groups), cloneSpan(rec.Sessions)
+ t.mem = &c
+ t.mu.Unlock()
+ return nil
+ }
+ raw, err := json.Marshal(rec)
+ if err != nil {
+ return err
+ }
+ return writeDurably(p, raw)
+}
+
+func (t *Turns) loadTurn() (turnRecord, bool, error) {
+ p := t.turnFile()
+ if p == "" {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if t.mem == nil {
+ return turnRecord{}, false, nil
+ }
+ return *t.mem, true, nil
+ }
+ raw, err := os.ReadFile(p)
+ if errors.Is(err, fs.ErrNotExist) {
+ return turnRecord{}, false, nil
+ }
+ if err != nil {
+ return turnRecord{}, false, err
+ }
+ var rec turnRecord
+ if err := json.Unmarshal(raw, &rec); err != nil || rec.ID == "" {
+ return turnRecord{}, false, errors.Join(ErrUnsettled, errors.New("mac: unreadable turn record"), err)
+ }
+ return rec, true, nil
+}
+
+// dropTurn removes the stored record if it is still id's.
+func (t *Turns) dropTurn(id string) error {
+ rec, ok, err := t.loadTurn()
+ if err != nil || !ok || rec.ID != id {
+ return err
+ }
+ if p := t.turnFile(); p != "" {
+ if err := os.Remove(p); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ return err
+ }
+ return nil
+ }
+ t.mu.Lock()
+ t.mem = nil
+ t.mu.Unlock()
+ return nil
+}
+
+func cloneSpan(s span) span {
+ if s == nil {
+ return nil
+ }
+ c := span{}
+ for k, v := range s {
+ c[k] = v
+ }
+ return c
+}
+
+// writeDurably writes raw beside p, syncs it and renames it over p.
+func writeDurably(p string, raw []byte) error {
+ f, err := os.OpenFile(p+".new", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
+ if err != nil {
+ return err
+ }
+ _, err = f.Write(raw)
+ if serr := f.Sync(); err == nil {
+ err = serr
+ }
+ if cerr := f.Close(); err == nil {
+ err = cerr
+ }
+ if err != nil {
+ return err
+ }
+ return os.Rename(p+".new", p)
+}
+
+var self struct {
+ once sync.Once
+ id ProcID
+}
+
+// selfID is this runner process's identity.
+func selfID() ProcID {
+ self.once.Do(func() {
+ if q, ok := platformProcs.Lookup(os.Getpid()); ok {
+ self.id = q.ID
+ } else {
+ self.id = ProcID{PID: os.Getpid()}
+ }
+ })
+ return self.id
+}
+
+// alive: the process id names is still running (same pid, same start).
+func alive(id ProcID) bool {
+ if id.PID <= 0 {
+ return false
+ }
+ q, ok := platformProcs.Lookup(id.PID)
+ return ok && q.ID == id
+}
+
+func (t *Turns) pending() string {
+ if t == nil || t.lock == "" {
+ return ""
+ }
+ return t.lock + ".pending"
+}
+
+// pendingRecord is a sandboxed attempt whose T cleanup is not done yet:
+// written before anything of the attempt starts (and again with its
+// group once there is one), removed only once its end is proven and T
+// is cleaned. Runner is the runner process whose turn wrote it: only
+// that attempt in that process, or a later process once it is gone (a
+// restart), may finish it.
+type pendingRecord struct {
+ Attempt string `json:"attempt"`
+ PGID int `json:"pgid"`
+ Before tempListing `json:"before"`
+ Runner ProcID `json:"runner"`
+}
+
+// writePending records r durably. Without a lock file (tests) there is
+// nowhere to keep it.
+func (t *Turns) writePending(r pendingRecord) error {
+ p := t.pending()
+ if p == "" {
+ return nil
+ }
+ raw, err := json.Marshal(r)
+ if err != nil {
+ return err
+ }
+ return writeDurably(p, raw)
+}
+
+// readPending is the record an earlier attempt left; ok is false when
+// there is none. One that cannot be read is an error: nothing runs
+// until a person looks.
+func (t *Turns) readPending() (r pendingRecord, ok bool, err error) {
+ p := t.pending()
+ if p == "" {
+ return r, false, nil
+ }
+ raw, err := os.ReadFile(p)
+ if errors.Is(err, fs.ErrNotExist) {
+ return r, false, nil
+ }
+ if err != nil {
+ return r, false, err
+ }
+ if err := json.Unmarshal(raw, &r); err != nil || r.Attempt == "" || r.Before == nil {
+ return r, false, errors.Join(ErrUserTemp, errors.New("mac: unreadable pending cleanup"), err)
+ }
+ return r, true, nil
+}
+
+// mayFinish: u may finish r. Its owner: the attempt, in the runner
+// process that wrote it (the run itself, or its proof later). A restart:
+// the process that wrote it is gone (or was older than the owner field).
+// Never another turn of a live owner.
+func (t *Turns) mayFinish(u *Turn, r pendingRecord) bool {
+ if r.Runner.PID == 0 || !alive(r.Runner) {
+ return true
+ }
+ return r.Runner == selfID() && u.owns(r.Attempt)
+}
+
+// dropPending removes the record once its cleanup is done.
+func (t *Turns) dropPending() error {
+ p := t.pending()
+ if p == "" {
+ return nil
+ }
+ if err := os.Remove(p); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ return err
+ }
+ return nil
+}
+
+// Pending reports whether an attempt's cleanup is still to be done
+// (the warm waits for it: that attempt's end is not proven yet).
+func (t *Turns) Pending() bool {
+ _, err := os.Lstat(t.pending())
+ return t.pending() != "" && err == nil
+}
diff --git a/internal/runner/mac/usertemp.go b/internal/runner/mac/usertemp.go
index f2bd0091..351226d6 100644
--- a/internal/runner/mac/usertemp.go
+++ b/internal/runner/mac/usertemp.go
@@ -2,14 +2,12 @@ package mac
import (
"context"
- "encoding/json"
"errors"
"io/fs"
"os"
"path/filepath"
"strings"
"syscall"
- "time"
)
// The runner user's DARWIN_USER_TEMP_DIR ("T"). Xcode writes there
@@ -265,177 +263,3 @@ func unlock(dir *os.Root, name string, depth int) error {
}
return nil
}
-
-// Turns lets one gate run at a time on a Mac, across the runner's
-// processes (the worker and the probe command): a channel within a
-// process and an flock on a file in the state dir, which no checks
-// profile lets a gate reach, between them. A sandboxed attempt's T
-// cleanup removes what appeared in T while it ran, so nothing else of
-// the runner's may run beside it. It also keeps a cleanup that did not
-// finish (lock + ".pending": what T held before, as JSON): until a later
-// one finishes it, no sandboxed gate runs.
-type Turns struct {
- ch chan struct{}
- lock string
- f *os.File
-}
-
-// NewTurns makes the runner's one turn; lock is its file in the state
-// dir ("" keeps the turn within this process).
-func NewTurns(lock string) *Turns { return &Turns{ch: make(chan struct{}, 1), lock: lock} }
-
-func (t *Turns) take(ctx context.Context) error {
- select {
- case t.ch <- struct{}{}:
- case <-ctx.Done():
- return ctx.Err()
- }
- if t.lock == "" {
- return nil
- }
- f, err := os.OpenFile(t.lock, os.O_CREATE|os.O_RDWR, 0600)
- if err != nil {
- <-t.ch
- return err
- }
- for {
- err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
- if err == nil {
- t.f = f
- return nil
- }
- if !errors.Is(err, syscall.EWOULDBLOCK) {
- f.Close()
- <-t.ch
- return err
- }
- select {
- case <-ctx.Done():
- f.Close()
- <-t.ch
- return ctx.Err()
- case <-time.After(250 * time.Millisecond):
- }
- }
-}
-
-// TryTake takes the turn only if it is free now (in this process and
-// the others); Give gives it back.
-func (t *Turns) TryTake() bool {
- select {
- case t.ch <- struct{}{}:
- default:
- return false
- }
- if t.lock == "" {
- return true
- }
- f, err := os.OpenFile(t.lock, os.O_CREATE|os.O_RDWR, 0600)
- if err == nil {
- if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err == nil {
- t.f = f
- return true
- }
- f.Close()
- }
- <-t.ch
- return false
-}
-
-// Give gives the turn back.
-func (t *Turns) Give() { t.give() }
-
-func (t *Turns) give() {
- if t.f != nil {
- _ = syscall.Flock(int(t.f.Fd()), syscall.LOCK_UN)
- t.f.Close()
- t.f = nil
- }
- <-t.ch
-}
-
-func (t *Turns) pending() string {
- if t == nil || t.lock == "" {
- return ""
- }
- return t.lock + ".pending"
-}
-
-// pendingRecord is a sandboxed attempt whose T cleanup is not done yet:
-// written before anything of the attempt starts (and again with its
-// group once there is one), removed only once its end is proven and T
-// is cleaned. A runner killed meanwhile leaves it for the next gate,
-// in any runner process.
-type pendingRecord struct {
- Attempt string `json:"attempt"`
- PGID int `json:"pgid"`
- Before tempListing `json:"before"`
-}
-
-// writePending records r durably (written beside, then renamed over).
-// Without a lock file (tests) there is nowhere to keep it.
-func (t *Turns) writePending(r pendingRecord) error {
- p := t.pending()
- if p == "" {
- return nil
- }
- raw, err := json.Marshal(r)
- if err != nil {
- return err
- }
- f, err := os.OpenFile(p+".new", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
- if err != nil {
- return err
- }
- _, err = f.Write(raw)
- if serr := f.Sync(); err == nil {
- err = serr
- }
- if cerr := f.Close(); err == nil {
- err = cerr
- }
- if err != nil {
- return err
- }
- return os.Rename(p+".new", p)
-}
-
-// readPending is the record an earlier attempt left; ok is false when
-// there is none. One that cannot be read is an error: nothing runs
-// until a person looks.
-func (t *Turns) readPending() (r pendingRecord, ok bool, err error) {
- p := t.pending()
- if p == "" {
- return r, false, nil
- }
- raw, err := os.ReadFile(p)
- if errors.Is(err, fs.ErrNotExist) {
- return r, false, nil
- }
- if err != nil {
- return r, false, err
- }
- if err := json.Unmarshal(raw, &r); err != nil || r.Attempt == "" || r.Before == nil {
- return r, false, errors.Join(ErrUserTemp, errors.New("mac: unreadable pending cleanup"), err)
- }
- return r, true, nil
-}
-
-// dropPending removes the record once its cleanup is done.
-func (t *Turns) dropPending() error {
- p := t.pending()
- if p == "" {
- return nil
- }
- if err := os.Remove(p); err != nil && !errors.Is(err, fs.ErrNotExist) {
- return err
- }
- return nil
-}
-
-// Pending reports whether an attempt's cleanup is still to be done
-// (the warm waits for it: that attempt's end is not proven yet).
-func (t *Turns) Pending() bool {
- _, err := os.Lstat(t.pending())
- return t.pending() != "" && err == nil
-}
diff --git a/internal/runner/mac/usertemp_test.go b/internal/runner/mac/usertemp_test.go
index 40117677..6259fb00 100644
--- a/internal/runner/mac/usertemp_test.go
+++ b/internal/runner/mac/usertemp_test.go
@@ -157,38 +157,52 @@ func TestGateCleanupKeepsASwappedTemporaryItemsTarget(t *testing.T) {
}
// A run whose end is not proven may still be writing T: nothing is
-// removed then.
+// removed then; by that attempt's own proof (Verify), never by the next
+// gate's turn.
func TestGateCleanupWaitsForTheProvenEnd(t *testing.T) {
g, dir := gateFixture(t, true)
_, temp := userTempFixture(t)
g.UserTemp, g.Settle, g.Turns = temp, 500*time.Millisecond, NewTurns(filepath.Join(t.TempDir(), "lock"))
- g.find = func(string) ([]Proc, error) { return []Proc{{PID: 1 << 30, PGID: 1 << 30}}, nil }
+ g.procs = withPhantom()
quieted := 0
g.QuietSimulators = func(context.Context) { quieted++ }
- res, _ := run(g, dir, "checks-t-3", time.Minute, `touch `+quote(filepath.Join(temp, "late")))
+ res, id := run(g, dir, "checks-t-3", time.Minute, `touch `+quote(filepath.Join(temp, "late")))
if res.Terminated || !exists(filepath.Join(temp, "late")) || quieted != 0 {
t.Fatalf("cleaned before the end was proven: %+v", res)
}
- // The next gate finishes that cleanup before anything of its own runs.
- g.find = nil
- res, _ = run(g, dir, "checks-t-3b", time.Minute, `ls `+quote(temp)+`; touch `+quote(filepath.Join(temp, "next")))
- if !res.Terminated || strings.Contains(res.Output, "late") || exists(filepath.Join(temp, "late")) || exists(filepath.Join(temp, "next")) || exists(g.Turns.pending()) {
- t.Fatalf("the left cleanup was not finished first: %+v", res)
+ // The next gate's turn neither finishes it nor runs.
+ g.procs = nil
+ if res, _ := run(g, dir, "checks-t-3b", time.Minute, `touch `+quote(filepath.Join(temp, "next"))); res.Reason != "checks_unavailable" || exists(filepath.Join(temp, "next")) || !exists(filepath.Join(temp, "late")) || !g.Turns.Pending() {
+ t.Fatalf("another turn finished or ran past the cleanup: %+v", res)
+ }
+ // Its own proof finishes it; then gates run again.
+ if !g.Verify(id) || exists(filepath.Join(temp, "late")) || g.Turns.Pending() {
+ t.Fatal("the attempt's proof did not finish its cleanup")
+ }
+ res, _ = run(g, dir, "checks-t-3c", time.Minute, `ls `+quote(temp)+`; touch `+quote(filepath.Join(temp, "next")))
+ if !res.Terminated || strings.Contains(res.Output, "late") || exists(filepath.Join(temp, "next")) || exists(g.Turns.pending()) {
+ t.Fatalf("not run, or not cleaned, after the proof: %+v", res)
}
// One that cannot be finished (T is no longer a folder of this
- // user's): nothing runs.
- g.find = func(string) ([]Proc, error) { return []Proc{{PID: 1 << 30, PGID: 1 << 30}}, nil }
- run(g, dir, "checks-t-3c", time.Minute, `true`)
- g.find = nil
+ // user's): its proof says not over, and nothing runs.
+ g.procs = withPhantom()
+ _, id = run(g, dir, "checks-t-3d", time.Minute, `true`)
+ g.procs = nil
if err := os.Chmod(temp, 0755); err != nil {
t.Fatal(err)
}
- if res, _ := run(g, dir, "checks-t-3d", time.Minute, `touch `+quote(filepath.Join(temp, "ran"))); res.Reason != "checks_unavailable" || exists(filepath.Join(temp, "ran")) {
+ if g.Verify(id) {
+ t.Fatal("proven over with its cleanup not done")
+ }
+ if res, _ := run(g, dir, "checks-t-3e", time.Minute, `touch `+quote(filepath.Join(temp, "ran"))); res.Reason != "checks_unavailable" || exists(filepath.Join(temp, "ran")) {
t.Fatalf("ran with a cleanup left that cannot be finished: %+v", res)
}
if err := os.Chmod(temp, 0700); err != nil {
t.Fatal(err)
}
+ if !g.Verify(id) || g.Turns.Pending() {
+ t.Fatal("the cleanup was not finished once it could be")
+ }
// A T that cannot be listed: nothing runs.
g.UserTemp = filepath.Join(temp, "gone")
if res, _ := run(g, dir, "checks-t-4", time.Minute, `touch `+quote(filepath.Join(temp, "ran"))); res.Reason != "checks_unavailable" || exists(filepath.Join(temp, "ran")) {
@@ -230,16 +244,17 @@ func TestGatesTakeTurns(t *testing.T) {
if len(lines) != 4 || strings.TrimSuffix(lines[0], "-start") != strings.TrimSuffix(lines[1], "-end") {
t.Fatalf("gates overlapped: %v", lines)
}
- if err := turns.take(context.Background()); err != nil {
+ held, err := turns.Take(context.Background(), OpEngineering)
+ if err != nil {
t.Fatal(err)
}
- if b.Turns.TryTake() {
+ if _, ok := b.Turns.TryTake(OpWarm); ok {
t.Fatal("TryTake while another holds the turn")
}
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
res := b.Run(ctx, "checks-turn-c", dirB, []string{"/bin/sh", "-c", "touch " + quote(log+".c")}, time.Minute, func(string) error { return nil })
- turns.give()
+ held.Give()
if res.Reason != "cancelled" || !res.Terminated || exists(log+".c") {
t.Fatalf("ran without its turn: %+v", res)
}
@@ -329,18 +344,13 @@ func TestGatePendingCleanupSurvivesTheRunner(t *testing.T) {
t.Fatal(err)
}
// Still running (a process with its marker): nothing runs, nothing goes.
- g.find = func(a string) ([]Proc, error) {
- if a == "checks-dead" {
- return []Proc{{PID: 1 << 30, PGID: 1 << 30}}, nil
- }
- return nil, nil
- }
+ g.procs = withPhantom("checks-dead")
ran := filepath.Join(t.TempDir(), "ran")
if res, _ := run(g, dir, "checks-p-1", time.Minute, `touch `+quote(ran)); res.Reason != "checks_unavailable" || exists(ran) || !exists(filepath.Join(temp, "leftover")) {
t.Fatalf("ran beside an unproven attempt: %+v", res)
}
// Over: its leftovers go before the next gate runs, and the record.
- g.find = func(string) ([]Proc, error) { return nil, nil }
+ g.procs = nil
quieted := 0
g.QuietSimulators = func(context.Context) { quieted++ }
res, _ := run(g, dir, "checks-p-2", time.Minute, `ls `+quote(temp))
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go
index 4eab1f44..18462a8b 100644
--- a/internal/runner/thin/mac.go
+++ b/internal/runner/thin/mac.go
@@ -35,6 +35,10 @@ import (
// macGate adapts a Mac gate to the worker's GateRunner.
type macGate struct{ g *mac.Gate }
+// A Mac launch of the pinned CLI goes through the same starter as a
+// Linux one (recordedStart).
+var _ starter = (*mac.Starter)(nil)
+
func (m macGate) Sandbox() string { return m.g.Sandbox }
func (m macGate) Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(string) error) gateResult {
@@ -111,8 +115,10 @@ func unsandboxedChosen(ctx context.Context) bool {
return chosen
}
-// Verify settles a recorded attempt the same way whatever confined it.
-func (m *macChecks) Verify(id string) bool { return m.bare.Verify(id) }
+// Verify settles a recorded attempt the same way whatever confined it,
+// with the user temp, so the attempt's own unfinished cleanup is
+// finished once its end is proven.
+func (m *macChecks) Verify(id string) bool { return m.sandboxed.Verify(id) }
// macTaint is sticky: set once a check ran outside the sandbox, kept in
// the state dir and by the instance (which says so in every welcome), so
@@ -454,11 +460,15 @@ func (h *macHost) warm(ctx context.Context, x wire.Xcode) {
defer h.warmMu.Unlock()
// Not while a gate runs (its T cleanup could take what the warm
// writes there): the next gathering tries again, as after a failure.
- if h.warmed == key || h.turns != nil && !h.turns.TryTake() {
+ if h.warmed == key {
return
}
if h.turns != nil {
- defer h.turns.Give()
+ turn, ok := h.turns.TryTake(mac.OpWarm)
+ if !ok {
+ return
+ }
+ defer turn.Give()
// Nor while an earlier attempt's end is unproven (its cleanup
// pending): the next gate settles that first.
if h.turns.Pending() {
@@ -534,7 +544,14 @@ func (h *macHost) run(ctx context.Context, name string, args ...string) (string,
ownGroup(cmd)
cmd.WaitDelay = commandWaitDelay
done := h.watchSlow(name, args)
- out, err := cmd.Output()
+ // The runner's own helper (mac.StartOwn): a turn's sweep spares it.
+ var buf strings.Builder
+ cmd.Stdout = &buf
+ err := mac.StartOwn(cmd)
+ if err == nil {
+ err = cmd.Wait()
+ }
+ out := buf.String()
if errors.Is(err, exec.ErrWaitDelay) {
// The command itself exited successfully; only something it left
// behind in its group still held the pipe. That goes, and what
@@ -546,7 +563,7 @@ func (h *macHost) run(ctx context.Context, name string, args ...string) (string,
}
}
done(err)
- return string(out), err
+ return out, err
}
// watchSlow warns when a command is still running after slowCommand,
@@ -655,9 +672,14 @@ func newMacHost(c runner.Config, o Options) (h *macHost, err error) {
h.tools = macTools(h.paths.InstallDir, home, getenv)
h.fetchClaude = mac.OfficialClaude(getenv)
h.env = []string{"HOME=" + home, "PATH=" + gatePath(h.tools), "CI=1", "LANG=en_US.UTF-8"}
- // One turn for every gate and the warm, across this user's runner
- // processes (the worker and the probe command).
+ // One turn for every operation (a gate, a probe run, the warm, and
+ // Engineering, asks and token operations), across this user's runner
+ // processes. On a Mac each turn's end also sweeps the runner user
+ // (spec §8.8); off a Mac there is no such table and nothing sweeps.
h.turns = mac.NewTurns(filepath.Join(c.StateDir, "mac-gate.lock"))
+ if p := mac.MachineProcs(); p != nil {
+ h.turns.Sweep(p)
+ }
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
if out, err := h.logged(slog.LevelInfo)(ctx, "/usr/bin/xcode-select", "-p"); err == nil && filepath.IsAbs(strings.TrimSpace(out)) {
h.env = append(h.env, "DEVELOPER_DIR="+strings.TrimSpace(out))
@@ -786,7 +808,7 @@ func (h *macHost) warmNow(ctx context.Context) {
}
func (h *macHost) probeHost(version string, gate func(string, string) *mac.Gate) mac.ProbeHost {
- return mac.ProbeHost{Exec: h.run, Tools: h.tools, Paths: h.paths, Scratch: filepath.Join(h.scratch, "probes"), UID: os.Getuid(), Version: version,
+ return mac.ProbeHost{Exec: h.run, Tools: h.tools, Paths: h.paths, Scratch: filepath.Join(h.scratch, "probes"), UID: os.Getuid(), Version: version, Turns: h.turns,
Gate: func(sandboxed bool) *mac.Gate {
if sandboxed {
return gate(h.tools.SRT, wire.SandboxSeatbelt)
diff --git a/internal/runner/thin/mac_test.go b/internal/runner/thin/mac_test.go
index 73f1a251..1f45ce98 100644
--- a/internal/runner/thin/mac_test.go
+++ b/internal/runner/thin/mac_test.go
@@ -342,11 +342,12 @@ func TestMacWarmsThePluginCacheOncePerXcode(t *testing.T) {
h := &macHost{tools: mac.Tools{Xcodebuild: xb}, turns: mac.NewTurns(filepath.Join(dir, "lock"))}
b52, b60 := wire.Xcode{Version: "27.2", Build: "27B52"}, wire.Xcode{Version: "27.2", Build: "27B60"}
other := mac.NewTurns(filepath.Join(dir, "lock"))
- if !other.TryTake() {
+ turn, ok := other.TryTake(mac.OpCheck)
+ if !ok {
t.Fatal("turn")
}
h.warm(context.Background(), b52)
- other.Give()
+ turn.Give()
// Nor while an earlier attempt's cleanup is pending.
_ = os.WriteFile(filepath.Join(dir, "lock.pending"), nil, 0600)
h.warm(context.Background(), b52)