package thin import ( "context" "encoding/json" "net" "path/filepath" "strconv" "strings" "sync" "sync/atomic" "time" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/runner/mac/fprobe" "amadan.net/oficina/equipo/internal/runner/mac/proc" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/wire" ) // macEngineering is a Mac worker's shipped Engineering probes, F1 to F7 // (mac/fprobe, slice F task 14), and the Engineering status they make. // The results live in this process's memory only. The launches need the // worker (its Engineering launch, its own Claude connections), which // runWorker binds once it has them. type macEngineering struct { h *macHost store fprobe.Store poke chan struct{} mu sync.Mutex // worker, conns and caps are bound by runWorker; last is F1 to F7 as // the newest capability report said them. worker *Worker conns *Conns caps func(context.Context) wire.Capabilities last []wire.Probe // live reads the capability report afresh; now is the clock. live func(context.Context) wire.Capabilities now func() time.Time } // readNow is the capability report read afresh, with the guards' status // and Unproven as credentialCaps says them now (never the hour-old report). func (e *macEngineering) readNow(ctx context.Context) wire.Capabilities { live := e.live if live == nil { live = func(ctx context.Context) wire.Capabilities { return mac.Capabilities(ctx, e.h.run, e.h.tools) } } c := live(ctx) if e.h.creds != nil { e.h.credentialCaps(ctx, &c) } return c } func (e *macEngineering) clock() time.Time { if e.now != nil { return e.now() } return time.Now() } // statusNow is the Engineering status decided now, at each use (an // admission, every launch): the inputs read afresh and the results' age // now. WorkerEngineering.Status on a Mac. func (e *macEngineering) statusNow(ctx context.Context) *wire.EngineeringStatus { c := e.readNow(ctx) st, _ := e.decide(&c) return &st } // xcodeNow is whether sandboxed Xcode access holds now: F5 denied for the // inputs read afresh and under a day old. func (e *macEngineering) xcodeNow(ctx context.Context) bool { c := e.readNow(ctx) _, probes := e.decide(&c) return fprobe.XcodeAllowed(probes) } // probePermission is the probe launch's permission tool: the Engineering // rules (inner) and then the probe's own (Spec.Permit: Bash only as the // hashed script with this run's nonce, no native write outside the tree); // ask hears every answer. func probePermission(inner func(json.RawMessage, provider.Policy) json.RawMessage, s fprobe.Spec, ask func(fprobe.Ask)) func(json.RawMessage, provider.Policy) json.RawMessage { return func(raw json.RawMessage, p provider.Policy) json.RawMessage { out := inner(raw, p) var q struct { Tool string `json:"tool_name"` ToolUseID string `json:"tool_use_id"` Input json.RawMessage `json:"input"` } if json.Unmarshal(raw, &q) != nil || !denied(out) && !s.Permit(q.Tool, q.Input) { out, _ = json.Marshal(map[string]string{"behavior": "deny", "message": "a probe launch runs only its own script"}) } ask(fprobe.Ask{Tool: q.Tool, ToolUseID: q.ToolUseID, Input: q.Input, Allowed: !denied(out)}) return out } } // fprobeEvery is how often the loop looks whether a launch is due. const fprobeEvery = 15 * time.Minute func newMacEngineering(h *macHost) *macEngineering { return &macEngineering{h: h, poke: make(chan struct{}, 1)} } // bind gives the probes the worker that launches them, its connections // and its capability report. func (e *macEngineering) bind(w *Worker, conns *Conns, caps func(context.Context) wire.Capabilities) { e.mu.Lock() e.worker, e.conns, e.caps = w, conns, caps e.mu.Unlock() e.soon() } // soon asks the loop to look now (a connection changed, P2 reported). func (e *macEngineering) soon() { if e == nil { return } select { case e.poke <- struct{}{}: default: } } // p2 is whether this process's trusted P2 is denied. func (e *macEngineering) p2() bool { r, ok := e.h.probes.trusted() return ok && r.Sandboxed() } // conn is why no Claude connection is usable ("" when one is). func (e *macEngineering) conn(caps *wire.Capabilities) (string, string) { e.mu.Lock() conns := e.conns e.mu.Unlock() switch { case caps.Unproven == wire.UnprovenCredential: // The Mac's connections are closed until a launch's end is proven. return wire.EngineeringNoConnection, wire.UnprovenCredential case conns == nil: return wire.EngineeringNoConnection, "" } return fprobe.ConnState(conns.Held(), conns.Usable), "" } // compose adds F1 to F7 to caps, sets its Engineering status from them, // the guards' status (credentialCaps) and the connections, and gives the // claude tag with ready. func (e *macEngineering) compose(caps *wire.Capabilities) { if e == nil { return } st, probes := e.decide(caps) caps.Probes, caps.Engineering = append(caps.Probes, probes...), &st if st.State == wire.EngineeringReady { caps.Tags = append(caps.Tags, wire.TagClaude) } e.mu.Lock() e.last = probes e.mu.Unlock() } // decide is the status and F1 to F7 for caps (its inputs, its guards' // status, its Unproven) and the connections, now. func (e *macEngineering) decide(caps *wire.Capabilities) (wire.EngineeringStatus, []wire.Probe) { verified := caps.Harness.Claude != "" probes := e.store.Probes(fprobe.NewInputs(e.h.version, verified, caps.Xcode, caps.Simulators), e.clock(), e.p2()) conn, why := e.conn(caps) p2 := "" if r, ok := e.h.probes.trusted(); ok { p2 = r.Probe("P2").Verdict } return fprobe.Status(fprobe.State{Guards: caps.Engineering, CLI: verified, Probes: probes, Conn: conn, ConnReason: why, P2: p2}), probes } // xcode: F5 is denied as the newest capability report says it. func (e *macEngineering) xcode() bool { if e == nil { return false } e.mu.Lock() defer e.mu.Unlock() return fprobe.XcodeAllowed(e.last) } // start runs the due launches now and whenever asked, or every // fprobeEvery; refresh tells the instance after a run. func (e *macEngineering) start(ctx context.Context, refresh func()) { go func() { for { if host, ok := e.host(ctx); ok { if results := e.store.Run(ctx, host); len(results) > 0 && ctx.Err() == nil { if e.h.log != nil { var v []string for _, r := range results { v = append(v, verdicts(r.Probes)) } e.h.log.Info("engineering probes finished", "verdicts", strings.Join(v, " ")) } refresh() } } select { case <-ctx.Done(): return case <-e.poke: case <-time.After(fprobeEvery): } } }() } // host is the probes' view of this Mac now; false while they cannot run // (no worker yet, no usable Claude connection). func (e *macEngineering) host(ctx context.Context) (fprobe.Host, bool) { e.mu.Lock() w, conns, capsOf := e.worker, e.conns, e.caps e.mu.Unlock() if w == nil || w.Eng == nil || conns == nil || capsOf == nil { return fprobe.Host{}, false } // The connections first: without a usable one nothing runs, and the // capability report is not gathered for nothing (its first gathering // is the first hello's). if fprobe.ConnState(conns.Held(), conns.Usable) != "" { return fprobe.Host{}, false } caps := capsOf(ctx) if c, _ := e.conn(&caps); c != "" { return fprobe.Host{}, false } h, cfg := e.h, w.Engine.O.Runner var tokens []string for _, b := range conns.bindings() { if b.Provider == wire.ProviderClaude && b.Kind == wire.KindToken { tokens = append(tokens, filepath.Join(b.ProviderHome, provider.TokenFile)) } } return fprobe.Host{ // The inputs each launch runs under, read afresh (not the report). Live: func(ctx context.Context) (fprobe.Inputs, []wire.Simulator) { c := e.readNow(ctx) return fprobe.NewInputs(h.version, c.Harness.Claude != "", c.Xcode, c.Simulators), c.Simulators }, Paths: h.paths, RuntimeRoot: filepath.Join(cfg.ScratchRoot, "homes"), TokenFiles: tokens, Runner: cfg.Executable, Tools: h.tools, Simulators: caps.Simulators, Scratch: filepath.Join(h.scratch, "fprobe"), P2Denied: e.p2(), Secrets: func(ctx context.Context) ([][]byte, error) { s, err := w.Eng.Secrets(ctx) return secretForms(s), err }, Turns: h.turns, Launch: w.probeLaunch, Listen: func() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") }, Resolve: func(ctx context.Context, name string) bool { addrs, err := net.DefaultResolver.LookupHost(ctx, name) return err == nil && len(addrs) > 0 }, Exposed: mac.Exposed, Exec: h.run, Lookup: proc.Platform.Lookup, Alive: func(id proc.ID) (bool, bool) { return proc.Alive(proc.Platform, id) }, }, true } // probeNote, in tests, adds the fake CLI's directives to a probe // launch's prompt (nil in a release). var probeNote func(fprobe.Spec) string // probeLaunch is one probe launch: the Engineering launch itself // (w.launch: the guards, the runtime copy, the policy for the probe tree // at its real path, the token by descriptor, the Keychain watch, the // proven stop), on the Mac's first usable Claude connection and its // small model, with no step log and no kept session, before the Mac is // ready. Its permission tool is probePermission; its scratch (TMPDIR) is // the probe's, where only the script writes; obs sees the runtime copy // before the CLI starts, the CLI's pid once its group is on record (only // that counts as started) and every frame of its stream. func (w *Worker) probeLaunch(ctx context.Context, s fprobe.Spec, obs fprobe.Observer) fprobe.Outcome { e := w.Engine for _, c := range e.Conns.bindings() { if c.Provider != wire.ProviderClaude || c.Kind != wire.KindToken || !e.Conns.Usable(c.ID) { continue } c.Model = provider.ClaudeGlanceModel prompt := s.Prompt if probeNote != nil { prompt += probeNote(s) } var started atomic.Bool r := stepRow{DispatchCommand: wire.DispatchCommand{TaskID: "fprobe", StepID: s.Launch, Attempt: 1}} if s.Xcode { r.XcodeAccess = wire.XcodeAccessSandboxed } perm := probePermission(claude.StepPermission, s, func(q fprobe.Ask) { if obs.Ask != nil { obs.Ask(q) } }) spec := specialistRun{action: "implement", binding: c, tools: stepTools, names: []string{"submit_candidate", "ask_person", "submit_render"}, permission: perm, call: func(context.Context, string, string, json.RawMessage) (string, bool) { return stepToolText, false }, prompt: prompt, limit: s.Limit, noLog: true, probe: true, scratch: s.Scratch, copied: obs.Copy, tap: obs.Event, record: func(_ context.Context, id string) error { // pg::: the CLI leads its own group. if f := strings.SplitN(id, ":", 3); len(f) == 3 && f[1] != "0" && started.CompareAndSwap(false, true) && obs.Started != nil { if pid, err := strconv.Atoi(f[1]); err == nil { obs.Started(pid) } } return nil }} res := w.launch(ctx, r, workspace.TaskTree{Dir: s.Tree}, spec, "fprobe-"+s.Launch+"-"+strings.ReplaceAll(uuid(), "-", "")[:12], nil) return fprobe.Outcome{Started: started.Load(), Proven: res.terminated, Reason: res.reason} } return fprobe.Outcome{Reason: "no_connection"} }