package fprobe import ( "bytes" "context" "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "io/fs" "net" "os" "path/filepath" "strings" "sync" "sync/atomic" "syscall" "time" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/runner/mac/proc" "amadan.net/oficina/equipo/internal/wire" ) // Host is what the probes reach on the Mac. Every effect goes through it, // so the probes run on Linux against fakes and recorded outputs. type Host struct { // Inputs are the inputs now (NewInputs), recorded with each result. Inputs Inputs // Paths are the ยง4.2 places; RuntimeRoot holds the connections' // runtime copies; TokenFiles are where each Claude connection keeps // its token (F3 reads them by path, F6 natively). Paths mac.Paths RuntimeRoot string TokenFiles []string // Tools are Xcode's (F5, F7); Simulators the capability report's. Tools mac.Tools Simulators []wire.Simulator // Scratch is where probe trees are made (outside every denied place). Scratch string // P2Denied: this process's trusted P2 is denied (F5 runs only then). P2Denied bool // Secrets are the forms of every secret the runner knows (each // connection's token, raw, hex and base64): F3 searches for them. Secrets func(context.Context) ([][]byte, error) // Turns is the Mac's turns: a probe run is one OpProbe turn, its // launches inside it. nil takes none (tests). Turns *mac.Turns // Launch runs one probe launch of the pinned CLI with s's settings, // worktree, prompt and limit, and returns once its end is known; ask // hears each permission request the runner's tool answered, with its // answer, before the CLI acts on it. Launch func(ctx context.Context, s Spec, obs Observer) Outcome // Live is the inputs now, read afresh (nil: Inputs); Runner is the // runner's binary (its __fprobe helper); ProcArgs reads a process's // KERN_PROCARGS2 outside the sandbox (nil: ProcArgs); Alive tells // whether a process is still running, and whether that is known. Live func(context.Context) (Inputs, []wire.Simulator) Runner string ProcArgs func(pid int) ([]byte, error) Alive func(proc.ID) (alive, known bool) // Listen opens a loopback port whose accepts are ground truth; // Resolve looks a name up outside the sandbox; Exposed is P4's (the // runner user can list a home by Unix permissions); Exec runs a // command outside the sandbox (F7's control, F5's Keychain item); // Lookup reads a process of the runner user (F4). Listen func() (net.Listener, error) Resolve func(ctx context.Context, name string) bool Exposed func(home string) bool Exec mac.Exec Lookup func(pid int) (proc.Info, bool) // Now is the clock (nil: time.Now). Now func() time.Time // Limits bound each launch (nil: the defaults). Limits map[string]time.Duration } // limits are each launch's bound: A makes about a hundred tool calls, B // builds and tests P2's fixture (P2's own bound is 20 minutes), C waits // only for its child to start. var limits = map[string]time.Duration{LaunchA: 20 * time.Minute, LaunchB: 25 * time.Minute, LaunchC: 5 * time.Minute} func (h Host) limit(l string) time.Duration { if d, ok := h.Limits[l]; ok { return d } return limits[l] } func (h Host) now() time.Time { if h.Now != nil { return h.Now() } return time.Now() } // live is the inputs read now. func (h Host) live(ctx context.Context) Inputs { in, _ := h.fresh(ctx) return in } // fresh is the inputs and the simulators read now, together (#7: a // launch runs on the simulators its inputs name). func (h Host) fresh(ctx context.Context) (Inputs, []wire.Simulator) { if h.Live != nil { return h.Live(ctx) } return h.Inputs, h.Simulators } // procArgs reads pid's KERN_PROCARGS2 outside the sandbox. func (h Host) procArgs(pid int) ([]byte, error) { if h.ProcArgs != nil { return h.ProcArgs(pid) } return ProcArgs(pid) } // Spec is one probe launch. Protected execution evidence (the // controller's ruling, fix round 1): the model is the actor, so nothing // it can write or say counts. The one Bash command the launch's // permission tool allows is Command, the runner's script with this run's // nonce, and only while the script's bytes hash to ScriptSHA256. The // script lies in a directory outside the worktree and the scratch, which // no sandboxed command and no native write can reach; it records into // the launch's scratch, which native writes cannot reach and only the // script's Bash writes. type Spec struct { Launch string // Xcode: the sandboxed-Xcode settings (launch B); else no Xcode. Xcode bool // Tree is the probe tree, the launch's worktree (a real path). Tree string // Scratch is the launch's scratch (TMPDIR), where only the script // writes; Script the probe script, ScriptSHA256 its digest, Nonce this // run's argument (Command). Scratch, Script, ScriptSHA256, Nonce string // Protected are directories the script runs (F5's fixture) or reads, // beside it; ProtectedSHA256 is the digest of every file in them. Protected []string ProtectedSHA256 string // Prompt asks the model to run Command (and in A to make the native // tool calls); Limit bounds the launch. Prompt string Limit time.Duration } // Command is the one Bash command a probe launch may run. func (s Spec) Command() string { return "bash " + s.Script + " " + s.Nonce } // Permit is whether the probe launch's permission tool may allow a // request its Engineering rules allow: Bash only as Command, with the // script unchanged; a native write only inside the tree. func (s Spec) Permit(tool string, input json.RawMessage) bool { var in struct { Command string `json:"command"` FilePath string `json:"file_path"` NotebookPath string `json:"notebook_path"` } if json.Unmarshal(input, &in) != nil { return false } switch tool { case "Bash": if in.Command != s.Command() || s.Script == "" { return false } b, ok := readFile(s.Script, 1<<20) sum := sha256.Sum256(b) // Every protected input too, as it is now, just before the run. tree, err := treeDigest(s.Protected) return ok && hex.EncodeToString(sum[:]) == s.ScriptSHA256 && (len(s.Protected) == 0 || err == nil && tree == s.ProtectedSHA256) case "Write", "Edit", "MultiEdit", "NotebookEdit": p := filepath.Clean(firstNonEmpty(in.FilePath, in.NotebookPath)) return s.Tree != "" && strings.HasPrefix(p, s.Tree+"/") } return true } // Observer is what the runner sees of a probe launch while it runs. type Observer struct { // Ask hears each answer of the runner's permission tool, before the // CLI acts on it. Ask func(Ask) // Started is the CLI's process once its group is on record. Started func(pid int) // Copy is the connection's runtime copy, before the CLI starts. Copy func(dir string) error // Event is each frame of the CLI's stream. Event func(frame []byte) } // Ask is one permission request the runner's tool answered. type Ask struct { Tool string ToolUseID string Input json.RawMessage Allowed bool } // path is the file or directory a native tool's request names. func (a Ask) path() string { return inputPath(a.Input) } func inputPath(raw json.RawMessage) string { var in struct { FilePath string `json:"file_path"` Path string `json:"path"` } _ = json.Unmarshal(raw, &in) return filepath.Clean(firstNonEmpty(in.FilePath, in.Path)) } // Outcome is how a probe launch ended: whether the CLI started, whether // its end (and its descendants') is proven, and why it did not start or // finish ("" when it finished). type Outcome struct { Started, Proven bool Reason string } // Run runs the launches due now (Due) in one OpProbe turn, keeping each // result, and returns them. Each launch's inputs are read afresh before // it and again after it: a launch they changed under is undecided. A // launch the turn could not be taken for, or that could not start, is // undecided too: tried again after Retry. func (s *Store) Run(ctx context.Context, h Host) []Result { h.Inputs = h.live(ctx) due := s.Due(h.Inputs, h.now(), h.P2Denied) if len(due) == 0 { return nil } var out []Result ctx, give, err := h.Turns.Hold(ctx, mac.OpProbe) if err != nil { for _, l := range due { s.try(l, h.Inputs, h.now()) out = append(out, undecided(l, h, wire.ProbeDetailTurnBusy)) } return out } defer give() for _, l := range due { h.Inputs, h.Simulators = h.fresh(ctx) at := h.now() s.try(l, h.Inputs, at) var probes []wire.Probe switch l { case LaunchA: probes = launchA(ctx, h) case LaunchB: probes = launchB(ctx, h) case LaunchC: probes = launchC(ctx, h) } r := Result{Launch: l, Inputs: h.Inputs, At: at, Probes: probes} if h.live(context.WithoutCancel(ctx)).changed(h.Inputs) != "" { r.Probes = undecided(l, h, "inputs_changed").Probes } s.Put(r) out = append(out, r) if ctx.Err() != nil { break } } return out } // undecided is launch l's probes, each unavailable for why. func undecided(l string, h Host, why string) Result { r := Result{Launch: l, Inputs: h.Inputs, At: h.now()} for _, id := range launchProbes[l] { r.Probes = append(r.Probes, wire.Probe{ID: id, Verdict: wire.ProbeUnavailable, Detail: why}) } return r } // all is every probe of launch l with one verdict and detail. func all(l, verdict, detail string) []wire.Probe { var out []wire.Probe for _, id := range launchProbes[l] { out = append(out, wire.Probe{ID: id, Verdict: verdict, Detail: detail}) } return out } // reasonCode is a launch's reason as a detail parameter: a code, never // words ("unknown" otherwise). func reasonCode(r string) string { if r == "" || len(r) > 40 || strings.Trim(r, "abcdefghijklmnopqrstuvwxyz0123456789_") != "" { return "unknown" } return r } // launched is what a launch's outcome says for its probes before any // observation: unavailable when the CLI never started, failed when its // end is not proven (nothing it did can be trusted), nil to go on. func launched(l string, o Outcome) []wire.Probe { switch { case !o.Started: return all(l, wire.ProbeUnavailable, wire.ProbeDetail("launch_not_started", reasonCode(o.Reason))) case !o.Proven: return all(l, wire.ProbeFailed, wire.ProbeDetail("launch_unproven")) } return nil } // launchDir is one launch's places, all fresh and the runner's: the tree // (the worktree), run (the scratch, where only the script writes) and bin // (the script and the runner's lists for it, which nothing in the launch // can write). type launchDir struct { root, run, bin string t *tree } func newLaunchDir(scratch string) (*launchDir, error) { if err := os.MkdirAll(scratch, 0o700); err != nil { return nil, err } dir, err := os.MkdirTemp(scratch, "fprobe-") if err != nil { return nil, err } root, err := filepath.EvalSymlinks(dir) if err != nil { os.RemoveAll(dir) return nil, err } d := &launchDir{root: root, run: filepath.Join(root, "run"), bin: filepath.Join(root, "bin"), t: &tree{root: filepath.Join(root, "tree"), planted: map[string][]byte{}}} for _, p := range []string{d.t.root, d.run, d.bin} { if err := os.Mkdir(p, 0o700); err != nil { d.remove() return nil, err } } return d, nil } // remove deletes the launch's places whole (nothing is kept). func (d *launchDir) remove() { os.RemoveAll(d.root) } // spec is the launch's Spec with its script written (0500, in bin). func (d *launchDir) spec(l, script string, xcode bool) (Spec, error) { path := filepath.Join(d.bin, "probe-"+strings.ToLower(l)+".sh") if err := os.WriteFile(path, []byte(script), 0o500); err != nil { return Spec{}, err } sum := sha256.Sum256([]byte(script)) return Spec{Launch: l, Xcode: xcode, Tree: d.t.root, Scratch: d.run, Script: path, ScriptSHA256: hex.EncodeToString(sum[:]), Nonce: nonce()}, nil } // protect makes dir (inside bin) one of the spec's protected inputs and // records the digest of every file in them. func (d *launchDir) protect(s *Spec, dir string) error { if !strings.HasPrefix(dir, d.bin+"/") { return errors.New("fprobe: a protected input outside bin") } s.Protected = append(s.Protected, dir) sum, err := treeDigest(s.Protected) s.ProtectedSHA256 = sum return err } // treeDigest is the digest of every entry under dirs: each path, kind, // mode and content (a link's target), in order. func treeDigest(dirs []string) (string, error) { h := sha256.New() for _, dir := range dirs { err := filepath.WalkDir(dir, func(p string, e fs.DirEntry, err error) error { if err != nil { return err } info, err := os.Lstat(p) if err != nil { return err } fmt.Fprintf(h, "%s %v\n", p, info.Mode()) switch { case info.Mode()&fs.ModeSymlink != 0: t, err := os.Readlink(p) if err != nil { return err } h.Write([]byte(t)) case info.Mode().IsRegular(): b, err := os.ReadFile(p) if err != nil { return err } fmt.Fprintf(h, "%d\n", len(b)) h.Write(b) } return nil }) if err != nil { return "", err } } return hex.EncodeToString(h.Sum(nil)), nil } // list writes one of the runner's lists for the script. func (d *launchDir) list(name string, lines []string) error { body := strings.Join(lines, "\n") if body != "" { body += "\n" } return os.WriteFile(filepath.Join(d.bin, name), []byte(body), 0o600) } // read is what the script recorded under run/out. func (d *launchDir) read(name string) string { b, _ := readFile(filepath.Join(d.run, "out", name), 1<<20) return string(b) } // find searches the tree and the scratch (where[rel] = "tree" or // "scratch"). func (d *launchDir) find(needles map[string][][]byte) (map[string][]string, bool) { hits, whole := d.t.find(needles) run := &tree{root: d.run, planted: map[string][]byte{}} rh, rwhole := run.find(needles) for k, files := range rh { for _, f := range files { hits[k] = append(hits[k], "scratch:"+f) } } return hits, whole && rwhole } // where splits found files into the scratch's (the script's) and the // tree's, by base name. func where(files []string) (scratch, inTree []string) { for _, f := range files { if rest, ok := strings.CutPrefix(f, "scratch:"); ok { scratch = append(scratch, filepath.Base(rest)) } else { inTree = append(inTree, filepath.Base(f)) } } return scratch, inTree } // evidence is what the runner saw of a launch: its tool's answers, the // CLI's tool events, the CLI's pid. type evidence struct { mu sync.Mutex asks []Ask uses []*toolUse ids map[string]*toolUse pid int } // toolUse is one tool call as the CLI's own stream reports it: its // tool_use, and its tool_result once that comes. type toolUse struct { ID, Tool string Input json.RawMessage Done, Error bool Text string } func (e *evidence) ask(q Ask) { e.mu.Lock(); e.asks = append(e.asks, q); e.mu.Unlock() } func (e *evidence) started(pid int) { e.mu.Lock(); e.pid = pid; e.mu.Unlock() } // event reads one frame of the CLI's stream: an assistant message's // tool_use blocks and a user message's tool_result blocks. Anything else // (model text among it) is not evidence and is ignored. func (e *evidence) event(frame []byte) { var f struct { Type string `json:"type"` Message struct { Content []struct { Type string `json:"type"` ID string `json:"id"` Name string `json:"name"` Input json.RawMessage `json:"input"` ToolUseID string `json:"tool_use_id"` IsError bool `json:"is_error"` Content json.RawMessage `json:"content"` } `json:"content"` } `json:"message"` } if json.Unmarshal(frame, &f) != nil { return } e.mu.Lock() defer e.mu.Unlock() if e.ids == nil { e.ids = map[string]*toolUse{} } for _, c := range f.Message.Content { switch { case f.Type == "assistant" && c.Type == "tool_use" && c.ID != "": u := &toolUse{ID: c.ID, Tool: c.Name, Input: c.Input} e.uses = append(e.uses, u) e.ids[c.ID] = u case f.Type == "user" && c.Type == "tool_result" && e.ids[c.ToolUseID] != nil: u := e.ids[c.ToolUseID] u.Done, u.Error, u.Text = true, c.IsError, resultText(c.Content) } } } // resultText is a tool_result's content: a string, or its text blocks. func resultText(raw json.RawMessage) string { var s string if json.Unmarshal(raw, &s) == nil { return s } var blocks []struct { Text string `json:"text"` } _ = json.Unmarshal(raw, &blocks) var b strings.Builder for _, x := range blocks { b.WriteString(x.Text) } return b.String() } func (e *evidence) observer() Observer { return Observer{Ask: e.ask, Started: e.started, Event: e.event} } // judged is a launch's probes unless the evidence does not hold: the // runner's tool never allowed Command, it allowed some other Bash // command, or the scratch does not hold this run's begin and end. Then no // success verdict stands, and each failure says why first. func (e *evidence) judged(probes []wire.Probe, s Spec, d *launchDir) []wire.Probe { return e.judgedEnd(probes, s, d, true) } // judgedEnd is judged; with end false the script's end is not required // (launch C is cancelled by design while its script waits). func (e *evidence) judgedEnd(probes []wire.Probe, s Spec, d *launchDir, end bool) []wire.Probe { e.mu.Lock() ran, other := false, false for _, q := range e.asks { var in struct { Command string `json:"command"` } _ = json.Unmarshal(q.Input, &in) if q.Tool == "Bash" && q.Allowed { ran, other = ran || in.Command == s.Command(), other || in.Command != s.Command() } } e.mu.Unlock() switch { case !ran: return notRun(probes, wire.ProbeDetail("script_not_run")) case other: return notRun(probes, wire.ProbeDetail("other_command")) case strings.TrimSpace(d.read("begin")) != "begin "+s.Nonce || end && strings.TrimSpace(d.read("end")) != "end "+s.Nonce: return notRun(probes, wire.ProbeDetail("records_foreign")) } return probes } // notRun marks probes for why: no success verdict stands, and each // failure says why first. func notRun(probes []wire.Probe, why string) []wire.Probe { for i, p := range probes { switch p.Verdict { case wire.EngineeringProbeSuccess(p.ID): probes[i].Verdict, probes[i].Detail = wire.ProbeFailed, why case wire.ProbeFailed: probes[i].Detail = wire.ProbeDetails(why, p.Detail) } } return probes } // tree is the launch's worktree. planted maps each path the runner put // there to what it wrote (nil for a link): a planted file that no longer // holds it is searched like any other. type tree struct { root string planted map[string][]byte } func (t *tree) path(rel string) string { return filepath.Join(t.root, rel) } // plant writes a file the runner owns in the tree. func (t *tree) plant(rel string, body []byte, mode os.FileMode) error { p := t.path(rel) if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { return err } t.planted[p] = body return os.WriteFile(p, body, mode) } // mark notes a path the runner made some other way (a link). func (t *tree) mark(rel string) string { p := t.path(rel); t.planted[p] = nil; return p } func readFile(p string, max int64) ([]byte, bool) { info, err := os.Lstat(p) if err != nil || !info.Mode().IsRegular() { return nil, false } f, err := os.OpenFile(p, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0) if err != nil { return nil, false } defer f.Close() b, err := io.ReadAll(io.LimitReader(f, max+1)) return b, err == nil && int64(len(b)) <= max } // scanBound bounds what the search reads of a tree. const scanBound = 64 << 20 // find searches every regular file the runner did not plant (links are // never followed) for each of needles, and returns, per needle, the // files (relative) holding it. whole is false when the tree held more // than the search reads or a file could not be read whole: nothing it // did not read may count as absent. func (t *tree) find(needles map[string][][]byte) (hits map[string][]string, whole bool) { hits, whole = map[string][]string{}, true var read int64 _ = filepath.WalkDir(t.root, func(p string, d fs.DirEntry, err error) error { if err != nil { whole = false return nil } want, planted := t.planted[p] if d.IsDir() || planted && want == nil || !d.Type().IsRegular() { return nil } b, ok := readFile(p, scanBound-read) read += int64(len(b)) if !ok { whole = false return nil } if planted && bytes.Equal(b, want) { return nil } rel, _ := filepath.Rel(t.root, p) for name, forms := range needles { for _, f := range forms { if len(f) > 0 && bytes.Contains(b, f) { hits[name] = append(hits[name], rel) break } } } return nil }) return hits, whole } // records reads a script's record file: "name code" per line, the first // line for a name counting. func records(raw string) map[string]string { out := map[string]string{} for _, line := range strings.Split(raw, "\n") { f := strings.Fields(line) if len(f) == 2 { if _, seen := out[f[0]]; !seen { out[f[0]] = f[1] } } } return out } // listener is a loopback port that counts what reached it. type listener struct { l net.Listener hits atomic.Int64 wg sync.WaitGroup } func listen(h Host) (*listener, error) { l, err := h.Listen() if err != nil { return nil, err } x := &listener{l: l} x.wg.Add(1) go func() { defer x.wg.Done() for { c, err := l.Accept() if err != nil { return } x.hits.Add(1) c.Close() } }() return x, nil } func (x *listener) port() string { _, p, _ := net.SplitHostPort(x.l.Addr().String()) return p } // close stops it and says how many connections it saw. func (x *listener) close() int64 { x.l.Close() x.wg.Wait() return x.hits.Load() } // nonce is a fresh sentinel value: what no sandboxed command may read. func nonce() string { b := make([]byte, 16) _, _ = rand.Read(b) return "EQUIPO-NONCE-" + hex.EncodeToString(b) } // tag is a short fresh name part. func tag() string { return strings.TrimPrefix(nonce(), "EQUIPO-NONCE-")[:12] } // quote is s as one shell word. func quote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" } func firstNonEmpty(s ...string) string { for _, x := range s { if x != "" { return x } } return "" }