package mac import ( "cmp" "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/mac/proc" "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); CleanLimit is how much longer than // the stop's deadline the user-temp cleanup may take (3 minutes: a // simulator shutdown). Grace, Settle, Poll, CleanLimit 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) // Unsandboxed: what this runs is repository or model-chosen code // outside a sandbox (an unsandboxed check). Unsandboxed bool } // 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. TTY (a sign-in's) is the leader's stdin, // stdout, stderr and controlling terminal instead. type Command struct { Argv, Env []string Dir string Files []*os.File Pipes bool Stdout, Stderr io.Writer TTY *os.File } 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() } // cleanLimit bounds the user-temp cleanup (a simulator shutdown). func (x *Executor) cleanLimit() time.Duration { return cmp.Or(x.CleanLimit, 3*time.Minute) } // StopBudget is the most a stopped run's Wait takes: the proof, then the cleanup. func (x *Executor) StopBudget() time.Duration { return x.settleLimit() + x.cleanLimit() } func (x *Executor) settleLimit() time.Duration { return cmp.Or(max(x.Settle, 0), 30*time.Second) } // validMarker: a marker fits a record ("pg::") 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 x.Unsandboxed { // On record before anything of it starts. if err := turn.markUnsandboxed(); err != nil { return nil, errors.Join(ErrRecord, err) } } } 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{}), aborted: 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) var began time.Time var bootID string if turn != nil { turn.mu.Lock() began, bootID = turn.rec.Began, turn.rec.BootID turn.mu.Unlock() } // 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, time.Now().Add(x.settleLimit()), time.Now().Add(x.settleLimit()+x.cleanLimit())); 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: proc.Self(), Began: began, BootID: bootID}); 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, Setctty: c.TTY != nil} if c.TTY != nil { cmd.Stdin, cmd.Stdout, cmd.Stderr = c.TTY, c.TTY, c.TTY } 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: proc.Self(), Began: began, BootID: bootID}) } var noted error if turn != nil { noted = turn.note(r.scope.Groups, r.scope.Sessions) } if err := errors.Join(noted, 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() } if !r.Finish(context.WithoutCancel(ctx)) { proven = false } 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{} // unwritten is the turn record's last failed write: the operation is // stopped and its proof withheld until a write succeeds. unwritten error abortOnce sync.Once // aborted closes when the operation is stopped on its own (its // turn's record could not be written). aborted chan struct{} pollOnce sync.Once stopOnce sync.Once proven bool temp *tempState finishOnce sync.Once // cleaned: Finish's cleanup is done. cleaned bool 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 } // Aborted is closed when the run stopped itself (its turn's record // could not be written). func (r *Run) Aborted() <-chan struct{} { return r.aborted } // 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(time.Now().Add(every), r.procs, nil) if err == nil { r.mu.Lock() r.adopt(list) grew := r.scope.Track(list, own) groups, sessions := r.scope.Groups.Clone(), r.scope.Sessions.Clone() failed := r.unwritten != nil r.mu.Unlock() if (grew || failed) && r.turn != nil { err := r.turn.note(groups, sessions) r.mu.Lock() r.unwritten = err r.mu.Unlock() if err != nil { // What the attempt made is not on record for a // restart: the attempt goes now. r.abortOnce.Do(func() { close(r.aborted) go r.Stop() }) } } } 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 { reaped := func() bool { select { case <-r.exited: return true default: return false } } deadline := time.Now().Add(r.x.settleLimit()) out := r.scope.Settle(r.own, deadline, grace, reaped, r.adopt) if r.turn == nil { return out == proc.Proven && time.Now().Before(deadline) } // Proven only with everything it made durably on record (a restart // must find the same). killed := make([]ProcID, 0, len(r.scope.Killed)) for id := range r.scope.Killed { killed = append(killed, id) } err := r.turn.finish(r.marker, r.scope.Groups, r.scope.Sessions, killed) r.mu.Lock() r.unwritten = err r.mu.Unlock() // The deadline covers the final note (its write and fsync) too. if out != proc.Proven || err != nil || !time.Now().Before(deadline) { r.turn.unprovenEnd() return false } return true } // Finish is the user-temp cleanup once the end is proven: simulators // quieted, what appeared in T removed, then the record, within // CleanLimit read after the last; done (or nothing to clean) or not. // Failed or late, the pending and turn records stay for Verify. func (r *Run) Finish(ctx context.Context) bool { r.finishOnce.Do(func() { if r.temp == nil { r.cleaned = true return } defer r.temp.close() if !r.proven { return } by := time.Now().Add(r.x.cleanLimit()) qctx, cancel := context.WithDeadline(context.WithoutCancel(ctx), by) defer cancel() if r.x.QuietSimulators != nil { r.x.QuietSimulators(qctx) } r.cleaned = r.temp.clean() == nil && time.Now().Before(by) && r.x.Turns.dropPending() == nil && time.Now().Before(by) if !r.cleaned && r.turn != nil { r.turn.unprovenEnd() } }) return r.cleaned } // 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 (proc.SettleMarked), its simulators // shut down, then T cleaned against what it held before. Another live // owner's: ErrPendingCleanup, nothing touched. The proof is due by // settleBy, the rest by cleanBy. func (x *Executor) finishPending(ctx context.Context, turn *Turn, settleBy, cleanBy time.Time) error { r, ok, err := x.Turns.readPending() if err != nil || !ok { return err } if !x.Turns.mayFinish(turn, r) { return ErrPendingCleanup } // SettleMarked refuses a proof once settleBy has passed (its last // act): the cleanup's proof read is under the caller's deadline. // An attempt of an earlier boot is over (its group id is this boot's // to use); otherwise its end is proven first. b, berr := x.Turns.bootNow() if !proc.Rebooted(r.BootID, r.Began, b, berr) && !proc.SettleMarked(x.procs(), x.own(), r.PGID, r.Attempt, settleBy) { // 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")) } // Bounded by cleanBy: past it the record stays and a later call // continues (shutting simulators down and cleaning T again is safe). qctx, cancel := context.WithDeadline(context.WithoutCancel(ctx), cleanBy) defer cancel() if x.QuietSimulators != nil { x.QuietSimulators(qctx) } s, err := openTemp(x.UserTemp, r.Before) if err != nil { return err } defer s.close() if err := s.clean(); err != nil { return err } if !time.Now().Before(cleanBy) || x.Turns.dropPending() != nil || !time.Now().Before(cleanBy) { return errors.Join(ErrPendingCleanup, errors.New("mac: the cleanup failed or outlasted its bound")) } return nil } // 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 (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. // // - whatever its turn still owes (a group, session or process another // user now holds: never signalled) must be gone. // // Ended only when the group is gone (kill(-pgid, 0) is ESRCH), nothing // carries the marker, its turn is settled and owes nothing, and its // cleanup is done. It only reads what consumers rely on: after a // reboot it keeps a completion that every later proof of the // record reads, until each consumer has acknowledged it (Acknowledge). func (x *Executor) Verify(id string) bool { pgid, attempt, ok := proc.ParseRecord(id) if !ok { return false } deadline := time.Now().Add(x.settleLimit()) 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 || x.Turns.debts.Owes(attempt) { u, ok := x.Turns.tryTakeBy(OpRecover, deadline) if !ok { return false } defer u.Give() u.adopt(attempt) held = u } } // What the attempt owes: judged holding the turn, under the one // deadline; nothing goes unless the whole proof holds. rebooted, met := false, true if held != nil { var err error if rebooted, met, err = x.Turns.clearOwed(held, attempt, deadline); err != nil { return false } } if held != nil && !rebooted { // The pending cleanup's record keeps the attempt's boot when its // turn's record is gone (settled, then the cleanup failed again). r, pending, err := x.Turns.readPending() b, berr := x.Turns.bootNow() rebooted = err == nil && pending && r.Attempt == attempt && proc.Rebooted(r.BootID, r.Began, b, berr) } // A reboot is a boot-qualified clearance: the old boot's group id is // this boot's to use, and nothing is signalled. if !met || !rebooted && !proc.SettleMarked(x.procs(), x.own(), pgid, attempt, deadline) || !time.Now().Before(deadline) { return false } if held != nil && x.UserTemp != "" { r, pending, err := x.Turns.readPending() if err != nil { return false } if pending && r.Attempt == attempt { // The cleanup's own bound, the final save's too. cleanBy := time.Now().Add(x.cleanLimit()) if x.finishPending(context.Background(), held, deadline, cleanBy) != nil { return false } deadline = cleanBy } } if x.Turns == nil { return true } var err error if b, berr := x.Turns.bootNow(); rebooted { // Kept for every consumer (and any later proof) of the record. err = errors.Join(berr, x.Turns.debts.Complete(attempt, b.ID, deadline)) } else { err = x.Turns.debts.Discharge(attempt, deadline) } return err == nil && time.Now().Before(deadline) } // Acknowledge: consumer (ConsumerStep, ConsumerKeychain) has durably // kept what Verify proved of id, so its share of a reboot's completion // may go. Call it only after that consumer's own result is committed. func (x *Executor) Acknowledge(id, consumer string) { if _, attempt, ok := proc.ParseRecord(id); ok && x.Turns != nil { _ = x.Turns.debts.Acknowledge(attempt, consumer, []string{ConsumerStep, ConsumerKeychain}) } } // The consumers of a record's proof (Acknowledge): the step's recovery // and the credential (Keychain) recovery. const ( ConsumerStep = "step" ConsumerKeychain = "keychain" ) // Marked lists this user's processes whose environment carries // EQUIPO_ATTEMPT= where the kernel shows it (proc.Marked). func Marked(attempt string) ([]Proc, error) { return proc.Marked(attempt) } // 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 with the user-temp cleanup done (nil) or not (ErrUnproven). 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 <-p.run.aborted: case <-ctx.Done(): } proven := p.run.Stop() p.stop() cleaned := p.run.Finish(ctx) exit := provider.Exit{Code: exitCode(p.run.waitErr), ObservedAt: time.Now()} if !proven || !cleaned { return exit, ErrUnproven } return exit, nil }