package thin import ( "amadan.net/oficina/equipo/internal/runner/provider/pi" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io/fs" "log/slog" "net/netip" "os" "path/filepath" "runtime" "slices" "strings" "golang.org/x/sys/unix" "sync" "sync/atomic" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/runner/metered" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/webread" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/sealbox" "amadan.net/oficina/equipo/internal/wire" ) // ExitSuperseded is the process exit status after losing the lease; the // unit must not restart on it, or two processes would take turns. const ExitSuperseded = 3 // Options are the thin runner's settings beyond runner.Config. type Options struct { Version string Claude ClaudeOptions // Codex configures Codex coordinator sessions (pinned digests). Codex CodexOptions // Pi, in tests, is a fake Pi's install and digests; empty, the // runner's own (EQUIPO_PI_ROOT, the committed pins). Pi PiOptions // OpenCode, in tests, is a fake OpenCode's install and digests; // empty, the runner's own (EQUIPO_OPENCODE_ROOT, the committed pins). OpenCode OpenCodeOptions Logger *slog.Logger // Connected observes the stream for tests. Connected func(bool) // Forge overrides the credential-file forge (tests use local repos). Forge Forge // IndexPace spaces the context index's fetches (default 4s). IndexPace time.Duration // NoCreate turns repository creation off (EQUIPO_RUNNER_CREATE_REPOS=0). NoCreate bool // Home is the namespace for new work that fits no related namespace // (EQUIPO_RUNNER_HOME_NAMESPACE). It must also be in CreateIn. Home string // NoMoveIn turns automatic moving in and exploring off // (EQUIPO_RUNNER_MOVE_IN=0). NoMoveIn bool // MaxStep bounds one Engineering step (EQUIPO_RUNNER_MAX_STEP, 5 to 60 // minutes; default 20) and the local checks gate; StepNote is appended // to its prompt (tests steer the fake CLI with it). MaxStep time.Duration StepNote string // KeptRetention bounds an unused kept step session (default // KeptSessionRetention). KeptRetention time.Duration // MergeEvery spaces the merge checks of watched task branches // (default: the minute reach check's pace). MergeEvery time.Duration // Protocol caps the runner stream protocol offered (tests: 1 acts as // a slice 4 runner); 0 is the current one. Protocol int // FakePlatform (EQUIPO_FAKE_PLATFORM=darwin/arm64) starts the test // build's fake Mac worker; any other build refuses it. FakeBin is put // first on its gates' PATH (the fake xcodebuild). FakePlatform, FakeBin string // Getenv is the environment the runner was started with, its env // file (--env-file) included; nil is the process's. Getenv func(string) string // FakeSandbox is what the fake worker says confined its checks // (EQUIPO_FAKE_SANDBOX): none unless a scenario plays a Mac whose // probe P2 denied (seatbelt). Test build only, like the fake itself. FakeSandbox string // AccountsRoot holds the homes of connections added from the app // (EQUIPO_ACCOUNTS_ROOT; default ~/.local/share/equipo/accounts). AccountsRoot string // ConnectLimit bounds a connection attempt (default ConnectLimit). ConnectLimit time.Duration // ResearchFetch stands in for the Research fetch phase's sandboxed // fetcher, and ResearchAddresses for this machine's interface // addresses (the hello's and every Research step's): tests only, so // no test reaches the network. nil: the real ones. Never read from // the environment. ResearchFetch func(context.Context, webread.LaunchConfig, webread.Plan) error ResearchAddresses func() ([]netip.Addr, error) // ReadCodexLimits stands in for the Codex reading probe's app-server // read (tests); nil: provider.ReadCodexLimits with the pinned CLI. ReadCodexLimits func(context.Context, provider.Binding) (provider.Identity, json.RawMessage, error) } // OptionsFromEnv reads the runner's optional thin settings. func OptionsFromEnv(getenv func(string) string) Options { return Options{Getenv: getenv, FakePlatform: getenv("EQUIPO_FAKE_PLATFORM"), FakeBin: getenv("EQUIPO_FAKE_BIN"), FakeSandbox: getenv("EQUIPO_FAKE_SANDBOX"), NoCreate: getenv("EQUIPO_RUNNER_CREATE_REPOS") == "0", Home: getenv("EQUIPO_RUNNER_HOME_NAMESPACE"), NoMoveIn: getenv("EQUIPO_RUNNER_MOVE_IN") == "0", IndexPace: 4 * time.Second, AccountsRoot: getenv("EQUIPO_ACCOUNTS_ROOT"), MaxStep: maxStepFrom(getenv("EQUIPO_RUNNER_MAX_STEP")), Claude: ClaudeOptions{Profile: AnthropicProfile()}} } // Bounds of EQUIPO_RUNNER_MAX_STEP: under the stall sweep's 90 minutes // with room for the push, and long enough for a step to do anything. const ( minMaxStep = 5 * time.Minute maxMaxStep = 60 * time.Minute ) // maxStepFrom reads EQUIPO_RUNNER_MAX_STEP, a Go duration of 5 to 60 // minutes; anything else (or nothing) is the default. func maxStepFrom(value string) time.Duration { d, err := time.ParseDuration(value) if err != nil || d < minMaxStep || d > maxMaxStep { return DefaultMaxStep } return d } // SessionRoot is where durable coordinator transcripts live by default: // beside the state directory, never inside a runtime or credential home. func SessionRoot(c runner.Config) string { return filepath.Join(filepath.Dir(c.StateDir), "sessions") } // Run serves the instance until ctx ends or a newer generation takes over. func Run(ctx context.Context, c runner.Config, o Options) error { if err := c.Validate(); err != nil { return err } if p := o.Claude.Profile; p != nil && p.Version == "" { // The profile read names the runner by its build. named := *p named.Version = o.Version o.Claude.Profile = &named } if o.FakePlatform != "" { if fake == nil { return ErrNotTestBuild } platform, ok := fake.platform(o.FakePlatform) if !ok { return ErrNotTestBuild } if o.Logger != nil { o.Logger.Warn("test build: the fake Mac worker runs checks in a process group without a sandbox", "build", fake.marker()) } w, err := fake.setup(ctx, &c, o) if err != nil { return err } return runWorker(ctx, c, o, platform, w) } if runtime.GOOS == "darwin" { return runMac(ctx, c, o) } // Ownership first: the state lock, then the scratch and workspace // roots. Only then may recovery touch namespaces or scratch. var manager *containment.Manager release, err := startup(ctx, c, o.Logger, func(ctx context.Context) error { var err error manager, err = containment.New(containment.Config{Binary: c.Bwrap(), RunnerBinary: c.Executable, ScratchRoot: c.ScratchRoot, ProviderNetworks: []provider.NetworkContract{{Provider: "claude"}, {Provider: "codex"}}}) if err != nil { return err } // Namespaces of a previous process died with it (--die-with-parent); // verify each exit and release its record and scratch. if records, err := manager.Records(ctx); err == nil { for _, r := range records { _ = manager.Forget(ctx, r) } } return nil }) if err != nil { return err } defer release() creds, state, err := openRunner(ctx, c, o.Logger) if err != nil { return err } defer state.Close() o.Claude.Runner, o.Claude.Manager, o.Claude.State, o.Claude.Logger = c, manager, state, o.Logger if o.Claude.SessionRoot == "" { o.Claude.SessionRoot = SessionRoot(c) } if err = os.MkdirAll(o.Claude.SessionRoot, 0700); err != nil { return err } o.Claude.defaults() ctx, cancel := context.WithCancel(ctx) defer cancel() platform := hostPlatform() // Previews: loaded once; the capability says whether this runner can // publish them (the instance shows "previews aren't set up" when not). preview := previewOptions(c, o.Logger) // A paired CARLOS devbox wins over Carloku temporary sites. devbox := ProbeDevbox(c, o.Logger, nil) // Merged websites publish to their confirmed places through carlos. site := ProbeSite(c, o.Logger) // The page renderer (Linux amd64 only): checked in the background, so // the connect never waits on its fixture render; a change of its // health goes out in the next hello. renderer := rendererHealth(c, platform.OS, platform.Arch, linkedRendererPin(), o.Logger) caps := &Capabilities{Probe: linuxCapabilities(c, PreviewHostOf(devbox, preview), site, o.ResearchAddresses, renderer), Logger: o.Logger} link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected, Protocol: o.Protocol, WorkerOnly: platform.OS == "darwin", Role: enrolledRole(c, creds.Bearer.Role)} if renderer != nil { renderer.Changed = func() { caps.Stale(); link.HelloSoon() } } renderer.Start(ctx) link.Files = &Files{State: state, SessionRoot: o.Claude.SessionRoot, Logger: o.Logger} // Attachments stay bounded whether or not anything arrives. go link.Files.Run(ctx, 10*time.Minute) fg := o.Forge if fg == nil { ff := NewFileForge(c.AmadanCredentialPath, c.StateDir, !o.NoCreate).(*fileForge) ff.accessTargets = state.accessReadTargets // Each repository it created must have a credential its merges // can use; say which do not, before a merge finds out. ff.checkCreated(ctx, o.Logger) fg, err = NewForges(ff) if err != nil { return err } } else if ff, ok := fg.(*fileForge); ok { ff.accessTargets = state.accessReadTargets } clones := &Clones{Root: c.WorkspaceRoot, Git: c.GitPath, Forge: fg} index := &Index{Forge: fg, Clones: clones, Path: filepath.Join(c.StateDir, "catalog.json"), Logger: o.Logger, Changed: link.HelloSoon, Pace: o.IndexPace} tools := &bridge{State: state, Link: link, Forge: fg, Clones: clones, Index: index, Logger: o.Logger, SessionRoot: o.Claude.SessionRoot, Activity: link.Activity} o.Claude.Tools, o.Claude.Catalog = tools.Reply, func() []wire.RepoInfo { return index.AccessCatalog(ctx, state) } o.Claude.Protocol = link.LastProtocol conns := &Conns{Runner: c, State: state, Logger: o.Logger, Refresh: o.Claude.Refresh, LockWait: o.Claude.LockWait} conns.ClaudeUsage = o.Claude.Profile conns.ClaudeStatus = func(ctx context.Context, b provider.Binding) (provider.Identity, string, error) { return provider.ReadClaudeStatus(ctx, b, provider.LoginOptions{ClaudePath: c.ClaudePath}) } // A Codex reading older than fifteen minutes is refreshed without a // model turn before the scheduler decides. Claude usage is read by // the hourly check and Check again. conns.Reading = CodexReading(c, o.ReadCodexLimits, o.Claude.LockWait) // A token check is a real request; its usage counts like any other, // and the rate limit the provider reported on it is recorded as a // turn's is: headroom, or limited until its reset. Not for a refused // token, which is no connection. conns.Verify = func(ctx context.Context, b runner.AccountBinding) error { res, err := o.Claude.CheckToken(ctx, b) if res.Seen != nil && !errors.Is(err, provider.ErrLoginRequired) { if res.Seen.Limited { conns.Limit(b.ID, *res.Seen) } else { conns.Observe(b.ID, *res.Seen, "") } } if rerr := state.ReportCheck(context.Background(), res.Rows); rerr != nil && o.Logger != nil { o.Logger.Warn("token check usage", "err", sanitize(rerr)) } if res.Seen != nil || res.Named { // The headroom, or the account its profile named, goes with // the next hello, not the next beat. link.HelloSoon() } else { link.Notify() } return err } engine := &Engine{State: state, Conns: conns, Logger: o.Logger, Emit: link.Delta, Act: link.Activity, Notify: link.Notify, Authorize: link.Confirm, Open: func(person, lane string, b runner.AccountBinding) (Coordinator, error) { return openLane(o.Claude, o.Codex, person, lane, b) }, Glance: func(person string, b runner.AccountBinding) (Glancer, error) { return OpenGlance(o.Claude, o.Codex, person, b) }, SendGlance: link.Glance, Glances: link.Glances, OpenLookup: func(person string, b runner.AccountBinding) (Glancer, string, error) { return OpenLookup(o.Claude, o.Codex, person, b) }} var wakeSteps atomic.Pointer[func()] conns.Changed = func() { engine.ConnectionsChanged() link.HelloSoon() if wake := wakeSteps.Load(); wake != nil { (*wake)() } } link.Engine = engine if o.AccountsRoot == "" { o.AccountsRoot = DefaultAccountsRoot() } connector := &Connector{Runner: c, State: state, Conns: conns, Root: o.AccountsRoot, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), Notify: link.Notify, Logger: o.Logger, Limit: o.ConnectLimit, RunnerID: creds.Bearer.RunnerID, Manager: manager} // The metered guard (connectors spec S1). Its slots are reconciled // before anything is admitted: a slot whose attempt's namespace is // proven gone is released with its charge, or with the spend unknown. conns.Meter = &metered.Meter{DB: state.db, Gone: connector.namespaceGone, Changed: func() { conns.changed() }} // A model's first use in a step is probed by the Connector, which // holds the provider clients (§16.4). conns.Prober = connector.probeModel if err = conns.Meter.Recover(ctx); err != nil && o.Logger != nil { o.Logger.Warn("metered recovery", "err", sanitize(err)) } // The seal key: the X25519 form of the enrolment key the owner // approved; secrets for token connections are sealed to it. sealKey := "" if key, err := runner.ReadMachineKey(c.StateDir); err == nil { if keys, err := sealbox.FromEd25519(key); err == nil { connector.Seal, sealKey = &keys, keys.PublicString() } clear(key) } else if o.Logger != nil { o.Logger.Warn("no seal key: token connections cannot be added", "err", sanitize(err)) } if err = connector.Start(ctx); err != nil { return err } link.Connector = connector // Token connections made before the profile read existed are read // once now (profile.go), beside hello and the checks, never before. go o.Claude.readProfilesAtStart(ctx, conns, link.HelloSoon) createIn := &namespaces{} recheck := make(chan struct{}, 1) link.Recheck = func() { select { case recheck <- struct{}{}: default: } } go createIn.loop(ctx, fg, link, index, recheck) var settle *settler if !o.NoMoveIn { settle = &settler{State: state, Link: link, Index: index, SessionRoot: o.Claude.SessionRoot, Persons: coordinatorPersons(c), Logger: o.Logger} index.Refreshed = func() { settle.Check(ctx) } } engine.ResetDesk = func(person string) error { if err := resetConversation(ctx, state, o.Claude.SessionRoot, person); err != nil { return err } if settle != nil { settle.forget(person) go settle.Check(ctx) } link.Notify() return nil } if af, ok := fg.(AccessForge); ok { link.Access = &AccessEngine{State: state, Forge: af, Authorize: link.ConfirmAccess, Refresh: func() { index.Kick(); link.HelloSoon() }, Notify: link.Notify, Logger: o.Logger} accessDone := make(chan struct{}) go func() { defer close(accessDone); link.Access.Run(ctx) }() defer func() { cancel(); <-accessDone }() } go index.Loop(ctx) link.Hello = func() wire.Hello { repos := fg.Repos() if repos == nil { repos = []string{} } in := createIn.get() home := "" if slices.Contains(in, o.Home) { home = o.Home } catalog := index.AccessCatalog(ctx, state) if catalog == nil { catalog = []wire.RepoInfo{} } report := caps.Get(ctx) return wire.Hello{Repos: repos, CreateIn: in, Home: home, Agent: fg.Agent(), Catalog: catalog, Connections: conns.Held(), Versions: map[string]string{"runner": o.Version, "claude": provider.ClaudeVersion}, SealKey: sealKey, Platform: &platform, Label: c.MachineLabel, Sandbox: wire.SandboxBubblewrap, Capabilities: &report} } if err = engine.Start(ctx); err != nil { return err } engineer := &Engineer{DiffSecrets: []string{creds.Bearer.Token}, O: o.Claude, Codex: o.Codex, Pi: piOptions(c, o.Pi), OpenCode: opencodeOptions(c, o.OpenCode), Clones: clones, Forge: fg, CI: hostedCIOf(fg), Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, ConfirmMerge: link.ConfirmMerge, ConfirmPreview: link.ConfirmPreview, ConfirmRender: link.ConfirmRender, Preview: preview, Devbox: devbox, Site: site, ConfirmPublish: link.ConfirmPublish, ConfirmMint: link.ConfirmMint, SiteChanged: func() { caps.Stale(); link.HelloSoon() }, ConfirmPublication: link.ConfirmPublication, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), MaxStep: o.MaxStep, Note: o.StepNote, Spoken: func() int { p, _ := link.Spoken(); return p }, Healthy: conns.Usable, Conns: conns, Delta: link.Delta, Activity: link.Activity, StepActivity: link.StepActivity, Retention: o.KeptRetention, Host: c.MachineLabel, Merged: func(string) { index.Kick() }} engineer.Renderer = renderer link.Forget = engineer.RemoveKept link.TaskEnded = engineer.PreviewTaskEnded // A Research step that met an address outside the confirmed inventory // has the next hello say what is here now. engineer.ResearchAddresses = func() { caps.Stale(); link.HelloSoon() } engineer.rh.launch, engineer.rh.addrs = o.ResearchFetch, o.ResearchAddresses if devbox != nil { // The domain, once a share tells it, goes out in the next hello. devbox.Learnt = link.HelloSoon } merges := &MergeWatch{State: state, Clones: clones, Git: c.GitPath, Notify: link.Notify, Logger: o.Logger, Every: o.MergeEvery} if merges.Every <= 0 { merges.Every = reachEvery + 5*time.Second } link.Synced = func() { merges.Kick() // Each sync (start, reconnect, and so a new rule's first start) // warms the Assistant lanes in use, where the instance has them. if proto, _ := link.Spoken(); proto >= wire.ProtocolAssistant { engine.WarmAssistants() } } go merges.Loop(ctx) if engineer.MaxStep == 0 { engineer.MaxStep = DefaultMaxStep } tags := func() []string { return caps.Get(ctx).Tags } steps := &StepEngine{State: state, Exec: placementGuard(tags, caps.Stale, engineer.Exec), Ask: engineer.ask, Notify: link.Notify, Logger: o.Logger, Sweep: func(ctx context.Context) { engineer.Sweep(ctx, state) engineer.sweepKept(ctx, state) engineer.SweepPublications(ctx, state) }, Verify: func(ctx context.Context, id string) bool { return verifiedExit(ctx, manager, id) }, TerminationKind: wire.TerminationNamespace} link.Steps = steps relay := &Relay{State: state, Engine: engineer, Notify: link.Notify, Logger: o.Logger} link.Relay = relay go relay.Loop(ctx) // A change of a connection's standing also looks again at questions // held by the metered guard. steps.Meter = conns.Meter // A question on a step's kept Pi session runs through the guard on // its own connection (connectors spec §7, Ask). steps.MeteredAsk = engineer.askPi wake := steps.MeteredChanged wakeSteps.Store(&wake) // A new reading wakes the steps the scheduler holds. conns.Readings = steps.MeteredChanged if err = steps.Start(ctx); err != nil { return err } go conns.Loop(ctx) err = link.Run(ctx) if errors.Is(err, ErrSuperseded) { cancel() engine.Wait() steps.Wait() _ = state.Supersede(context.Background()) return err } cancel() engine.Wait() steps.Wait() if ctx.Err() != nil && !errors.Is(err, ErrRevoked) { return nil } return err } // resetConversation clears the person's own conversation once its // coordinator process is closed: the main desk and the main lane's // session go, and the instance hears the notebook is empty. func resetConversation(ctx context.Context, state *State, sessionRoot, person string) error { desk, err := OpenDesk(sessionRoot, person) if err == nil { err = desk.Clear() } if err == nil { err = state.deleteSession(ctx, person, wire.LaneCoordinator) } if err == nil { err = state.SendNotebook(ctx, wire.NotebookReport{Person: person}) } return err } // namespaces caches where the agent may create repositories, refreshed in // the background so a hello never waits on the hub. type namespaces struct { mu sync.Mutex ns []string } func (n *namespaces) get() []string { n.mu.Lock() defer n.mu.Unlock() return append([]string{}, n.ns...) } // loop watches what the agent may create in and what it reaches: a // cheap conditional check about once a minute, and at once when a // person acts on a grant card (recheck). A change in reach is sent in a // hello and refreshes the index for the new repositories only. func (n *namespaces) loop(ctx context.Context, f Forge, link *Link, index *Index, recheck <-chan struct{}) { var reach []string for { rctx, cancel := context.WithTimeout(ctx, 40*time.Second) ns := f.CreateIn(rctx) now := f.Reachable(rctx) cancel() n.mu.Lock() changed := !slices.Equal(ns, n.ns) n.ns = ns n.mu.Unlock() moved := reach != nil && !slices.Equal(now, reach) reach = now if changed || moved { link.HelloSoon() } if moved && index != nil { index.Kick() } select { case <-ctx.Done(): return case <-time.After(reachEvery + 5*time.Second): case <-recheck: f.Recheck() } } } // ErrRootShared means a scratch or workspace root belongs to another // runner's state directory, or another runner holds it now. var ErrRootShared = errors.New("runner root shared with another runner") const ownerFile = ".equipo-root-owner" // startup orders what a runner may touch: its state lock, then exclusive // ownership of its scratch and workspace roots, then recovery of what its // own dead processes left (namespaces, then credential copies and other // scratch). A runner refused its roots recovers and deletes nothing. func startup(ctx context.Context, c runner.Config, log *slog.Logger, recover func(context.Context) error) (func(), error) { done := startPhase(log, "state_lock") lock, err := runner.LockState(c.StateDir) done(err) if err != nil { return nil, err } done = startPhase(log, "claim_roots") roots, err := claimRoots(c) done(err) if err != nil { lock.Close() return nil, err } release := func() { roots(); lock.Close() } done = startPhase(log, "sweep") if err = recover(ctx); err == nil { err = sweepOrphans(c) } done(err) if err != nil { release() return nil, err } return release, nil } // openRunner reads the runner's credential and opens its state, each a // logged startup phase. Nothing of the credential is logged. func openRunner(ctx context.Context, c runner.Config, log *slog.Logger) (runnerproto.CredentialRotation, *State, error) { done := startPhase(log, "credentials") creds, err := runner.ReadCredentials(filepath.Join(c.StateDir, "credentials.json")) done(credentialLogError(err)) if err != nil { return creds, nil, err } done = startPhase(log, "open_state") state, err := OpenState(ctx, c.StateDir) done(err) return creds, state, err } // credentialLogError is a credential read failure as it may be logged: a // path, policy or identity error as it is; anything the decoder said // about the file's content only by its type. func credentialLogError(err error) error { var path *fs.PathError if err == nil || errors.As(err, &path) || errors.Is(err, provider.ErrPolicy) || errors.Is(err, provider.ErrIdentity) { return err } return fmt.Errorf("unreadable credential file (%T)", err) } // startPhase logs a startup phase's start; the function it returns logs // its end, how long it took and its error. A silent hang at start is // pinned to the phase that started and never ended. func startPhase(log *slog.Logger, phase string) func(error) { if log == nil { return func(error) {} } start := time.Now() log.Info("startup phase", "phase", phase) return func(err error) { if err != nil { log.Warn("startup phase failed", "phase", phase, "took", took(start), "err", err.Error()) return } log.Info("startup phase done", "phase", phase, "took", took(start)) } } // took is the time since start, rounded for a log line. func took(start time.Time) time.Duration { d := time.Since(start) if d >= time.Second { return d.Round(time.Millisecond) } return d.Round(time.Microsecond) } // prepareRoots claims the roots and sweeps orphans. func prepareRoots(c runner.Config) (func(), error) { release, err := claimRoots(c) if err != nil { return nil, err } if err = sweepOrphans(c); err != nil { release() return nil, err } return release, nil } // claimRoots takes exclusive ownership of the scratch and workspace roots // for this state directory: an owner record naming it, and a lock held for // the life of the process. func claimRoots(c runner.Config) (func(), error) { var locks []*os.File release := func() { for _, f := range locks { f.Close() } } for _, root := range []string{c.ScratchRoot, c.WorkspaceRoot} { if err := os.MkdirAll(root, 0700); err != nil { release() return nil, err } f, err := os.OpenFile(filepath.Join(root, ownerFile+".lock"), os.O_CREATE|os.O_RDWR, 0600) if err != nil { release() return nil, err } locks = append(locks, f) if unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB) != nil { release() return nil, ErrRootShared } owner := filepath.Join(root, ownerFile) raw, err := os.ReadFile(owner) switch { case errors.Is(err, os.ErrNotExist): err = os.WriteFile(owner, []byte(c.StateDir+"\n"), 0600) case err == nil && strings.TrimSpace(string(raw)) != c.StateDir: err = ErrRootShared } if err != nil { release() return nil, err } } return release, nil } // sweepOrphans removes what coordinator processes create, by owner prefix, // without following links. func sweepOrphans(c runner.Config) error { for dir, prefixes := range map[string][]string{ filepath.Join(c.ScratchRoot, "homes"): {"account-", "config-"}, c.ScratchRoot: {"policy-"}, c.WorkspaceRoot: {"converse-", "step-"}, c.StateDir: {"coord-tool-"}, macToolRoot(c): {macToolDirPrefix}, } { entries, err := os.ReadDir(dir) if errors.Is(err, os.ErrNotExist) { continue } if err != nil { return err } for _, e := range entries { for _, prefix := range prefixes { if strings.HasPrefix(e.Name(), prefix) && e.Type().IsDir() { if err := os.RemoveAll(filepath.Join(dir, e.Name())); err != nil { return err } } } } } return nil } // verifiedExit reports whether a namespace's exit is verified: its record // is gone (released only after proof) or is released now with its proof. func verifiedExit(ctx context.Context, m *containment.Manager, id string) bool { records, err := m.Records(ctx) if err != nil { return false } if _, unrecorded := unrecordedKey(id); id == "" || unrecorded { // No namespace recorded for the attempt: verified only when none // of this runner's namespaces remains. return len(records) == 0 } for _, r := range records { if r.ID == id { return m.Forget(ctx, r) == nil } } return true } // enrolledRole is the role the runner was enrolled with: kept at // enrolment, or named by its credential; "" when it predates roles. func enrolledRole(c runner.Config, credential string) string { if role := runner.ReadRole(c.StateDir); role != "" { return role } if credential == wire.RoleWorker { return wire.RoleWorker } return "" } // ErrNotTestBuild refuses EQUIPO_FAKE_PLATFORM outside the test build: // no release binary runs the unsandboxed fake worker. var ErrNotTestBuild = errors.New("EQUIPO_FAKE_PLATFORM: this runner is not a test build") // workerSetup is what differs between workers: the capability report, // the gate, how a gate is found in a tree, what must be ready before // judging, and what runs once the worker holds its roots. type workerSetup struct { probe func(context.Context) wire.Capabilities gate GateRunner find func(dir string) (gate, string, bool) ready func(context.Context) error // started runs after startup with a function that refreshes the // capability report; welcomed sees each welcome. started func(ctx context.Context, refresh func()) welcomed func(wire.Welcome, *Worker, context.CancelCauseFunc) // creds is a Mac's credential operations (maccreds.go): with them the // worker holds Claude connections of its own (nil: none). creds *macCreds // engineering is a Mac's Engineering pieces (with creds; runWorker // adds what needs the runner's state: its status, secrets, scanner). engineering *WorkerEngineering // fprobes are a Mac's F probes, bound to the worker once it has its // Engineering pieces and connections. fprobes *macEngineering } // workerRecord is the process record Verify settles: an attempt that // recorded no group is settled by its marker alone. An empty record is // never an ended attempt. func workerRecord(id string) string { if key, ok := unrecordedKey(id); ok { return mac.RecordID(0, attemptMarker(key)) } return id } // attemptMarker is the EQUIPO_ATTEMPT value of a worker's attempt. func attemptMarker(key string) string { sum := sha256.Sum256([]byte(key)) return "checks/" + hex.EncodeToString(sum[:8]) } // ErrUpdated ends a worker that replaced its binary with the instance's // release: the service manager starts the new one. var ErrUpdated = errors.New("runner updated to the instance's release") // runWorker serves the instance as a worker: it runs the steps placed on // it and nothing else (no coordinator, no clone, no forge credential). func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Platform, w workerSetup) error { release, err := startup(ctx, c, o.Logger, func(context.Context) error { return nil }) if err != nil { return err } defer release() creds, state, err := openRunner(ctx, c, o.Logger) if err != nil { return err } defer state.Close() ctx, cancel := context.WithCancelCause(ctx) defer cancel(nil) caps := &Capabilities{Probe: w.probe, Logger: o.Logger} link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected, Protocol: o.Protocol, WorkerOnly: true, Role: enrolledRole(c, creds.Bearer.Role)} // A Mac's own Claude connections (slice F task 11): said in hello // only once the welcome says 37. var own *workerConns if w.creds != nil { // A connection that changes can change the Engineering status: the // report is gathered again, and the probes look. own = openWorkerConns(c, o, state, creds.Bearer, w.creds, link.Notify, func() { caps.Stale() link.HelloSoon() if w.fprobes != nil { w.fprobes.soon() } }) } link.Hello = func() wire.Hello { report := caps.Get(ctx) h := wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": o.Version}, Platform: &platform, Label: c.MachineLabel, Sandbox: w.gate.Sandbox(), Capabilities: &report} spoken, _ := link.Spoken() if own != nil { own.hello(spoken, &h) } if spoken < wire.ProtocolMacEngineering { // Before a welcome says 37 (and below it) none of slice F's // report either: an older instance refuses a hello it cannot // read, and a worker it refuses takes it for protocol 1 and // stops (M9g). The welcome at 37 asks for the whole report. wire.WithoutMacEngineering(&h) } return h } // Its owners include the person it is enrolled for, as on the primary: // before their first connection here they have no binding. engineer := &Engineer{O: o.Claude, Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), MaxStep: o.MaxStep, Host: c.MachineLabel, Note: o.StepNote, Retention: o.KeptRetention, Spoken: func() int { p, _ := link.Spoken(); return p }, Delta: link.Delta, Activity: link.Activity} engineer.O.Runner, engineer.O.State, engineer.O.Logger = c, state, o.Logger if own != nil { // Engineering on a Mac picks among the worker's own connections. engineer.O = own.claude engineer.Conns, engineer.Healthy = own.conns, own.conns.Usable } if engineer.O.SessionRoot == "" { engineer.O.SessionRoot = SessionRoot(c) } worker := &Worker{State: state, Engine: engineer, Gate: w.gate, MaxStep: o.MaxStep, StepRoot: filepath.Join(c.ScratchRoot, "worker-steps"), Find: w.find, Ready: w.ready} if w.engineering != nil && w.creds != nil && own != nil { eng := *w.engineering eng.Creds = w.creds if eng.Leaks == nil { eng.Leaks = engineer.workerLeaks } // The status the capability report says now: until every part of // it is ready (task 14 composes it), no Engineering runs here. eng.Status = func(ctx context.Context) *wire.EngineeringStatus { return caps.Get(ctx).Engineering } if w.fprobes != nil { // A Mac decides afresh at each use: the inputs now, the // results' age now (never the hour-old report). eng.Status = w.fprobes.statusNow } eng.Secrets = func(context.Context) ([]string, error) { return workerSecrets(c, creds.Bearer.Token) } worker.Eng = &eng if w.fprobes != nil { w.fprobes.bind(worker, own.conns, caps.Get) } } // The worker's relay answers the instance's send_pack for its // committed candidates, from its store; forget_task releases them. relay := &Relay{State: state, Engine: engineer, Worker: worker, Notify: link.Notify, Logger: o.Logger} link.Relay = relay link.Forget = func(dirs []string) { worker.forget(context.WithoutCancel(ctx), dirs) } link.Welcomed = func(welcome wire.Welcome) { if w.welcomed != nil { w.welcomed(welcome, worker, cancel) } if own != nil { // The first hello said no connections and none of slice F's // report: the next says them. link.HelloSoon() } } if own != nil { if err := own.start(ctx); err != nil { return err } link.Connector = own.connector go own.claude.readProfilesAtStart(ctx, own.conns, link.HelloSoon) go own.conns.Loop(ctx) } if w.started != nil { w.started(ctx, func() { caps.Stale(); link.HelloSoon() }) } tags := func() []string { return caps.Get(ctx).Tags } // Questions about the Engineering it ran are answered here, from the // sessions it kept (worker_ask.go). steps := &StepEngine{State: state, Exec: placementGuard(tags, caps.Stale, worker.Exec), Ask: worker.ask, Notify: link.Notify, Logger: o.Logger, Sweep: worker.sweep, Verify: func(_ context.Context, id string) bool { return w.gate.Verify(workerRecord(id)) }, TerminationKind: wire.TerminationProcessGroup, Acknowledge: func(_ context.Context, id string) { acknowledge(w.gate, workerRecord(id)) }} link.Steps = steps if err := steps.Start(ctx); err != nil { return err } go relay.Loop(ctx) err = link.Run(ctx) updated := errors.Is(context.Cause(ctx), ErrUpdated) cancel(nil) steps.Wait() if updated { return ErrUpdated } if errors.Is(err, ErrSuperseded) { _ = state.Supersede(context.Background()) return err } if ctx.Err() != nil && !errors.Is(err, ErrRevoked) { return nil } return err } // piOptions is the runner's Pi: the install at EQUIPO_PI_ROOT, held to // this platform's committed pins unless a test pins its fake's. func piOptions(c runner.Config, test PiOptions) PiOptions { if test.Install.Node != "" { return test } if c.PiRoot == "" { return PiOptions{} } node, tree := pi.Paths(c.PiRoot) return PiOptions{Install: pi.Install{Node: node, Tree: tree}} }