// 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" "time" ) // How the runner finds what an operation left (spec §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 or path: // // (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, with their descendants seen while they lived); // (c) the marker, wherever the kernel shows it. // // The one exception to (b): once the first kill pass has begun, what // launchd starts again from a system path (a relaunched on-demand agent) // is not the operation's. // 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, read before deadline // (a read still running then is given up). List(deadline time.Time, markers []string) ([]Info, error) // Lookup is pid as it is now; ok is false once it is gone, is // another user's, or cannot be read. 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 // SessionGone reports whether no process of any user is in session // sid; false when that cannot be read. SessionGone(sid int) bool // 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 // Now is the time now in the clock of the table's start times. Now() int64 } // 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") // Alive reads whether id is still running. known is false when that // cannot be told (the pid is there, ours to signal, and its identity // unreadable): a caller deciding ownership treats that as alive. func Alive(t Table, id ID) (alive, known bool) { if id.PID <= 0 { return false, true } switch err := t.Signal(id.PID, 0); { case errors.Is(err, syscall.ESRCH), errors.Is(err, syscall.EPERM): // Gone, or another user's process has the pid now. return false, true case err != nil: return false, false } q, ok := t.Lookup(id.PID) if !ok { return false, false } return q.ID == id, true } // 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, and the descendants of each seen // while it lived. A sweep never signals them. gate 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; mu guards // the record itself. type Own struct { gate sync.RWMutex mu sync.Mutex ids map[ID]bool } // Runner is this process's registry; every helper the runner starts // for itself goes through Start. 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.gate.RLock() defer o.gate.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") } // Owns reports whether id is on record as the runner's own. func (o *Own) Owns(id ID) bool { o.mu.Lock() defer o.mu.Unlock() return o.ids[id] } // Add records id as own (a helper started some other way). func (o *Own) Add(id ID) { o.mu.Lock() defer o.mu.Unlock() if o.ids == nil { o.ids = map[ID]bool{} } o.ids[id] = true } // Snapshot lists p with no helper half-started. A process whose parent // (started no later than it) is own becomes own itself, so it stays the // runner's when that parent exits; identities no longer listed are // forgotten (they cannot come back). func (o *Own) Snapshot(deadline time.Time, p Table, markers []string) ([]Info, map[ID]bool, error) { o.gate.Lock() defer o.gate.Unlock() list, err := p.List(deadline, markers) if err != nil { return nil, nil, err } o.mu.Lock() defer o.mu.Unlock() by := Index(list) own := map[ID]bool{} for _, q := range byStart(list) { if o.ids[q.ID] { own[q.ID] = true continue } if parent, ok := by[q.PPID]; ok && parent.Start <= q.Start && own[parent.ID] { own[q.ID] = true } } o.ids = own return list, maps(own), nil } func maps(m map[ID]bool) map[ID]bool { c := make(map[ID]bool, len(m)) for k, v := range m { c[k] = v } return c } func byStart(list []Info) []Info { 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 }) return sorted } // 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 or // /usr/sbin. Exact case. Only a relaunch after the kill pass began is // judged by it. 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/"), strings.HasPrefix(p, "/usr/sbin/"): 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, the kill // set (every process it signalled), 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 // Killed is every process the stop signalled: each must be gone. Killed map[ID]bool // before is the turn's table at its start; nil: no runner-user sweep. before map[ID]bool // relaunchAfter is the table's clock just before the first kill // pass's signals (0 before it): a launchd child from a system path // started later is a relaunch. relaunchAfter int64 procs Table } // NewScope is a scope over p for markers; before is the turn's table // when it began (nil: no runner-user sweep). 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{}, Killed: map[ID]bool{}, procs: p} if before != nil { s.before = map[ID]bool{} for _, id := range before { s.before[id] = true } } return s } // Resume is a scope over p carrying on a stored turn's: its markers, // groups, sessions and kill set. With sweep, before is the turn's table // when it began (a nil one is empty); without, there is no sweep. func Resume(p Table, markers []string, sweep bool, before []ID, groups, sessions Span, killed []ID) *Scope { if !sweep { before = nil } else if before == nil { before = []ID{} } s := NewScope(p, markers, before) for id, at := range groups { s.Groups[id] = at } for id, at := range sessions { s.Sessions[id] = at } for _, id := range killed { s.Killed[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 { by := Index(list) top := int64(0) for _, q := range list { top = max(top, q.Start) } grew := false for _, q := range byStart(list) { 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 and is not the runner's own, // whatever its path, but a launchd relaunch after the kill pass began. // 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) || s.Killed[q.ID]: out = append(out, q) case s.before != nil && !s.before[q.ID] && !s.relaunch(q): out = append(out, q) } } return out } // relaunch: launchd started q from a system path after the first kill // pass began (a killed on-demand agent started again), read for the // same process (its identity again after the path). func (s *Scope) relaunch(q Info) bool { if s.relaunchAfter == 0 || q.Start <= s.relaunchAfter || q.PPID != 1 || !SystemPath(s.procs.Path(q.PID)) { return false } now, ok := s.procs.Lookup(q.PID) return ok && now.ID == q.ID } // Index is list by pid. 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 read again just before (same pid, // same start, still the runner user's), and adds it to the kill set. A // group is signalled whole only while a target read just now is still // 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 { s.Killed[q.ID] = true if q.PGID <= 1 || done[q.PGID] { continue } if _, ours := s.Groups[q.PGID]; ours && s.InGroup(q, q.PGID) { done[q.PGID] = true _ = s.procs.Signal(-q.PGID, sig) } } for _, q := range targets { if s.Still(q) { _ = s.procs.Signal(q.PID, sig) } } } // Still: q, read now, is the same process and still the runner user's. func (s *Scope) Still(q Info) bool { now, ok := s.procs.Lookup(q.PID) return ok && now.ID == q.ID && now.UID == s.uid } // InGroup: q, read now, is the same process and still in group pgid. func (s *Scope) InGroup(q Info, pgid int) bool { now, ok := s.procs.Lookup(q.PID) return ok && now.ID == q.ID && now.UID == s.uid && now.PGID == pgid } // Gone reports whether every obligation is met: each process in the // kill set gone (by identity), each group gone (kill(-pgid, 0) is // ESRCH) and each session without a member of any user. Nothing is // signalled: a group or session another user now holds keeps it false. func (s *Scope) Gone() bool { for id := range s.Killed { if !s.gone(id) { return false } } for g := range s.Groups { if !errors.Is(s.procs.Signal(-g, 0), syscall.ESRCH) { return false } } for sid := range s.Sessions { if !s.procs.SessionGone(sid) { return false } } return true } // gone: id has ended for sure: no process has its pid (ESRCH), or the // pid is a later process of ours. EPERM is not gone: it may be the same // process, now another user's (a setuid program that called setuid). func (s *Scope) gone(id ID) bool { if errors.Is(s.procs.Signal(id.PID, 0), syscall.ESRCH) { return true } q, ok := s.procs.Lookup(id.PID) return ok && q.Start != id.Start } // Outcome is how a settle ended. type Outcome int const ( // Proven: nothing of the scope is left. Proven Outcome = iota // Owed: nothing of the runner user's is left to kill, but a process, // group or session of the scope is still there (another user's, or // unreadable): never signalled, it must end before the proof. Owed // Left: a process of the runner user's is still a target. Left ) // Settle ends the scope before deadline, in three phases (each sees // every table read in time): // 1. the first kill pass: the targets of the first read are signalled, // the relaunch cutoff taken from the table's clock just before; // 2. discovery: exactly one more read, whose new targets join the kill // set and are signalled; // 3. checks: later reads add and spare nothing; they signal the kill // set again (SIGTERM within grace of the start, then SIGKILL) and // test the proof. // // Proven only when a read in time shows nothing of the kill set and no // marked process, reaped says the leader is reaped and Gone holds, all // before the deadline. Owed only when the last read in time, after any // failed one, showed nothing of the runner user's left (a late read // clears nothing, though what it shows left counts); else Left. func (s *Scope) Settle(own *Own, deadline time.Time, grace time.Duration, reaped func() bool, each func([]Info)) Outcome { start := time.Now() clear, phase := false, 0 for { list, mine, err := own.Snapshot(deadline, s.procs, s.markers) // A read that came back too late proves nothing and clears // nothing; what it shows left still counts. late := !time.Now().Before(deadline) if err != nil { clear = false } else { if each != nil { each(list) } var left, kill []Info if phase < 2 { left = s.Targets(list, mine) s.oblige(left) kill = left } else { left, kill = s.remaining(list, mine) } switch { case !late: clear = len(left) == 0 if clear && reaped() && s.Gone() && time.Now().Before(deadline) { return Proven } case len(left) > 0: clear = false } if phase == 0 && s.before != nil { s.relaunchAfter = s.procs.Now() } sig := syscall.SIGKILL if time.Since(start) < grace { sig = syscall.SIGTERM } s.Kill(kill, sig) phase = min(phase+1, 2) } if !time.Now().Before(deadline) { if clear { return Owed } return Left } time.Sleep(min(100*time.Millisecond, time.Until(deadline))) } } // oblige makes the groups and sessions targets lead obligations: a // process born into one later (a fork from a dying target) keeps the // proof waiting, though no later read adds it. func (s *Scope) oblige(targets []Info) { for _, q := range targets { if _, ok := s.Groups[q.PGID]; !ok && q.PGID == q.PID { s.Groups[q.PGID] = q.Start } if _, ok := s.Sessions[q.SID]; !ok && q.SID == q.PID { s.Sessions[q.SID] = q.Start } } } // remaining is, in a check read, what keeps the proof and the Mac's // clearance from holding: the kill set's processes still listed // (signalled again), and, never added or signalled, marked processes // and any other process of the runner user born during the turn that is // not the runner's own nor a launchd relaunch. func (s *Scope) remaining(list []Info, own map[ID]bool) (left, kill []Info) { by := Index(list) for _, q := range list { if q.UID != s.uid || q.PID == s.self || q.PID <= 1 || own[q.ID] { continue } switch { case s.Killed[q.ID]: left, kill = append(left, q), append(kill, q) case s.marked(q), s.Seen[q.ID] || s.member(q, by): left = append(left, q) case s.before != nil && !s.before[q.ID] && !s.relaunch(q): left = append(left, q) } } return left, kill } // Obligation is what an unproven turn still owes, kept past its record: // the markers it launched and the processes, groups and sessions that // must be gone (none is ever signalled again). type Obligation struct { Markers []string `json:"markers"` // Began and BootID are the turn's start and the boot it ran in (a // later boot ends it); Before is the runner user's table then. Began time.Time `json:"began,omitzero"` BootID string `json:"boot_id,omitempty"` Before []ID `json:"before,omitempty"` // Left is how many unaccounted processes the last idle read found. Left int `json:"left,omitempty"` // FlagsKnown and UnsandboxedRan are the turn's (an idle read clears // only a turn whose record shows nothing ran outside a sandbox). FlagsKnown bool `json:"flags_known,omitempty"` UnsandboxedRan bool `json:"unsandboxed_ran,omitempty"` // ProvenIn is set on a completion: the boot (its id) whose start // proved the attempt over; ProvenAt when, and Recorded which // consumers have taken it (Complete). ProvenIn string `json:"proven_in,omitempty"` ProvenAt time.Time `json:"proven_at,omitzero"` Recorded []string `json:"recorded,omitempty"` // Incomplete: the turn's record was never completed, so what it owes // cannot be known: never met. Incomplete bool `json:"incomplete,omitempty"` Killed []ID `json:"killed,omitempty"` Groups Span `json:"groups,omitempty"` Sessions Span `json:"sessions,omitempty"` } // Owe is what s still owes. func (s *Scope) Owe() Obligation { o := Obligation{Markers: slices.Clone(s.markers), Groups: Span{}, Sessions: Span{}} for id := range s.Killed { o.Killed = append(o.Killed, id) } for k, v := range s.Groups { o.Groups[k] = v } for k, v := range s.Sessions { o.Sessions[k] = v } return o } // Met reports whether everything o names is gone now. func (o Obligation) Met(p Table) bool { return !o.Incomplete && o.gone(p) } // gone: every process, group and session o names is gone, for every // user (its being incomplete aside). func (o Obligation) gone(p Table) bool { s := NewScope(p, o.Markers, nil) for _, id := range o.Killed { s.Killed[id] = true } for k, v := range o.Groups { s.Groups[k] = v } for k, v := range o.Sessions { s.Sessions[k] = v } return s.Gone() } // Boot is one boot of the machine: its identity and when it began. type Boot struct { ID string Time time.Time }