| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "net" |
| 7 | "path/filepath" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | "sync" |
| 11 | "sync/atomic" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/runner/mac" |
| 15 | "amadan.net/oficina/equipo/internal/runner/mac/fprobe" |
| 16 | "amadan.net/oficina/equipo/internal/runner/mac/proc" |
| 17 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 18 | "amadan.net/oficina/equipo/internal/runner/provider/claude" |
| 19 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 20 | "amadan.net/oficina/equipo/internal/wire" |
| 21 | ) |
| 22 | |
| 23 | // macEngineering is a Mac worker's shipped Engineering probes, F1 to F7 |
| 24 | // (mac/fprobe, slice F task 14), and the Engineering status they make. |
| 25 | // The results live in this process's memory only. The launches need the |
| 26 | // worker (its Engineering launch, its own Claude connections), which |
| 27 | // runWorker binds once it has them. |
| 28 | type macEngineering struct { |
| 29 | h *macHost |
| 30 | store fprobe.Store |
| 31 | poke chan struct{} |
| 32 | |
| 33 | mu sync.Mutex |
| 34 | // worker, conns and caps are bound by runWorker; last is F1 to F7 as |
| 35 | // the newest capability report said them. |
| 36 | worker *Worker |
| 37 | conns *Conns |
| 38 | caps func(context.Context) wire.Capabilities |
| 39 | last []wire.Probe |
| 40 | // live reads the capability report afresh; now is the clock. |
| 41 | live func(context.Context) wire.Capabilities |
| 42 | now func() time.Time |
| 43 | } |
| 44 | |
| 45 | // readNow is the capability report read afresh, with the guards' status |
| 46 | // and Unproven as credentialCaps says them now (never the hour-old report). |
| 47 | func (e *macEngineering) readNow(ctx context.Context) wire.Capabilities { |
| 48 | live := e.live |
| 49 | if live == nil { |
| 50 | live = func(ctx context.Context) wire.Capabilities { return mac.Capabilities(ctx, e.h.run, e.h.tools) } |
| 51 | } |
| 52 | c := live(ctx) |
| 53 | if e.h.creds != nil { |
| 54 | e.h.credentialCaps(ctx, &c) |
| 55 | } |
| 56 | return c |
| 57 | } |
| 58 | |
| 59 | func (e *macEngineering) clock() time.Time { |
| 60 | if e.now != nil { |
| 61 | return e.now() |
| 62 | } |
| 63 | return time.Now() |
| 64 | } |
| 65 | |
| 66 | // statusNow is the Engineering status decided now, at each use (an |
| 67 | // admission, every launch): the inputs read afresh and the results' age |
| 68 | // now. WorkerEngineering.Status on a Mac. |
| 69 | func (e *macEngineering) statusNow(ctx context.Context) *wire.EngineeringStatus { |
| 70 | c := e.readNow(ctx) |
| 71 | st, _ := e.decide(&c) |
| 72 | return &st |
| 73 | } |
| 74 | |
| 75 | // xcodeNow is whether sandboxed Xcode access holds now: F5 denied for the |
| 76 | // inputs read afresh and under a day old. |
| 77 | func (e *macEngineering) xcodeNow(ctx context.Context) bool { |
| 78 | c := e.readNow(ctx) |
| 79 | _, probes := e.decide(&c) |
| 80 | return fprobe.XcodeAllowed(probes) |
| 81 | } |
| 82 | |
| 83 | // probePermission is the probe launch's permission tool: the Engineering |
| 84 | // rules (inner) and then the probe's own (Spec.Permit: Bash only as the |
| 85 | // hashed script with this run's nonce, no native write outside the tree); |
| 86 | // ask hears every answer. |
| 87 | func probePermission(inner func(json.RawMessage, provider.Policy) json.RawMessage, s fprobe.Spec, ask func(fprobe.Ask)) func(json.RawMessage, provider.Policy) json.RawMessage { |
| 88 | return func(raw json.RawMessage, p provider.Policy) json.RawMessage { |
| 89 | out := inner(raw, p) |
| 90 | var q struct { |
| 91 | Tool string `json:"tool_name"` |
| 92 | ToolUseID string `json:"tool_use_id"` |
| 93 | Input json.RawMessage `json:"input"` |
| 94 | } |
| 95 | if json.Unmarshal(raw, &q) != nil || !denied(out) && !s.Permit(q.Tool, q.Input) { |
| 96 | out, _ = json.Marshal(map[string]string{"behavior": "deny", "message": "a probe launch runs only its own script"}) |
| 97 | } |
| 98 | ask(fprobe.Ask{Tool: q.Tool, ToolUseID: q.ToolUseID, Input: q.Input, Allowed: !denied(out)}) |
| 99 | return out |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | // fprobeEvery is how often the loop looks whether a launch is due. |
| 104 | const fprobeEvery = 15 * time.Minute |
| 105 | |
| 106 | func newMacEngineering(h *macHost) *macEngineering { |
| 107 | return &macEngineering{h: h, poke: make(chan struct{}, 1)} |
| 108 | } |
| 109 | |
| 110 | // bind gives the probes the worker that launches them, its connections |
| 111 | // and its capability report. |
| 112 | func (e *macEngineering) bind(w *Worker, conns *Conns, caps func(context.Context) wire.Capabilities) { |
| 113 | e.mu.Lock() |
| 114 | e.worker, e.conns, e.caps = w, conns, caps |
| 115 | e.mu.Unlock() |
| 116 | e.soon() |
| 117 | } |
| 118 | |
| 119 | // soon asks the loop to look now (a connection changed, P2 reported). |
| 120 | func (e *macEngineering) soon() { |
| 121 | if e == nil { |
| 122 | return |
| 123 | } |
| 124 | select { |
| 125 | case e.poke <- struct{}{}: |
| 126 | default: |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | // p2 is whether this process's trusted P2 is denied. |
| 131 | func (e *macEngineering) p2() bool { |
| 132 | r, ok := e.h.probes.trusted() |
| 133 | return ok && r.Sandboxed() |
| 134 | } |
| 135 | |
| 136 | // conn is why no Claude connection is usable ("" when one is). |
| 137 | func (e *macEngineering) conn(caps *wire.Capabilities) (string, string) { |
| 138 | e.mu.Lock() |
| 139 | conns := e.conns |
| 140 | e.mu.Unlock() |
| 141 | switch { |
| 142 | case caps.Unproven == wire.UnprovenCredential: |
| 143 | // The Mac's connections are closed until a launch's end is proven. |
| 144 | return wire.EngineeringNoConnection, wire.UnprovenCredential |
| 145 | case conns == nil: |
| 146 | return wire.EngineeringNoConnection, "" |
| 147 | } |
| 148 | return fprobe.ConnState(conns.Held(), conns.Usable), "" |
| 149 | } |
| 150 | |
| 151 | // compose adds F1 to F7 to caps, sets its Engineering status from them, |
| 152 | // the guards' status (credentialCaps) and the connections, and gives the |
| 153 | // claude tag with ready. |
| 154 | func (e *macEngineering) compose(caps *wire.Capabilities) { |
| 155 | if e == nil { |
| 156 | return |
| 157 | } |
| 158 | st, probes := e.decide(caps) |
| 159 | caps.Probes, caps.Engineering = append(caps.Probes, probes...), &st |
| 160 | if st.State == wire.EngineeringReady { |
| 161 | caps.Tags = append(caps.Tags, wire.TagClaude) |
| 162 | } |
| 163 | e.mu.Lock() |
| 164 | e.last = probes |
| 165 | e.mu.Unlock() |
| 166 | } |
| 167 | |
| 168 | // decide is the status and F1 to F7 for caps (its inputs, its guards' |
| 169 | // status, its Unproven) and the connections, now. |
| 170 | func (e *macEngineering) decide(caps *wire.Capabilities) (wire.EngineeringStatus, []wire.Probe) { |
| 171 | verified := caps.Harness.Claude != "" |
| 172 | probes := e.store.Probes(fprobe.NewInputs(e.h.version, verified, caps.Xcode, caps.Simulators), e.clock(), e.p2()) |
| 173 | conn, why := e.conn(caps) |
| 174 | p2 := "" |
| 175 | if r, ok := e.h.probes.trusted(); ok { |
| 176 | p2 = r.Probe("P2").Verdict |
| 177 | } |
| 178 | return fprobe.Status(fprobe.State{Guards: caps.Engineering, CLI: verified, Probes: probes, Conn: conn, ConnReason: why, P2: p2}), probes |
| 179 | } |
| 180 | |
| 181 | // xcode: F5 is denied as the newest capability report says it. |
| 182 | func (e *macEngineering) xcode() bool { |
| 183 | if e == nil { |
| 184 | return false |
| 185 | } |
| 186 | e.mu.Lock() |
| 187 | defer e.mu.Unlock() |
| 188 | return fprobe.XcodeAllowed(e.last) |
| 189 | } |
| 190 | |
| 191 | // start runs the due launches now and whenever asked, or every |
| 192 | // fprobeEvery; refresh tells the instance after a run. |
| 193 | func (e *macEngineering) start(ctx context.Context, refresh func()) { |
| 194 | go func() { |
| 195 | for { |
| 196 | if host, ok := e.host(ctx); ok { |
| 197 | if results := e.store.Run(ctx, host); len(results) > 0 && ctx.Err() == nil { |
| 198 | if e.h.log != nil { |
| 199 | var v []string |
| 200 | for _, r := range results { |
| 201 | v = append(v, verdicts(r.Probes)) |
| 202 | } |
| 203 | e.h.log.Info("engineering probes finished", "verdicts", strings.Join(v, " ")) |
| 204 | } |
| 205 | refresh() |
| 206 | } |
| 207 | } |
| 208 | select { |
| 209 | case <-ctx.Done(): |
| 210 | return |
| 211 | case <-e.poke: |
| 212 | case <-time.After(fprobeEvery): |
| 213 | } |
| 214 | } |
| 215 | }() |
| 216 | } |
| 217 | |
| 218 | // host is the probes' view of this Mac now; false while they cannot run |
| 219 | // (no worker yet, no usable Claude connection). |
| 220 | func (e *macEngineering) host(ctx context.Context) (fprobe.Host, bool) { |
| 221 | e.mu.Lock() |
| 222 | w, conns, capsOf := e.worker, e.conns, e.caps |
| 223 | e.mu.Unlock() |
| 224 | if w == nil || w.Eng == nil || conns == nil || capsOf == nil { |
| 225 | return fprobe.Host{}, false |
| 226 | } |
| 227 | // The connections first: without a usable one nothing runs, and the |
| 228 | // capability report is not gathered for nothing (its first gathering |
| 229 | // is the first hello's). |
| 230 | if fprobe.ConnState(conns.Held(), conns.Usable) != "" { |
| 231 | return fprobe.Host{}, false |
| 232 | } |
| 233 | caps := capsOf(ctx) |
| 234 | if c, _ := e.conn(&caps); c != "" { |
| 235 | return fprobe.Host{}, false |
| 236 | } |
| 237 | h, cfg := e.h, w.Engine.O.Runner |
| 238 | var tokens []string |
| 239 | for _, b := range conns.bindings() { |
| 240 | if b.Provider == wire.ProviderClaude && b.Kind == wire.KindToken { |
| 241 | tokens = append(tokens, filepath.Join(b.ProviderHome, provider.TokenFile)) |
| 242 | } |
| 243 | } |
| 244 | return fprobe.Host{ |
| 245 | // The inputs each launch runs under, read afresh (not the report). |
| 246 | Live: func(ctx context.Context) (fprobe.Inputs, []wire.Simulator) { |
| 247 | c := e.readNow(ctx) |
| 248 | return fprobe.NewInputs(h.version, c.Harness.Claude != "", c.Xcode, c.Simulators), c.Simulators |
| 249 | }, |
| 250 | Paths: h.paths, RuntimeRoot: filepath.Join(cfg.ScratchRoot, "homes"), TokenFiles: tokens, Runner: cfg.Executable, |
| 251 | Tools: h.tools, Simulators: caps.Simulators, Scratch: filepath.Join(h.scratch, "fprobe"), P2Denied: e.p2(), |
| 252 | Secrets: func(ctx context.Context) ([][]byte, error) { |
| 253 | s, err := w.Eng.Secrets(ctx) |
| 254 | return secretForms(s), err |
| 255 | }, |
| 256 | Turns: h.turns, Launch: w.probeLaunch, |
| 257 | Listen: func() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") }, |
| 258 | Resolve: func(ctx context.Context, name string) bool { |
| 259 | addrs, err := net.DefaultResolver.LookupHost(ctx, name) |
| 260 | return err == nil && len(addrs) > 0 |
| 261 | }, |
| 262 | Exposed: mac.Exposed, Exec: h.run, Lookup: proc.Platform.Lookup, |
| 263 | Alive: func(id proc.ID) (bool, bool) { return proc.Alive(proc.Platform, id) }, |
| 264 | }, true |
| 265 | } |
| 266 | |
| 267 | // probeNote, in tests, adds the fake CLI's directives to a probe |
| 268 | // launch's prompt (nil in a release). |
| 269 | var probeNote func(fprobe.Spec) string |
| 270 | |
| 271 | // probeLaunch is one probe launch: the Engineering launch itself |
| 272 | // (w.launch: the guards, the runtime copy, the policy for the probe tree |
| 273 | // at its real path, the token by descriptor, the Keychain watch, the |
| 274 | // proven stop), on the Mac's first usable Claude connection and its |
| 275 | // small model, with no step log and no kept session, before the Mac is |
| 276 | // ready. Its permission tool is probePermission; its scratch (TMPDIR) is |
| 277 | // the probe's, where only the script writes; obs sees the runtime copy |
| 278 | // before the CLI starts, the CLI's pid once its group is on record (only |
| 279 | // that counts as started) and every frame of its stream. |
| 280 | func (w *Worker) probeLaunch(ctx context.Context, s fprobe.Spec, obs fprobe.Observer) fprobe.Outcome { |
| 281 | e := w.Engine |
| 282 | for _, c := range e.Conns.bindings() { |
| 283 | if c.Provider != wire.ProviderClaude || c.Kind != wire.KindToken || !e.Conns.Usable(c.ID) { |
| 284 | continue |
| 285 | } |
| 286 | c.Model = provider.ClaudeGlanceModel |
| 287 | prompt := s.Prompt |
| 288 | if probeNote != nil { |
| 289 | prompt += probeNote(s) |
| 290 | } |
| 291 | var started atomic.Bool |
| 292 | r := stepRow{DispatchCommand: wire.DispatchCommand{TaskID: "fprobe", StepID: s.Launch, Attempt: 1}} |
| 293 | if s.Xcode { |
| 294 | r.XcodeAccess = wire.XcodeAccessSandboxed |
| 295 | } |
| 296 | perm := probePermission(claude.StepPermission, s, func(q fprobe.Ask) { |
| 297 | if obs.Ask != nil { |
| 298 | obs.Ask(q) |
| 299 | } |
| 300 | }) |
| 301 | spec := specialistRun{action: "implement", binding: c, tools: stepTools, names: []string{"submit_candidate", "ask_person", "submit_render"}, permission: perm, |
| 302 | call: func(context.Context, string, string, json.RawMessage) (string, bool) { return stepToolText, false }, prompt: prompt, limit: s.Limit, noLog: true, probe: true, |
| 303 | scratch: s.Scratch, copied: obs.Copy, tap: obs.Event, |
| 304 | record: func(_ context.Context, id string) error { |
| 305 | // pg:<pid>:<marker>: the CLI leads its own group. |
| 306 | if f := strings.SplitN(id, ":", 3); len(f) == 3 && f[1] != "0" && started.CompareAndSwap(false, true) && obs.Started != nil { |
| 307 | if pid, err := strconv.Atoi(f[1]); err == nil { |
| 308 | obs.Started(pid) |
| 309 | } |
| 310 | } |
| 311 | return nil |
| 312 | }} |
| 313 | res := w.launch(ctx, r, workspace.TaskTree{Dir: s.Tree}, spec, "fprobe-"+s.Launch+"-"+strings.ReplaceAll(uuid(), "-", "")[:12], nil) |
| 314 | return fprobe.Outcome{Started: started.Load(), Proven: res.terminated, Reason: res.reason} |
| 315 | } |
| 316 | return fprobe.Outcome{Reason: "no_connection"} |
| 317 | } |
| 318 | |