oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package proc is the Mac runner's view of its user's processes (spec
2// §5 and its 2026-11-28 addendum, §8.8): identities that survive pid
3// reuse, the kernel's table behind a seam, the runner's own helpers, and
4// what one operation may have left.
5package proc
6
7import (
8 "errors"
9 "os"
10 "os/exec"
11 "slices"
12 "strings"
13 "sync"
14 "syscall"
15 "time"
16)
17
18// How the runner finds what an operation left (spec §8.8). Claude Code
19// starts every Bash command in a session of its own (setsid), and macOS
20// 27.2 hides the environment of platform binaries (bash, zsh, sleep,
21// env, sandbox-exec) even from their own user, so neither the attempt's
22// group nor its marker finds them all. Three nets, all keyed by process
23// identity (pid and kernel start time), never by name or path:
24//
25// (a) while the operation runs, the processes under its leader and
26// every group and session they make;
27// (b) at its end, every process of the runner user that did not exist
28// when the turn began, except the runner and what it started for
29// itself (Own, with their descendants seen while they lived);
30// (c) the marker, wherever the kernel shows it.
31//
32// The one exception to (b): once the first kill pass has begun, what
33// launchd starts again from a system path (a relaunched on-demand agent)
34// is not the operation's.
35
36// ID names one process for its whole life: its pid and the kernel's
37// start time (on a Mac microseconds since the epoch, on Linux clock
38// ticks since boot). A pid used again later has another start: another
39// ID.
40type ID struct {
41 PID int `json:"pid"`
42 Start int64 `json:"start"`
43}
44
45// Info is one process of the runner user as the kernel reports it.
46type Info struct {
47 ID
48 PPID, PGID, SID, UID int
49 // Marker is the EQUIPO_ATTEMPT value it carries, of those asked for
50 // ("" for none, or when the kernel does not show it).
51 Marker string
52}
53
54// Table is the process table (the seam: sysctl on a Mac, /proc on
55// Linux, recorded tables in tests).
56type Table interface {
57 // List is every process whose user is the runner's, each with
58 // which of markers its environment carries, read before deadline
59 // (a read still running then is given up).
60 List(deadline time.Time, markers []string) ([]Info, error)
61 // Lookup is pid as it is now; ok is false once it is gone, is
62 // another user's, or cannot be read.
63 Lookup(pid int) (Info, bool)
64 // Path is the executable the kernel runs as pid (its file, not its
65 // argv[0], which the process may set), "" when unknown.
66 Path(pid int) string
67 // SessionGone reports whether no process of any user is in session
68 // sid; false when that cannot be read.
69 SessionGone(sid int) bool
70 // Sweeps reports whether this table may drive the runner-user sweep
71 // (b): on a Mac, where the runner user is dedicated; on Linux only a
72 // table scoped to a test's own processes.
73 Sweeps() bool
74 // Signal sends sig to pid (a negative pid: that group).
75 Signal(pid int, sig syscall.Signal) error
76 // Now is the time now in the clock of the table's start times.
77 Now() int64
78}
79
80// ErrNoSweep refuses a runner-user sweep on a table that may not drive
81// one (Linux outside a test's scope: other people's processes).
82var ErrNoSweep = errors.New("mac: this process table cannot sweep the runner user")
83
84// Alive reads whether id is still running. known is false when that
85// cannot be told (the pid is there, ours to signal, and its identity
86// unreadable): a caller deciding ownership treats that as alive.
87func Alive(t Table, id ID) (alive, known bool) {
88 if id.PID <= 0 {
89 return false, true
90 }
91 switch err := t.Signal(id.PID, 0); {
92 case errors.Is(err, syscall.ESRCH), errors.Is(err, syscall.EPERM):
93 // Gone, or another user's process has the pid now.
94 return false, true
95 case err != nil:
96 return false, false
97 }
98 q, ok := t.Lookup(id.PID)
99 if !ok {
100 return false, false
101 }
102 return q.ID == id, true
103}
104
105// Own is the runner's own processes: the runner itself and every helper
106// it starts for itself (simctl and ps queries, caffeinate, git, the
107// gitleaks scan, packing), each by ID, and the descendants of each seen
108// while it lived. A sweep never signals them. gate is held for reading
109// across a helper's start and registration and for writing across a
110// sweep's listing, so a helper is never listed unregistered; mu guards
111// the record itself.
112type Own struct {
113 gate sync.RWMutex
114 mu sync.Mutex
115 ids map[ID]bool
116}
117
118// Runner is this process's registry; every helper the runner starts
119// for itself goes through Start.
120var Runner = &Own{}
121
122// Start starts cmd as the runner's own helper (cmd.Start, then its
123// identity on record). A helper whose identity cannot be read while it
124// runs is killed and not started: unrecorded, a sweep would take it for
125// the operation's.
126func Start(cmd *exec.Cmd) error { return Runner.Start(cmd, Platform) }
127
128// Start starts cmd and records it as own, reading its identity from p.
129func (o *Own) Start(cmd *exec.Cmd, p Table) error {
130 o.gate.RLock()
131 defer o.gate.RUnlock()
132 if err := cmd.Start(); err != nil {
133 return err
134 }
135 pid := cmd.Process.Pid
136 if info, ok := p.Lookup(pid); ok && info.PID == pid {
137 o.Add(info.ID)
138 return nil
139 }
140 if syscall.Kill(pid, 0) == syscall.ESRCH {
141 // Already gone (or a zombie Wait will reap): nothing to spare.
142 return nil
143 }
144 _ = cmd.Process.Kill()
145 _ = cmd.Wait()
146 return errors.New("mac: a helper's identity could not be read")
147}
148
149// Owns reports whether id is on record as the runner's own.
150func (o *Own) Owns(id ID) bool {
151 o.mu.Lock()
152 defer o.mu.Unlock()
153 return o.ids[id]
154}
155
156// Add records id as own (a helper started some other way).
157func (o *Own) Add(id ID) {
158 o.mu.Lock()
159 defer o.mu.Unlock()
160 if o.ids == nil {
161 o.ids = map[ID]bool{}
162 }
163 o.ids[id] = true
164}
165
166// Snapshot lists p with no helper half-started. A process whose parent
167// (started no later than it) is own becomes own itself, so it stays the
168// runner's when that parent exits; identities no longer listed are
169// forgotten (they cannot come back).
170func (o *Own) Snapshot(deadline time.Time, p Table, markers []string) ([]Info, map[ID]bool, error) {
171 o.gate.Lock()
172 defer o.gate.Unlock()
173 list, err := p.List(deadline, markers)
174 if err != nil {
175 return nil, nil, err
176 }
177 o.mu.Lock()
178 defer o.mu.Unlock()
179 by := Index(list)
180 own := map[ID]bool{}
181 for _, q := range byStart(list) {
182 if o.ids[q.ID] {
183 own[q.ID] = true
184 continue
185 }
186 if parent, ok := by[q.PPID]; ok && parent.Start <= q.Start && own[parent.ID] {
187 own[q.ID] = true
188 }
189 }
190 o.ids = own
191 return list, maps(own), nil
192}
193
194func maps(m map[ID]bool) map[ID]bool {
195 c := make(map[ID]bool, len(m))
196 for k, v := range m {
197 c[k] = v
198 }
199 return c
200}
201
202func byStart(list []Info) []Info {
203 sorted := slices.Clone(list)
204 slices.SortFunc(sorted, func(a, b Info) int {
205 if a.Start != b.Start {
206 if a.Start < b.Start {
207 return -1
208 }
209 return 1
210 }
211 return a.PID - b.PID
212 })
213 return sorted
214}
215
216// SystemPath reports whether the kernel's path of an executable is one
217// only the system can write: under /System (but not its volumes, where
218// /System/Volumes/Data holds every user's files) or /usr/libexec or
219// /usr/sbin. Exact case. Only a relaunch after the kill pass began is
220// judged by it.
221func SystemPath(p string) bool {
222 if p == "" || strings.Contains(p, "/../") || strings.Contains(p, "/./") || strings.HasSuffix(p, "/..") {
223 return false
224 }
225 switch {
226 case strings.HasPrefix(p, "/System/Volumes/"):
227 return false
228 case strings.HasPrefix(p, "/System/"), strings.HasPrefix(p, "/usr/libexec/"), strings.HasPrefix(p, "/usr/sbin/"):
229 return true
230 }
231 return false
232}
233
234// Span is a group or session id an operation made, and the latest start
235// in the table it was first seen in: a leader with that pid started
236// after it is the id used again by someone else.
237type Span map[int]int64
238
239// Scope is what one operation (or a turn's operations) may have left:
240// its processes seen, their groups and sessions, its markers, the kill
241// set (every process it signalled), and, for the runner-user sweep, what
242// existed when the turn began.
243type Scope struct {
244 uid, self int
245 markers []string
246 Seen map[ID]bool
247 Groups Span
248 Sessions Span
249 // Killed is every process the stop signalled: each must be gone.
250 Killed map[ID]bool
251 // before is the turn's table at its start; nil: no runner-user sweep.
252 before map[ID]bool
253 // relaunchAfter is the table's clock just before the first kill
254 // pass's signals (0 before it): a launchd child from a system path
255 // started later is a relaunch.
256 relaunchAfter int64
257 procs Table
258}
259
260// NewScope is a scope over p for markers; before is the turn's table
261// when it began (nil: no runner-user sweep).
262func NewScope(p Table, markers []string, before []ID) *Scope {
263 s := &Scope{uid: os.Getuid(), self: os.Getpid(), markers: markers, Seen: map[ID]bool{}, Groups: Span{}, Sessions: Span{}, Killed: map[ID]bool{}, procs: p}
264 if before != nil {
265 s.before = map[ID]bool{}
266 for _, id := range before {
267 s.before[id] = true
268 }
269 }
270 return s
271}
272
273// Resume is a scope over p carrying on a stored turn's: its markers,
274// groups, sessions and kill set. With sweep, before is the turn's table
275// when it began (a nil one is empty); without, there is no sweep.
276func Resume(p Table, markers []string, sweep bool, before []ID, groups, sessions Span, killed []ID) *Scope {
277 if !sweep {
278 before = nil
279 } else if before == nil {
280 before = []ID{}
281 }
282 s := NewScope(p, markers, before)
283 for id, at := range groups {
284 s.Groups[id] = at
285 }
286 for id, at := range sessions {
287 s.Sessions[id] = at
288 }
289 for _, id := range killed {
290 s.Killed[id] = true
291 }
292 return s
293}
294
295// Track adds to the scope what list shows of it: children of what it
296// has seen (a true child started no earlier than its parent), members
297// of its groups and sessions (not of an id used again), and marked
298// processes; with each, its group and session. It reports whether a new
299// group or session was found.
300func (s *Scope) Track(list []Info, own map[ID]bool) bool {
301 by := Index(list)
302 top := int64(0)
303 for _, q := range list {
304 top = max(top, q.Start)
305 }
306 grew := false
307 for _, q := range byStart(list) {
308 if q.UID != s.uid || q.PID == s.self || own[q.ID] {
309 continue
310 }
311 parent, ok := by[q.PPID]
312 child := ok && parent.Start <= q.Start && s.Seen[parent.ID]
313 if !(child || s.Seen[q.ID] || s.member(q, by) || s.marked(q)) {
314 continue
315 }
316 s.Seen[q.ID] = true
317 for _, m := range []struct {
318 ids Span
319 id int
320 }{{s.Groups, q.PGID}, {s.Sessions, q.SID}} {
321 if _, ok := m.ids[m.id]; !ok && m.id > 1 {
322 m.ids[m.id] = top
323 grew = true
324 }
325 }
326 }
327 return grew
328}
329
330// member: q is in one of the scope's groups or sessions, and that id has
331// not been used again since (its leader, if alive, was there then).
332func (s *Scope) member(q Info, by map[int]Info) bool {
333 in := func(ids Span, id int) bool {
334 at, ok := ids[id]
335 if !ok || id <= 1 {
336 return false
337 }
338 leader, alive := by[id]
339 return !alive || leader.Start <= at || s.Seen[leader.ID]
340 }
341 return in(s.Groups, q.PGID) || in(s.Sessions, q.SID)
342}
343
344func (s *Scope) marked(q Info) bool {
345 return q.Marker != "" && slices.Contains(s.markers, q.Marker)
346}
347
348// Targets is what of list the stop must end: the scope's own processes
349// and, with a runner-user sweep, every process of the runner user that
350// was not there when the turn began and is not the runner's own,
351// whatever its path, but a launchd relaunch after the kill pass began.
352// Never another user's process, never the runner's own.
353func (s *Scope) Targets(list []Info, own map[ID]bool) []Info {
354 s.Track(list, own)
355 by := Index(list)
356 var out []Info
357 for _, q := range list {
358 if q.UID != s.uid || q.PID == s.self || q.PID <= 1 || own[q.ID] {
359 continue
360 }
361 switch {
362 case s.Seen[q.ID] || s.member(q, by) || s.marked(q) || s.Killed[q.ID]:
363 out = append(out, q)
364 case s.before != nil && !s.before[q.ID] && !s.relaunch(q):
365 out = append(out, q)
366 }
367 }
368 return out
369}
370
371// relaunch: launchd started q from a system path after the first kill
372// pass began (a killed on-demand agent started again), read for the
373// same process (its identity again after the path).
374func (s *Scope) relaunch(q Info) bool {
375 if s.relaunchAfter == 0 || q.Start <= s.relaunchAfter || q.PPID != 1 || !SystemPath(s.procs.Path(q.PID)) {
376 return false
377 }
378 now, ok := s.procs.Lookup(q.PID)
379 return ok && now.ID == q.ID
380}
381
382// Index is list by pid.
383func Index(list []Info) map[int]Info {
384 by := make(map[int]Info, len(list))
385 for _, q := range list {
386 by[q.PID] = q
387 }
388 return by
389}
390
391// Kill sends sig to each target, each read again just before (same pid,
392// same start, still the runner user's), and adds it to the kill set. A
393// group is signalled whole only while a target read just now is still
394// in it (a group id cannot be used again while it has a member).
395func (s *Scope) Kill(targets []Info, sig syscall.Signal) {
396 done := map[int]bool{}
397 for _, q := range targets {
398 s.Killed[q.ID] = true
399 if q.PGID <= 1 || done[q.PGID] {
400 continue
401 }
402 if _, ours := s.Groups[q.PGID]; ours && s.InGroup(q, q.PGID) {
403 done[q.PGID] = true
404 _ = s.procs.Signal(-q.PGID, sig)
405 }
406 }
407 for _, q := range targets {
408 if s.Still(q) {
409 _ = s.procs.Signal(q.PID, sig)
410 }
411 }
412}
413
414// Still: q, read now, is the same process and still the runner user's.
415func (s *Scope) Still(q Info) bool {
416 now, ok := s.procs.Lookup(q.PID)
417 return ok && now.ID == q.ID && now.UID == s.uid
418}
419
420// InGroup: q, read now, is the same process and still in group pgid.
421func (s *Scope) InGroup(q Info, pgid int) bool {
422 now, ok := s.procs.Lookup(q.PID)
423 return ok && now.ID == q.ID && now.UID == s.uid && now.PGID == pgid
424}
425
426// Gone reports whether every obligation is met: each process in the
427// kill set gone (by identity), each group gone (kill(-pgid, 0) is
428// ESRCH) and each session without a member of any user. Nothing is
429// signalled: a group or session another user now holds keeps it false.
430func (s *Scope) Gone() bool {
431 for id := range s.Killed {
432 if !s.gone(id) {
433 return false
434 }
435 }
436 for g := range s.Groups {
437 if !errors.Is(s.procs.Signal(-g, 0), syscall.ESRCH) {
438 return false
439 }
440 }
441 for sid := range s.Sessions {
442 if !s.procs.SessionGone(sid) {
443 return false
444 }
445 }
446 return true
447}
448
449// gone: id has ended for sure: no process has its pid (ESRCH), or the
450// pid is a later process of ours. EPERM is not gone: it may be the same
451// process, now another user's (a setuid program that called setuid).
452func (s *Scope) gone(id ID) bool {
453 if errors.Is(s.procs.Signal(id.PID, 0), syscall.ESRCH) {
454 return true
455 }
456 q, ok := s.procs.Lookup(id.PID)
457 return ok && q.Start != id.Start
458}
459
460// Outcome is how a settle ended.
461type Outcome int
462
463const (
464 // Proven: nothing of the scope is left.
465 Proven Outcome = iota
466 // Owed: nothing of the runner user's is left to kill, but a process,
467 // group or session of the scope is still there (another user's, or
468 // unreadable): never signalled, it must end before the proof.
469 Owed
470 // Left: a process of the runner user's is still a target.
471 Left
472)
473
474// Settle ends the scope before deadline, in three phases (each sees
475// every table read in time):
476// 1. the first kill pass: the targets of the first read are signalled,
477// the relaunch cutoff taken from the table's clock just before;
478// 2. discovery: exactly one more read, whose new targets join the kill
479// set and are signalled;
480// 3. checks: later reads add and spare nothing; they signal the kill
481// set again (SIGTERM within grace of the start, then SIGKILL) and
482// test the proof.
483//
484// Proven only when a read in time shows nothing of the kill set and no
485// marked process, reaped says the leader is reaped and Gone holds, all
486// before the deadline. Owed only when the last read in time, after any
487// failed one, showed nothing of the runner user's left (a late read
488// clears nothing, though what it shows left counts); else Left.
489func (s *Scope) Settle(own *Own, deadline time.Time, grace time.Duration, reaped func() bool, each func([]Info)) Outcome {
490 start := time.Now()
491 clear, phase := false, 0
492 for {
493 list, mine, err := own.Snapshot(deadline, s.procs, s.markers)
494 // A read that came back too late proves nothing and clears
495 // nothing; what it shows left still counts.
496 late := !time.Now().Before(deadline)
497 if err != nil {
498 clear = false
499 } else {
500 if each != nil {
501 each(list)
502 }
503 var left, kill []Info
504 if phase < 2 {
505 left = s.Targets(list, mine)
506 s.oblige(left)
507 kill = left
508 } else {
509 left, kill = s.remaining(list, mine)
510 }
511 switch {
512 case !late:
513 clear = len(left) == 0
514 if clear && reaped() && s.Gone() && time.Now().Before(deadline) {
515 return Proven
516 }
517 case len(left) > 0:
518 clear = false
519 }
520 if phase == 0 && s.before != nil {
521 s.relaunchAfter = s.procs.Now()
522 }
523 sig := syscall.SIGKILL
524 if time.Since(start) < grace {
525 sig = syscall.SIGTERM
526 }
527 s.Kill(kill, sig)
528 phase = min(phase+1, 2)
529 }
530 if !time.Now().Before(deadline) {
531 if clear {
532 return Owed
533 }
534 return Left
535 }
536 time.Sleep(min(100*time.Millisecond, time.Until(deadline)))
537 }
538}
539
540// oblige makes the groups and sessions targets lead obligations: a
541// process born into one later (a fork from a dying target) keeps the
542// proof waiting, though no later read adds it.
543func (s *Scope) oblige(targets []Info) {
544 for _, q := range targets {
545 if _, ok := s.Groups[q.PGID]; !ok && q.PGID == q.PID {
546 s.Groups[q.PGID] = q.Start
547 }
548 if _, ok := s.Sessions[q.SID]; !ok && q.SID == q.PID {
549 s.Sessions[q.SID] = q.Start
550 }
551 }
552}
553
554// remaining is, in a check read, what keeps the proof and the Mac's
555// clearance from holding: the kill set's processes still listed
556// (signalled again), and, never added or signalled, marked processes
557// and any other process of the runner user born during the turn that is
558// not the runner's own nor a launchd relaunch.
559func (s *Scope) remaining(list []Info, own map[ID]bool) (left, kill []Info) {
560 by := Index(list)
561 for _, q := range list {
562 if q.UID != s.uid || q.PID == s.self || q.PID <= 1 || own[q.ID] {
563 continue
564 }
565 switch {
566 case s.Killed[q.ID]:
567 left, kill = append(left, q), append(kill, q)
568 case s.marked(q), s.Seen[q.ID] || s.member(q, by):
569 left = append(left, q)
570 case s.before != nil && !s.before[q.ID] && !s.relaunch(q):
571 left = append(left, q)
572 }
573 }
574 return left, kill
575}
576
577// Obligation is what an unproven turn still owes, kept past its record:
578// the markers it launched and the processes, groups and sessions that
579// must be gone (none is ever signalled again).
580type Obligation struct {
581 Markers []string `json:"markers"`
582 // Began and BootID are the turn's start and the boot it ran in (a
583 // later boot ends it); Before is the runner user's table then.
584 Began time.Time `json:"began,omitzero"`
585 BootID string `json:"boot_id,omitempty"`
586 Before []ID `json:"before,omitempty"`
587 // Left is how many unaccounted processes the last idle read found.
588 Left int `json:"left,omitempty"`
589 // FlagsKnown and UnsandboxedRan are the turn's (an idle read clears
590 // only a turn whose record shows nothing ran outside a sandbox).
591 FlagsKnown bool `json:"flags_known,omitempty"`
592 UnsandboxedRan bool `json:"unsandboxed_ran,omitempty"`
593 // ProvenIn is set on a completion: the boot (its id) whose start
594 // proved the attempt over; ProvenAt when, and Recorded which
595 // consumers have taken it (Complete).
596 ProvenIn string `json:"proven_in,omitempty"`
597 ProvenAt time.Time `json:"proven_at,omitzero"`
598 Recorded []string `json:"recorded,omitempty"`
599 // Incomplete: the turn's record was never completed, so what it owes
600 // cannot be known: never met.
601 Incomplete bool `json:"incomplete,omitempty"`
602 Killed []ID `json:"killed,omitempty"`
603 Groups Span `json:"groups,omitempty"`
604 Sessions Span `json:"sessions,omitempty"`
605}
606
607// Owe is what s still owes.
608func (s *Scope) Owe() Obligation {
609 o := Obligation{Markers: slices.Clone(s.markers), Groups: Span{}, Sessions: Span{}}
610 for id := range s.Killed {
611 o.Killed = append(o.Killed, id)
612 }
613 for k, v := range s.Groups {
614 o.Groups[k] = v
615 }
616 for k, v := range s.Sessions {
617 o.Sessions[k] = v
618 }
619 return o
620}
621
622// Met reports whether everything o names is gone now.
623func (o Obligation) Met(p Table) bool {
624 return !o.Incomplete && o.gone(p)
625}
626
627// gone: every process, group and session o names is gone, for every
628// user (its being incomplete aside).
629func (o Obligation) gone(p Table) bool {
630 s := NewScope(p, o.Markers, nil)
631 for _, id := range o.Killed {
632 s.Killed[id] = true
633 }
634 for k, v := range o.Groups {
635 s.Groups[k] = v
636 }
637 for k, v := range o.Sessions {
638 s.Sessions[k] = v
639 }
640 return s.Gone()
641}
642
643// Boot is one boot of the machine: its identity and when it began.
644type Boot struct {
645 ID string
646 Time time.Time
647}
648