Skip to main content

safe_chains/engine/
resolve.rs

1//! The profile resolver — turning a parsed command into its behavior profile
2//! (annex `behavioral-taxonomy-engine`). Runs via `engine::bridge`, which is
3//! AUTHORITATIVE for every command it can resolve (`engine_verdict(tokens).unwrap_or(legacy)`
4//! in `cst::check::leaf_verdict`) — there is no opt-out.
5//!
6//! This file holds the dispatch (`resolve`) and the per-command `resolve_*` functions;
7//! the shared toolkit they build on lives in submodules: `flags` (the getopt-style
8//! flag walker), `locus` (`classify_locus` — the [`LocalLocus`] ladder that refines the
9//! old `is_safe_write_target` boolean, v1.4 §2.2), and `capability` (the builders that
10//! stamp out each `Capability` with the facet pairing its operation warrants).
11
12use super::facet::*;
13use crate::parse::{Token, has_flag};
14
15mod backup;
16mod capability;
17mod path_verdicts;
18mod tar_paths;
19mod transfer;
20pub(crate) use path_verdicts::{
21    read_content_verdict, read_tree_verdict, rebind_is_stricter_than_write, worst_path_element, write_target_verdict,
22};
23pub(crate) use tar_paths::tar_bound;
24use transfer::resolve_transfer;
25mod flags;
26pub(crate) mod frozen_reach;
27pub(crate) mod frozen_walk;
28pub(crate) mod link_mode;
29pub(crate) mod locus;
30pub(crate) mod regions;
31mod stage_output;
32use stage_output::StageOutput;
33pub(crate) use stage_output::SubClaim;
34#[cfg(test)]
35mod scenarios;
36#[cfg(test)]
37#[path = "resolve/shell_operand_tests.rs"]
38mod shell_operand_tests;
39
40use capability::{
41    breadth_scale, creates, destroys, executes, mutates, observes, observes_path, overwrites, reads_content, reads_path, reads_to_model,
42    worst, writes_export_file,
43};
44use flags::{walk_positionals, walk_value};
45pub(crate) use locus::{FrozenWrite, anchoring_of, frozen_write_kind, is_unpinnable, names_credential_store};
46use locus::{classify_locus, read_locus, write_locus};
47
48/// For `for VAR in ITEMS; do …$VAR…`, the representatives to bind `$VAR` to in the body: the
49/// worst-READ item and the worst-WRITE item of the list (they can differ, so a read and a
50/// write of `$VAR` each get their list's worst case). `$VAR` then inherits the list's locus
51/// per operation — the `find … {}`→path binding, one layer up. `None` for an empty list, which
52/// leaves `$VAR` fail-closed (machine). An item the classifier cannot bound — an UNDECLARED command
53/// substitution, a process substitution, arithmetic — worst-cases to machine via a `$`-carrying
54/// sentinel representative. An item from a substitution whose inner command DECLARED its output
55/// locus is bounded, so it is classified like any other path: `for f in $(fd a app/)` reads the
56/// worktree, and `for f in $(fd a /etc)` still lands at machine because that is what the tag says.
57/// (The test here used to be a `__SAFE_CHAINS_` PREFIX match, which caught the bounded sentinel too
58/// and made the loop form deny while the bare `cat $(fd a app/)` was allowed.)
59pub(crate) fn loop_reprs(items: &[String]) -> Option<(String, String)> {
60    if items.is_empty() {
61        return None;
62    }
63    let faced: Vec<(String, LocalLocus, LocalLocus)> = items
64        .iter()
65        .map(|s| {
66            if crate::cst::check::is_opaque_value(s) {
67                ("$loop_sub".to_string(), LocalLocus::Machine, LocalLocus::Machine)
68            } else {
69                (s.clone(), read_locus(s), write_locus(s))
70            }
71        })
72        .collect();
73    let read_item = faced.iter().max_by_key(|(_, r, _)| *r).map(|(s, _, _)| s.clone())?;
74    let write_item = faced.iter().max_by_key(|(_, _, w)| *w).map(|(s, _, _)| s.clone())?;
75    // Freeze against the CURRENT (outer) loop bindings, so an inner representative like `$d/x`
76    // doesn't carry a stale outer variable into the body — nested loops compose.
77    //
78    // A GLOB item above the workspace gets no representative at all. `for f in /etc/*` binds `$f`
79    // to the literal `/etc/*`, and the body then reads a path whose last component the glob will
80    // choose — `/etc/shadow` among them — while the shield is asked about a string containing a
81    // `*`, which names nothing and clears every time.
82    let read_repr = if crate::engine::resolve::locus::glob_above_workspace(&read_item) {
83        crate::engine::resolve::locus::UNKNOWABLE_ITEM.to_string()
84    } else {
85        crate::pathctx::expand_vars(&read_item, false).into_owned()
86    };
87    let write_repr = crate::pathctx::expand_vars(&write_item, true).into_owned();
88    Some((read_repr, write_repr))
89}
90
91/// The verdict for EXECUTING the code in file `path` — used to gate an interpreter/runner's
92/// script operand (`bash x.sh`, `python x.py`, `node x.js`, `go run pkg/`) by its EXECUTOR
93/// locus. A worktree-local script is the dev loop → admitted at `developer`; a foreign one
94/// (`/tmp/x.sh`, `~/x.py`, `/usr/local/bin/x`) or an unpinnable path (`$VAR`, glob, `..`
95/// beyond cwd → `machine`) denies. `CallerFile` trust (code from a named file). See
96/// docs/design/behavioral-taxonomy-execution-origin.md.
97pub(crate) fn execute_file_verdict(path: &str) -> crate::verdict::Verdict {
98    // `name=/tmp/y/entry.js` is the file after `=`. The `=` separates a name from a path only
99    // when it comes before any slash; `/tmp/foo=bar/ok.js` is one path and is judged whole.
100    if let Some((name, rhs)) = path.split_once('=')
101        && !name.contains('/')
102    {
103        if rhs.is_empty() {
104            return crate::engine::bridge::project(&worst("named entry has no file"));
105        }
106        return execute_file_verdict(rhs);
107    }
108    // A GLOB executor (`bash *.sh`) names no specific file — the matched code is unknown, so
109    // it cannot be pinned to a worktree executor; deny (design §6). ($VAR/../cmdsub are already
110    // worst-cased by classify_locus.) A glob stays fine as a read/write OPERAND, where every
111    // match is locus-gated; only as an EXECUTOR is the code it would run unknowable.
112    if path.contains(['*', '?', '[']) {
113        return crate::engine::bridge::project(&worst("glob executor — the code that would run is unknown (§6)"));
114    }
115    // A PROCESS-SUBSTITUTION executor (`sh <(curl …)`) runs the OUTPUT of the inner command, not
116    // the inner command. The inner command is checked separately and is usually safe on its own —
117    // `curl` prints, `echo` prints — which is exactly how this hid: `sh <(curl …)` auto-approved
118    // while the identical `curl … | sh` denied. A command that is safe to RUN is not the same as a
119    // command whose output is safe to EXECUTE.
120    //
121    // Only in the executor slot. As a DATA operand the sentinel stays worktree-ordinary on purpose,
122    // because reading a `/dev/fd` pipe really is as safe as the inner command (`diff <(ls) <(ls)`).
123    if path.contains(crate::cst::eval::PROCSUB_SENTINEL) {
124        return crate::engine::bridge::project(&worst(
125            "process-substitution executor — the code that would run is a command's output (§6)",
126        ));
127    }
128    // A URL executor (`borg --rsh http://evil/x`, `rsync -e file:~`) is not a workspace file. The
129    // locus layer admits a network URL at `worktree` on purpose — for a network OPERAND the
130    // command's own handler gates the network, and a URL's `..` is a path segment rather than a
131    // filesystem escape. In an EXECUTOR slot that reasoning inverts: the thing has to be a local
132    // file the project owns, and `http://…` is not one however harmless its `..` are. Third member
133    // of the same family as the glob and process-substitution rules above, as is any file below `node_modules` or `.git`.
134    if crate::engine::resolve::locus::is_url(path) || frozen_reach::runs_unreviewed_code(path) {
135        return crate::engine::bridge::project(&worst("URL, package or frozen-folder executor — the code is not the project's own (§6)"));
136    }
137    // An executor slot names a PATH. A value carrying whitespace is a command LINE, and judging it
138    // as one path is how `BORG_RSH='sh -c evil'` and `rsync -e 'sh -c evil'` were auto-approved:
139    // the whole string read as one oddly-named executable, which satisfied the bare-name rule.
140    //
141    // Every whitespace-separated token must therefore look like a path. That keeps the documented
142    // space-separated forms working (`LD_PRELOAD='/a.so /b.so'` judges both), while a token that is
143    // not a path — an interpreter's `-c`, the inline code after it — means the value was never a
144    // path and cannot be judged as one. Stated as a requirement ON the value, not as a list of
145    // forbidden programs: `sh -c evil` fails because `-c` is not a path, not because it is `sh`.
146    //
147    // Fail-CLOSED and known to over-deny: `rsync -e 'ssh -p 2222'` is a legitimate idiom that now
148    // refuses, because vetting a transport's own flags is a question this layer cannot answer.
149    if path.split_whitespace().count() > 1 {
150        let mut worst_seen = None;
151        for token in path.split_whitespace() {
152            if token.starts_with('-') {
153                return crate::engine::bridge::project(&worst(
154                    "executor value is a command line, not a path — a non-path token means the \
155                     code that would run is unknown",
156                ));
157            }
158            let v = execute_file_verdict(token);
159            worst_seen = Some(match worst_seen {
160                None => v,
161                Some(prev) => crate::verdict::Verdict::combine(prev, v),
162            });
163        }
164        return worst_seen.unwrap_or_else(|| crate::engine::bridge::project(&worst("empty executor value")));
165    }
166    let cap = executes(classify_locus(path), ExecutionTrust::CallerFile, "runs code from a named file");
167    crate::engine::bridge::project(&Profile::of(vec![cap]))
168}
169
170/// The verdict for running the CURRENT PROJECT's own code — an implicit-project runner
171/// (`cargo run`, `dotnet run`, `swift run`) with no path operand and no redirect out of the
172/// worktree. `SelfCode` @ `Worktree` → admitted at `developer`. A runner redirected out of the
173/// project (`cargo run --manifest-path ~/o/Cargo.toml`) resolves that path through
174/// [`execute_file_verdict`] instead. See docs/design/behavioral-taxonomy-execution-origin.md.
175pub(crate) fn execute_project_verdict() -> crate::verdict::Verdict {
176    let cap = executes(LocalLocus::Worktree, ExecutionTrust::SelfCode, "runs the current project's own code");
177    crate::engine::bridge::project(&Profile::of(vec![cap]))
178}
179
180/// Resolve a command's leaf tokens to its behavior profile, or `None` if the command
181/// has no resolver yet (the caller then worst-cases / falls back to the legacy
182/// classifier — §0 fail-closed). Redirects, substitutions, and chain semantics are the
183/// surrounding CST's job, not this leaf's (annex `…-engine` §1).
184pub fn resolve(tokens: &[Token]) -> Option<Profile> {
185    capability::with_operands(tokens, resolve_command)
186}
187
188fn resolve_command(tokens: &[Token]) -> Option<Profile> {
189    let arg0 = tokens.first().filter(|t| !crate::handlers::direct_script::is_relative_command_path(t.as_str()))?;
190    // Canonicalize the invoked token through the registry's alias map (`gcat` → `cat`) BEFORE the
191    // resolver lookup: Homebrew installs GNU coreutils as g-prefixed aliases, and without this
192    // they'd miss every resolver and fall through to the ungated legacy classifier (a fail-open —
193    // `gtee /etc/cron.d/job`, `gcat /etc/shadow`). The `tokens` are passed through unchanged; the
194    // resolver gates operands by position, not by re-reading the command name.
195    let canonical = crate::registry::canonical_name(arg0.command_name());
196    // `sudo`/`doas` ELEVATE the wrapped command's authority — they are a delegating wrapper, not a
197    // command of their own. Resolve the inner command and lift its authority to root (or `other-user`
198    // for `-u`), so the safety of `sudo X` is the safety of `X` run privileged: `sudo cat ./notes`
199    // → a root READ (local-admin), `sudo rm -rf /` → the catastrophe corner (denied everywhere).
200    if canonical == "openssl" {
201        return resolve_openssl(arg0, tokens);
202    }
203    if matches!(canonical, "sudo" | "doas") {
204        return resolve_privilege_wrapper(arg0, tokens);
205    }
206    // Phase 1: a subcommand tagged with a facet archetype (`profile = …`) classifies as that
207    // archetype's static capability — the derived, self-documenting successor to `candidate = true`.
208    // Checked BEFORE command-level behavior, since a subcommand tool carries no `[command.behavior]`.
209    if let Some(names) = crate::registry::sub_archetypes(tokens) {
210        if !trusted_command_path(arg0.as_str()) {
211            return Some(worst("resolvable name invoked from a non-standard path — possible spoof (§0)"));
212        }
213        // An endpoint flag pointed at THIS machine makes the sub a DIFFERENT operation, not the same
214        // one with softened edges: `put-item --endpoint-url http://localhost:8000` writes to a
215        // process here, so `remote-mutate`'s `sends-host-data`, `effortful` reversibility and (for
216        // create) `metered` cost are all describing a cloud service that isn't in the picture. The
217        // sub names the archetype it becomes, so the substitution stays reviewable data rather than
218        // ad-hoc facet arithmetic at resolve time.
219        //
220        // Destroy archetypes may not declare a substitute at all — `assert_no_loopback_profile_on_
221        // destroy` refuses it at build time. We cannot verify the emulator claim (`ssh -L
222        // 8000:dynamodb.us-east-1.amazonaws.com:443` makes `localhost:8000` production, and no
223        // static classifier sees the tunnel), and that lie is only unrecoverable in the destroy
224        // direction.
225        // One capability per archetype (the sub's profile + each present escalating flag); the level
226        // algebra takes the max. Fail-closed: an unknown archetype name → a worst capability, so a
227        // typo or `unclassified` can never silently pass (a proptest catches typos at test time).
228        let mut caps: Vec<Capability> = names
229            .iter()
230            .map(|n| {
231                crate::engine::archetype::archetype(n)
232                    .cloned()
233                    .unwrap_or_else(|| Capability::worst("subcommand/flag declares an unknown archetype (§0)"))
234            })
235            .collect();
236        // Destination-trust (exposure §4): a sub tagged `network_destination` gets its send TARGET
237        // classified onto the base archetype's `locus.provenance` — established remote / literal URL
238        // / opaque `$VAR` — or, for a command-transport form (`ext::…`), worst-cased as RCE.
239        if let Some(dest) = crate::registry::sub_destination_token(tokens) {
240            match destination_provenance(dest) {
241                Some(prov) => {
242                    if let Some(base) = caps.first_mut() {
243                        base.locus.provenance = prov;
244                    }
245                }
246                None => {
247                    return Some(worst("send target is a command transport (ext::…) — runs a local command, RCE (§4)"));
248                }
249            }
250        }
251        // A `data-export` sub with an OUTPUT-FILE flag (`db dump -f out.sql`) writes its bulk result
252        // to a local file — a SECOND capability beyond the remote read, gated at the file's locus
253        // (worktree write vs a system-path clobber). Absent → the export streams to stdout, so the
254        // profile is the remote read alone.
255        if let Some(path) = crate::registry::sub_output_path_token(tokens) {
256            caps.push(writes_export_file(classify_locus(path)));
257        }
258        // A declared endpoint flag naming THIS machine changes WHERE the call goes, so it changes
259        // exactly the facets the destination determines and nothing else. That boundary is the whole
260        // design: `remote-mutate` describes a cloud service in four places — it reaches a fixed
261        // remote, talks outbound, sends host data off the machine, and bills — and all four are
262        // false for `http://localhost:8000`. Its other facets (what the operation DOES: the
263        // operation itself, scale, retrieval, reversibility, persistence, disclosure) are properties
264        // of the call, not of its destination, and stay untouched.
265        //
266        // Composing rather than substituting a whole "local" archetype matters twice over: the
267        // remote archetypes do not each need a local twin, and nothing here asserts a fact the
268        // destination cannot establish. (An earlier cut swapped in `local-mutate-recoverable`, which
269        // claims `locus.local = worktree` and `persistence = data` — both untrue of a container.)
270        //
271        // DESTROY is skipped here and refused outright at build time by
272        // `assert_loopback_localizes_is_coherent`. The emulator claim is unverifiable: `ssh -L
273        // 8000:dynamodb.<region>.amazonaws.com:443` makes `localhost:8000` production and no static
274        // classifier sees the tunnel. Being wrong costs a stray write; being wrong about a delete
275        // costs the data.
276        if crate::registry::sub_loopback_localizes(tokens) {
277            for c in &mut caps {
278                if c.operation == Operation::Destroy {
279                    continue;
280                }
281                c.locus.remote = RemoteReach::None;
282                c.network.direction = NetDirection::Loopback;
283                c.network.payload = NetPayload::None;
284                c.cost = Cost::None;
285                // The archetype's prose describes the cloud call and is now half wrong; say so,
286                // or `--explain` prints "changes remote state" over a profile that reaches no
287                // remote. The facets carry the classification, but the prose is what a human reads.
288                c.because = format!("{} — but the endpoint names this machine, so no remote is reached", c.because);
289            }
290        }
291        return Some(Profile::of(caps));
292    }
293    // A flat command whose top-level classifying flag (`[[command.flag]]`) is present resolves to
294    // that flag's archetype — the flag-triggered mode of a bimodal tool: `age -d` / `sops --decrypt`
295    // reveal plaintext to the model (`decrypt-read`), while the bare/encrypt form falls through to
296    // ordinary resolution below. Checked after the profiled-sub walk (a sub match wins) so a
297    // subcommand form (`sops decrypt`) and the flag form (`sops -d`) both classify.
298    if let Some(names) = crate::registry::command_flag_archetypes(tokens) {
299        if !trusted_command_path(arg0.as_str()) {
300            return Some(worst("resolvable name invoked from a non-standard path — possible spoof (§0)"));
301        }
302        let caps: Vec<Capability> = names
303            .iter()
304            .map(|n| {
305                crate::engine::archetype::archetype(n)
306                    .cloned()
307                    .unwrap_or_else(|| Capability::worst("command flag declares an unknown archetype (§0)"))
308            })
309            .collect();
310        return Some(Profile::of(caps));
311    }
312    // Every facet-classified command declares `[command.behavior]` (the coreutils are all ported;
313    // dd/tar/sed/grep declare a `hook`). No declaration → the command is unresearched for the
314    // engine, so return `None` (the caller falls back to the legacy classifier).
315    let spec = crate::registry::command_behavior(canonical)?;
316    // A resolvable basename reached via a NON-STANDARD path (`/tmp/cat`, `~/bin/grep`)
317    // is not necessarily the real tool — a planted binary named `cat` would be certified as safe
318    // coreutils. Don't certify it; worst-case (§0). Bare names and standard bin paths are
319    // trusted. (Legacy classifies purely by basename and inherits the spoof; the engine is
320    // stricter here, which keeps it never-looser.)
321    if !trusted_command_path(arg0.as_str()) {
322        return Some(worst("resolvable name invoked from a non-standard path — possible spoof (§0)"));
323    }
324    Some(resolve_behavior(spec, tokens))
325}
326
327/// `sudo`/`doas`: resolve the wrapped command and ELEVATE its authority. Authority is the axis every
328/// level below `local-admin` pins to `user`, so a root capability lands at `local-admin` (or `yolo`)
329/// — the projection does the rest. Fail-closed: an unknown sudo option, a root shell/editor
330/// (`-i`/`-s`/`-e`), or an inner command from a non-standard path worst-cases; an unresolved inner
331/// returns `None` so the caller's legacy fallback denies it (never *looser* than the bare command).
332fn resolve_privilege_wrapper(arg0: &Token, tokens: &[Token]) -> Option<Profile> {
333    if !trusted_command_path(arg0.as_str()) {
334        return Some(worst("sudo/doas invoked from a non-standard path — possible spoof (§0)"));
335    }
336    let mut i = 1;
337    let mut run_as_other = false;
338    'scan: while let Some(tok) = tokens.get(i) {
339        let t = tok.as_str();
340        if t == "--" {
341            i += 1;
342            break;
343        }
344        if !t.starts_with('-') || t == "-" {
345            break; // the inner command starts here
346        }
347        if let Some(long) = t.strip_prefix("--") {
348            let (name, glued_val) = match long.split_once('=') {
349                Some((n, _)) => (n, true),
350                None => (long, false),
351            };
352            match name {
353                "login" | "shell" | "edit" => {
354                    return Some(worst("sudo -i/-s/-e runs a root shell or editor — arbitrary code as root (§0)"));
355                }
356                "user" | "other-user" => {
357                    run_as_other = true;
358                    if !glued_val {
359                        i += 1;
360                    }
361                }
362                "group" | "prompt" | "close-from" | "host" | "role" | "type" | "command-timeout" | "chroot" | "chdir" | "preserve-env" => {
363                    // `--preserve-env` is boolean OR `--preserve-env=list`; only the space form of the
364                    // others consumes a value. A bare `--preserve-env` just falls through (no skip).
365                    if !glued_val && name != "preserve-env" {
366                        i += 1;
367                    }
368                }
369                "background" | "stdin" | "non-interactive" | "reset-timestamp" | "remove-timestamp" | "set-home" | "askpass" | "help"
370                | "version" | "validate" | "list" | "bell" => {}
371                _ => return Some(worst("sudo: unrecognized option — fail-closed (§0)")),
372            }
373        } else {
374            // A short cluster (`-EH`, `-u root`, `-uroot`). Consume char by char; a valued flag eats
375            // the rest of the token as its value, or the next token if the rest is empty.
376            let rest = &t[1..];
377            for (idx, c) in rest.char_indices() {
378                match c {
379                    'i' | 's' | 'e' => {
380                        return Some(worst("sudo -i/-s/-e runs a root shell or editor — arbitrary code as root (§0)"));
381                    }
382                    'u' | 'U' | 'g' | 'p' | 'C' | 'h' | 'r' | 't' | 'T' | 'R' | 'D' => {
383                        if c == 'u' || c == 'U' {
384                            run_as_other = true;
385                        }
386                        if idx + c.len_utf8() == rest.len() {
387                            i += 1;
388                        } // value is the next token
389                        i += 1;
390                        continue 'scan; // rest of the token was this flag's value
391                    }
392                    'E' | 'H' | 'k' | 'K' | 'n' | 'b' | 'A' | 'S' | 'P' | 'B' | 'v' | 'l' => {}
393                    _ => return Some(worst("sudo: unrecognized option — fail-closed (§0)")),
394                }
395            }
396        }
397        i += 1;
398    }
399    // A valued short flag at end-of-input (`sudo -u`, `doas -r`) consumes a "next token" that isn't
400    // there, pushing `i` one past the end — clamp so the slice can't panic (fail-OPEN crash of the
401    // hook). An overshoot means no command was left to elevate, same as the empty case below.
402    let inner = &tokens[i.min(tokens.len())..];
403    if inner.is_empty() {
404        return None; // `sudo` / `sudo -v` / `sudo -l` — no command to elevate; legacy decides
405    }
406    let elevated = if run_as_other { Authority::OtherUser } else { Authority::Root };
407    let caps = resolve(inner)?
408        .capabilities
409        .into_iter()
410        .map(|mut c| {
411            c.authority = c.authority.max(elevated);
412            c
413        })
414        .collect();
415    Some(Profile::of(caps))
416}
417
418/// openssl decrypt / private-key disclosure resolver. openssl's flag grammar defeats declarative
419/// flag-gating — it accepts `--opt` as an alias for `-opt` on every subcommand, `-text` dumps the
420/// PRIVATE key components to stdout past `-pubout`/`-noout`, and `-out`'s VALUE can itself be stdout
421/// (`-out -`, `-out /dev/stdout`) — so the disclosure-prone subs are classified here in Rust. Returns
422/// `decrypt-read` (→ yolo, denied below) only when private/decrypted material reaches the MODEL
423/// (stdout); returns `None` for public-key ops, to-FILE extraction, encrypt/sign, and the ~30 benign
424/// subs, which fall through to openssl's declarative (allow_all) classification. Fail-closed: a spoofed
425/// path worst-cases; a disclosure sub always yields a verdict rather than abstaining to the permissive
426/// legacy default.
427fn resolve_openssl(arg0: &Token, tokens: &[Token]) -> Option<Profile> {
428    if !trusted_command_path(arg0.as_str()) {
429        return Some(worst("openssl invoked from a non-standard path — possible spoof (§0)"));
430    }
431    let sub = tokens.get(1)?.as_str();
432    let args = &tokens[2..];
433    let discloses = match sub {
434        // Private-key subs: private material reaches the model UNLESS the input is public (`-pubin`),
435        // or it's public-key output (`-pubout`) with no `-text` side channel — and then only if the
436        // (private-key) output actually goes to stdout, not a file.
437        "rsa" | "pkey" | "ec" | "dsa" => {
438            if openssl_flag(args, "-pubin") {
439                false
440            } else if openssl_flag(args, "-text") {
441                true // dumps the private exponent/primes to stdout regardless of -out/-noout/-pubout
442            } else if openssl_flag(args, "-pubout") {
443                false // public-key PEM out, no -text
444            } else {
445                openssl_output_reaches_model(args)
446            }
447        }
448        // PKCS#8 is a private-key format with no public mode; disclosed if it reaches stdout.
449        "pkcs8" => openssl_flag(args, "-text") || openssl_output_reaches_model(args),
450        // Unencrypted key export (`-nodes`/`-noenc`, OpenSSL 3.0 spelling); disclosed if it hits stdout.
451        "pkcs12" => (openssl_flag(args, "-nodes") || openssl_flag(args, "-noenc")) && openssl_output_reaches_model(args),
452        // Symmetric decrypt: plaintext to the model only when it goes to stdout.
453        "enc" => openssl_flag(args, "-d") && openssl_output_reaches_model(args),
454        "smime" => openssl_flag(args, "-decrypt") && openssl_output_reaches_model(args),
455        "cms" => (openssl_flag(args, "-decrypt") || openssl_flag(args, "-EncryptedData_decrypt")) && openssl_output_reaches_model(args),
456        _ => return None, // benign subs — openssl's declarative (allow_all) classification
457    };
458    if discloses {
459        let cap = crate::engine::archetype::archetype("decrypt-read")
460            .cloned()
461            .unwrap_or_else(|| Capability::worst("decrypt-read archetype missing (§0)"));
462        Some(Profile::of(vec![cap]))
463    } else {
464        None // public / to-file / encrypt / benign → legacy allow_all classification
465    }
466}
467
468/// Whether an openssl BOOLEAN flag (`-d`, `-text`, `-pubout`) is present, accepting the `--` twin
469/// openssl honors on every subcommand (`--d`, `--text`). Value flags use [`openssl_flag_value`].
470fn openssl_flag(args: &[Token], flag: &str) -> bool {
471    args.iter().any(|t| {
472        let s = t.as_str();
473        s == flag || (s.starts_with("--") && s.len() > 2 && &s[1..] == flag)
474    })
475}
476
477/// Whether the sub's OUTPUT reaches the model. FAIL-CLOSED (a path string cannot be soundly matched
478/// against a denylist of device spellings — the OS collapses `//dev/stdout`, `/dev/./stdout`,
479/// `/dev/fd//1` to the same device, and openssl honors the LAST of duplicate `-out`s): the output
480/// reaches the model UNLESS it is provably diverted to a single plain FILE. So it's model-reaching
481/// when `-noout` is absent AND NOT (exactly one `-out` whose value is a plain file). `-noout`
482/// suppresses the PEM output (a validate); `-text` is checked by the caller BEFORE this, since it
483/// dumps to stdout past both `-noout` and `-out`.
484fn openssl_output_reaches_model(args: &[Token]) -> bool {
485    if openssl_flag(args, "-noout") {
486        return false;
487    }
488    let outs = openssl_flag_values(args, "-out");
489    // Diverted to disk ONLY when there is exactly one `-out` naming a plain file. No `-out` (default
490    // stdout), a duplicate `-out` (last-wins — the first is untrustworthy), or a device/`-` value all
491    // reach the model.
492    !matches!(outs.as_slice(), [only] if out_value_is_plain_file(only))
493}
494
495/// Whether an `-out` value names a plain FILE (a safe diversion), as opposed to stdout/`-`, or a
496/// device / fd / console path (`/dev/stdout`, `/dev/stderr`, `/dev/fd/1`, `/proc/self/fd/1`). Collapses
497/// redundant `/`, `.`, and `..` segments first so alternate spellings can't evade. Fail-closed: `-`,
498/// empty, or any `/dev/…` or `/proc/…/fd/…` path is NOT a plain file. (Symlinks are classified by their
499/// literal spelling — out of scope for a static classifier, per AGENTS.md.)
500///
501/// A value that is itself a FLAG token (starts with `-`) is NOT proof of diversion: openssl's own
502/// parser lets a preceding valued flag SWALLOW the `-out` token as its value (`-provider-path -out
503/// -provider-path f.pem` leaves openssl with no `-out` → stdout), and our scan then misreads the next
504/// flag as the filename. The tell in every such bypass is a dash-leading `-out` value — reject it.
505fn out_value_is_plain_file(value: &str) -> bool {
506    if value.is_empty() || value.starts_with('-') {
507        return false;
508    }
509    let norm = collapse_path(value).to_ascii_lowercase();
510    let device_or_fd = norm == "/dev" || norm.starts_with("/dev/") || (norm.starts_with("/proc/") && norm.contains("/fd/"));
511    !device_or_fd
512}
513
514/// Collapse a path's redundant `/` / `.` / `..` segments (what the kernel does before opening it), so
515/// `//dev/stdout`, `/dev/./stdout`, `/dev/fd//1`, `/foo/../dev/stdout` all normalize to the device
516/// path. A leading `..` on a relative path is kept (can't resolve above an unknown cwd).
517fn collapse_path(p: &str) -> String {
518    let absolute = p.starts_with('/');
519    let mut stack: Vec<&str> = Vec::new();
520    for seg in p.split('/') {
521        match seg {
522            "" | "." => {}
523            ".." => {
524                if matches!(stack.last(), Some(&s) if s != "..") {
525                    stack.pop();
526                } else if !absolute {
527                    stack.push("..");
528                }
529            }
530            s => stack.push(s),
531        }
532    }
533    let joined = stack.join("/");
534    if absolute { format!("/{joined}") } else { joined }
535}
536
537/// Every value of a valued openssl flag (`-out file` / `--out file` / `-out=file` / `--out=file`),
538/// accepting the `--` twin — ALL occurrences, in order (openssl honors the last; the caller fails
539/// closed on duplicates).
540fn openssl_flag_values<'a>(args: &'a [Token], flag: &str) -> Vec<&'a str> {
541    let twin = format!("-{flag}"); // `-out` → `--out`
542    let mut out = Vec::new();
543    let mut i = 0;
544    while i < args.len() {
545        let s = args[i].as_str();
546        if let Some(v) = s.strip_prefix(flag).or_else(|| s.strip_prefix(twin.as_str())).and_then(|r| r.strip_prefix('=')) {
547            out.push(v);
548        } else if (s == flag || s == twin)
549            && let Some(next) = args.get(i + 1)
550        {
551            out.push(next.as_str());
552            i += 1;
553        }
554        i += 1;
555    }
556    out
557}
558
559/// Classify a network-destination token's PROVENANCE (exposure §4). `None` (a bare invocation) is
560/// the configured default → `Established`. A command-transport form (`ext::<cmd>`) is not a
561/// destination but LOCAL CODE, signalled by a `None` return so the caller worst-cases it as RCE.
562fn destination_provenance(dest: Option<&str>) -> Option<Provenance> {
563    let Some(tok) = dest else {
564        return Some(Provenance::Established);
565    };
566    if tok.starts_with("ext::") {
567        return None; // `git push ext::sh -c …` runs a local command — RCE, not egress
568    }
569    // A variable / substitution: the actual target is not in the command string, so it cannot be
570    // reviewed — the fail-closed case.
571    if tok.contains('$') || tok.contains('`') {
572        return Some(Provenance::Opaque);
573    }
574    // Spelled inline: a URL scheme, an scp-style `user@host:path`, or a filesystem path. Otherwise a
575    // bare word is a reference to a configured remote (established by a prior `clone`/`remote add`).
576    let literal = tok.contains("://")
577        || (tok.contains('@') && tok.contains(':'))
578        || tok.starts_with('/')
579        || tok.starts_with("./")
580        || tok.starts_with("../");
581    Some(if literal { Provenance::Literal } else { Provenance::Established })
582}
583
584/// The generic, declaration-driven resolver: build a `Profile` from a command's
585/// `[command.behavior]` (`BehaviorSpec`) and its tokens. This is the non-legacy classification
586/// path expressed in TOML — the operation + operand-role + flag grammar are data, and this one
587/// function replaces a hardcoded `resolve_*`. Irreducible token logic a declaration can't
588/// express is delegated to a named `hook`.
589fn resolve_behavior(spec: &crate::registry::types::BehaviorSpec, tokens: &[Token]) -> Profile {
590    use crate::registry::types::{BehaviorHook, PositionalRole};
591    if let Some(hook) = spec.hook {
592        return match hook {
593            // grep's hook supplies the operand set (the irreducible token logic); the declared
594            // operation + the builders supply the facets — the composition seam (§8). grep is
595            // observe-only, so its operands become content reads.
596            BehaviorHook::Grep => {
597                let Some(g) = grep_operands(tokens) else {
598                    return worst("grep: unrecognized flag or missing pattern — worst-cased (§0)");
599                };
600                let mut caps: Vec<Capability> = g
601                    .pattern_files
602                    .iter()
603                    .map(|f| reads_path(f, Scale::Single, "reads a grep -f pattern file"))
604                    .collect();
605                caps.extend(reads_to_model(&g.files, g.scale));
606                Profile::of(caps)
607            }
608            // dd/tar/sed parse their own irregular operand syntax (`key=value`, dashless mode
609            // bundles, a mini-language script) AND build their own multi-role profiles, so their
610            // hook returns the full `Profile` — the parser and the facets are entangled with the
611            // parse and stay in Rust (their DATA — flag/param sets — is small and audited).
612            BehaviorHook::Dd => resolve_dd(tokens),
613            BehaviorHook::Tar => resolve_tar(tokens),
614            BehaviorHook::Sed => resolve_sed(tokens),
615            BehaviorHook::Perl => resolve_perl(tokens),
616        };
617    }
618    // No path operands (echo): a pure stdout emitter, handled BEFORE the flag walk — echo has no
619    // flag grammar (it prints any `-x` verbatim), so walking would wrongly reject it. `observe`
620    // with model disclosure and no fs/net/exec; its args touch nothing.
621    if matches!(spec.positionals, PositionalRole::None) {
622        return match spec.operation {
623            Operation::Observe => {
624                let mut c = Capability::new(Operation::Observe);
625                c.disclosure.audience = DisclosureAudience::LocalProcess;
626                c.because = "behavior: prints its arguments to stdout; no fs/net/exec/secret".to_string();
627                Profile::of(vec![c])
628            }
629            _ => worst("behavior: none-operand role supports only observe (§0)"),
630        };
631    }
632    let long: Vec<&str> = spec.long.iter().map(String::as_str).collect();
633    let valued_long: Vec<&str> = spec.valued_long.iter().map(String::as_str).collect();
634    let Some(operands) = walk_positionals(&spec.short, &spec.valued_short, &long, &valued_long, spec.numeric_shorthand, tokens) else {
635        return worst("behavior: unrecognized flag — worst-cased (§0)");
636    };
637    let scale = behavior_scale(spec, &operands, tokens);
638    // Path-flag values (e.g. `touch -r REF`) are gated alongside the positional operands.
639    let flag_caps = path_flag_caps(spec, tokens);
640    match spec.positionals {
641        PositionalRole::Read => {
642            let mut caps = reads_to_model(&operands, scale);
643            caps.extend(flag_caps);
644            Profile::of(caps)
645        }
646        PositionalRole::Write => {
647            if operands.is_empty() {
648                // `rm --help` prints usage and exits. It is not a write whose target is hidden, so
649                // worst-casing it denied every informational invocation of every write command:
650                // `rm --help`, `mkdir --help`, `rmdir --version`. The flag already passed the
651                // command's own grammar to get here, and no operand survived the walk.
652                //
653                // LONG forms only, the same rule and the same reasoning the output-claim voider
654                // uses below: `-h`/`-V` are not reliably help/version (`sort -h` is human-numeric
655                // sort), so honoring the short spellings here would be guessing.
656                if tokens.iter().skip(1).any(|t| matches!(t.as_str(), "--help" | "--version")) {
657                    let mut c = Capability::new(Operation::Observe);
658                    c.disclosure.audience = DisclosureAudience::LocalProcess;
659                    c.because = "behavior: prints usage and exits; nothing is written".to_string();
660                    return Profile::of(vec![c]);
661                }
662                return worst("behavior: write operation with no operand — worst-cased (§0)");
663            }
664            let judge = |p: &String| match spec.operation {
665                // A destroy UNBINDS the name, so it reads the rebind face: `rm -rf ~/.config`
666                // removes what the trust root points at, while `touch ~/.config/x` does not.
667                Operation::Destroy => destroys(locus::rebind_locus(p), scale),
668                Operation::Create => creates(classify_locus(p), scale),
669                Operation::Mutate => mutates(classify_locus(p), scale, "behavior: in-place mutate"),
670                _ => Capability::worst("behavior: unsupported write operation — worst-cased (§0)"),
671            };
672            let mut caps: Vec<Capability> =
673                link_mode::judged(tokens, || frozen_reach::with_reached(spec, &operands, tokens).iter().map(judge).collect());
674            caps.extend(flag_caps);
675            Profile::of(caps)
676        }
677        PositionalRole::Transfer => resolve_transfer(spec, operands, flag_caps, tokens),
678        // None is handled above (before the flag walk); pattern-then-read routes through a hook
679        // (grep). Neither reaches here, so both fail closed.
680        PositionalRole::None | PositionalRole::PatternThenRead => worst("behavior: operand role not resolvable without a hook (§0)"),
681    }
682}
683
684/// Capabilities for a command's declared PATH-FLAGS: a valued flag whose value is a path
685/// (`touch -r REF` reads REF's timestamp) is gated by its role's locus, exactly like an operand
686/// — so an out-of-workspace value denies. Folds the `[command.path_gate]` idea into behavior.
687fn path_flag_caps(spec: &crate::registry::types::BehaviorSpec, tokens: &[Token]) -> Vec<Capability> {
688    use crate::registry::types::PathRole;
689    let mut caps = Vec::new();
690    for pf in &spec.path_flags {
691        let short = pf.short.unwrap_or(0);
692        let long = pf.long.as_deref().unwrap_or("");
693        if let Some(v) = walk_value(&spec.valued_short, tokens, short, long) {
694            caps.push(match pf.role {
695                PathRole::Read => observes_path(v, Scale::Single, "behavior: a flag value is a read path"),
696                PathRole::Write => mutates(write_locus(v), Scale::Single, "behavior: a flag value is a write path"),
697            });
698        }
699    }
700    caps
701}
702
703/// The `Scale` for a behavior resolution: `single` always yields one item; `breadth` widens on
704/// operand count, a glob, or a declared unbounded flag (`rm -r`) via `breadth_scale`.
705fn behavior_scale(spec: &crate::registry::types::BehaviorSpec, operands: &[&str], tokens: &[Token]) -> Scale {
706    use crate::registry::types::ScaleModel;
707    match spec.scale {
708        ScaleModel::Single => Scale::Single,
709        ScaleModel::Breadth => {
710            let recursive = spec.unbounded_flags.iter().any(|f| flags::behavior_flag_present(tokens, f));
711            breadth_scale(operands, recursive)
712        }
713    }
714}
715
716/// A command name with no resolver and no plausible future one — the stable stand-in for
717/// "unresearched" across engine tests. Using a real tool here is a trap: when `rm` gained
718/// a resolver, three tests that used `rm` as their unresearched example silently broke.
719/// A name that will never be a real tool can never be silently repurposed.
720#[cfg(test)]
721pub(crate) const UNRESOLVED_CMD: &[&str] = &["safe-chains-unresolved-sentinel"];
722
723/// Whether `arg0` is a trusted way to name a tool the registry already knows.
724///
725/// A bare name is trusted: the shell resolves it through `$PATH`, and this classifier does not
726/// look at the filesystem. An absolute path is trusted only after `~` expansion and a lexical
727/// `.`/`..` collapse, and only when what remains is one plain filename in a directory that
728/// ships programs: the system bin directories, Homebrew's link farm and the real formula
729/// binary under it, a mise install (not its shims), or a rustup proxy or toolchain. Anything
730/// else (`./x`, `/tmp/x`, a path that only looks like it starts in `/bin`) is a different program.
731pub(crate) fn trusted_command_path(arg0: &str) -> bool {
732    if arg0.is_empty() || arg0.contains('\0') || arg0.contains('$') {
733        return false;
734    }
735    if !arg0.contains('/') && !arg0.starts_with('~') {
736        return plain_tool_name(arg0);
737    }
738    if !(arg0.starts_with('/') || arg0.starts_with("~/")) {
739        return false;
740    }
741    let Some(expanded) = expand_tilde(arg0) else {
742        return false;
743    };
744    let Some(normalized) = lexical_absolute(&expanded) else {
745        return false;
746    };
747    trusted_normalized(&normalized)
748}
749
750/// The registry key for this invocation. A trusted spelling is the tool it names. Any other
751/// spelling is its own program, matched only by a rule that names that path.
752pub(crate) fn invocation_name(token: &Token) -> &str {
753    if trusted_command_path(token.as_str()) { token.command_name() } else { token.as_str() }
754}
755
756pub(crate) fn dispatch_name(token: &Token) -> &str {
757    let basename = token.command_name();
758    if basename == "heavy-slot.sh" { basename } else { invocation_name(token) }
759}
760
761fn plain_tool_name(s: &str) -> bool {
762    !s.is_empty()
763        && s != "."
764        && s != ".."
765        && !s.starts_with('-')
766        && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '+' | '@'))
767}
768
769fn expand_tilde(arg0: &str) -> Option<String> {
770    let Some(rest) = arg0.strip_prefix("~/") else {
771        return Some(arg0.to_string());
772    };
773    let home = crate::process_home::var().ok()?;
774    let home = home.trim_end_matches('/');
775    if !home.starts_with('/') || home.contains('\0') {
776        return None;
777    }
778    Some(format!("{home}/{rest}"))
779}
780
781fn lexical_absolute(path: &str) -> Option<String> {
782    if !path.starts_with('/') {
783        return None;
784    }
785    let mut parts: Vec<&str> = Vec::new();
786    for seg in path.split('/') {
787        match seg {
788            "" | "." => {}
789            ".." => {
790                parts.pop();
791            }
792            s => parts.push(s),
793        }
794    }
795    if parts.iter().any(|s| !plain_tool_name(s)) {
796        return None;
797    }
798    Some(format!("/{}", parts.join("/")))
799}
800
801fn trusted_normalized(path: &str) -> bool {
802    let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
803    let Some((name, dirs)) = parts.split_last() else {
804        return false;
805    };
806    if !plain_tool_name(name) {
807        return false;
808    }
809    let parent = format!("/{}", dirs.join("/"));
810    const SYSTEM_BIN_DIRS: &[&str] = &[
811        "/bin", "/usr/bin", "/sbin", "/usr/sbin", "/usr/local/bin", "/usr/local/sbin", "/opt/bin", "/opt/homebrew/bin",
812        "/opt/homebrew/sbin", "/home/linuxbrew/.linuxbrew/bin", "/home/linuxbrew/.linuxbrew/sbin", "/usr/local/cargo/bin",
813    ];
814    if SYSTEM_BIN_DIRS.contains(&parent.as_str()) {
815        return true;
816    }
817    formula_bin(dirs) || mise_install_bin(dirs) || rustup_toolchain_bin(dirs)
818}
819
820fn formula_bin(dirs: &[&str]) -> bool {
821    let Some((leaf, mid)) = dirs.split_last() else {
822        return false;
823    };
824    if !matches!(*leaf, "bin" | "sbin") {
825        return false;
826    }
827    const ROOTS: &[&[&str]] = &[&["opt", "homebrew"], &["usr", "local"], &["home", "linuxbrew", ".linuxbrew"]];
828    ROOTS.iter().any(|root| {
829        let opt = mid.len() == root.len() + 2
830            && mid.get(..root.len()) == Some(*root)
831            && mid[root.len()] == "opt"
832            && plain_tool_name(mid[root.len() + 1]);
833        let cellar = mid.len() == root.len() + 3
834            && mid.get(..root.len()) == Some(*root)
835            && mid[root.len()] == "Cellar"
836            && plain_tool_name(mid[root.len() + 1])
837            && plain_tool_name(mid[root.len() + 2]);
838        opt || cellar
839    })
840}
841
842fn home_dirs() -> Option<Vec<String>> {
843    let home = crate::process_home::var().ok()?;
844    let home = home.trim_end_matches('/');
845    if !home.starts_with('/') || home.contains('\0') {
846        return None;
847    }
848    Some(home.split('/').filter(|s| !s.is_empty()).map(str::to_string).collect())
849}
850
851fn mise_install_bin(dirs: &[&str]) -> bool {
852    let Some(home) = home_dirs() else {
853        return false;
854    };
855    let home_ref: Vec<&str> = home.iter().map(String::as_str).collect();
856    let Some(rest) = dirs.strip_prefix(home_ref.as_slice()) else {
857        return false;
858    };
859    rest.len() == 7
860        && rest[0] == ".local"
861        && rest[1] == "share"
862        && rest[2] == "mise"
863        && rest[3] == "installs"
864        && plain_tool_name(rest[4])
865        && plain_tool_name(rest[5])
866        && rest[6] == "bin"
867}
868
869fn rustup_toolchain_bin(dirs: &[&str]) -> bool {
870    if dirs.len() == 6 && dirs[..4] == ["usr", "local", "rustup", "toolchains"] && dirs[5] == "bin" && plain_tool_name(dirs[4]) {
871        return true;
872    }
873    let Some(home) = home_dirs() else {
874        return false;
875    };
876    let home_ref: Vec<&str> = home.iter().map(String::as_str).collect();
877    let Some(rest) = dirs.strip_prefix(home_ref.as_slice()) else {
878        return false;
879    };
880    rest == [".cargo", "bin"]
881        || (rest.len() == 4 && rest[0] == ".rustup" && rest[1] == "toolchains" && rest[3] == "bin" && plain_tool_name(rest[2]))
882}
883
884/// The classified operand set of a `grep` invocation: the positional file operands (read at
885/// `scale`, empty = stdin) and the `-f`/`--file` pattern files (each read once). This is the
886/// irreducible token logic a `[command.behavior]` declaration can't express — grep's
887/// pattern-vs-file disambiguation, `-e`/`-f` pattern flags, and the unknown-`--token`-is-a-
888/// pattern heuristic. The declared `operation` (observe) and the builders turn these operands
889/// into capabilities in `resolve_behavior`'s hook arm; this function assigns no facets.
890struct GrepOperands<'a> {
891    files: Vec<&'a str>,
892    pattern_files: Vec<&'a str>,
893    scale: Scale,
894}
895
896/// Walk a `grep` command into its `GrepOperands`, or `None` to fail closed (unrecognized flag,
897/// or no pattern operand). The behavior hook (`BehaviorHook::Grep`) for `commands/text/grep.toml`.
898fn grep_operands(tokens: &[Token]) -> Option<GrepOperands<'_>> {
899    // `-r` (or --recursive); `-R`/--dereference-recursive is not benign and worst-cases
900    // in the walk below, so it needn't be detected here.
901    let recursive = has_flag(tokens, Some("-r"), Some("--recursive"));
902    let scale = if recursive { Scale::Unbounded } else { Scale::Single };
903
904    let mut files = Vec::new(); // positional file operands
905    let mut pattern_files = Vec::new(); // -f/--file pattern files grep reads
906    let mut pattern_from_flag = false;
907    let mut unknown_flag = false;
908    let mut flags_done = false;
909    let mut i = 1;
910    while i < tokens.len() {
911        let t = tokens[i].as_str();
912        let next = tokens.get(i + 1).map(Token::as_str);
913        if !flags_done && t == "--" {
914            flags_done = true;
915            i += 1;
916        } else if flags_done || !t.starts_with('-') || t == "-" {
917            files.push(t);
918            i += 1;
919        } else if t.starts_with("--") {
920            if let Some(v) = t.strip_prefix("--file=") {
921                pattern_from_flag = true;
922                pattern_files.push(v);
923                i += 1;
924            } else if t == "--file" {
925                pattern_from_flag = true;
926                pattern_files.extend(next);
927                i += 2;
928            } else if t == "--regexp" {
929                pattern_from_flag = true;
930                i += 2;
931            } else if t.starts_with("--regexp=") {
932                pattern_from_flag = true;
933                i += 1;
934            } else if grep_long_known(t) {
935                i += 1;
936            } else if grep_long_dangerous(t) {
937                unknown_flag = true;
938                i += 1;
939            } else {
940                // An unrecognized `--token` is not a grep flag: it is the search PATTERN
941                // (grep patterns commonly look like `-->`, `---`, `--foo`). Treat it as a
942                // positional so the file operands classify the read, matching legacy.
943                files.push(t);
944                i += 1;
945            }
946        } else {
947            match grep_short_cluster(t, next) {
948                GrepShort::Unrecognized => {
949                    unknown_flag = true;
950                    i += 1;
951                }
952                GrepShort::Standalone => i += 1,
953                GrepShort::Pattern { file, consumes_next } => {
954                    pattern_files.extend(file);
955                    pattern_from_flag = true;
956                    i += if consumes_next { 2 } else { 1 };
957                }
958                GrepShort::SkipValue { consumes_next } => i += if consumes_next { 2 } else { 1 },
959            }
960        }
961    }
962
963    if unknown_flag {
964        return None; // unrecognized flag → fail closed (§0)
965    }
966    if files.is_empty() {
967        // No positional operand → grep has no pattern (a `-e`/`-f` pattern still needs a
968        // search target). This is a usage error; the legacy classifier denies it, so the
969        // engine must not be looser — fail closed (§0).
970        return None;
971    }
972
973    if !pattern_from_flag {
974        files.remove(0); // the first positional is the PATTERN, not a file
975    }
976    if recursive && files.is_empty() {
977        files.push("."); // grep -r with no path searches the cwd
978    }
979
980    Some(GrepOperands { files, pattern_files, scale })
981}
982
983/// The outcome of parsing one grep short-option cluster.
984enum GrepShort<'a> {
985    /// An unrecognized short (e.g. `-R`, symlink-dereferencing recursive) → the caller worst-cases.
986    Unrecognized,
987    /// All chars benign; no value taken.
988    Standalone,
989    /// `-e`/`-f` supplied the pattern (so positionals are files); `-f`'s value, if any,
990    /// is a pattern file grep reads.
991    Pattern { file: Option<&'a str>, consumes_next: bool },
992    /// `-m`/`-A`/`-B`/`-C`/`-d` — a count/action value to skip.
993    SkipValue { consumes_next: bool },
994}
995
996/// Parse a grep short-option cluster (e.g. `-ifpatterns`), honoring GNU semantics that a
997/// value-taking short consumes the rest of its cluster (glued) or the next token.
998fn grep_short_cluster<'a>(cluster: &'a str, next: Option<&'a str>) -> GrepShort<'a> {
999    // NB: `r` (recursive) is benign, but `R` (--dereference-recursive) follows symlinks
1000    // and can escape the classified locus, so it is NOT benign — it worst-cases. `P`
1001    // (PCRE, `--perl-regexp`) IS benign: GNU grep's PCRE2 does not implement Perl's
1002    // `(?{code})` execution, so it runs no code — it's just another regex engine like `-E`/`-F`.
1003    const BENIGN: &[u8] = b"ivnclLoqswxHhaIrzZEFGbUP";
1004    let bytes = cluster.as_bytes();
1005    let mut k = 1;
1006    while k < bytes.len() {
1007        // Non-ASCII bytes aren't flags and would make `cluster[k + 1..]` slice mid-char.
1008        if !bytes[k].is_ascii() {
1009            return GrepShort::Unrecognized;
1010        }
1011        let glued = &cluster[k + 1..]; // safe: bytes[k] is ASCII → k+1 is a char boundary
1012        let has = !glued.is_empty();
1013        match bytes[k] {
1014            b'f' => {
1015                let file = if has { Some(glued) } else { next };
1016                return GrepShort::Pattern { file, consumes_next: !has };
1017            }
1018            b'e' => return GrepShort::Pattern { file: None, consumes_next: !has },
1019            b'm' | b'A' | b'B' | b'C' | b'd' => return GrepShort::SkipValue { consumes_next: !has },
1020            b if BENIGN.contains(&b) => k += 1,
1021            _ => return GrepShort::Unrecognized,
1022        }
1023    }
1024    GrepShort::Standalone
1025}
1026
1027/// Whether a grep long flag (its `--name`, ignoring any `=value`) is recognized-benign.
1028/// `--dereference-recursive` and anything unlisted are not → worst-case (§0).
1029fn grep_long_known(flag: &str) -> bool {
1030    const KNOWN: &[&str] = &[
1031        "--recursive", "--ignore-case", "--invert-match", // NB: --dereference-recursive
1032        // (symlink-following) is intentionally absent → worst-case (M2)
1033        "--line-number", "--count", "--files-with-matches", "--files-without-match", "--only-matching", "--perl-regexp", "--word-regexp",
1034        "--line-regexp", "--fixed-strings", "--extended-regexp", "--basic-regexp", "--with-filename", "--no-filename", "--quiet",
1035        "--silent", "--no-messages", "--null", "--byte-offset", "--text", "--color", "--colour", "--help", "--version", "--after-context",
1036        "--before-context", "--context", "--max-count", "--include", "--exclude", "--exclude-dir", "--include-dir", "--binary-files",
1037        "--devices", "--directories",
1038    ];
1039    let name = flag.split('=').next().unwrap_or(flag);
1040    KNOWN.contains(&name)
1041}
1042
1043/// `--dereference-recursive`, the long `-R` (follows symlinks out of the classified locus, M2), and `--file`. GNU grep
1044/// takes any unambiguous prefix of a long option, so a prefix counts too. Every OTHER unrecognized `--token` is a
1045/// search pattern, not a flag. (`--perl-regexp`/`-P` is NOT here — PCRE2 executes no code, so it is benign, like `-E`.)
1046fn grep_long_dangerous(flag: &str) -> bool {
1047    let name = flag.split('=').next().unwrap_or(flag);
1048    name.len() > 3 && ["--dereference-recursive", "--file"].iter().any(|option| option.starts_with(name))
1049}
1050
1051/// `dd if=IN of=OUT bs=… …` — the operand-model breaker: `dd` takes NO getopt flags or
1052/// positionals, only `key=value` operands, so the shared `Flags`/`positionals` toolkit does
1053/// not apply and it parses its own. `if=` reads (default stdin), `of=` writes (default
1054/// stdout). It is still a transfer at the facet level — `dd if=~/.ssh/id_rsa of=./x` denies
1055/// on the input locus, `dd if=./x of=/dev/rdisk0` denies on the output locus (a raw device
1056/// is beneath the fs) — but the roles arrive inside `key=value`, not positional slots, which
1057/// is why its conservation probe is `Operands::Custom`. `bs`/`count`/`conv`/… are benign
1058/// transfer parameters; any other key, or a non-`key=value` operand, worst-cases (§0).
1059fn resolve_dd(tokens: &[Token]) -> Profile {
1060    const PARAMS: &[&str] = &["bs", "ibs", "obs", "cbs", "count", "skip", "seek", "conv", "iflag", "oflag", "status"];
1061    let (mut input, mut output) = (None, None);
1062    for t in &tokens[1..] {
1063        let t = t.as_str();
1064        if t == "--help" || t == "--version" {
1065            continue;
1066        }
1067        let Some((key, val)) = t.split_once('=') else {
1068            return worst("dd: non key=value operand — worst-cased (§0)");
1069        };
1070        match key {
1071            "if" => input = Some(val),
1072            "of" => output = Some(val),
1073            k if PARAMS.contains(&k) => {}
1074            _ => return worst("dd: unrecognized operand — worst-cased (§0)"),
1075        }
1076    }
1077    // dd touches exactly one input and one output — a `single` blast radius, whatever the
1078    // data VOLUME. The disk-wipe danger of `of=/dev/rdisk0` is carried by its device locus,
1079    // not by scale.
1080    // Built from the PATH, not just its locus: the locus says which rung `if=` reaches, and the
1081    // shield is what says whether the file on that rung is a credential store. Reading the rung
1082    // alone let `dd if=/etc/shadow of=./safe` copy a file `cat /etc/shadow` refuses, then read the
1083    // copy out of the worktree — the shield was never asked.
1084    match output {
1085        // of= names a sink: read the input into it (no model disclosure) + write the sink.
1086        Some(of) => Profile::of(vec![
1087            match input {
1088                Some(i) => observes_path(i, Scale::Single, "dd reads its input (if=) into the output"),
1089                None => observes(LocalLocus::Process, Scale::Single, "dd reads stdin into the output"),
1090            },
1091            overwrites(classify_locus(of), Scale::Single, false),
1092        ]),
1093        // no of= → output is stdout, so the input content reaches the model (like `cat`).
1094        None => Profile::of(vec![match input {
1095            Some(i) => reads_path(i, Scale::Single, "dd copies its input to stdout (→ the model)"),
1096            None => reads_content(LocalLocus::Process, Scale::Single, "dd copies stdin to stdout (→ the model)"),
1097        }]),
1098    }
1099}
1100
1101/// `tar` — the flag-SYNTAX breaker: its options may be written WITHOUT a leading dash
1102/// (`tar czf` == `tar -czf`), so the getopt walker misreads the cluster as a positional; tar
1103/// parses its own. The mode letter splits the profile sharply:
1104///   - create/append (`c`/`r`/`u`): reads each member (source) + writes the archive (dest) —
1105///     a bundler, so `tar czf - ~/.ssh` denies on the member locus (golden-set).
1106///   - list (`t`): reads the archive, prints member names to the model.
1107///   - extract (`x`) and the rarer modes: extraction writes an ARCHIVE-CONTROLLED set of
1108///     paths that `..`-traversal can send anywhere — unknowable without opening the archive,
1109///     so worst-case (§0). Any value-taking option we don't model (`-C`, `-T`, …) or an
1110///     unknown letter also worst-cases.
1111fn resolve_tar(tokens: &[Token]) -> Profile {
1112    let mut p = TarParse::default();
1113    // `-C DIR` changes the directory for the members that FOLLOW it, so a member's real locus
1114    // is `DIR/member` — the same `find … {}`→path binding. tar applies `-C` CUMULATIVELY: each
1115    // `-C` chdir's relative to the already-changed directory, so consecutive `-C /  -C etc`
1116    // resolves to `/etc`, not `etc`. Compose relative values onto the active dir (via the same
1117    // `tar_bound` join, which also lets an absolute value replace and routes any `..` through
1118    // the unpinnable guard); stamp each positional with the accumulated dir.
1119    let mut dir: Option<String> = None;
1120    let mut i = 1;
1121    while i < tokens.len() {
1122        let t = tokens[i].as_str();
1123        if t == "-C" || t == "--directory" {
1124            dir = tokens.get(i + 1).map(|d| tar_bound(dir.as_deref(), d.as_str()));
1125            i += 2;
1126            continue;
1127        }
1128        if let Some(d) = t.strip_prefix("--directory=").or_else(|| t.strip_prefix("-C").filter(|d| !d.is_empty())) {
1129            dir = Some(tar_bound(dir.as_deref(), d));
1130            i += 1;
1131            continue;
1132        }
1133        if let Some(long) = t.strip_prefix("--") {
1134            p.long_option(long);
1135        } else if let Some(cluster) = t.strip_prefix('-').filter(|c| !c.is_empty()) {
1136            p.cluster(cluster);
1137        } else if i == 1 {
1138            p.cluster(t); // dashless old-style option bundle (only the first argument)
1139        } else {
1140            p.positionals.push((dir.clone(), t));
1141        }
1142        i += 1;
1143    }
1144    p.into_profile()
1145}
1146
1147/// A tar positional: a member/archive path with the accumulated `-C` directory active when it
1148/// appeared (already composed across consecutive `-C` options).
1149type TarPositional<'a> = (Option<String>, &'a str);
1150
1151/// A tar positional borrowed for classification: (`-C` dir, path).
1152type TarRef<'a> = (Option<&'a str>, &'a str);
1153
1154/// Accumulated `tar` parse: the mode, whether `-f` wants an archive, and `reject` — set by
1155/// any option we can't model safely (an unknown letter, or a value-taking option like `-T`
1156/// / `-X` whose ordered operand consumption we don't track). `-C` IS modeled (see
1157/// `resolve_tar`); it only reaches `cluster` inside a mixed bundle, which still worst-cases.
1158#[derive(Default)]
1159struct TarParse<'a> {
1160    mode: Option<u8>,
1161    want_archive: bool,
1162    reject: bool,
1163    long_archive: Option<&'a str>,
1164    /// `h` or `--dereference` archives what a member that is a link leads to.
1165    members: link_mode::LinkUse,
1166    /// Each positional with the `-C` directory active when it appeared (`None` = cwd).
1167    positionals: Vec<TarPositional<'a>>,
1168}
1169
1170impl<'a> TarParse<'a> {
1171    fn cluster(&mut self, cluster: &str) {
1172        const NOVAL: &[u8] = b"vzjJZpkmOwhSlPa"; // benign no-value option letters
1173        for b in cluster.bytes() {
1174            match b {
1175                b'c' | b'x' | b't' | b'r' | b'u' | b'A' | b'd' => self.mode = Some(b),
1176                b'f' => self.want_archive = true,
1177                b'h' => self.members = link_mode::LinkUse::Target,
1178                b'C' | b'T' | b'X' | b'b' | b'H' | b'g' | b'K' | b'N' => self.reject = true,
1179                x if NOVAL.contains(&x) => {}
1180                _ => self.reject = true,
1181            }
1182        }
1183    }
1184
1185    fn long_option(&mut self, long: &'a str) {
1186        let name = long.split('=').next().unwrap_or(long);
1187        match name {
1188            "create" => self.mode = Some(b'c'),
1189            "extract" | "get" => self.mode = Some(b'x'),
1190            "list" => self.mode = Some(b't'),
1191            "dereference" => self.members = link_mode::LinkUse::Target,
1192            "append" => self.mode = Some(b'r'),
1193            "update" => self.mode = Some(b'u'),
1194            "file" => match long.split_once('=') {
1195                Some((_, v)) => self.long_archive = Some(v),
1196                None => self.want_archive = true,
1197            },
1198            "gzip"
1199            | "bzip2"
1200            | "xz"
1201            | "zstd"
1202            | "compress"
1203            | "verbose"
1204            | "preserve-permissions"
1205            | "same-permissions"
1206            | "to-stdout"
1207            | "help"
1208            | "version"
1209            | "totals" => {}
1210            _ => self.reject = true,
1211        }
1212    }
1213
1214    fn into_profile(self) -> Profile {
1215        let Some(mode) = self.mode.filter(|_| !self.reject) else {
1216            return worst("tar: unrecognized/unmodeled option — worst-cased (§0)");
1217        };
1218        // Separate the archive from the members. `--file=X` names it directly; a bare `f`
1219        // (dashless `czf` or dashed `-czf`) takes the FIRST positional as the archive.
1220        let (archive, members): (Option<TarRef>, &[TarPositional]) = if let Some(a) = self.long_archive {
1221            (Some((None, a)), &self.positionals)
1222        } else if self.want_archive {
1223            match self.positionals.split_first() {
1224                Some((first, rest)) => (Some((first.0.as_deref(), first.1)), rest),
1225                None => return worst("tar: -f without an archive — worst-cased (§0)"),
1226            }
1227        } else {
1228            (None, &self.positionals) // archive is stdin/stdout
1229        };
1230        // A `-` archive (or none) is a stdout/stdin stream, not a file to gate.
1231        let archive_file = archive.filter(|(_, a)| *a != "-");
1232        if archive_file.is_some_and(|(_, a)| tar_paths::names_a_remote_archive(a)) {
1233            return worst("tar: GNU tar opens an archive named host:path on another machine over rsh or ssh — worst-cased (§0)");
1234        }
1235
1236        match mode {
1237            b'c' | b'r' | b'u' => {
1238                // UNBOUNDED, not bounded: a member that is a directory is archived with everything
1239                // under it, so `tar -cf x.tar ~` packs every key in home into a worktree file that
1240                // is then ordinary to read. The member names the root of a sweep, not a file.
1241                let member =
1242                    |(dir, m): &TarPositional| observes_path(&tar_bound(dir.as_deref(), m), Scale::Unbounded, "tar reads a member");
1243                let read = || members.iter().map(member).collect::<Vec<Capability>>();
1244                let mut caps = if self.members == link_mode::LinkUse::Target { read() } else { crate::pathctx::on_the_link(read) };
1245                if let Some((dir, a)) = archive_file {
1246                    caps.push(overwrites(classify_locus(&tar_bound(dir, a)), Scale::Single, false));
1247                }
1248                if caps.is_empty() {
1249                    return worst("tar create with no members — worst-cased (§0)");
1250                }
1251                Profile::of(caps)
1252            }
1253            b't' => {
1254                // Gated on the archive's PATH, not just its rung: `tar tf /etc/shadow` opens the
1255                // credential store and reports what it found there, which is a read of it however
1256                // poorly it parses as an archive.
1257                Profile::of(vec![match archive_file {
1258                    Some((dir, a)) => reads_path(&tar_bound(dir, a), Scale::Single, "tar lists the archive's members (names → the model)"),
1259                    None => reads_content(LocalLocus::Process, Scale::Single, "tar lists stdin's members (names → the model)"),
1260                }])
1261            }
1262            // x (extract) and A/d: archive-controlled, ..-escapable writes → worst-case.
1263            _ => worst("tar extract writes an archive-controlled, ..-escapable path set — worst-cased (§0)"),
1264        }
1265    }
1266}
1267
1268/// `sed` — the read-becomes-WRITE breaker: `sed 's/…/…/' FILE` reads FILE and prints to the
1269/// model, but `sed -i` edits the SAME file operands **in place** (a mutate), so a single
1270/// flag flips the operation on the same slots. Two more wrinkles: `-i` takes an OPTIONAL
1271/// glued suffix (`-i.bak`) the getopt walker can't express, and — like `grep` — the first
1272/// positional is the SCRIPT unless `-e`/`-f` supplied it (`-f` also reads a script file).
1273/// So `sed` parses its own flags.
1274fn resolve_sed(tokens: &[Token]) -> Profile {
1275    // HP-7: sed is a mini-language. Its `e` command/modifier executes text as a shell command
1276    // (RCE), and its `w`/`W`/`r`/`R` commands write/read arbitrary files EMBEDDED in the script —
1277    // both invisible to flag parsing. Scan the script(s): an `e`/unknown command worst-cases; the
1278    // file commands' filenames get gated by locus below (a local write is fine, `/etc/cron.d/x` is
1279    // not), exactly like the operand files.
1280    let script = crate::handlers::coreutils::sed::scan_sed(tokens);
1281    if script.exec || script.unknown {
1282        return worst("sed: script has an `e` exec or unmodeled command — worst-cased (§0, HP-7)");
1283    }
1284    // A `-f`/`--file` script comes from a file we can't read — its `e`/`w`/`r` commands are invisible,
1285    // so we can't verify it (like `awk -f`, `bash script.sh`, mlr `--load`). Worst-case it.
1286    if script.script_file {
1287        return worst("sed: -f runs a script file we can't inspect — worst-cased (§0)");
1288    }
1289    const BOOL: &[u8] = b"nrEsuz"; // no-value short flags
1290    let mut in_place = false;
1291    let mut script_from_flag = false;
1292    let mut script_files: Vec<&str> = Vec::new(); // -f FILE — sed reads these
1293    let mut files: Vec<&str> = Vec::new();
1294    let mut flags_done = false;
1295    let mut i = 1;
1296    while i < tokens.len() {
1297        let t = tokens[i].as_str();
1298        let next = tokens.get(i + 1).map(Token::as_str);
1299        if !flags_done && t == "--" {
1300            flags_done = true;
1301            i += 1;
1302        } else if flags_done || t == "-" || !t.starts_with('-') {
1303            files.push(t);
1304            i += 1;
1305        } else if let Some(long) = t.strip_prefix("--") {
1306            match sed_long(long, next, &mut in_place, &mut script_from_flag, &mut script_files) {
1307                Some(consumed) => i += consumed,
1308                None => return worst("sed: unrecognized flag — worst-cased (§0)"),
1309            }
1310        } else {
1311            match sed_cluster(&t[1..], next, BOOL) {
1312                SedShort::Bad => return worst("sed: unrecognized flag — worst-cased (§0)"),
1313                SedShort::InPlace { consumes_next } => {
1314                    in_place = true;
1315                    i += usize::from(consumes_next) + 1;
1316                }
1317                SedShort::Standalone => i += 1,
1318                SedShort::Script { consumes_next } => {
1319                    script_from_flag = true;
1320                    i += usize::from(consumes_next) + 1;
1321                }
1322                SedShort::ScriptFile { file, consumes_next } => {
1323                    script_from_flag = true;
1324                    script_files.extend(file);
1325                    i += usize::from(consumes_next) + 1;
1326                }
1327                SedShort::SkipValue { consumes_next } => i += usize::from(consumes_next) + 1,
1328            }
1329        }
1330    }
1331    // Without -e/-f, the first positional is the SCRIPT, not a file.
1332    if !script_from_flag && !files.is_empty() {
1333        files.remove(0);
1334    }
1335    // Blast radius: a glob (`sed -i … *`) or several operands is bounded, not single — so a
1336    // sweeping in-place edit is scored honestly (still worktree-bound by locus; a system or
1337    // home path denies whatever the scale).
1338    let scale = breadth_scale(&files, false);
1339    let mut caps: Vec<Capability> = script_files
1340        .iter()
1341        .map(|f| observes_path(f, Scale::Single, "sed reads an -f script file"))
1342        .collect();
1343    // Script-embedded file commands (`w`/`W` write, `r`/`R` read, `s///w` write) — gate each target
1344    // by its locus, just like an operand file.
1345    caps.extend(script.writes.iter().map(|f| mutates(classify_locus(f), Scale::Single, "sed w/W writes a file")));
1346    caps.extend(script.reads.iter().map(|f| observes_path(f, Scale::Single, "sed r/R reads a file")));
1347    if in_place {
1348        caps.extend(files.iter().map(|f| mutates(classify_locus(f), scale, "sed -i edits the file in place")));
1349        caps.extend(
1350            backup::in_place_backups(tokens, &files, true)
1351                .iter()
1352                .map(|b| mutates(classify_locus(b), scale, "sed -i writes a backup")),
1353        );
1354    } else {
1355        caps.extend(reads_to_model(&files, scale));
1356    }
1357    Profile::of(caps)
1358}
1359
1360/// The locus of the paths a `$( … )` can PRODUCE, or `None` when nothing bounds them.
1361///
1362/// This is a different question from "is the inner command safe to run", and conflating the two is
1363/// a fail-open: `echo` is inert and `$(echo /etc/shadow)` still names a credential file. So a
1364/// command only gets an answer here if it has declared one (`[command.output]`); everything else
1365/// stays unpinnable, exactly as before. See docs/design/behavioral-taxonomy-substitution-locus.md.
1366pub(crate) fn substitution_claim(script: &crate::cst::Script) -> Option<SubClaim> {
1367    // A pipeline's VALUE is its last stage's stdout; the earlier stages feed it and are verdicted
1368    // separately as usual. Pass-through filters (`… | head -1`) emit a SUBSET of what they were
1369    // given, so walking back over them reaches the stage that actually produced the paths.
1370    let [stmt] = script.0.as_slice() else { return None };
1371    let cmds = &stmt.pipeline.commands;
1372    let mut idx = cmds.len().checked_sub(1)?;
1373    loop {
1374        match stage_output_locus(cmds.get(idx)?)? {
1375            StageOutput::Locus(l) => return Some(SubClaim::Locus(l)),
1376            StageOutput::Here(dir, _) if idx + 1 == cmds.len() => return Some(SubClaim::Literal(dir)),
1377            StageOutput::Here(_, l) => return Some(SubClaim::Locus(l)),
1378            // A pass-through filter emits a SUBSET of its input words, so it cannot turn an atom
1379            // into something with a separator — the claim survives the filter unchanged.
1380            StageOutput::Atom => return Some(SubClaim::Atom),
1381            StageOutput::PassThrough => idx = idx.checked_sub(1)?,
1382        }
1383    }
1384}
1385
1386fn stage_output_locus(cmd: &crate::cst::Cmd) -> Option<StageOutput> {
1387    let crate::cst::Cmd::Simple(simple) = cmd else { return None };
1388    let words: Vec<String> = simple.words.iter().map(crate::cst::Word::eval).collect();
1389    use crate::registry::types::OutputLocus;
1390    let (name, args) = words.split_first()?;
1391    // A resolvable name reached from a non-standard path (`./fd`) may not be the real tool, so it
1392    // gets no output-locus claim — the same spoof rule `resolve` applies to the command itself.
1393    if !trusted_command_path(name) {
1394        return None;
1395    }
1396    let token = Token::from_raw(name.clone());
1397    let canonical = crate::registry::canonical_name(token.command_name());
1398    // A SUB's claim wins over the command's, and narrows `args` to what follows the sub path so the
1399    // sub name is not counted as a path operand (`git ls-files src/` must see `src/`, not `ls-files`).
1400    let (rule, args) = match crate::registry::sub_output_locus(canonical, args) {
1401        Some((rule, rest)) => (rule, rest),
1402        None => (crate::registry::command_output_locus(canonical)?, args),
1403    };
1404    // At least one required flag must be present, or the command prints something other than paths
1405    // entirely — `git diff` without `--name-only` prints a patch. Checked before `invalidated_by`
1406    // because it is the stronger condition: absent, there is no claim to invalidate.
1407    if !rule.requires.is_empty() && !rule.requires.iter().any(|r| args.iter().any(|a| flags::flag_present(a, std::slice::from_ref(r)))) {
1408        return None;
1409    }
1410    // `--help` and `--version` replace the command's DATA output with prose, and EVERY output
1411    // claim is a statement about the data. GNU `seq --help` prints
1412    // `<https://www.gnu.org/software/coreutils/>` — slash-bearing words under an `atom` claim that
1413    // says no word can contain a separator. Handled here rather than in each command's
1414    // `invalidated_by` so it holds for claims that do not exist yet: the danger is not seq (whose
1415    // help leaks only URLs, which as paths are relative) but the next atom source whose help
1416    // prints `/etc/foo.conf`, which would hand an ABSOLUTE path to a caller told it was confined.
1417    //
1418    // Long forms only. `-h` and `-V` are not reliably help/version — `sort -h` is human-numeric
1419    // sort — so treating them as informational would void real claims. A command whose OWN grammar
1420    // maps a short flag to help lists it in `invalidated_by` (see seq).
1421    //
1422    // Not caught by the local install: macOS ships BSD seq, whose help is terse and slash-free.
1423    if args.iter().any(|a| a == "--help" || a == "--version") {
1424        return None;
1425    }
1426    // A flag that changes what stdout CONTAINS (`fd -x cat {}` prints file bodies, `fd -l` prints
1427    // `ls -l` rows) voids the claim — the output is no longer a path at all.
1428    if args.iter().any(|a| flags::flag_present(a, &rule.invalidated_by)) {
1429        return None;
1430    }
1431
1432    match rule.locus_from {
1433        // An ATOM names no locus — a separator-free word is not a path and cannot stand in for
1434        // one. It pays off in the PATH layer instead: a literal prefix around a FLANKED atom leaf
1435        // is confinable, because the atom cannot introduce a `/` and the flanking rules out the
1436        // leaf being `.` or `..`. Both halves of that are enforced in `locus::neutralize_atoms`;
1437        // on its own this claim widens nothing, since an atom sentinel is `is_unpinnable`.
1438        OutputLocus::Atom => Some(StageOutput::Atom),
1439        // The cwd is a worktree path only while it is one. At `user` or above the claim names a
1440        // directory, not a file, and a suffix such as `/shadow` would never be shown to the shield.
1441        // Same bound as `Operands`.
1442        OutputLocus::Cwd => stage_output::of_cwd(read_locus(".")),
1443        // Output descends the command's own path operands, so it is bounded by their worst read
1444        // locus. `fd x app/ lib/` → worktree; `fd x /` → machine.
1445        OutputLocus::Operands => {
1446            // ANY unpinnable argument voids the claim, checked before the path-shape filter and
1447            // over every argument rather than the ones that look like roots. A `$VAR` root carries
1448            // no `/`, so shape-filtering first read `fd pat $SECRET` as having no root at all and
1449            // reported worktree — while the command searches wherever `$SECRET` points.
1450            if args.iter().any(|a| is_unpinnable(a)) {
1451                return None;
1452            }
1453            let roots = candidate_roots(args, &rule.valued);
1454            // No path operand means the command searches `.` (`fd pattern`), which is the cwd.
1455            let worst = roots.iter().map(|r| read_locus(r)).max().unwrap_or_else(|| read_locus("."));
1456            // A bounded claim is only meaningful BELOW `user`. At worktree/adjacent/temp nothing
1457            // under the root can be a credential store, so the rung is the whole truth about the
1458            // value. At `user` or above it is not: the claim carries a LOCUS and says nothing about
1459            // WHICH file, and which file is exactly what the shield needs to see.
1460            //
1461            // `cat $(fd pat ~/.ssh)` was allowed while `cat ~/.ssh/id_rsa` denied — the tag reported
1462            // `machine`, the shield was never consulted because there was no path to consult it
1463            // about, and a substitution ended up more permissive than a path it could produce.
1464            // Caught by no_abstraction_is_more_permissive_than_a_path_it_could_denote.
1465            //
1466            // Same rule, and the same reasoning, as the synthetic pipe representative in
1467            // `cst::check::stage_output_repr`. Dropping the claim leaves the ordinary unpinnable
1468            // sentinel, which `reads_path` then treats as unshieldable.
1469            if worst >= LocalLocus::User {
1470                return None;
1471            }
1472            Some(StageOutput::Locus(worst))
1473        }
1474        // Only a filter when it is filtering: given a file operand it prints that file's CONTENTS,
1475        // which are caller-controlled text and no kind of path.
1476        OutputLocus::Stdin => {
1477            if candidate_roots(args, &rule.valued).is_empty() {
1478                Some(StageOutput::PassThrough)
1479            } else {
1480                None
1481            }
1482        }
1483    }
1484}
1485
1486/// Every argument that could name a search ROOT, over-approximated on purpose.
1487///
1488/// Under-counting here is a fail-OPEN — a missed root means a lower locus than the command actually
1489/// reaches — so EVERY non-flag argument counts, plus any path glued to a flag
1490/// (`--search-path=/etc`, `-E/etc/x`). Over-counting only ever raises the locus, which denies.
1491///
1492/// It deliberately does NOT ask whether an argument looks like a path. That test (`looks_like_path`)
1493/// keys on a `/` or a `.`, so a bare `~` failed it and `cat $(fd pat ~)` auto-approved a sweep of
1494/// the home directory as though it were worktree-local. A shape heuristic cannot be the last word
1495/// on a question whose wrong answer opens a hole.
1496fn candidate_roots<'a>(args: &'a [String], valued: &[String]) -> Vec<&'a str> {
1497    let mut roots = Vec::new();
1498    let mut skip_value = false;
1499    for a in args {
1500        if std::mem::take(&mut skip_value) {
1501            continue;
1502        }
1503        if a.starts_with('-') {
1504            // `valued` declares "this flag's value is NOT a path" (a count, a separator), so its
1505            // value is skipped in BOTH spellings. Handling only the separated form denied
1506            // `head --lines=5` while `head -n 5` passed — the same operation, two spellings.
1507            let (head, glued_value) = match a.split_once('=') {
1508                Some((h, v)) => (h, Some(v)),
1509                None => (a.as_str(), None),
1510            };
1511            if valued.iter().any(|v| v == head) {
1512                skip_value = glued_value.is_none();
1513                continue;
1514            }
1515            // Otherwise a glued value can still name a root. After `=` the whole value counts —
1516            // keying on `/` alone missed `--search-path=~`, the same blind spot as the shape test.
1517            // Without an `=`, a glued short value starts at the first path-ish character.
1518            let glued = glued_value.or_else(|| a.find(['/', '~']).map(|i| &a[i..]));
1519            if let Some(v) = glued.filter(|v| !v.is_empty()) {
1520                roots.push(v);
1521            }
1522            continue;
1523        }
1524        roots.push(a.as_str());
1525    }
1526    roots
1527}
1528
1529fn resolve_perl(tokens: &[Token]) -> Profile {
1530    // perl's `-e` one-liner is arbitrary code, so the identifier gate in `handlers::perl` decides
1531    // whether the CODE is inert. What that gate cannot do is judge the OPERANDS: it never looked at
1532    // them, which is why `perl -pe s/a/b/ /etc/shadow` used to read a credential file and print it
1533    // to the model. Both halves are needed — an inert one-liner over a system file is still an
1534    // exfiltration, and a worktree file rewritten by unmodeled code is still RCE.
1535    use crate::handlers::perl::PerlCode;
1536    let Some(scan) = crate::handlers::perl::scan_perl(tokens) else {
1537        return worst("perl: unmodeled flag cluster — worst-cased (§0)");
1538    };
1539    match scan.code {
1540        PerlCode::None => {
1541            let mut c = Capability::new(Operation::Observe);
1542            c.disclosure.audience = DisclosureAudience::LocalProcess;
1543            c.because = "perl: reports its own version/usage".to_string();
1544            return Profile::of(vec![c]);
1545        }
1546        // No `-e`/`-E` means the first operand is a SCRIPT FILE whose contents we cannot inspect
1547        // (like `sed -f`, `awk -f`, `bash x.sh`), and a failed identifier gate means the one-liner
1548        // reached outside the modeled vocabulary. Neither is separable from arbitrary execution.
1549        PerlCode::Opaque => return worst("perl: no inspectable -e/-E one-liner — worst-cased (§0)"),
1550        PerlCode::Inspectable => {}
1551    }
1552    // A sweeping in-place edit (`perl -pi -e … *`) is bounded but not single; locus still binds
1553    // each operand, so breadth widens the blast radius without ever admitting a system path.
1554    let files: Vec<&str> = scan.files.iter().map(String::as_str).collect();
1555    let scale = breadth_scale(&files, false);
1556    // No `execute` capability, deliberately. perl does run code, so recording one looks more
1557    // honest — but it is the wrong model here and the experiment says so: an
1558    // `executes(caller-inline)` capability denies at every band, which would take out every perl
1559    // one-liner including the in-place edits this hook exists to admit. The reason it denies is
1560    // that the `execute` rung describes running code of UNKNOWN content, and by this point the
1561    // identifier gate has already established the opposite — the one-liner reaches nothing but
1562    // pure built-ins, no I/O, no exec, no network. What remains observable is the operand reads
1563    // and writes below, and those ARE the profile. If the gate's vocabulary ever admits an
1564    // identifier with side effects, the fix belongs in the gate, not in a capability here.
1565    let caps: Vec<Capability> = if scan.in_place {
1566        let backups = backup::in_place_backups(tokens, &files, false);
1567        files
1568            .iter()
1569            .copied()
1570            .chain(backups.iter().map(String::as_str))
1571            .map(|f| mutates(classify_locus(f), scale, "perl -i edits the file in place"))
1572            .collect()
1573    } else {
1574        reads_to_model(&files, scale)
1575    };
1576    Profile::of(caps.into_iter().chain(path_verdicts::runs_modules_from(&scan.load_paths)).collect())
1577}
1578
1579/// The outcome of parsing one `sed` short-option cluster.
1580enum SedShort<'a> {
1581    Bad,
1582    Standalone,
1583    InPlace { consumes_next: bool },                           // -i[SUFFIX], or BSD's separate `-i ''`
1584    Script { consumes_next: bool },                            // -e SCRIPT
1585    ScriptFile { file: Option<&'a str>, consumes_next: bool }, // -f FILE
1586    SkipValue { consumes_next: bool },                         // -l N
1587}
1588
1589fn sed_cluster<'a>(cluster: &'a str, next: Option<&'a str>, boolset: &[u8]) -> SedShort<'a> {
1590    let bytes = cluster.as_bytes();
1591    let mut k = 0;
1592    while k < bytes.len() {
1593        // A flag byte is ASCII; a non-ASCII lead/continuation byte is not a flag, and slicing
1594        // `cluster[k + 1..]` at it would land mid-char and panic. Bail as unrecognized.
1595        if !bytes[k].is_ascii() {
1596            return SedShort::Bad;
1597        }
1598        let glued = &cluster[k + 1..]; // safe: bytes[k] is ASCII → k+1 is a char boundary
1599        let has = !glued.is_empty();
1600        match bytes[k] {
1601            // `-i[SUFFIX]` glued is the GNU spelling. BSD (macOS) requires the suffix as a SEPARATE
1602            // word, empty for "no backup", so `sed -i '' 's/a/b/' f` is the standard macOS form.
1603            //
1604            // Modelled GNU-only, `-i` consumed nothing, so `''` landed in the first positional —
1605            // which for sed is the SCRIPT. Everything shifted one: the real script became a FILE
1606            // operand, and since operands are word-split, any absolute-looking token inside it
1607            // decided the locus. A JS comment did it in practice — the `//` in
1608            // `s|…|// TEMP: no-op|` read as the filesystem root and the edit denied at `machine`.
1609            //
1610            // ONLY an empty next word is consumed. Under BSD the word after `-i` is a suffix, not a
1611            // path, so accepting a non-empty one would let `-i /etc/passwd` swallow a real operand.
1612            b'i' => return SedShort::InPlace { consumes_next: !has && next == Some("") },
1613            b'e' => return SedShort::Script { consumes_next: !has },
1614            b'f' => {
1615                let file = if has { Some(glued) } else { next };
1616                return SedShort::ScriptFile { file, consumes_next: !has };
1617            }
1618            b'l' if has || next.is_some() => return SedShort::SkipValue { consumes_next: !has }, // -l N
1619            b if boolset.contains(&b) => k += 1,
1620            _ => return SedShort::Bad,
1621        }
1622    }
1623    SedShort::Standalone
1624}
1625
1626/// Parse a `sed` long option, returning how many tokens it consumed, or `None` if unknown.
1627fn sed_long<'a>(
1628    long: &'a str,
1629    next: Option<&'a str>,
1630    in_place: &mut bool,
1631    script_from_flag: &mut bool,
1632    script_files: &mut Vec<&'a str>,
1633) -> Option<usize> {
1634    let name = long.split('=').next().unwrap_or(long);
1635    match name {
1636        "in-place" => *in_place = true, // --in-place[=SUFFIX] (glued only)
1637        "expression" => {
1638            *script_from_flag = true;
1639            return Some(if long.contains('=') { 1 } else { 2 });
1640        }
1641        "file" => {
1642            *script_from_flag = true;
1643            match long.split_once('=') {
1644                Some((_, v)) => script_files.push(v),
1645                None => {
1646                    script_files.extend(next);
1647                    return Some(2);
1648                }
1649            }
1650        }
1651        "quiet" | "silent" | "regexp-extended" | "null-data" | "separate" | "unbuffered" | "posix" | "help" | "version" | "debug"
1652        | "follow-symlinks" | "sandbox" | "zero-terminated" | "line-length" => {}
1653        _ => return None,
1654    }
1655    Some(1)
1656}
1657
1658#[cfg(test)]
1659mod tests {
1660    use super::*;
1661
1662    fn toks(parts: &[&str]) -> Vec<Token> {
1663        parts.iter().map(|p| Token::from_test(p)).collect()
1664    }
1665
1666    fn level(name: &str) -> &'static crate::engine::level::Level {
1667        crate::engine::authoring::default_levels().iter().find(|l| l.name == name).expect("level exists")
1668    }
1669
1670    fn inert() -> &'static crate::engine::level::Level {
1671        level("paranoid")
1672    }
1673
1674    fn read_local() -> &'static crate::engine::level::Level {
1675        level("reader")
1676    }
1677
1678    /// `resolve_openssl` contract: a private-key/decrypt form reaching the MODEL classifies as
1679    /// decrypt-read (secret=reads → refused by developer, admitted only by yolo); a public/to-file/
1680    /// validate form ABSTAINS (None → openssl's legacy allow_all); a spoofed path worst-cases.
1681    #[test]
1682    fn openssl_resolver_gates_model_disclosure_only() {
1683        let (dev, yolo) = (level("developer"), level("yolo"));
1684        for parts in [
1685            &["openssl", "rsa", "-in", "priv.pem"][..],
1686            &["openssl", "rsa", "-in", "priv.pem", "-pubout", "-text"], // -text past -pubout
1687            &["openssl", "rsa", "-in", "priv.pem", "-out", "/dev/stdout"], // -out value is stdout
1688            &["openssl", "rsa", "-in", "priv.pem", "-noout", "-text"],
1689            &["openssl", "pkcs8", "-in", "priv.pem"],
1690            &["openssl", "enc", "--d", "-k", "p", "-in", "c"], // --opt alias
1691            &["openssl", "cms", "-EncryptedData_decrypt", "-in", "m"],
1692            &["openssl", "pkcs12", "-in", "f.p12", "-noenc"],
1693        ] {
1694            let p = resolve(&toks(parts)).unwrap_or_else(|| panic!("resolves: {parts:?}"));
1695            assert!(p.capabilities.iter().any(|c| c.secret.level == SecretLevel::Reads), "secret=reads: {parts:?}",);
1696            assert!(!dev.admits(&p), "developer refuses: {parts:?}");
1697            assert!(yolo.admits(&p), "yolo admits: {parts:?}");
1698        }
1699        for parts in [
1700            &["openssl", "rsa", "-in", "priv.pem", "-pubout"][..],
1701            &["openssl", "rsa", "-in", "priv.pem", "-noout"], // validate, no output
1702            &["openssl", "rsa", "-in", "enc.pem", "-out", "clean.pem"], // to a FILE, off the model
1703            &["openssl", "pkey", "-in", "pub.pem", "-pubin", "-text"], // public input → public text
1704            &["openssl", "pkcs12", "-in", "f.p12", "-nodes", "-out", "k.pem"],
1705            &["openssl", "enc", "-e", "-in", "x", "-out", "x.enc", "-k", "p"],
1706            &["openssl", "x509", "-in", "c", "-noout", "-text"],
1707        ] {
1708            assert!(resolve(&toks(parts)).is_none(), "resolver abstains (→ legacy): {parts:?}");
1709        }
1710    }
1711
1712    /// The output-destination check is FAIL-CLOSED: only a single plain-file `-out` diverts the key
1713    /// off the model. Path-normalization spellings, `/dev/stderr`, and duplicate `-out` (openssl honors
1714    /// the last) must all read as model-reaching — the sign-off review found the old device-spelling
1715    /// denylist let these through.
1716    #[test]
1717    fn openssl_output_destination_is_fail_closed() {
1718        let dev = level("developer");
1719        let reaches_model = |args: &[&str]| {
1720            let mut parts = vec!["openssl", "rsa", "-in", "priv.pem"];
1721            parts.extend_from_slice(args);
1722            // decrypt-read (secret=reads, refused by developer) ⇔ the output reached the model; a
1723            // diverted output makes the resolver ABSTAIN (None → openssl's benign legacy).
1724            match resolve(&toks(&parts)) {
1725                None => false,
1726                Some(p) => p.capabilities.iter().any(|c| c.secret.level == SecretLevel::Reads) && !dev.admits(&p),
1727            }
1728        };
1729        for evasion in [
1730            &["-out", "//dev/stdout"][..],
1731            &["-out", "/dev/./stdout"],
1732            &["-out", "//dev/fd/1"],
1733            &["-out", "/dev/fd//1"],
1734            &["-out=//dev/stdout"],
1735            &["-out", "/dev/stderr"],
1736            &["-out", "/foo/../dev/stdout"],
1737            &["-out", "dup.pem", "-out", "/dev/stdout"], // last-wins
1738            &["-out", "-"],
1739            // openssl's parser lets `-provider-path` swallow the `-out` token → openssl writes to
1740            // stdout; our scan then misreads the trailing flag as the filename. A dash-leading `-out`
1741            // value is the tell → fail closed.
1742            &["-provider-path", "-out", "-provider-path", "safe.pem"],
1743            &["-out", "-anything"],
1744        ] {
1745            assert!(reaches_model(evasion), "must read as model-reaching: {evasion:?}");
1746        }
1747        for diverted in [
1748            &["-out", "clean.pem"][..],
1749            &["-out", "./sub/key.pem"],
1750            &["-out", "devnotes.pem"], // "dev" prefix on a filename is not the /dev device
1751            &["-out", "/home/u/key.pem"],
1752            &["-noout"],
1753        ] {
1754            assert!(!reaches_model(diverted), "must divert off the model: {diverted:?}");
1755        }
1756    }
1757
1758    #[test]
1759    fn echo_resolves_to_a_benign_inert_profile() {
1760        let p = resolve(&toks(&["echo", "hi"])).expect("echo has a resolver");
1761        assert_eq!(p.capabilities.len(), 1);
1762        let c = &p.capabilities[0];
1763        assert_eq!(c.operation, Operation::Observe);
1764        assert_eq!(c.locus.local, LocalLocus::Process);
1765        assert_eq!(c.disclosure.audience, DisclosureAudience::LocalProcess);
1766        assert!(!c.because.is_empty(), "a structural certification cites its reason");
1767        // admitted at the *strictest* level — every facet (network/exec/secret/…) is zero
1768        assert!(inert().admits(&p), "echo is fully certified and inert-safe");
1769    }
1770
1771    #[test]
1772    fn echo_flags_do_not_change_its_profile() {
1773        let bare = resolve(&toks(&["echo", "hi"])).expect("echo");
1774        let flagged = resolve(&toks(&["echo", "-n", "-e", "hi"])).expect("echo -n -e");
1775        assert_eq!(bare, flagged);
1776        assert!(inert().admits(&flagged));
1777    }
1778
1779    #[test]
1780    fn an_unresearched_command_has_no_resolver() {
1781        assert!(resolve(&toks(UNRESOLVED_CMD)).is_none(), "unresearched → caller worst-cases");
1782        assert!(resolve(&[]).is_none(), "empty tokens");
1783    }
1784
1785    #[test]
1786    fn cat_of_a_worktree_file_is_read_local() {
1787        let p = resolve(&toks(&["cat", "./notes.md"])).expect("cat");
1788        assert!(read_local().admits(&p), "cat ./notes.md");
1789        assert!(!inert().admits(&p), "reading a real file is above inert");
1790    }
1791
1792    #[test]
1793    fn cat_of_a_path_the_shield_cannot_clear_is_denied() {
1794        // What bounds a read is the shield, not the rung: a credential store, another user's
1795        // home, a raw device, or a path we cannot resolve well enough to ASK about.
1796        for path in [
1797            "~/.ssh/id_rsa", "/etc/shadow", "$SECRET", "/var/lib/mysql/data", "/dev/mem", "/root/.bashrc",
1798            // `resolve` alone has no cwd binding, so a `..` cannot be pinned to the directory it
1799            // would land in and the unpinnable guard takes it. With a cwd (the CLI, the hook) the
1800            // same path resolves and reads — `path_policy_corpus.tsv` covers that end.
1801            "../outside",
1802        ] {
1803            let p = resolve(&toks(&["cat", path])).expect("cat");
1804            assert!(!read_local().admits(&p), "cat {path} must not be admitted as a local read");
1805        }
1806        // …while ordinary files on those same rungs now read, which is the whole point of the
1807        // shield being a NAME test rather than a rung test.
1808        for path in ["~/notes", "/etc/hosts", "/usr/bin/python3"] {
1809            let p = resolve(&toks(&["cat", path])).expect("cat");
1810            assert!(read_local().admits(&p), "cat {path} is an ordinary read");
1811        }
1812    }
1813
1814    #[test]
1815    fn machine_config_reads_but_its_credential_bearing_files_do_not() {
1816        for path in ["/etc/hosts", "/etc/os-release", "/usr/local/etc/nginx/nginx.conf"] {
1817            let p = resolve(&toks(&["cat", path])).expect("cat");
1818            assert!(read_local().admits(&p), "cat {path} is ordinary machine config");
1819        }
1820        // Same rung, different answer, and the rung is not what decided it: an auth log records
1821        // credentials outright, so it is a store however public the directory around it looks.
1822        for path in ["/var/log/auth.log", "/etc/shadow"] {
1823            let p = resolve(&toks(&["cat", path])).expect("cat");
1824            assert!(!read_local().admits(&p), "cat {path} reads credentials");
1825        }
1826    }
1827
1828    /// Distributed package CONTENT is read-admitted; its WRITE face is not.
1829    ///
1830    /// A man page, a vendored crate README, a toolchain source file: read yes, WRITE no.
1831    ///
1832    /// These used to be readable via a `package-content` region role that admitted the roots
1833    /// explicitly. That role is gone — it existed to get reads working while the bound was low,
1834    /// and it cut `/usr` into halves (`share` readable, `etc` not) that nothing justified as a
1835    /// boundary. Reads reach these paths on the general policy now.
1836    ///
1837    /// The assertion that still earns its keep is the WRITE half. Opening reads must not have
1838    /// widened what the agent can alter, and these are the paths where a write would be an
1839    /// install rather than an edit.
1840    #[test]
1841    fn package_content_is_readable_but_never_writable() {
1842        for path in [
1843            "/usr/share/doc/x",
1844            "/usr/share/man/man1/git.1",
1845            "/usr/local/share/doc/x/README",
1846            "/opt/homebrew/lib/node_modules/npm/package.json",
1847            "/Library/Developer/CommandLineTools/usr/include/stdio.h",
1848            "/nix/store/abc/share/doc/README",
1849            "~/.cargo/registry/src/idx/serde-1.0/README.md",
1850            "~/.rustup/toolchains/stable/lib/rustlib/src/core/src/lib.rs",
1851            "~/go/pkg/mod/github.com/x/y@v1/README.md",
1852            "~/.local/share/mise/installs/node/22/README.md",
1853        ] {
1854            let read = resolve(&toks(&["cat", path])).expect("cat");
1855            assert!(read_local().admits(&read), "reading package content {path} should be admitted");
1856            let write = resolve(&toks(&["rm", "-rf", path])).expect("rm");
1857            assert!(!read_local().admits(&write), "package content {path} must NOT be writable — this widens disclosure only");
1858        }
1859    }
1860
1861    /// The credential shield outranks an admit prefix, whatever the specificity ordering says.
1862    ///
1863    /// Specificity ranks exact ≫ prefix ≫ segment, so every subtree admit outranked the shield's
1864    /// segment match: `/usr/share/.ssh/id_rsa` was APPROVED the moment package content became
1865    /// readable. A shield that a new admit node can widen is not a shield.
1866    #[test]
1867    fn an_admit_prefix_can_never_widen_the_credential_shield() {
1868        for path in [
1869            "/usr/share/.ssh/id_rsa", "/usr/local/lib/.aws/credentials", "/opt/homebrew/share/.gnupg/secring.gpg",
1870            "~/.cargo/registry/.ssh/id_ed25519", "/nix/store/x/.aws/credentials",
1871        ] {
1872            let p = resolve(&toks(&["cat", path])).expect("cat");
1873            assert!(!read_local().admits(&p), "an admit prefix widened the shield at {path}");
1874        }
1875    }
1876
1877    #[test]
1878    fn cat_stdin_is_process_scoped() {
1879        assert!(inert().admits(&resolve(&toks(&["cat"])).expect("cat")), "no operand → stdin");
1880        assert!(inert().admits(&resolve(&toks(&["cat", "-"])).expect("cat -")), "- → stdin");
1881    }
1882
1883    #[test]
1884    fn cat_reads_every_file_operand_and_one_home_read_sinks_it() {
1885        let p = resolve(&toks(&["cat", "-n", "a.txt", "src/b.rs"])).expect("cat");
1886        assert_eq!(p.capabilities.len(), 2, "-n is a flag; two files");
1887        assert!(read_local().admits(&p), "both worktree");
1888
1889        let mixed = resolve(&toks(&["cat", "a.txt", "~/.ssh/id_rsa"])).expect("cat");
1890        assert!(!read_local().admits(&mixed), "one home read sinks the whole profile");
1891    }
1892
1893    #[test]
1894    fn cat_double_dash_treats_the_rest_as_files() {
1895        let p = resolve(&toks(&["cat", "--", "-n"])).expect("cat");
1896        assert_eq!(p.capabilities.len(), 1, "-n after -- is a filename");
1897        assert!(read_local().admits(&p));
1898    }
1899
1900    #[test]
1901    fn head_tail_wc_read_like_cat_and_honor_numeric_shorthand() {
1902        use crate::engine::bridge::project;
1903        use crate::verdict::{SafetyLevel, Verdict};
1904        // worktree reads → read-local (SafeRead); home reads → denied by locus, same as cat.
1905        for cmd in [
1906            vec!["head", "README.md"],
1907            vec!["head", "-n", "5", "src/main.rs"],
1908            vec!["head", "-20", "src/main.rs"], // obsolete -NUM form must parse
1909            vec!["tail", "-f", "./log.txt"],    // follow is still a bounded read
1910            vec!["tail", "-n", "100", "./log.txt"],
1911            vec!["wc", "-l", "./notes.md"],
1912        ] {
1913            assert_eq!(project(&resolve(&toks(&cmd)).expect("read")), Verdict::Allowed(SafetyLevel::SafeRead), "{cmd:?}");
1914        }
1915        // reading stdin (`-`) is process-scoped → inert, like `cat -`.
1916        assert_eq!(project(&resolve(&toks(&["wc", "-c", "-"])).expect("wc")), Verdict::Allowed(SafetyLevel::Inert), "wc stdin");
1917        for cmd in [vec!["head", "~/.ssh/id_rsa"], vec!["tail", "/etc/shadow"], vec!["wc", "-l", "$SECRET"]] {
1918            assert_eq!(project(&resolve(&toks(&cmd)).expect("read")), Verdict::Denied, "{cmd:?} beyond worktree");
1919        }
1920        // -NUM consumes no operand: `head -20 file` reads exactly `file`, not a phantom "20".
1921        let p = resolve(&toks(&["head", "-20", "src/main.rs"])).expect("head");
1922        assert_eq!(p.capabilities.len(), 1, "-20 is the count, not a file");
1923        // wc --files0-from reads an unpinnable set → worst-case → denied.
1924        assert_eq!(project(&resolve(&toks(&["wc", "--files0-from=list"])).expect("wc")), Verdict::Denied, "--files0-from");
1925        assert_eq!(project(&resolve(&toks(&["wc", "--files0-from", "-"])).expect("wc")), Verdict::Denied, "--files0-from -");
1926        // unknown flags fail closed.
1927        assert_eq!(project(&resolve(&toks(&["head", "-Z", "x"])).expect("head")), Verdict::Denied, "unknown flag");
1928    }
1929
1930    #[test]
1931    fn grep_reads_its_files_not_the_pattern() {
1932        let p = resolve(&toks(&["grep", "foo", "file.txt"])).expect("grep");
1933        assert_eq!(p.capabilities.len(), 1, "the pattern is not a file");
1934        assert!(read_local().admits(&p));
1935    }
1936
1937    #[test]
1938    fn grep_beyond_the_worktree_is_denied() {
1939        for args in [vec!["grep", "foo", "~/.ssh/config"], vec!["grep", "-r", "foo", "~"], vec!["grep", "foo", "$DIR"]] {
1940            let p = resolve(&toks(&args)).expect("grep");
1941            assert!(!read_local().admits(&p), "{args:?}");
1942        }
1943    }
1944
1945    #[test]
1946    fn grep_recursive_is_unbounded_and_defaults_to_cwd() {
1947        let p = resolve(&toks(&["grep", "-r", "foo", "src/"])).expect("grep");
1948        assert!(p.capabilities.iter().all(|c| c.scale == Scale::Unbounded), "-r → unbounded");
1949        assert!(read_local().admits(&p), "recursive worktree search");
1950
1951        let cwd = resolve(&toks(&["grep", "-r", "foo"])).expect("grep");
1952        assert!(cwd.capabilities.iter().all(|c| c.locus.local == LocalLocus::Worktree), "cwd, not stdin");
1953        assert!(read_local().admits(&cwd));
1954    }
1955
1956    #[test]
1957    fn grep_e_and_f_supply_the_pattern_so_positionals_are_files() {
1958        // -e: pattern is the flag's value; file.txt is the only file
1959        let e = resolve(&toks(&["grep", "-e", "foo", "file.txt"])).expect("grep -e");
1960        assert_eq!(e.capabilities.len(), 1);
1961        assert!(read_local().admits(&e));
1962
1963        // -f: the pattern FILE is itself a read
1964        let f = resolve(&toks(&["grep", "-f", "patterns.txt", "file.txt"])).expect("grep -f");
1965        assert_eq!(f.capabilities.len(), 2, "patterns.txt + file.txt");
1966        assert!(read_local().admits(&f));
1967
1968        // The `-f` value is gated as a read like any other operand: an ordinary home file is
1969        // readable now, a credential store is not — and the flag is what makes it a read at all.
1970        let home = resolve(&toks(&["grep", "-f", "~/.secret-patterns", "file.txt"])).expect("grep -f");
1971        assert!(read_local().admits(&home), "an ordinary home pattern file reads");
1972        let shielded = resolve(&toks(&["grep", "-f", "~/.ssh/id_rsa", "file.txt"])).expect("grep -f");
1973        assert!(!read_local().admits(&shielded), "a shielded pattern file is still a credential read");
1974
1975        // glued short value: -fpatterns.txt and -ifpatterns.txt both name a pattern file
1976        let glued = resolve(&toks(&["grep", "-fpatterns.txt", "file.txt"])).expect("grep -f glued");
1977        assert_eq!(glued.capabilities.len(), 2, "glued -f value is still a read");
1978        // The glued spelling classifies as the spaced one does — ordinary home file reads, a
1979        // shielded one does not. What must never differ between the two forms is the ANSWER.
1980        let glued_home = resolve(&toks(&["grep", "-if~/.secrets", "x"])).expect("grep -if glued");
1981        assert!(read_local().admits(&glued_home), "glued ordinary home pattern file reads");
1982        let glued_shield = resolve(&toks(&["grep", "-if~/.ssh/id_rsa", "x"])).expect("grep -if glued");
1983        assert!(!read_local().admits(&glued_shield), "glued shielded pattern file is a credential read");
1984    }
1985
1986    #[test]
1987    fn grep_long_flags() {
1988        // --file / --file= name a pattern file grep also reads (2 caps)
1989        assert_eq!(resolve(&toks(&["grep", "--file", "p.txt", "f.txt"])).expect("grep").capabilities.len(), 2);
1990        assert_eq!(resolve(&toks(&["grep", "--file=p.txt", "f.txt"])).expect("grep").capabilities.len(), 2);
1991
1992        // --regexp supplies the pattern; the positional is the file
1993        let r = resolve(&toks(&["grep", "--regexp", "foo", "f.txt"])).expect("grep");
1994        assert_eq!(r.capabilities.len(), 1);
1995        assert!(read_local().admits(&r));
1996
1997        // a space-separated long value (`--max-count 5`) is imprecise — `5` is read as a
1998        // phantom positional — but FAIL-SAFE: still worktree-bounded, admitted at
1999        // read-local, never looser. (Precise handling needs the TOML flag schema.)
2000        let m = resolve(&toks(&["grep", "--max-count", "5", "foo", "f.txt"])).expect("grep");
2001        assert!(read_local().admits(&m), "--max-count 5 is fail-safe (imprecise)");
2002
2003        // --perl-regexp (PCRE2) runs no code — benign like any regex-engine flag; reads read-local.
2004        let pcre = resolve(&toks(&["grep", "--perl-regexp", "foo", "f"])).expect("grep");
2005        assert!(read_local().admits(&pcre), "grep --perl-regexp reads a file, it does not exec");
2006    }
2007
2008    #[test]
2009    fn grep_dash_patterns_are_search_patterns_not_flags() {
2010        // A `--`-prefixed token that is not a recognized grep flag is a SEARCH PATTERN, not
2011        // an unknown flag — grep patterns commonly look like `-->`, `---`, `--foo`. The
2012        // engine must read the file operand at read-local, matching the legacy handler, not
2013        // worst-case it.
2014        for args in [
2015            vec!["grep", "-->", "file.txt"],
2016            vec!["grep", "---", "file.txt"],
2017            vec!["grep", "--some-pattern", "file.txt"],
2018            vec!["grep", "-rn", "-->", "src/"],
2019            vec!["grep", "-i", "-r", "-n", "-->", "src/"],
2020        ] {
2021            let p = resolve(&toks(&args)).expect("grep");
2022            assert!(read_local().admits(&p), "dash-pattern should read-local: {args:?}");
2023            assert!(!inert().admits(&p), "it still reads a file: {args:?}");
2024        }
2025        // but the genuinely-dangerous long (--dereference-recursive, symlink escape) worst-cases
2026        let args = vec!["grep", "--dereference-recursive", "foo", "dir"];
2027        let p = resolve(&toks(&args)).expect("grep");
2028        assert!(!read_local().admits(&p), "dangerous long must worst-case: {args:?}");
2029        // PCRE flags now read-local (PCRE2 execs no code): -P short, --perl-regexp long, -oP combined.
2030        for args in [vec!["grep", "-P", "foo", "f"], vec!["grep", "--perl-regexp", "foo", "f"], vec!["grep", "-oP", "foo", "f"]] {
2031            let p = resolve(&toks(&args)).expect("grep");
2032            assert!(read_local().admits(&p), "grep PCRE flag should read-local: {args:?}");
2033        }
2034    }
2035
2036    #[test]
2037    fn grep_stdin_and_standalone_flags() {
2038        assert!(inert().admits(&resolve(&toks(&["grep", "foo"])).expect("grep")), "no file → stdin");
2039        let p = resolve(&toks(&["grep", "-i", "-n", "foo", "file.txt"])).expect("grep");
2040        assert_eq!(p.capabilities.len(), 1, "-i -n standalone; foo pattern; file.txt file");
2041        assert!(read_local().admits(&p));
2042    }
2043
2044    /// The complete resolved capability for a single-capability invocation, with
2045    /// `because` cleared so the assertion is over the **facets** (not the prose).
2046    fn one_cap(cmd: &[&str]) -> Capability {
2047        let p = resolve(&toks(cmd)).expect("resolves");
2048        assert_eq!(p.capabilities.len(), 1, "{cmd:?} is a single-capability invocation");
2049        let mut c = p.capabilities[0].clone();
2050        c.because = String::new();
2051        c
2052    }
2053
2054    /// A read the credential shield cannot clear must SAY so, on the secret axis.
2055    ///
2056    /// Enumerated over the shield's own region nodes plus the unpinnable spellings, because the
2057    /// claim has to survive a new store being declared and a new reader being written. Two halves,
2058    /// and the second is the one that is easy to lose:
2059    ///
2060    ///  - a path that NAMES a store (`~/.ssh/id_rsa`) — the shield can check it and it fails;
2061    ///  - a path the shield cannot check AT ALL (`$VAR`, an undeclared `$(…)`, an xargs item) —
2062    ///    unknowable, so possibly a credential, so refused.
2063    ///
2064    /// Today both also deny by locus, which is exactly why this guard is worth having: the locus
2065    /// cap makes the secret claim invisible in the verdict, so nothing else would notice it going
2066    /// missing — and it is the only thing that keeps `find / | xargs -I{} cat {}` refused once
2067    /// local reads open up (TODO.md).
2068    #[test]
2069    fn a_read_the_shield_cannot_clear_claims_secret() {
2070        let secret_of = |cmd: &str| {
2071            let toks: Vec<Token> = shell_words::split(cmd).expect("splits").into_iter().map(Token::from_raw).collect();
2072            resolve(&toks).map(|p| p.capabilities.iter().any(|c| c.secret.level == crate::engine::facet::SecretLevel::Reads))
2073        };
2074
2075        // Every declared credential store, read by the plainest reader there is.
2076        let mut checked = 0usize;
2077        for path in crate::engine::resolve::regions::declared_region_paths() {
2078            if !crate::engine::resolve::names_credential_store(&path) {
2079                continue;
2080            }
2081            // A node is a SUBTREE (`~/.ssh/`), a SEGMENT (`.ssh`) or an EXACT file
2082            // (`/etc/master.passwd`). Only the first two have anything beneath them; appending to
2083            // the exact form names a path that is not the node and is not shielded.
2084            // QUOTED, because several stores have a space in them (`~/Library/Application
2085            // Support/Firefox/`) and an unquoted probe splits into two tokens, neither of which is
2086            // the node — the guard would pass by never testing them.
2087            let probe = if path.ends_with('/') || !path.contains('/') {
2088                format!("cat '{}/probe'", path.trim_end_matches('/'))
2089            } else {
2090                format!("cat '{path}'")
2091            };
2092            if let Some(claims) = secret_of(&probe) {
2093                checked += 1;
2094                assert!(claims, "`{probe}` reads a declared credential store without claiming secret");
2095            }
2096        }
2097        assert!(checked > 0, "no credential store was probed — the guard is vacuous");
2098
2099        // Paths the shield cannot be consulted about at all.
2100        for cmd in ["cat $SOMEVAR", "cat $(hostname)", "head -c 20 ${HOME}x/$Y"] {
2101            assert_eq!(secret_of(cmd), Some(true), "`{cmd}` names a path the shield cannot check, so it must claim secret");
2102        }
2103
2104        // ...and an ordinary, checkable read does NOT — the claim has to discriminate, or it is
2105        // just a second way of spelling "deny everything".
2106        for cmd in ["cat ./README.md", "cat src/lib.rs"] {
2107            assert_eq!(secret_of(cmd), Some(false), "`{cmd}` must not claim a secret read");
2108        }
2109    }
2110
2111    /// Golden profiles: assert **every** facet of the resolved capability for
2112    /// representative invocations. This is the "all facets covered" check (§0) — struct
2113    /// equality means a facet the resolver forgot (left at a wrong default) or set wrong
2114    /// fails the test, per command. When commands carry TOML profiles, the expected
2115    /// profile is derived from the TOML instead of hand-built here.
2116    #[test]
2117    fn golden_profiles_cover_every_facet() {
2118        // echo — the reference `structural` profile: observe, process-scoped, output to
2119        // the model, and every other axis provably zero.
2120        let mut echo = Capability::new(Operation::Observe);
2121        echo.disclosure.audience = DisclosureAudience::LocalProcess;
2122        assert_eq!(one_cap(&["echo", "hi"]), echo, "echo");
2123
2124        // cat of a worktree file — observe · worktree · content-to-model.
2125        let mut cat = Capability::new(Operation::Observe);
2126        cat.locus.local = LocalLocus::Worktree;
2127        cat.disclosure.audience = DisclosureAudience::LocalProcess;
2128        assert_eq!(one_cap(&["cat", "./notes.md"]), cat, "cat ./notes.md");
2129
2130        // cat of a plain home file resolves to `user` — the rung the ladder defines for `~` and
2131        // that, until 2026-08-15, no production path ever reached (everything under home fell
2132        // through to `unknown`/`machine`, the same rung as /etc/hosts). Still denies: `user` sits
2133        // above the reader level's cap. The rung is now HONEST, which is the prerequisite for a
2134        // level admitting a home read without also admitting the whole machine.
2135        let mut cat_home = cat.clone();
2136        cat_home.locus.local = LocalLocus::User;
2137        assert_eq!(one_cap(&["cat", "~/notes.txt"]), cat_home, "cat ~/notes.txt");
2138
2139        // An ordinary home DOTFILE is ordinary: `.zshrc` is `user`, like any other file in home.
2140        assert_eq!(one_cap(&["cat", "~/.zshrc"]), cat_home, "cat ~/.zshrc");
2141
2142        // A CREDENTIAL dotfile is not, and it is the shield that says so rather than the rung.
2143        // Excluding dotfiles from the `user` rung protected nothing — an excluded path fell through
2144        // to machine, which the read policy admits — so the shield names them instead.
2145        let mut cat_dot = cat.clone();
2146        cat_dot.locus.local = LocalLocus::Machine;
2147        cat_dot.secret.level = SecretLevel::Reads;
2148        cat_dot.reversibility = Reversibility::Exposed;
2149        assert_eq!(one_cap(&["cat", "~/.git-credentials"]), cat_dot, "cat ~/.git-credentials");
2150
2151        // cat of a home CREDENTIAL store: machine locus AND — the part that was missing until
2152        // 2026-08-14 — a `secret · reads` claim. The region carried `reads_secret = true` all along,
2153        // but nothing put it on the capability, so this golden recorded "reading an SSH private key
2154        // claims no secret" and the denial rested entirely on the locus cap. Both facets now, which
2155        // is what lets the locus cap be relaxed without handing over the key.
2156        let mut cat_cred = cat.clone();
2157        cat_cred.locus.local = LocalLocus::Machine;
2158        cat_cred.secret.level = SecretLevel::Reads;
2159        cat_cred.reversibility = Reversibility::Exposed;
2160        assert_eq!(one_cap(&["cat", "~/.ssh/id_rsa"]), cat_cred, "cat ~/.ssh/id_rsa");
2161
2162        // grep of a worktree file — like cat, bounded to the single searched file.
2163        assert_eq!(one_cap(&["grep", "foo", "file.txt"]), cat, "grep foo file.txt");
2164
2165        // grep -r — the recursive search raises scale to unbounded and nothing else.
2166        let mut grep_r = cat.clone();
2167        grep_r.scale = Scale::Unbounded;
2168        assert_eq!(one_cap(&["grep", "-r", "foo", "src/"]), grep_r, "grep -r foo src/");
2169
2170        // rm — destroy · worktree · effortful; no net/exec/secret.
2171        let mut rm = Capability::new(Operation::Destroy);
2172        rm.locus.local = LocalLocus::Worktree;
2173        rm.reversibility = Reversibility::Effortful;
2174        assert_eq!(one_cap(&["rm", "./x"]), rm, "rm ./x");
2175
2176        // mkdir — create · worktree · trivial · leaves data. A fresh dir is rmdir-removable.
2177        let mut mkdir = Capability::new(Operation::Create);
2178        mkdir.locus.local = LocalLocus::Worktree;
2179        mkdir.reversibility = Reversibility::Trivial;
2180        mkdir.persistence.level = PersistenceLevel::Data;
2181        assert_eq!(one_cap(&["mkdir", "./build"]), mkdir, "mkdir ./build");
2182
2183        // touch — the same create · worktree · trivial · data shape as mkdir.
2184        assert_eq!(one_cap(&["touch", "./new.txt"]), mkdir, "touch ./new.txt");
2185
2186        // cp -n ./a ./b — a guaranteed-non-clobbering copy is TWO capabilities:
2187        // a source read (observe, worktree, NO model disclosure) and a trivial dest create.
2188        let cp = resolve(&toks(&["cp", "-n", "./a", "./b"])).expect("cp");
2189        assert_eq!(cp.capabilities.len(), 2, "cp = source read + dest write");
2190        let mut src = Capability::new(Operation::Observe);
2191        src.locus.local = LocalLocus::Worktree; // disclosure.audience stays `none`: file→file
2192        assert_eq!(clear_because(&cp.capabilities[0]), src, "cp source read");
2193        let mut dst = Capability::new(Operation::Create);
2194        dst.locus.local = LocalLocus::Worktree;
2195        dst.reversibility = Reversibility::Trivial; // -n → cannot overwrite
2196        dst.persistence.level = PersistenceLevel::Data;
2197        assert_eq!(clear_because(&cp.capabilities[1]), dst, "cp -n dest write");
2198
2199        // mv ./a ./b — a relocation: source MUTATE (trivial, transient — the entry leaves)
2200        // + dest CREATE (recoverable overwrite). Contrast cp's source, which is an observe.
2201        let mv = resolve(&toks(&["mv", "./a", "./b"])).expect("mv");
2202        let mut mv_src = Capability::new(Operation::Mutate);
2203        mv_src.locus.local = LocalLocus::Worktree;
2204        mv_src.reversibility = Reversibility::Trivial;
2205        assert_eq!(clear_because(&mv.capabilities[0]), mv_src, "mv source relocation");
2206        let mut mv_dst = Capability::new(Operation::Create);
2207        mv_dst.locus.local = LocalLocus::Worktree;
2208        mv_dst.reversibility = Reversibility::Recoverable;
2209        mv_dst.persistence.level = PersistenceLevel::Data;
2210        assert_eq!(clear_because(&mv.capabilities[1]), mv_dst, "mv dest write");
2211
2212        // ln ./a ./b — target bridged (observe, no model disclosure) + link create (trivial,
2213        // no -f). Same facet shapes as cp -n, the point being ln reuses `observes`.
2214        let ln = resolve(&toks(&["ln", "./a", "./b"])).expect("ln");
2215        let mut ln_tgt = Capability::new(Operation::Observe);
2216        ln_tgt.locus.local = LocalLocus::Worktree;
2217        assert_eq!(clear_because(&ln.capabilities[0]), ln_tgt, "ln target bridge");
2218        let mut ln_link = Capability::new(Operation::Create);
2219        ln_link.locus.local = LocalLocus::Worktree;
2220        ln_link.reversibility = Reversibility::Trivial;
2221        ln_link.persistence.level = PersistenceLevel::Data;
2222        assert_eq!(clear_because(&ln.capabilities[1]), ln_link, "ln link create");
2223    }
2224
2225    fn clear_because(c: &Capability) -> Capability {
2226        let mut c = c.clone();
2227        c.because = String::new();
2228        c
2229    }
2230
2231    #[test]
2232    fn mkdir_creates_in_the_worktree_but_not_beyond_it() {
2233        use crate::engine::bridge::project;
2234        use crate::verdict::{SafetyLevel, Verdict};
2235        // a fresh dir is a trivial-reversibility create → write-local (SafeWrite)
2236        for cmd in [vec!["mkdir", "./build"], vec!["mkdir", "-p", "a/b/c"], vec!["mkdir", "-m", "755", "./x"]] {
2237            assert_eq!(project(&resolve(&toks(&cmd)).expect("mkdir")), Verdict::Allowed(SafetyLevel::SafeWrite), "{cmd:?}");
2238        }
2239        // outside the worktree → denied by locus
2240        for cmd in [vec!["mkdir", "/etc/evil"], vec!["mkdir", "~/newdir"], vec!["mkdir", "$HOME/x"]] {
2241            assert_eq!(project(&resolve(&toks(&cmd)).expect("mkdir")), Verdict::Denied, "{cmd:?}");
2242        }
2243        // Creating a protected path is the same write as putting a file there.
2244        for cmd in ["mkdir .git", "mkdir -p a/.git", "mkdir /etc/foo"] {
2245            assert_eq!(crate::command_verdict(cmd), Verdict::Denied, "{cmd}");
2246        }
2247        for cmd in ["mkdir build", "mkdir -p src/x"] {
2248            assert_eq!(crate::command_verdict(cmd), Verdict::Allowed(SafetyLevel::SafeWrite), "{cmd}");
2249        }
2250        // a glued valued short (-m755) and its value must not be read as operands
2251        let g = resolve(&toks(&["mkdir", "-m755", "./x"])).expect("mkdir");
2252        assert_eq!(g.capabilities.len(), 1, "-m755 glued: only ./x is an operand");
2253        assert_eq!(g.capabilities[0].locus.local, LocalLocus::Worktree);
2254        // fail-closed on an unknown flag / no operand
2255        assert_eq!(project(&resolve(&toks(&["mkdir", "-Q", "x"])).expect("mkdir")), Verdict::Denied, "unknown flag");
2256        assert_eq!(project(&resolve(&toks(&["mkdir"])).expect("mkdir")), Verdict::Denied, "no operand");
2257    }
2258
2259    #[test]
2260    fn cp_splits_source_and_dest_loci_and_overwrite_gates_the_level() {
2261        use crate::engine::bridge::project;
2262        use crate::verdict::{SafetyLevel, Verdict};
2263
2264        // a copy is a create/overwrite, not a destroy → write-local (SafeWrite), matching
2265        // echo > config.json. Overwriting is recoverable; -n can't clobber (trivial). Both
2266        // write-local — the destroy-vs-create boundary keeps cp below rm.
2267        let plain = resolve(&toks(&["cp", "./a", "./b"])).expect("cp");
2268        assert_eq!(plain.capabilities.last().unwrap().reversibility, Reversibility::Recoverable, "dest overwrite");
2269        assert_eq!(project(&plain), Verdict::Allowed(SafetyLevel::SafeWrite), "cp ./a ./b");
2270        let nc = resolve(&toks(&["cp", "-n", "./a", "./b"])).expect("cp");
2271        assert_eq!(nc.capabilities.last().unwrap().reversibility, Reversibility::Trivial, "-n cannot clobber");
2272        assert_eq!(project(&nc), Verdict::Allowed(SafetyLevel::SafeWrite), "cp -n ./a ./b");
2273
2274        // reading a home/system SOURCE is denied by the source locus — no secret detector,
2275        // just the read locus (cp can't smuggle ~/.ssh/id_rsa into the worktree).
2276        assert_eq!(project(&resolve(&toks(&["cp", "~/.ssh/id_rsa", "./x"])).expect("cp")), Verdict::Denied, "home source");
2277        assert_eq!(project(&resolve(&toks(&["cp", "/etc/shadow", "./x"])).expect("cp")), Verdict::Denied, "system source");
2278        // writing a home/system DEST is denied by the dest locus.
2279        assert_eq!(project(&resolve(&toks(&["cp", "./x", "~/backdoor"])).expect("cp")), Verdict::Denied, "home dest");
2280        assert_eq!(project(&resolve(&toks(&["cp", "./x", "/etc/cron.d/x"])).expect("cp")), Verdict::Denied, "system dest");
2281
2282        // -t DIR makes every positional a source; the dir is the dest. All three spellings
2283        // (separate, --long=, and glued short) must parse the same way.
2284        for form in [
2285            vec!["cp", "-t", "./dest", "./a", "./b"],
2286            vec!["cp", "--target-directory=./dest", "./a", "./b"],
2287            vec!["cp", "-t./dest", "./a", "./b"], // glued short — previously worst-cased
2288        ] {
2289            let t = resolve(&toks(&form)).expect("cp -t");
2290            assert_eq!(t.capabilities.len(), 3, "{form:?}: 2 sources + 1 dest");
2291            assert_eq!(project(&t), Verdict::Allowed(SafetyLevel::SafeWrite), "{form:?}");
2292        }
2293        // a glued -t pointing outside the worktree is still denied by the dest locus.
2294        assert_eq!(project(&resolve(&toks(&["cp", "-t/etc", "./a"])).expect("cp")), Verdict::Denied, "cp -t/etc");
2295
2296        // optional-argument longs (--backup[=X], --preserve[=X]) must NOT swallow the
2297        // source operand: bare and glued forms both leave ./a a source and ./b the dest.
2298        for form in
2299            [vec!["cp", "--backup", "./a", "./b"], vec!["cp", "--preserve", "./a", "./b"], vec!["cp", "--preserve=mode", "./a", "./b"]]
2300        {
2301            let c = resolve(&toks(&form)).expect("cp");
2302            assert_eq!(c.capabilities.len(), 2, "{form:?}: source read + dest write");
2303            assert_eq!(project(&c), Verdict::Allowed(SafetyLevel::SafeWrite), "{form:?}");
2304        }
2305
2306        // recursion raises scale to unbounded; a lone operand / unknown flag worst-cases.
2307        assert_eq!(resolve(&toks(&["cp", "-r", "./a", "./b"])).expect("cp").capabilities[0].scale, Scale::Unbounded);
2308        assert_eq!(project(&resolve(&toks(&["cp", "./only"])).expect("cp")), Verdict::Denied, "no dest");
2309        assert_eq!(project(&resolve(&toks(&["cp", "-Q", "./a", "./b"])).expect("cp")), Verdict::Denied, "unknown flag");
2310        // -t naming a dest with NO source operands is a usage error → fail closed (not a lone,
2311        // benign dest write).
2312        assert_eq!(project(&resolve(&toks(&["cp", "-t", "./dest"])).expect("cp")), Verdict::Denied, "-t no source");
2313    }
2314
2315    #[test]
2316    fn mv_relocates_within_the_worktree_and_gates_both_loci() {
2317        use crate::engine::bridge::project;
2318        use crate::verdict::{SafetyLevel, Verdict};
2319
2320        // a move within the worktree is a mutate (source) + create (dest), both trivial/
2321        // recoverable → write-local, NOT developer. Unlike rm, a move relocates, not destroys.
2322        let m = resolve(&toks(&["mv", "./a", "./b"])).expect("mv");
2323        assert_eq!(m.capabilities[0].operation, Operation::Mutate, "source is a relocation, not a destroy");
2324        assert_eq!(m.capabilities[0].reversibility, Reversibility::Trivial, "mv back");
2325        assert_eq!(project(&m), Verdict::Allowed(SafetyLevel::SafeWrite), "mv ./a ./b");
2326
2327        // both loci are gated as writes: source-out and dest-out both deny.
2328        assert_eq!(project(&resolve(&toks(&["mv", "~/.ssh/id_rsa", "./x"])).expect("mv")), Verdict::Denied, "source in home");
2329        assert_eq!(project(&resolve(&toks(&["mv", "./x", "~/exfil"])).expect("mv")), Verdict::Denied, "dest in home");
2330        // moving a worktree-TRUSTED file mutates .git → denied, even though cp of it is
2331        // allowed (cp only READS .git/config; the dest write puts cp at SafeWrite).
2332        assert_eq!(project(&resolve(&toks(&["mv", ".git/config", "./x"])).expect("mv")), Verdict::Denied, "mv .git/config");
2333        assert_eq!(
2334            project(&resolve(&toks(&["cp", ".git/config", "./x"])).expect("cp")),
2335            Verdict::Allowed(SafetyLevel::SafeWrite),
2336            "cp .git/config reads"
2337        );
2338
2339        // The relocate source gates at its REBIND face, not its read face. safe-chains' own config
2340        // READS at worktree-trusted but rebinds at system-integrity (un-grantable, and above what
2341        // any level below yolo admits): `mv`ing it REMOVES it, so the removal must gate at the
2342        // rebind face; a `cp` of it only READS (worktree-trusted). Both deny by verdict, so assert
2343        // the source LOCUS to pin the face — this is the case a read-face relocate would fail open
2344        // on, and the value pins that the face is the strict one rather than plain `machine`.
2345        let cfg = "~/.config/safe-chains.toml";
2346        assert_eq!(
2347            resolve(&toks(&["mv", cfg, "./x"])).expect("mv").capabilities[0].locus.local,
2348            LocalLocus::SystemIntegrity,
2349            "mv source removal gates at the REBIND face",
2350        );
2351        assert_eq!(
2352            resolve(&toks(&["cp", cfg, "./x"])).expect("cp").capabilities[0].locus.local,
2353            LocalLocus::WorktreeTrusted,
2354            "cp source read gates at the READ face",
2355        );
2356
2357        // -t DIR and glued forms; fail-closed on unknown flag / lone operand.
2358        let t = resolve(&toks(&["mv", "-t", "./dest", "./a", "./b"])).expect("mv -t");
2359        assert_eq!(t.capabilities.len(), 3, "2 sources + 1 dest");
2360        assert_eq!(project(&resolve(&toks(&["mv", "./only"])).expect("mv")), Verdict::Denied, "no dest");
2361        assert_eq!(project(&resolve(&toks(&["mv", "-Q", "./a", "./b"])).expect("mv")), Verdict::Denied, "unknown flag");
2362    }
2363
2364    #[test]
2365    fn ln_is_cp_by_reference_and_gates_the_target_locus() {
2366        use crate::engine::bridge::project;
2367        use crate::verdict::{SafetyLevel, Verdict};
2368
2369        // a worktree link (hard or symbolic) is target-read + link-create → write-local.
2370        for cmd in [vec!["ln", "./a", "./b"], vec!["ln", "-s", "./target", "./link"]] {
2371            let p = resolve(&toks(&cmd)).expect("ln");
2372            assert_eq!(p.capabilities[0].operation, Operation::Observe, "target is a bridged read");
2373            assert_eq!(project(&p), Verdict::Allowed(SafetyLevel::SafeWrite), "{cmd:?}");
2374        }
2375        // the cp-bypass is closed: linking a SECRET/unreadable TARGET denies on the target
2376        // locus, exactly as `cp` of it would (a link would otherwise alias the secret in).
2377        assert_eq!(project(&resolve(&toks(&["ln", "~/.ssh/id_rsa", "./x"])).expect("ln")), Verdict::Denied, "hard link to home credential");
2378        assert_eq!(project(&resolve(&toks(&["ln", "-s", "/etc/shadow", "./x"])).expect("ln")), Verdict::Denied, "symlink to secret");
2379        // An out-of-workspace target is judged as a write too: whatever later writes through the link
2380        // writes the target.
2381        assert_eq!(project(&resolve(&toks(&["ln", "-s", "/etc/hosts", "./x"])).expect("ln")), Verdict::Denied, "symlink to a system path");
2382        // writing the LINK outside the worktree denies on the link locus.
2383        assert_eq!(project(&resolve(&toks(&["ln", "-s", "./a", "~/evil"])).expect("ln")), Verdict::Denied, "link into home");
2384        // -t DIR, lone operand, unknown flag.
2385        assert_eq!(resolve(&toks(&["ln", "-t", "./dir", "./a", "./b"])).expect("ln -t").capabilities.len(), 5);
2386        assert_eq!(project(&resolve(&toks(&["ln", "./only"])).expect("ln")), Verdict::Denied, "no link name");
2387        assert_eq!(project(&resolve(&toks(&["ln", "-Q", "./a", "./b"])).expect("ln")), Verdict::Denied, "unknown flag");
2388        // -f (a clobber flag PRESENT) flips the link-create from the no-clobber default
2389        // (`trivial`) to `recoverable` — still write-local. Exercises the `clobber_flags`-present
2390        // branch of the transfer arm, the inverse of cp/mv's `no_clobber_flags`.
2391        let forced = resolve(&toks(&["ln", "-f", "./a", "./b"])).expect("ln -f");
2392        assert_eq!(project(&forced), Verdict::Allowed(SafetyLevel::SafeWrite), "ln -f worktree link");
2393        assert_eq!(forced.capabilities[1].reversibility, Reversibility::Recoverable, "ln -f overwrites → recoverable");
2394        assert_eq!(
2395            resolve(&toks(&["ln", "./a", "./b"])).expect("ln").capabilities[1].reversibility,
2396            Reversibility::Trivial,
2397            "ln default no-clobber → trivial",
2398        );
2399    }
2400
2401    #[test]
2402    fn dd_parses_key_value_operands_and_gates_both_sides() {
2403        use crate::engine::bridge::project;
2404        use crate::verdict::{SafetyLevel, Verdict};
2405
2406        // a worktree-to-worktree copy → write-local; params (bs/count/conv) are ignored.
2407        assert_eq!(
2408            project(&resolve(&toks(&["dd", "if=./a", "of=./b", "bs=1M", "count=10"])).expect("dd")),
2409            Verdict::Allowed(SafetyLevel::SafeWrite),
2410            "dd worktree copy",
2411        );
2412        // input from stdout (no of=) discloses the input content to the model, like cat.
2413        assert_eq!(project(&resolve(&toks(&["dd", "if=./notes"])).expect("dd")), Verdict::Allowed(SafetyLevel::SafeRead), "dd to stdout");
2414        assert_eq!(project(&resolve(&toks(&["dd"])).expect("dd")), Verdict::Allowed(SafetyLevel::Inert), "bare dd is stdin→stdout");
2415
2416        // both sides gated by locus: a home INPUT or a device/home OUTPUT denies.
2417        for cmd in [
2418            vec!["dd", "if=~/.ssh/id_rsa", "of=./x"], // read a home secret
2419            vec!["dd", "if=./x", "of=/dev/rdisk0"],   // write a raw device (disk wipe)
2420            vec!["dd", "if=./x", "of=/dev/sda"],
2421            vec!["dd", "if=./x", "of=~/backup"], // write into home
2422            vec!["dd", "if=~/.ssh/id_rsa"],      // home secret to stdout (→ model)
2423        ] {
2424            assert_eq!(project(&resolve(&toks(&cmd)).expect("dd")), Verdict::Denied, "{cmd:?}");
2425        }
2426        // fail-closed: a non key=value operand, or an unknown key, worst-cases.
2427        assert_eq!(project(&resolve(&toks(&["dd", "./file"])).expect("dd")), Verdict::Denied, "positional operand");
2428        assert_eq!(project(&resolve(&toks(&["dd", "exec=evil", "of=./x"])).expect("dd")), Verdict::Denied, "unknown key");
2429    }
2430
2431    #[test]
2432    fn tar_parses_dashless_bundles_and_splits_by_mode() {
2433        use crate::engine::bridge::project;
2434        use crate::verdict::{SafetyLevel, Verdict};
2435
2436        // dashless `czf` and dashed `-czf` and the long form all parse the same: a create is
2437        // members-read + archive-write → write-local for a worktree backup.
2438        for cmd in [
2439            vec!["tar", "czf", "backup.tar", "./src"],
2440            vec!["tar", "-czf", "backup.tar", "./src"],
2441            vec!["tar", "--create", "--file=backup.tar", "./src"],
2442        ] {
2443            assert_eq!(project(&resolve(&toks(&cmd)).expect("tar")), Verdict::Allowed(SafetyLevel::SafeWrite), "{cmd:?}");
2444        }
2445        // list reads the archive → read-local.
2446        assert_eq!(project(&resolve(&toks(&["tar", "tzf", "backup.tar"])).expect("tar")), Verdict::Allowed(SafetyLevel::SafeRead), "list");
2447
2448        // the bundler-exfil case (golden-set): a home member denies on the member locus,
2449        // whether the archive goes to stdout or a file.
2450        assert_eq!(project(&resolve(&toks(&["tar", "czf", "-", "~/.ssh"])).expect("tar")), Verdict::Denied, "bundle secret to stdout");
2451        assert_eq!(project(&resolve(&toks(&["tar", "czf", "out.tar", "~/.aws"])).expect("tar")), Verdict::Denied, "bundle home member");
2452        // a home/system ARCHIVE denies on the archive write locus.
2453        assert_eq!(project(&resolve(&toks(&["tar", "cf", "~/backup.tar", "./src"])).expect("tar")), Verdict::Denied, "archive into home");
2454
2455        // extract is archive-controlled (..-escapable) → worst-case, even for a benign archive.
2456        assert_eq!(project(&resolve(&toks(&["tar", "xzf", "release.tar"])).expect("tar")), Verdict::Denied, "extract");
2457        // `tar cf backup.tar` with no members creates an empty archive — a benign worktree
2458        // write, so SafeWrite (not a fail-closed case).
2459        assert_eq!(
2460            project(&resolve(&toks(&["tar", "cf", "backup.tar"])).expect("tar")),
2461            Verdict::Allowed(SafetyLevel::SafeWrite),
2462            "empty archive"
2463        );
2464        // fail-closed: an unmodeled value option (-C), no mode, an empty profile, a bad letter.
2465        assert_eq!(project(&resolve(&toks(&["tar", "-C", "/etc", "xf", "a.tar"])).expect("tar")), Verdict::Denied, "-C unmodeled");
2466        assert_eq!(project(&resolve(&toks(&["tar", "c"])).expect("tar")), Verdict::Denied, "create to stdout, no members");
2467        assert_eq!(project(&resolve(&toks(&["tar", "zf", "backup.tar"])).expect("tar")), Verdict::Denied, "no mode letter");
2468    }
2469
2470    /// perl's two gates are independent and BOTH are required: the identifier allowlist decides
2471    /// whether the one-liner is inert, locus decides whether the operands may be touched. The
2472    /// second was missing — `perl -pe 's/a/b/' /etc/shadow` auto-approved, because the handler
2473    /// judged only the code — so the read cases below are the regression, and the `-i` cases are
2474    /// the capability the missing gate had been standing in for.
2475    /// Parse `line` and ask what a `$( … )` around it would evaluate to.
2476    #[cfg(test)]
2477    fn sub_locus(line: &str) -> Option<LocalLocus> {
2478        let script = crate::cst::parse(line).expect("parses");
2479        match substitution_claim(&script)? {
2480            SubClaim::Locus(l) => Some(l),
2481            // An atom names no locus, so these callers — which ask "which rung does this value
2482            // point at" — correctly see nothing.
2483            SubClaim::Atom => None,
2484            SubClaim::Literal(dir) => Some(read_locus(&dir)),
2485        }
2486    }
2487
2488    /// No output claim survives `--help` / `--version`, for EVERY command that declares one.
2489    ///
2490    /// Enumerated over the registry rather than spot-checked on seq, because the failure is a
2491    /// property of what those flags DO — replace the command's data output with prose — and so it
2492    /// applies to every claim, including ones added later. The prose routinely carries paths and
2493    /// URLs: GNU `seq --help` prints `<https://www.gnu.org/software/coreutils/>` under an `atom`
2494    /// claim asserting no word holds a separator.
2495    ///
2496    /// Missed by hand-probing because macOS ships BSD seq, whose help is terse and slash-free —
2497    /// the local install disagreed with the upstream the claim is written against.
2498    #[test]
2499    fn no_output_claim_survives_a_help_or_version_flag() {
2500        let mut probed = 0usize;
2501        for (scope, spec) in crate::registry::output_claims() {
2502            // A claim gated on a required flag is only ever live WITH it, so the probe has to carry
2503            // it — otherwise the assertion holds for the boring reason and guards nothing.
2504            let scope = match spec.requires.first() {
2505                Some(required) => format!("{scope} {required}"),
2506                None => scope,
2507            };
2508            for flag in ["--help", "--version"] {
2509                let line = format!("{scope} {flag}");
2510                let Some(script) = crate::cst::parse(&line) else { continue };
2511                probed += 1;
2512                assert!(
2513                    substitution_claim(&script).is_none(),
2514                    "`{line}` still carries an output claim, but --help/--version print prose \
2515                     rather than the command's data, so the claim does not describe it"
2516                );
2517            }
2518        }
2519        assert!(probed > 0, "nothing declares an output claim; this guard would be vacuous");
2520    }
2521
2522    /// A sub-scoped claim must survive every TRUSTED spelling of its command, and no other.
2523    ///
2524    /// The walker keys on the registry name, so it has to be handed the CANONICALIZED one — the
2525    /// same key the command-level lookup gets. Given the raw first word instead, `/usr/bin/git diff
2526    /// --name-only` silently lost the claim that bare `git` kept: one operation, two spellings, two
2527    /// answers, which is the false-deny class the flag-form guards exist to kill.
2528    ///
2529    /// The other half is that this must NOT extend trust: `./git` is a worktree binary that may not
2530    /// be git at all, and `trusted_command_path` is what keeps it claimless.
2531    #[test]
2532    fn a_sub_claim_follows_every_trusted_spelling_of_its_command() {
2533        let bare = sub_locus("git diff --name-only");
2534        assert!(bare.is_some(), "precondition: bare `git diff --name-only` should carry a claim");
2535        for spelling in ["/usr/bin/git", "/opt/homebrew/bin/git"] {
2536            assert_eq!(
2537                sub_locus(&format!("{spelling} diff --name-only")),
2538                bare,
2539                "`{spelling} diff --name-only` disagrees with the bare spelling",
2540            );
2541        }
2542        for untrusted in ["./git", "/tmp/git", "../git"] {
2543            assert_eq!(
2544                sub_locus(&format!("{untrusted} diff --name-only")),
2545                None,
2546                "`{untrusted}` is not a trusted path to git and must earn no output claim",
2547            );
2548        }
2549    }
2550
2551    #[test]
2552    fn a_pwd_outside_the_worktree_does_not_stand_in_for_a_file_there() {
2553        let home = crate::process_home::var().expect("HOME");
2554        let root = format!("{}/projects/app", home.trim_end_matches('/'));
2555        let _guard = crate::pathctx::enter(crate::pathctx::PathCtx { cwd: Some(root.clone()), root: Some(root), session_id: None });
2556        for command in
2557            ["cd /etc && cat $(pwd)/shadow", "cd /var/log && cat $(pwd)/auth.log", "cd ~/Library && cat $(pwd)/Keychains/login.keychain-db"]
2558        {
2559            assert!(!crate::is_safe_command(command), "{command}");
2560        }
2561        assert!(crate::is_safe_command("cat $(pwd)/notes.txt"));
2562        assert!(crate::is_safe_command("cd /tmp/y && cat $(pwd)/notes.txt"));
2563    }
2564
2565    #[test]
2566    fn a_program_named_by_a_path_is_the_tool_only_inside_a_known_location() {
2567        for denied in [
2568            "./.scratch/cargo test", "./x/ls", "/tmp/x/memory_pressure", "/bin/../tmp/x/cat", "/opt/homebrew/bin/../../../../tmp/x/cat",
2569            "/bin/../tmp/x/ls",
2570        ] {
2571            assert!(!crate::is_safe_command(denied), "approved from outside a known location: {denied}");
2572        }
2573        for allowed in ["/bin/ls", "/usr/bin/grep foo file.txt", "/bin/./ls", "/usr/bin/../bin/ls", "/opt/homebrew/bin/ls"] {
2574            assert!(crate::is_safe_command(allowed), "known location stopped approving: {allowed}");
2575        }
2576        let home = crate::process_home::var().expect("HOME");
2577        let home = home.trim_end_matches('/');
2578        for allowed in [
2579            "/opt/homebrew/opt/ripgrep/bin/grep foo file.txt",
2580            "/opt/homebrew/Cellar/ripgrep/14.1.0/bin/grep foo file.txt",
2581            "/usr/local/opt/grep/bin/grep foo file.txt",
2582            "/usr/local/Cellar/grep/3.11/bin/grep foo file.txt",
2583            "/home/linuxbrew/.linuxbrew/bin/grep foo file.txt",
2584            "/home/linuxbrew/.linuxbrew/Cellar/grep/3.11/bin/grep foo file.txt",
2585            "/opt/bin/grep foo file.txt",
2586            "/usr/local/cargo/bin/grep foo file.txt",
2587            "/usr/local/rustup/toolchains/stable/bin/grep foo file.txt",
2588            &format!("{home}/.cargo/bin/grep foo file.txt"),
2589            &format!("{home}/.rustup/toolchains/stable/bin/grep foo file.txt"),
2590            &format!("{home}/.local/share/mise/installs/ripgrep/14.1.0/bin/grep foo file.txt"),
2591            "~/.cargo/bin/grep foo file.txt",
2592            "~/.local/share/mise/installs/ripgrep/14.1.0/bin/grep foo file.txt",
2593        ] {
2594            assert!(crate::is_safe_command(allowed), "toolchain path stopped approving: {allowed}");
2595        }
2596        let rules = "\
2597[[command]]
2598name = \"scripts/attest\"
2599level = \"SafeRead\"
2600bare = true
2601
2602[[command]]
2603name = \"bin/check.sh\"
2604level = \"SafeRead\"
2605bare = true
2606";
2607        crate::registry::with_test_commands(rules, || {
2608            assert!(crate::is_safe_command("scripts/attest"), "a rule that names the path");
2609            assert!(crate::is_safe_command("bin/check.sh"), "a rule that names the path");
2610            assert!(!crate::is_safe_command("attest"), "the rule is the path, not the last component");
2611            assert!(!crate::is_safe_command("./scripts/attest"), "a different spelling is a different program");
2612        });
2613    }
2614
2615    /// A claim gated on `requires` must be DEAD without its flag. `git diff` prints a patch and
2616    /// `jj diff` a diff; only `--name-only` turns either into a list of paths, so the ungated
2617    /// invocation must stay unpinnable. Without this, `requires` could be silently ignored and the
2618    /// claim would widen every invocation of the sub.
2619    #[test]
2620    fn a_required_flag_is_necessary_for_its_claim() {
2621        let mut probed = 0usize;
2622        for (scope, spec) in crate::registry::output_claims() {
2623            if spec.requires.is_empty() {
2624                continue;
2625            }
2626            probed += 1;
2627            let Some(script) = crate::cst::parse(&scope) else { continue };
2628            assert_eq!(
2629                substitution_claim(&script).map(|_| ()),
2630                None,
2631                "`{scope}` carries an output claim without any of {:?}, which the declaration says \
2632                 are required for the output to be paths at all",
2633                spec.requires,
2634            );
2635            // ...and LIVE with it, or the declaration describes nothing.
2636            for required in &spec.requires {
2637                let line = format!("{scope} {required}");
2638                let Some(script) = crate::cst::parse(&line) else { continue };
2639                assert!(
2640                    substitution_claim(&script).is_some(),
2641                    "`{line}` carries no output claim, but `{required}` is declared as one of the \
2642                     flags that makes the claim hold"
2643                );
2644            }
2645        }
2646        assert!(probed > 0, "nothing declares `requires`; this guard would be vacuous");
2647    }
2648
2649    /// Fail-closed, enumerated over the REGISTRY: every `[command.output]` claim is probed on a HOT
2650    /// root, and must never report a locus below what reading that root reports. This is the
2651    /// fail-open the whole feature risks — a missed search root means the substitution is admitted
2652    /// at worktree while the command actually reaches `/etc`. The `match` is EXHAUSTIVE, so a new
2653    /// `OutputLocus` variant must state how it is probed or the build breaks.
2654    ///
2655    /// Red→green: drop the glued-value branch from `candidate_roots` and
2656    /// `fd --search-path=/etc x` stops reporting machine.
2657    #[test]
2658    fn every_output_claim_is_bounded_by_its_roots() {
2659        use crate::registry::types::OutputLocus;
2660
2661        let mut probed = 0usize;
2662        for (scope, spec) in crate::registry::output_claims() {
2663            probed += 1;
2664            // A `requires`-gated claim is only live with its flag, so every probe below carries it.
2665            // `name` is therefore the invocation PREFIX, not just a command name.
2666            let name = match spec.requires.first() {
2667                Some(required) => format!("{scope} {required}"),
2668                None => scope.clone(),
2669            };
2670            let name = name.as_str();
2671            match spec.locus_from {
2672                // An `atom` claim is that no output word can contain a separator, so the check is
2673                // the claim: run the command's OWN examples and read what they would print. A
2674                // command whose examples emit a `/` is mis-declared, and the consequence is not
2675                // subtle — the confinement layer treats the value as unable to leave its
2676                // component, so a separator would let it walk anywhere the prefix can reach.
2677                //
2678                // Enumerated over the registry rather than spot-checked, because the next command
2679                // to declare `atom` gets this for free, which is the only way a data-driven claim
2680                // stays honest as the data grows.
2681                // An `atom` claim cannot be checked the way the others can. The rest are probed by
2682                // asking the resolver where a HOT root lands, but "no output word contains a
2683                // separator" is a fact about the TOOL, and the only mechanical way to confirm it
2684                // would be to run the command — which a unit test must not do for arbitrary
2685                // registry entries.
2686                //
2687                // So this is a REVIEW gate, not a proof: the claim has to be argued per command,
2688                // and a new declaration fails here until someone does that and adds it. What makes
2689                // it worth having is the failure mode it guards — an atom is treated as unable to
2690                // leave its path component, so a tool that CAN emit a `/` would let the value walk
2691                // anywhere its prefix reaches. `seq`'s argument is in its TOML: numbers only, with
2692                // the three flags that inject caller text (`-s`, `-t`, `-f`) in `invalidated_by`.
2693                //
2694                // The soundness of the confinement ITSELF — that a separator-free value beside
2695                // literal text cannot escape — is proved separately, by
2696                // `a_flanked_atom_never_moves_where_the_write_lands`.
2697                OutputLocus::Atom => {
2698                    const ARGUED: &[&str] = &["seq"];
2699                    assert!(
2700                        ARGUED.contains(&name),
2701                        "command '{name}' declares `locus_from = \"atom\"`, which asserts that no \
2702                         word it prints can contain a separator. That cannot be checked here \
2703                         without running the command, so it must be argued in the command's TOML \
2704                         (what it prints, and which flags reshape it into `invalidated_by`) and \
2705                         then listed in ARGUED."
2706                    );
2707                }
2708                OutputLocus::Operands => {
2709                    // `~` is here as a named case, not just inside HOT_PATHS, because it is the
2710                    // spelling that actually got through: it carries neither `/` nor `.`, so the
2711                    // path-SHAPE test skipped it and `cat $(fd pat ~)` swept the home directory
2712                    // while reporting worktree.
2713                    let hot_roots: Vec<&str> = HOT_PATHS.iter().copied().chain(["~", "~/.ssh"]).collect();
2714                    for hot in hot_roots {
2715                        // Every spelling a root can arrive in: bare operand, separated flag value,
2716                        // glued long value, glued short value. Missing any is the fail-open.
2717                        for line in [
2718                            format!("{name} pat {hot}"),
2719                            format!("{name} --base-directory {hot} pat"),
2720                            format!("{name} --search-path={hot} pat"),
2721                            format!("{name} -E{hot} pat"),
2722                        ] {
2723                            let got = sub_locus(&line);
2724                            let want = read_locus(hot);
2725                            assert!(got.is_none_or(|l| l >= want), "`{line}`: reported {got:?}, but reading {hot} is {want:?}",);
2726                        }
2727                    }
2728                    // A substitution in a root slot is unknowable — no claim.
2729                    assert_eq!(sub_locus(&format!("{name} pat $(hostname)")), None, "{name}: nested sub");
2730                }
2731                // Its output is the cwd, which takes no root operand; the guard that matters is
2732                // that it does not somehow report BELOW the cwd's own locus.
2733                OutputLocus::Cwd => {
2734                    assert_eq!(sub_locus(name), Some(read_locus(".")), "{name}: bare");
2735                }
2736                // A filter only filters while it has no file operand — given one it prints that
2737                // file's CONTENTS, which are not paths and must void the claim.
2738                OutputLocus::Stdin => {
2739                    for hot in HOT_PATHS {
2740                        assert_eq!(sub_locus(&format!("{name} {hot}")), None, "{name}: a file operand makes it print contents, not paths",);
2741                    }
2742                }
2743            }
2744            // Every flag the command declares as invalidating must actually void the claim.
2745            for flag in &spec.invalidated_by {
2746                let line = format!("{name} {flag} pat");
2747                assert_eq!(sub_locus(&line), None, "`{line}`: {flag} is declared invalidating");
2748            }
2749        }
2750        assert!(probed > 0, "no command declares [command.output] — the guard is vacuous");
2751        // The enumeration must reach SUB-scoped claims, not just command-scoped ones. Without this
2752        // the extension is silently self-defeating: a walker that stopped at the top level would
2753        // make every `[command.sub.output]` skip the probes above and the guard would still be
2754        // green, reporting coverage it does not have.
2755        assert!(
2756            crate::registry::output_claims().iter().any(|(scope, _)| scope.contains(' ')),
2757            "no sub-scoped output claim was enumerated, so `[command.sub.output]` is unprobed",
2758        );
2759    }
2760
2761    /// Enumerated over the REGISTRY: a flag declared `valued` on `[command.output]` means "this
2762    /// value is not a path", and BOTH spellings must agree. Handling only the separated form denied
2763    /// `head --lines=5` while `head -n 5` passed — one operation, two spellings, two answers, which
2764    /// is the false-deny class the flag-form equivalence guards exist to kill.
2765    #[test]
2766    fn output_valued_flags_agree_across_spellings() {
2767        use crate::registry::types::OutputLocus;
2768        let mut checked = 0usize;
2769        for (scope, spec) in crate::registry::output_claims() {
2770            // As above: a `requires`-gated claim is only live with its flag, so the probe carries it.
2771            let name = match spec.requires.first() {
2772                Some(required) => format!("{scope} {required}"),
2773                None => scope.clone(),
2774            };
2775            let name = name.as_str();
2776            for flag in &spec.valued {
2777                // An invalidating flag voids the claim by design, so it is not a spelling case.
2778                if spec.invalidated_by.contains(flag) {
2779                    continue;
2780                }
2781                // Two things are load-bearing about the probe shape, and without EITHER the
2782                // guard silently passes a broken skip:
2783                //  - a PRODUCER stage, because a lone `stdin` command walks back off the end of
2784                //    the pipeline and reports `None` whether or not it saw a file operand, hiding
2785                //    the difference entirely;
2786                //  - a TRAILING OPERAND, because a glued form that over-skips (swallowing the
2787                //    next argument as if it were a separated value) is indistinguishable from a
2788                //    correct one until there is a next argument to lose.
2789                // Together they expose the over-skip as a file operand going missing — which for
2790                // a `stdin` claim is a fail-open: contents get classified as if they were paths.
2791                let producer = match spec.locus_from {
2792                    OutputLocus::Stdin => "fd a app/ | ",
2793                    _ => "",
2794                };
2795                for tail in ["", " /etc/hosts"] {
2796                    let separated = sub_locus(&format!("{producer}{name} {flag} 5{tail}"));
2797                    let glued = sub_locus(&format!("{producer}{name} {flag}=5{tail}"));
2798                    assert_eq!(separated, glued, "{name} {flag} (tail {tail:?}): separated {separated:?}, glued {glued:?}",);
2799                    checked += 1;
2800                }
2801            }
2802        }
2803        assert!(checked > 0, "no output claim declares a valued flag — the guard is vacuous");
2804    }
2805
2806    /// The default is unpinnable. A command that has NOT been researched for its output locus must
2807    /// keep the opaque sentinel, so the feature can only ever widen through a deliberate
2808    /// declaration — never by a command happening to look read-only.
2809    #[test]
2810    fn undeclared_commands_get_no_output_claim() {
2811        // `echo` is the load-bearing case: as safe as a command gets, and its output is whatever
2812        // the caller typed. If it ever acquires a claim, `cat $(echo /etc/shadow)` opens up.
2813        for line in ["echo /etc/shadow", "hostname", "cat ./f", "ls", "git rev-parse --show-toplevel"] {
2814            assert_eq!(sub_locus(line), None, "`{line}` must have no output claim");
2815        }
2816        assert!(!crate::is_safe_command("cat $(echo /etc/shadow)"), "echo must not bound its output");
2817    }
2818
2819    #[test]
2820    fn perl_i_worktree_vs_system() {
2821        use crate::engine::bridge::project;
2822        use crate::verdict::{SafetyLevel, Verdict};
2823
2824        // No -i: the operands are content reads, gated by READ locus.
2825        let read = resolve(&toks(&["perl", "-pe", "s/x/y/", "./foo"])).expect("perl");
2826        assert_eq!(read.capabilities[0].operation, Operation::Observe, "no -i → read");
2827        assert_eq!(project(&read), Verdict::Allowed(SafetyLevel::SafeRead), "perl read");
2828
2829        // -i flips them to in-place MUTATES, admitted only in the worktree.
2830        let edit = resolve(&toks(&["perl", "-pi", "-e", "s/x/y/", "./foo"])).expect("perl");
2831        assert_eq!(edit.capabilities[0].operation, Operation::Mutate, "-i → in-place write");
2832        assert_eq!(project(&edit), Verdict::Allowed(SafetyLevel::SafeWrite), "perl -i worktree");
2833        let glued = resolve(&toks(&["perl", "-i.bak", "-pe", "s/x/y/", "./foo"])).expect("perl");
2834        assert_eq!(glued.capabilities[0].operation, Operation::Mutate, "-i.bak is still in-place");
2835
2836        // THE REGRESSION: an inert one-liner does not license the operand. It is gated exactly as
2837        // `cat` and `sed` gate theirs — so a credential store or an unpinnable path denies, while
2838        // an ordinary machine file (asserted below) reads.
2839        for cmd in [
2840            vec!["perl", "-pe", "s/a/b/", "/etc/shadow"],
2841            vec!["perl", "-ne", "print", "~/.ssh/id_rsa"],
2842            vec!["perl", "-pe", "s/a/b/", "$CONFIG"], // unpinnable
2843            vec!["perl", "-pi", "-e", "s/a/b/", "/etc/hosts"],
2844            vec!["perl", "-pi", "-e", "s/a/b/", "~/.bashrc"],
2845            vec!["perl", "-pi", "-e", "s/a/b/", "../outside"],
2846        ] {
2847            assert_eq!(project(&resolve(&toks(&cmd)).expect("perl")), Verdict::Denied, "{cmd:?} must deny");
2848        }
2849        // The WRITE half stays put: reading /etc/passwd is fine, rewriting it in place is not.
2850        assert_eq!(
2851            project(&resolve(&toks(&["perl", "-pe", "s/a/b/", "/etc/passwd"])).expect("perl")),
2852            Verdict::Allowed(SafetyLevel::SafeRead),
2853            "an inert one-liner over an ordinary machine file is a read"
2854        );
2855
2856        // Opaque code is refused whatever the operand: no `-e` means the first operand is a script
2857        // file we cannot read, and a failed identifier gate means the one-liner left the vocabulary.
2858        for cmd in [
2859            vec!["perl", "./script.pl"],
2860            vec!["perl", "-n", "./file.txt"],
2861            vec!["perl", "-e", "system(\"rm -rf /\")", "./foo"],
2862            vec!["perl", "-pie", "s/a/b/", "./foo"], // ambiguous suffix spelling — unmodeled
2863        ] {
2864            assert_eq!(project(&resolve(&toks(&cmd)).expect("perl")), Verdict::Denied, "{cmd:?} must deny");
2865        }
2866
2867        // A worktree-scoped sweep is bounded, not single — scored honestly, still admitted.
2868        let glob = resolve(&toks(&["perl", "-pi", "-e", "s/a/b/", "*"])).expect("perl");
2869        assert_eq!(glob.capabilities[0].scale, Scale::Bounded, "a glob is a bounded blast radius");
2870        assert_eq!(project(&glob), Verdict::Allowed(SafetyLevel::SafeWrite), "perl -i * (worktree)");
2871    }
2872
2873    #[test]
2874    fn sed_i_flips_read_to_write_and_locus_stops_system_wide_damage() {
2875        use crate::engine::bridge::project;
2876        use crate::verdict::{SafetyLevel, Verdict};
2877
2878        // -i turns the file operands from reads into in-place MUTATES.
2879        let read = resolve(&toks(&["sed", "s/x/y/", "./foo"])).expect("sed");
2880        assert_eq!(read.capabilities[0].operation, Operation::Observe, "no -i → read");
2881        assert_eq!(project(&read), Verdict::Allowed(SafetyLevel::SafeRead), "sed read");
2882        let edit = resolve(&toks(&["sed", "-i", "s/x/y/", "./foo"])).expect("sed");
2883        assert_eq!(edit.capabilities[0].operation, Operation::Mutate, "-i → in-place write");
2884        assert_eq!(project(&edit), Verdict::Allowed(SafetyLevel::SafeWrite), "sed -i worktree");
2885
2886        // THE CONCERN: a stray system-wide `sed -i` is stopped by LOCUS — a system, home, or
2887        // unpinnable target denies whatever the scale. Damage needs a target above the
2888        // worktree, and every such target is denied.
2889        for cmd in [
2890            vec!["sed", "-i", "s/a/b/", "/etc/passwd"],
2891            vec!["sed", "-i", "s/a/b/", "/etc/hosts"],
2892            vec!["sed", "-i", "s/a/b/", "~/.bashrc"],
2893            vec!["sed", "-i", "s/a/b/", "$CONFIG"],      // unpinnable
2894            vec!["sed", "-i", "s/a/b/", "../outside"],   // escapes the worktree
2895            vec!["sed", "-i", "-e", "s/a/b/", "/etc/x"], // -e script, system file
2896        ] {
2897            assert_eq!(project(&resolve(&toks(&cmd)).expect("sed")), Verdict::Denied, "{cmd:?} must deny");
2898        }
2899
2900        // A worktree-scoped sweep IS allowed — bounded, recoverable, your own project files.
2901        // The glob/multi-operand blast radius is scored as `bounded`, still write-local.
2902        let glob = resolve(&toks(&["sed", "-i", "s/a/b/", "*"])).expect("sed");
2903        assert_eq!(glob.capabilities[0].scale, Scale::Bounded, "a glob is a bounded blast radius");
2904        assert_eq!(project(&glob), Verdict::Allowed(SafetyLevel::SafeWrite), "sed -i * (worktree)");
2905        assert_eq!(
2906            project(&resolve(&toks(&["sed", "-i", "s/a/b/", "a", "b", "c"])).expect("sed")),
2907            Verdict::Allowed(SafetyLevel::SafeWrite),
2908            "multi-file"
2909        );
2910
2911        // -i.bak (optional glued suffix) still parses as in-place.
2912        assert_eq!(
2913            project(&resolve(&toks(&["sed", "-i.bak", "s/a/b/", "./foo"])).expect("sed")),
2914            Verdict::Allowed(SafetyLevel::SafeWrite),
2915            "-i.bak"
2916        );
2917        // -f runs a script file we can't inspect (its e/w/r commands are invisible) → denied, like
2918        // `awk -f`, `bash script.sh`, mlr `--load`.
2919        assert_eq!(
2920            project(&resolve(&toks(&["sed", "-f", "script.sed", "./foo"])).expect("sed")),
2921            Verdict::Denied,
2922            "-f script file unanalyzable"
2923        );
2924        // a home file read (no -i) still denies by locus, like cat.
2925        assert_eq!(project(&resolve(&toks(&["sed", "s/a/b/", "~/.ssh/id_rsa"])).expect("sed")), Verdict::Denied, "read home secret");
2926        assert_eq!(project(&resolve(&toks(&["sed", "-Q", "./foo"])).expect("sed")), Verdict::Denied, "unknown flag");
2927    }
2928
2929    #[test]
2930    fn sed_exec_command_is_worst_cased_at_parity_with_legacy() {
2931        use crate::engine::bridge::project;
2932        use crate::verdict::Verdict;
2933        // The `e` command/modifier executes text as a shell command (RCE). The resolver must
2934        // worst-case it — flag parsing alone treated the script as opaque and let it through.
2935        for cmd in [
2936            vec!["sed", "s/test/touch tmp/e", "file"], // s///e modifier
2937            vec!["sed", "-e", "s/x/cmd/e", "file"],    // via -e
2938            vec!["sed", "s/x/cmd/ew", "file"],         // e flag BEFORE the greedy w flag
2939            vec!["sed", "1e", "file"],                 // address + e
2940            vec!["sed", "e"],                          // bare e
2941            vec!["sed", "-e", "e"],
2942            vec!["sed", "1e reboot", "file"], // address + e WITH a command argument
2943            vec!["sed", "p;e id", "file"],    // e after a `;` separator
2944        ] {
2945            assert_eq!(project(&resolve(&toks(&cmd)).expect("sed")), Verdict::Denied, "{cmd:?}: exec must deny");
2946        }
2947        // `s/x/cmd/we` is NOT here: `w` is greedy-to-EOL, so `we` writes to a file named `e` (a
2948        // local SafeWrite), not w-then-e exec. `sed '1e reboot'` — the former residual gap — is now
2949        // caught by the sed sub-parser (`scan_sed`).
2950    }
2951
2952    /// HP-19 #1 (engine): `classify_locus` now resolves relative paths against the ambient
2953    /// cwd/root. With no context it falls back to relative-is-worktree (status quo); under a
2954    /// `cd /etc` context the same operands resolve to `/etc/*` and deny.
2955    #[test]
2956    fn classify_locus_resolves_relative_operands_against_the_cwd_context() {
2957        use crate::engine::bridge::project;
2958        use crate::pathctx::PathCtx;
2959        use crate::verdict::{SafetyLevel, Verdict};
2960
2961        // No context → relative is worktree (fallback), and a sweeping edit is write-local.
2962        for p in ["*", "passwd", "config"] {
2963            assert_eq!(classify_locus(p), LocalLocus::Worktree, "{p}: no ctx → worktree");
2964        }
2965        assert_eq!(
2966            project(&resolve(&toks(&["sed", "-i", "s/a/b/", "*"])).expect("sed")),
2967            Verdict::Allowed(SafetyLevel::SafeWrite),
2968            "no ctx: sed -i *"
2969        );
2970
2971        // Context says the shell is in /etc → relative operands are /etc/* → machine → deny.
2972        let _g = crate::pathctx::enter(PathCtx { cwd: Some("/etc".into()), root: Some("/home/u/proj".into()), ..Default::default() });
2973        for p in ["*", "hosts", "config", "cron.d"] {
2974            assert_eq!(classify_locus(p), LocalLocus::Machine, "{p}: cwd=/etc → machine");
2975        }
2976        // /etc/passwd is the identity substrate: its WRITE face worst-cases to system-integrity
2977        // (above machine → above local-admin), even reached as a relative operand from cwd=/etc.
2978        assert_eq!(classify_locus("passwd"), LocalLocus::SystemIntegrity, "passwd: cwd=/etc → system-integrity");
2979        assert_eq!(project(&resolve(&toks(&["sed", "-i", "s/a/b/", "*"])).expect("sed")), Verdict::Denied, "cwd=/etc: sed -i * denied");
2980        assert_eq!(project(&resolve(&toks(&["dd", "if=./x", "of=passwd"])).expect("dd")), Verdict::Denied, "cwd=/etc: dd of=passwd denied");
2981        assert_eq!(project(&resolve(&toks(&["cp", "./payload", "config"])).expect("cp")), Verdict::Denied, "cwd=/etc: cp denied");
2982    }
2983
2984    /// One operation, three spellings of in-place, one answer.
2985    ///
2986    /// BSD (macOS) spells the empty in-place suffix as a SEPARATE word — `sed -i '' SCRIPT FILE` —
2987    /// and modelled GNU-only, `-i` consumed nothing, so `''` landed in the first positional, which
2988    /// for sed is the SCRIPT. Everything shifted one: the real script became a FILE operand, got
2989    /// word-split, and any absolute-looking token inside it picked the locus. That is not a
2990    /// contrived input — the decision log caught it on `s|…|// TEMP: no-op|`, where the `//` of a
2991    /// JavaScript comment read as the filesystem root and a worktree edit denied at `machine`.
2992    ///
2993    /// Enumerated over scripts that contain the tokens which make the shift visible (`$`, `//`, a
2994    /// leading `/`), because the bug is invisible on a script that happens to hold none of them.
2995    #[test]
2996    fn sed_in_place_classifies_the_same_in_every_spelling() {
2997        use crate::engine::bridge::project;
2998        use crate::verdict::{SafetyLevel, Verdict};
2999
3000        for script in ["1257,$d", "s|x|// TEMP|", "s|a|/b|", "1,$s/x/y/"] {
3001            let bsd = resolve(&toks(&["sed", "-i", "", script, "./app.css"])).expect("sed");
3002            let gnu = resolve(&toks(&["sed", "-i.bak", script, "./app.css"])).expect("sed");
3003            let read = resolve(&toks(&["sed", "-n", script, "./app.css"])).expect("sed");
3004            assert_eq!(project(&bsd), Verdict::Allowed(SafetyLevel::SafeWrite), "`sed -i '' {script} ./app.css` is a worktree edit");
3005            assert_eq!(project(&bsd), project(&gnu), "{script}: -i '' and -i.bak must agree");
3006            assert!(matches!(project(&read), Verdict::Allowed(_)), "{script}: -n is a plain read");
3007        }
3008
3009        // The separate word is consumed ONLY when empty. Under BSD the token after `-i` is a
3010        // SUFFIX, so accepting a non-empty one would let `-i` swallow a real operand — and the
3011        // operand it swallowed would be the one carrying the locus.
3012        assert_eq!(
3013            project(&resolve(&toks(&["sed", "-i", "", "s/a/b/", "/etc/passwd"])).expect("sed")),
3014            Verdict::Denied,
3015            "the FILE after a consumed `-i ''` is still gated"
3016        );
3017    }
3018
3019    /// Which word a short flag consumes decides which word is the FILE, and the file carries the
3020    /// locus. Each pair below differs only in what the flag swallowed, and a wrong count moves a
3021    /// system path into or out of the operand list.
3022    #[test]
3023    fn sed_short_flags_consume_exactly_their_own_value() {
3024        use crate::engine::bridge::project;
3025        use crate::verdict::{SafetyLevel, Verdict};
3026        let verdict = |cmd: &[&str]| project(&resolve(&toks(cmd)).expect("sed"));
3027
3028        // `-e SCRIPT` takes the next word; `-eSCRIPT` takes nothing more.
3029        assert_eq!(verdict(&["sed", "-i", "-e", "/x/d", "./foo"]), Verdict::Allowed(SafetyLevel::SafeWrite), "-e consumed /x/d");
3030        assert_eq!(verdict(&["sed", "-i", "-e/x/d", "/etc/hosts"]), Verdict::Denied, "-eS leaves the file an operand");
3031
3032        // `-l N` (line length) takes its value, glued or separate.
3033        for cmd in [["sed", "-l", "5", "s/a/b/", "./foo"].as_slice(), &["sed", "-l5", "s/a/b/", "./foo"]] {
3034            assert_eq!(verdict(cmd), Verdict::Allowed(SafetyLevel::SafeRead), "{cmd:?}");
3035        }
3036        // A trailing `-l` with no value is malformed, and malformed fails closed.
3037        assert_eq!(verdict(&["sed", "-e", "p", "./foo", "-l"]), Verdict::Denied, "-l without a value");
3038
3039        // An unknown byte in a cluster fails closed even when the script is harmless.
3040        for cmd in [["sed", "-Q", "s/a/b/", "./foo"], ["sed", "-nQ", "s/a/b/", "./foo"]] {
3041            assert_eq!(verdict(&cmd), Verdict::Denied, "{cmd:?}");
3042        }
3043    }
3044
3045    #[test]
3046    fn touch_creates_in_the_worktree_and_gates_the_reference_path() {
3047        use crate::engine::bridge::project;
3048        use crate::verdict::{SafetyLevel, Verdict};
3049        for cmd in [
3050            vec!["touch", "./new.txt"],
3051            vec!["touch", "-c", "existing"],
3052            vec!["touch", "-r", "ref.txt", "./out"], // worktree reference: a read + a create, both worktree
3053            vec!["touch", "-d", "-1 day", "./out"],  // -d takes a DATE literal (not a path), dash-leading value
3054        ] {
3055            assert_eq!(project(&resolve(&toks(&cmd)).expect("touch")), Verdict::Allowed(SafetyLevel::SafeWrite), "{cmd:?}");
3056        }
3057        // `-r REF` reads REF's timestamp — a path-flag gated by REF's locus. A worktree ref is a
3058        // worktree read (allowed, 2 caps), but an out-of-workspace reference DENIES (it would
3059        // otherwise be an mtime/existence oracle for arbitrary paths).
3060        let p = resolve(&toks(&["touch", "-r", "ref.txt", "./out"])).expect("touch");
3061        assert_eq!(p.capabilities.len(), 2, "./out create + ref.txt read");
3062        assert!(p.capabilities.iter().any(|c| c.operation == Operation::Observe), "the -r reference is a read");
3063        // An ordinary home reference is an ordinary read of its mtime; a credential store's is
3064        // not, and neither is a path the shield cannot be asked about.
3065        assert_eq!(
3066            project(&resolve(&toks(&["touch", "-r", "~/.bashrc", "./out"])).expect("touch")),
3067            Verdict::Allowed(SafetyLevel::SafeWrite),
3068            "ordinary home reference"
3069        );
3070        assert_eq!(project(&resolve(&toks(&["touch", "-r", "/etc/shadow", "./out"])).expect("touch")), Verdict::Denied, "system reference");
3071        assert_eq!(
3072            project(&resolve(&toks(&["touch", "--reference=/etc/shadow", "./out"])).expect("touch")),
3073            Verdict::Denied,
3074            "long glued reference"
3075        );
3076        assert_eq!(
3077            project(&resolve(&toks(&["touch", "--reference", "/etc/shadow", "./out"])).expect("touch")),
3078            Verdict::Denied,
3079            "long spaced reference"
3080        );
3081        // -d's dash-leading date literal is NOT a path and is NOT gated.
3082        assert_eq!(
3083            project(&resolve(&toks(&["touch", "-d", "-1 day", "/tmp/../etc/x"])).expect("touch")),
3084            Verdict::Denied,
3085            "operand still gated"
3086        );
3087        // beyond the worktree, and fail-closed cases
3088        assert_eq!(project(&resolve(&toks(&["touch", "/etc/x"])).expect("touch")), Verdict::Denied, "system path");
3089        assert_eq!(project(&resolve(&toks(&["touch", "-Z", "x"])).expect("touch")), Verdict::Denied, "unknown flag");
3090        assert_eq!(project(&resolve(&toks(&["touch"])).expect("touch")), Verdict::Denied, "no operand");
3091    }
3092
3093    #[test]
3094    fn worst_case_is_denied_even_by_a_permissive_yolo_shaped_level() {
3095        use crate::engine::level::{Clause, Level, OrdBound};
3096        // a yolo-shaped level: allow anything local up to `machine`, minus a destroy corner
3097        let yolo = Level::new("yolo-ish")
3098            .allowing(Clause { local_locus: Some(OrdBound::at_most(LocalLocus::Machine)), ..Default::default() })
3099            .denying(Clause {
3100                operation: Some(vec![Operation::Destroy]),
3101                reversibility: Some(OrdBound::at_least(Reversibility::Irreversible)),
3102                ..Default::default()
3103            });
3104        let wc = Profile::of(vec![Capability::worst("test")]);
3105        assert!(!yolo.admits(&wc), "worst_case (locus=kernel) exceeds even a machine-capped allow");
3106    }
3107
3108    #[test]
3109    fn rm_within_the_worktree_projects_to_developer_but_beyond_it_denies() {
3110        use crate::engine::bridge::project;
3111        use crate::verdict::{SafetyLevel, Verdict};
3112        // `developer` admits destroy WITHIN the worktree (golden-set decision 2), even
3113        // recursive/effortful; it maps to the legacy SafeWrite ceiling.
3114        for cmd in [
3115            vec!["rm", "./stale.log"],
3116            vec!["rm", "-rf", "./node_modules"],
3117            vec!["rm", "a", "b", "c"],
3118            vec!["rm", "--interactive=always", "./x"], // optional-arg long: must not worst-case
3119        ] {
3120            let p = resolve(&toks(&cmd)).expect("rm resolves");
3121            assert!(p.capabilities.iter().all(|c| c.operation == Operation::Destroy), "{cmd:?} destroys");
3122            assert_eq!(project(&p), Verdict::Allowed(SafetyLevel::SafeWrite), "{cmd:?} → developer");
3123        }
3124        // Deletion that reaches beyond the worktree (home/system) is above `developer`,
3125        // denied by locus — no clause admits a machine/user-scoped destroy.
3126        for cmd in [vec!["rm", "-rf", "/"], vec!["rm", "-rf", "~/notes"], vec!["rm", "/etc/hosts"]] {
3127            assert_eq!(project(&resolve(&toks(&cmd)).expect("rm")), Verdict::Denied, "{cmd:?} beyond worktree");
3128        }
3129    }
3130
3131    /// End-to-end: `rm -rf /` resolves to the `destroy · irreversible · unbounded` corner and
3132    /// is the one thing even a maximally-permissive yolo refuses — by facet, not by name.
3133    /// Everything one facet away stays yolo-admitted.
3134    #[test]
3135    fn rm_rf_root_is_the_one_thing_even_yolo_denies() {
3136        let yolo = level("yolo");
3137        let root = resolve(&toks(&["rm", "-rf", "/"])).expect("rm");
3138        assert_eq!(root.capabilities[0].reversibility, Reversibility::Irreversible, "rm -rf / is irreversible");
3139        assert_eq!(root.capabilities[0].scale, Scale::Unbounded);
3140        assert!(!yolo.admits(&root), "rm -rf / denied even at yolo");
3141        assert!(!yolo.admits(&resolve(&toks(&["rm", "-rf", "~/notes"])).expect("rm")), "rm -rf ~ likewise");
3142        // adjacent-by-one-facet stays yolo-allowed:
3143        assert!(yolo.admits(&resolve(&toks(&["rm", "-rf", "./node_modules"])).expect("rm")), "recoverable worktree");
3144        assert!(yolo.admits(&resolve(&toks(&["rm", "/etc/hosts"])).expect("rm")), "single (bounded) system delete");
3145    }
3146
3147    /// Phase 1 end-to-end: a subcommand tagged `profile = "<archetype>"` resolves (through the
3148    /// nested `<resource> <action>` grammar) to that archetype's exact static capability, so its
3149    /// verdict is DERIVED from facets, not hand-marked. Untagged sibling subs leave the engine
3150    /// abstaining (→ legacy).
3151    #[test]
3152    fn a_subcommand_profile_resolves_to_its_archetype() {
3153        let p = resolve(&toks(&["koyeb", "apps", "delete", "myapp"])).expect("koyeb apps delete resolves");
3154        assert_eq!(p.capabilities.len(), 1);
3155        assert_eq!(
3156            &p.capabilities[0],
3157            crate::engine::archetype::archetype("remote-destroy-recoverable").unwrap(),
3158            "the sub resolves to its declared archetype's capability",
3159        );
3160        // a differently-tagged action gets a different archetype
3161        let create = resolve(&toks(&["koyeb", "apps", "create", "myapp"])).expect("resolves");
3162        assert_eq!(create.capabilities[0].operation, Operation::Create);
3163        // an untagged read sub: no profile, no command behavior → the engine abstains (legacy decides)
3164        assert!(resolve(&toks(&["koyeb", "apps", "list"])).is_none(), "untagged sub → engine abstains");
3165    }
3166
3167    /// Per-flag escalation (Phase 1 layer): a dangerous flag ADDS a capability to the sub's profile,
3168    /// and the level algebra takes the max — so a benign base + a destructive flag lands at the
3169    /// flag's tier. `git push` is vcs-sync (network-admin); `git push --force` adds
3170    /// remote-destroy-irreversible and escalates past it, to yolo.
3171    #[test]
3172    fn an_escalating_flag_adds_a_capability_and_raises_the_tier() {
3173        let destroy = crate::engine::archetype::archetype("remote-destroy-irreversible").unwrap();
3174        // The vcs-sync base now carries the destination's provenance (exposure §4): `origin` and the
3175        // bare `--force` form (default remote) are both `established`.
3176        let vcs_sync = {
3177            let mut c = crate::engine::archetype::archetype("vcs-sync").unwrap().clone();
3178            c.locus.provenance = Provenance::Established;
3179            c
3180        };
3181
3182        let base = resolve(&toks(&["git", "push", "origin", "main"])).expect("git push resolves");
3183        assert_eq!(base.capabilities, vec![vcs_sync.clone()], "base is vcs-sync, established destination");
3184
3185        let forced = resolve(&toks(&["git", "push", "--force"])).expect("resolves");
3186        assert_eq!(forced.capabilities.len(), 2);
3187        assert!(
3188            forced.capabilities.contains(&vcs_sync) && forced.capabilities.contains(destroy),
3189            "--force ADDS remote-destroy-irreversible to the vcs-sync base"
3190        );
3191
3192        // the escalation MATTERS at the level layer: network-admin admits the base but not the
3193        // forced push; the flag pushed it up to yolo.
3194        let network_admin = level("network-admin");
3195        assert!(network_admin.admits(&base), "git push is network-admin");
3196        assert!(!network_admin.admits(&forced), "git push --force escalated past network-admin");
3197        assert!(level("yolo").admits(&forced), "and lands at yolo");
3198
3199        // the -f short form escalates identically
3200        assert_eq!(resolve(&toks(&["git", "push", "-f"])).unwrap().capabilities.len(), 2);
3201    }
3202
3203    /// Destination-trust (exposure §4): `git push`'s send TARGET is classified onto
3204    /// `locus.provenance`, and an `ext::` command-transport worst-cases as RCE. The one resolver
3205    /// that makes the `locus.provenance` facet actually bind to a command.
3206    #[test]
3207    fn git_push_destination_provenance_is_classified() {
3208        use crate::engine::bridge::project;
3209        use crate::verdict::Verdict;
3210
3211        let prov = |cmd: &[&str]| resolve(&toks(cmd)).expect("push resolves").capabilities[0].locus.provenance;
3212
3213        // bare (configured default) and a bare remote NAME → established (a prior deliberate act).
3214        assert_eq!(prov(&["git", "push"]), Provenance::Established, "bare push = default remote");
3215        assert_eq!(prov(&["git", "push", "origin", "main"]), Provenance::Established, "remote name");
3216        // a flag before the target doesn't hide it.
3217        assert_eq!(prov(&["git", "push", "--force", "origin"]), Provenance::Established, "flag then name");
3218        // spelled inline → literal (visible but injectable): URL, scp-path, filesystem path.
3219        assert_eq!(prov(&["git", "push", "https://h/x.git", "main"]), Provenance::Literal, "url");
3220        assert_eq!(prov(&["git", "push", "git@h:x.git"]), Provenance::Literal, "scp-style");
3221        assert_eq!(prov(&["git", "push", "/srv/mirror.git"]), Provenance::Literal, "path");
3222        // a variable / substitution → opaque (unreviewable).
3223        assert_eq!(prov(&["git", "push", "$REMOTE"]), Provenance::Opaque, "variable");
3224
3225        // network-admin admits established + literal, refuses opaque; the ext:: transport is RCE.
3226        let net = level("network-admin");
3227        assert!(net.admits(&resolve(&toks(&["git", "push", "origin"])).unwrap()), "established at network-admin");
3228        assert!(net.admits(&resolve(&toks(&["git", "push", "https://h/x.git"])).unwrap()), "literal URL at network-admin");
3229        assert!(!net.admits(&resolve(&toks(&["git", "push", "$REMOTE"])).unwrap()), "opaque above network-admin");
3230        // ext::<cmd> runs a local command — worst-cased, denied below yolo.
3231        assert_eq!(project(&resolve(&toks(&["git", "push", "ext::sh"])).unwrap()), Verdict::Denied, "ext:: is RCE");
3232        assert!(!net.admits(&resolve(&toks(&["git", "push", "ext::sh"])).unwrap()), "ext:: not at network-admin");
3233
3234        // `--repo=<dest>` OVERRIDES the positional (the fail-open the review found: `--repo=ext::sh`
3235        // slipping past a benign `origin`). Glued and space forms; a bare remote name still allows.
3236        assert_eq!(project(&resolve(&toks(&["git", "push", "--repo=ext::sh", "origin"])).unwrap()), Verdict::Denied, "--repo=ext:: is RCE");
3237        assert!(!net.admits(&resolve(&toks(&["git", "push", "--repo", "$VAR", "origin"])).unwrap()), "--repo $VAR is opaque");
3238        assert_eq!(prov(&["git", "push", "--repo=https://h/x.git", "main"]), Provenance::Literal, "--repo URL is literal");
3239        assert!(net.admits(&resolve(&toks(&["git", "push", "--repo=upstream", "main"])).unwrap()), "--repo=<remote name> is established");
3240    }
3241
3242    /// The `data-export` resolver: a bulk remote export (`supabase db dump`) is a read that
3243    /// auto-approves to stdout, but its OUTPUT-FILE form (`-f path`) adds a SECOND, path-gated local
3244    /// write — a dump to the worktree stays local (SafeWrite) while one to a system path gates on
3245    /// locus (denied), and the glued short `-f/path` spelling can't slip that gate. The unbounded
3246    /// `scale` records the volume without itself gating the read. See `behavioral-taxonomy-exposure.md`.
3247    #[test]
3248    fn data_export_gates_its_output_file() {
3249        use crate::engine::bridge::project;
3250        use crate::verdict::{SafetyLevel, Verdict};
3251
3252        // to stdout: the bulk remote read alone — one capability, auto-approves as a read.
3253        let stdout = resolve(&toks(&["supabase", "db", "dump", "--data-only"])).expect("dump resolves");
3254        assert_eq!(stdout.capabilities.len(), 1, "stdout dump = the remote read only");
3255        assert_eq!(stdout.capabilities[0].scale, Scale::Unbounded, "a dump records its volume");
3256        assert_eq!(project(&stdout), Verdict::Allowed(SafetyLevel::SafeRead), "bulk read auto-approves");
3257
3258        // -f into the worktree: read + a worktree write → still auto-approves (SafeWrite).
3259        for cmd in [vec!["supabase", "db", "dump", "-f", "dump.sql"], vec!["supabase", "db", "dump", "--file=dump.sql", "--data-only"]] {
3260            let p = resolve(&toks(&cmd)).expect("dump resolves");
3261            assert_eq!(p.capabilities.len(), 2, "{cmd:?}: the remote read + a local write");
3262            assert_eq!(project(&p), Verdict::Allowed(SafetyLevel::SafeWrite), "{cmd:?}");
3263        }
3264
3265        // -f onto a system path: the write gates on locus → denied, in every spelling — space,
3266        // glued `=`, AND the glued short `-f/path` that mustn't be a bypass.
3267        for cmd in [
3268            vec!["supabase", "db", "dump", "-f", "/etc/passwd"],
3269            vec!["supabase", "db", "dump", "--file=/etc/passwd"],
3270            vec!["supabase", "db", "dump", "-f/etc/passwd"],
3271        ] {
3272            let p = resolve(&toks(&cmd)).expect("resolves");
3273            assert!(
3274                p.capabilities
3275                    .iter()
3276                    .any(|c| c.operation == Operation::Create && c.locus.local == LocalLocus::SystemIntegrity),
3277                "{cmd:?} must emit a system-integrity create capability, got {:?}",
3278                p.capabilities,
3279            );
3280            assert_eq!(project(&p), Verdict::Denied, "{cmd:?} writes a system path");
3281        }
3282    }
3283
3284    /// `sudo`/`doas` elevate the wrapped command's AUTHORITY — the resolver that finally gives
3285    /// `local-admin` something to admit. `sudo <safe cmd>` = a root op (above every user-authority
3286    /// band); `sudo rm -rf /` stays the catastrophe corner; `-u`/`-i` and unknown options fail up.
3287    #[test]
3288    fn sudo_elevates_the_wrapped_commands_authority() {
3289        use crate::engine::bridge::project;
3290        use crate::verdict::Verdict;
3291        let (dev, local, net, yolo) = (level("developer"), level("local-admin"), level("network-admin"), level("yolo"));
3292
3293        // sudo cat ./notes — a ROOT read. Authority lifts to root; every band below local-admin pins
3294        // authority=user, so it lands at local-admin (and yolo), NOT developer/network-admin.
3295        let read = resolve(&toks(&["sudo", "cat", "./notes.md"])).expect("sudo cat resolves");
3296        assert_eq!(read.capabilities[0].authority, Authority::Root, "authority lifted to root");
3297        assert!(!dev.admits(&read) && !net.admits(&read), "a root op is above the user-authority bands");
3298        assert!(local.admits(&read) && yolo.admits(&read), "a root read is local-admin");
3299
3300        // benign flag clusters are skipped without losing the inner command (space + glued values too).
3301        assert_eq!(resolve(&toks(&["sudo", "-EH", "cat", "./x"])).unwrap().capabilities[0].authority, Authority::Root);
3302        assert_eq!(resolve(&toks(&["sudo", "-n", "-p", "pw", "cat", "./x"])).unwrap().capabilities[0].authority, Authority::Root);
3303
3304        // bumping authority does NOT rescue the catastrophe corner.
3305        assert_eq!(project(&resolve(&toks(&["sudo", "rm", "-rf", "/"])).unwrap()), Verdict::Denied, "sudo rm -rf / denied everywhere");
3306
3307        // -u (run as another user) → other-user authority → yolo-only (identity confusion tops the ladder).
3308        let other = resolve(&toks(&["sudo", "-u", "bob", "cat", "./x"])).expect("sudo -u resolves");
3309        assert_eq!(other.capabilities[0].authority, Authority::OtherUser, "-u = run as other user");
3310        assert!(!local.admits(&other) && yolo.admits(&other), "other-user is yolo-only");
3311        assert_eq!(
3312            resolve(&toks(&["sudo", "-ubob", "cat", "./x"])).unwrap().capabilities[0].authority,
3313            Authority::OtherUser,
3314            "glued -ubob"
3315        );
3316
3317        // -i / -s / -e launch a root shell or editor → arbitrary code, worst-cased.
3318        assert_eq!(project(&resolve(&toks(&["sudo", "-i"])).unwrap()), Verdict::Denied, "sudo -i is a root shell");
3319        assert!(!local.admits(&resolve(&toks(&["sudo", "-s", "bash"])).unwrap()), "root shell not local-admin");
3320
3321        // an UNRECOGNIZED sudo option fails closed.
3322        assert_eq!(project(&resolve(&toks(&["sudo", "--nonsense", "cat", "./x"])).unwrap()), Verdict::Denied, "unknown option worst-cases");
3323
3324        // an UNRESOLVED inner → None, so the caller's legacy fallback denies (never looser than bare).
3325        assert!(resolve(&toks(&["sudo", "totallyunknowncmd", "x"])).is_none(), "unresolved inner → legacy denies");
3326        // `sudo` with no command → None (legacy decides).
3327        assert!(resolve(&toks(&["sudo", "-v"])).is_none(), "no inner command");
3328
3329        // doas is the same wrapper.
3330        assert_eq!(resolve(&toks(&["doas", "cat", "./x"])).unwrap().capabilities[0].authority, Authority::Root);
3331
3332        // A valued short flag at end-of-input has no next-token value: `i` overshot the slice and
3333        // PANICKED (fail-open hook crash, found by the parse fuzzer). Now clamps → no inner → None.
3334        assert!(resolve(&toks(&["doas", "-r"])).is_none(), "doas -r must not panic");
3335        assert!(resolve(&toks(&["sudo", "-u"])).is_none(), "sudo -u must not panic");
3336        assert_eq!(crate::command_verdict("doas -r"), Verdict::Denied, "doas -r denied, not crashed");
3337
3338        // NEVER LOOSER: at the default band every `sudo …` is denied (root authority is auto-approved
3339        // by NO level below local-admin), exactly like the legacy classifier, which denies sudo whole.
3340        for cmd in ["sudo cat ./notes.md", "sudo rm -rf ./build", "sudo -EH cat ./x", "sudo -u bob ls"] {
3341            assert_eq!(crate::command_verdict(cmd), Verdict::Denied, "`{cmd}` must not auto-approve at the default band");
3342        }
3343    }
3344
3345    /// systemctl — the first REAL command user of the `local-privileged` archetype. Read subs stay
3346    /// SafeRead (any band); service-management subs land at local-admin; and `sudo systemctl restart`
3347    /// (previously fail-closed, since systemctl's inner sub was unmodeled) now resolves to local-admin.
3348    #[test]
3349    fn systemctl_service_management_is_local_admin() {
3350        use crate::verdict::Verdict;
3351        let (dev, local, net, yolo) = (level("developer"), level("local-admin"), level("network-admin"), level("yolo"));
3352
3353        // service management → local-privileged: local-admin and yolo admit; developer/network-admin don't.
3354        for sub in ["restart", "start", "stop", "enable", "disable", "mask", "daemon-reload", "kill"] {
3355            let p = resolve(&toks(&["systemctl", sub, "nginx"])).unwrap_or_else(|| panic!("systemctl {sub} resolves"));
3356            assert!(!dev.admits(&p) && !net.admits(&p), "systemctl {sub} is above developer/network-admin");
3357            assert!(local.admits(&p) && yolo.admits(&p), "systemctl {sub} is local-admin");
3358        }
3359        // reads stay auto-approvable (SafeRead), a power-state sub denies by omission (not modeled).
3360        assert!(crate::command_verdict("systemctl status nginx").is_allowed(), "status reads");
3361        assert_eq!(crate::command_verdict("systemctl reboot"), Verdict::Denied, "reboot omitted → denied");
3362
3363        // the fail-closed case is fixed: `sudo systemctl restart` resolves the inner sub (already root).
3364        let sudo_restart = resolve(&toks(&["sudo", "systemctl", "restart", "nginx"])).expect("resolves");
3365        assert!(local.admits(&sudo_restart), "sudo systemctl restart is local-admin");
3366        assert_eq!(crate::command_verdict("sudo systemctl restart nginx"), Verdict::Denied, "still not auto-approved at default");
3367    }
3368
3369    /// The flag-conditional-archetype resolver (the `when_absent` mechanism, npm exemplar):
3370    /// `npm ci --ignore-scripts` is a PINNED, scripts-off install → `local-install-pinned`
3371    /// (developer). Dropping `--ignore-scripts` escalates it to `supply-chain-build` (yolo — runs
3372    /// fetched code at install). `npm install`/`i` are FLOATING → always `supply-chain-build`. This
3373    /// is the pattern the package-manager fan-out replicates.
3374    #[test]
3375    fn npm_install_is_classified_by_pinning_and_scripts_off() {
3376        let (dev, yolo) = (level("developer"), level("yolo"));
3377
3378        // pinned (ci) + scripts-off → developer.
3379        let safe = resolve(&toks(&["npm", "ci", "--ignore-scripts"])).expect("npm ci --ignore-scripts");
3380        assert!(dev.admits(&safe), "pinned, scripts-off ci is developer");
3381
3382        // pinned but scripts-ON → the --ignore-scripts ABSENCE escalates to supply-chain-build → yolo.
3383        let scripts_on = resolve(&toks(&["npm", "ci"])).expect("npm ci");
3384        assert!(!dev.admits(&scripts_on), "ci without --ignore-scripts runs fetched code → above developer");
3385        assert!(yolo.admits(&scripts_on), "and lands at yolo");
3386
3387        // floating installs → supply-chain-build regardless of flags.
3388        for c in [&["npm", "install"][..], &["npm", "install", "left-pad"], &["npm", "i", "react"], &["npm", "install", "--ignore-scripts"]]
3389        {
3390            let p = resolve(&toks(c)).unwrap_or_else(|| panic!("{c:?} resolves"));
3391            assert!(!dev.admits(&p) && yolo.admits(&p), "{c:?}: floating install → supply-chain (yolo)");
3392        }
3393    }
3394
3395    #[test]
3396    fn rm_flag_and_operand_fail_closed() {
3397        use crate::engine::bridge::project;
3398        use crate::verdict::Verdict;
3399        for cmd in [
3400            vec!["rm", "--no-preserve-root", "-rf", "/"], // enables rm -rf / → must worst-case
3401            vec!["rm", "-Z", "x"],                        // unknown flag
3402            vec!["rm"],                                   // no operand (usage error)
3403        ] {
3404            assert_eq!(project(&resolve(&toks(&cmd)).expect("resolves")), Verdict::Denied, "{cmd:?}");
3405        }
3406        assert!(resolve(&toks(&["./rm", "x"])).is_none(), "a worktree path is a script, not rm");
3407    }
3408
3409    #[test]
3410    fn rm_scale_and_force_semantics() {
3411        let cap = |cmd: &[&str]| resolve(&toks(cmd)).expect("rm").capabilities[0].clone();
3412        assert_eq!(cap(&["rm", "./x"]).scale, Scale::Single);
3413        assert_eq!(cap(&["rm", "a", "b"]).scale, Scale::Bounded, "multiple operands");
3414        assert_eq!(cap(&["rm", "*.log"]).scale, Scale::Bounded, "a glob");
3415        assert_eq!(cap(&["rm", "-r", "./dir"]).scale, Scale::Unbounded, "recursive");
3416        // -f only suppresses prompts — it does NOT raise reversibility for rm
3417        assert_eq!(cap(&["rm", "./x"]).reversibility, Reversibility::Effortful);
3418        assert_eq!(cap(&["rm", "-f", "./x"]).reversibility, Reversibility::Effortful, "-f is not a raiser");
3419    }
3420
3421    #[test]
3422    fn a_resolvable_name_from_a_non_standard_path_worst_cases() {
3423        assert!(resolve(&toks(&["./cat", "x"])).is_none(), "a worktree path is a script, not cat");
3424        for cmd in [vec!["/tmp/cat", "x"], vec!["~/bin/grep", "foo", "f"]] {
3425            let p = resolve(&toks(&cmd)).expect("resolvable name");
3426            assert!(!read_local().admits(&p), "{cmd:?} from a non-standard path must worst-case");
3427        }
3428        // bare names and standard bin paths resolve normally
3429        assert!(read_local().admits(&resolve(&toks(&["cat", "./notes.md"])).expect("cat")));
3430        assert!(read_local().admits(&resolve(&toks(&["/usr/bin/cat", "./notes.md"])).expect("cat")));
3431        // a non-resolvable command from any path → None (the engine doesn't claim it)
3432        assert!(resolve(&toks(&["/tmp/mytool", "x"])).is_none());
3433    }
3434
3435    #[test]
3436    fn unrecognized_flags_worst_case_fail_closed() {
3437        for cmd in [
3438            vec!["cat", "-Z", "./x"],
3439            vec!["cat", "--wat", "./x"],
3440            vec!["grep", "-Q", "foo", "f"],   // unknown grep short char (-Z is benign: --null)
3441            vec!["grep", "-R", "foo", "dir"], // -R follows symlinks → escapes locus (M2)
3442        ] {
3443            let p = resolve(&toks(&cmd)).expect("resolver");
3444            assert!(!inert().admits(&p) && !read_local().admits(&p), "{cmd:?} must worst-case");
3445        }
3446        // recognized-benign flags still resolve normally
3447        assert!(read_local().admits(&resolve(&toks(&["cat", "-nA", "./x"])).expect("cat")));
3448        assert!(read_local().admits(&resolve(&toks(&["grep", "-rin", "foo", "src/"])).expect("grep")));
3449    }
3450
3451    use proptest::prelude::*;
3452
3453    /// The content-transfer commands: every one moves/bridges content between a source and
3454    /// a destination operand, so BOTH roles must be locus-gated. Extend this list as
3455    /// `install`/`dd`/`rsync`/`tar` land — a resolver that forgets to gate a role then fails
3456    /// the property below (the `ln` cp-bypass class, §HP re: capability laundering).
3457    const TRANSFER_CMDS: &[&str] = &["cp", "mv", "ln"];
3458
3459    /// A sensitive path that must never be laundered through a transfer command, in any
3460    /// role. Covers each locus rung above the worktree AND the two unpinnable markers.
3461    const HOT_PATHS: &[&str] = &["/etc/shadow", "~/.ssh/id_rsa", "$SECRET", "../out", "~/.aws"];
3462
3463    proptest! {
3464        /// No capability laundering: a hot path in EITHER operand role of a transfer command
3465        /// denies — you can neither pull a secret in (`cp ~/.ssh/id_rsa ./x`) nor push one
3466        /// out (`cp ./x /etc/cron.d/y`). This is the STRICT property that catches an ignored
3467        /// operand; plain locus-monotonicity does not, because ignoring a role leaves the
3468        /// verdict unchanged, and unchanged is "not looser".
3469        #[test]
3470        fn transfer_commands_gate_both_operand_roles(
3471            cmd in prop::sample::select(TRANSFER_CMDS),
3472            hot in prop::sample::select(HOT_PATHS),
3473        ) {
3474            use crate::engine::bridge::project;
3475            use crate::verdict::Verdict;
3476            let hot_source = resolve(&toks(&[cmd, hot, "./safe"])).expect("resolves");
3477            prop_assert_eq!(project(&hot_source), Verdict::Denied, "{} hot SOURCE ({})", cmd, hot);
3478            let hot_dest = resolve(&toks(&[cmd, "./safe", hot])).expect("resolves");
3479            prop_assert_eq!(project(&hot_dest), Verdict::Denied, "{} hot DEST ({})", cmd, hot);
3480        }
3481
3482        /// The sudo/doas flag walk must never panic (a panic in the resolver is a fail-OPEN hook
3483        /// crash) nor depend on evaluation order, for ANY flag salad — crucially a valued short flag
3484        /// at end-of-input (`doas -r`, `sudo -u`), which consumes a "next token" that isn't there and
3485        /// pushed `i` one past the end. That `&tokens[i..]` out-of-range is what the parse fuzzer hit
3486        /// on `doas -r`; uniform command sampling never lands on this resolver often enough to find it.
3487        #[test]
3488        fn sudo_family_flag_walk_never_panics(
3489            head in prop::sample::select(vec!["sudo", "doas"]),
3490            args in prop::collection::vec(
3491                prop_oneof![
3492                    Just("-u".to_string()), Just("-r".to_string()), Just("-g".to_string()),
3493                    Just("-i".to_string()), Just("-EH".to_string()), Just("-uEH".to_string()),
3494                    Just("-uroot".to_string()), Just("--".to_string()), Just("-".to_string()),
3495                    Just("root".to_string()), Just("cat".to_string()), Just("./x".to_string()),
3496                    "-[a-zA-Z]{1,4}",
3497                ],
3498                0..6,
3499            ),
3500        ) {
3501            let parts: Vec<&str> =
3502                std::iter::once(head).chain(args.iter().map(String::as_str)).collect();
3503            let a = resolve(&toks(&parts)).is_some();
3504            let b = resolve(&toks(&parts)).is_some();
3505            prop_assert_eq!(a, b, "nondeterministic verdict for {:?}", parts);
3506        }
3507    }
3508
3509    /// The exact roster of commands classified by `[command.behavior]`. Pinning it turns a
3510    /// DROPPED or typo'd behavior block into a test failure: `TomlCommand` deliberately lacks
3511    /// `deny_unknown_fields` (it must tolerate `[[trusted]]`), so a mistyped top-level key
3512    /// (`behaviour = …`) is silently dropped and the command reverts to its PERMISSIVE legacy
3513    /// fallback — a fail-open the enumeration guards can't see (they `continue` on `None`). This
3514    /// roster is that missing tripwire, and the guards below derive their non-vacuity floors from
3515    /// it so the floors track reality. Update deliberately when porting a command. `echo` is a
3516    /// none-role printer; `dd`/`tar`/`sed` are hook commands; `grep` is a hook + pattern-then-read;
3517    /// the other 10 are the plain positional coreutils.
3518    const EXPECTED_BEHAVIOR_COMMANDS: &[&str] = &[
3519        "cat", "chflags", "chmod", "cp", "dd", "echo", "grep", "head", "ln", "mkdir", "mv", "perl", "rm", "rmdir", "sed", "tail", "tar",
3520        "touch", "wc",
3521    ];
3522
3523    /// The behavior roster is exactly `EXPECTED_BEHAVIOR_COMMANDS` — no command silently lost its
3524    /// `[command.behavior]` (fail-open) and none was added without being pinned. Red→green: delete
3525    /// one command's behavior block and this fails.
3526    #[test]
3527    fn behavior_command_roster_is_pinned() {
3528        use std::collections::BTreeSet;
3529        let actual: BTreeSet<&str> = crate::registry::toml_command_names()
3530            .into_iter()
3531            .filter(|n| crate::registry::command_behavior(n).is_some())
3532            .collect();
3533        let expected: BTreeSet<&str> = EXPECTED_BEHAVIOR_COMMANDS.iter().copied().collect();
3534        assert_eq!(
3535            actual, expected,
3536            "behavior-command roster drifted — a [command.behavior] block was added, dropped, or \
3537             typo'd. A dropped block silently reverts the command to its fail-open legacy path."
3538        );
3539    }
3540
3541    /// Hot-path probes for a `[command.behavior]` command, keyed on its declared operand role
3542    /// (the parallel of `probes` for the `Operands` enum). A `@` in a slot is the hot path.
3543    fn behavior_probes(cmd: &str, role: crate::registry::types::PositionalRole, hot: &str) -> Vec<Vec<String>> {
3544        use crate::registry::types::PositionalRole;
3545        let inv =
3546            |slots: &[&str]| -> Vec<String> { std::iter::once(cmd.to_string()).chain(slots.iter().map(|s| s.replace('@', hot))).collect() };
3547        match role {
3548            PositionalRole::None => vec![],
3549            PositionalRole::Read | PositionalRole::Write => vec![inv(&["@"])],
3550            PositionalRole::PatternThenRead => vec![inv(&["PATTERN", "@"])],
3551            PositionalRole::Transfer => vec![inv(&["@", "./safe"]), inv(&["./safe", "@"])],
3552        }
3553    }
3554
3555    /// Hot-path probes for a HOOK command, whose irregular operand syntax `behavior_probes`
3556    /// (positional roles) can't express — dd's `key=value`, tar's dashless mode bundles, sed's
3557    /// script. The `match` is EXHAUSTIVE, so a new `BehaviorHook` variant must declare its probe
3558    /// rows here or the build breaks — restoring the "new entry covered automatically" property the
3559    /// deleted `every_touched_path_operand_is_gated` had via `Operands::Custom`. `@` = the hot slot.
3560    fn hook_probes(hook: crate::registry::types::BehaviorHook, cmd: &str, hot: &str) -> Vec<Vec<String>> {
3561        use crate::registry::types::BehaviorHook;
3562        let inv =
3563            |slots: &[&str]| -> Vec<String> { std::iter::once(cmd.to_string()).chain(slots.iter().map(|s| s.replace('@', hot))).collect() };
3564        match hook {
3565            // grep is pattern-then-read → already probed by `behavior_probes`; no extra rows.
3566            BehaviorHook::Grep => vec![],
3567            BehaviorHook::Dd => vec![inv(&["if=@", "of=./safe"]), inv(&["if=./safe", "of=@"])],
3568            BehaviorHook::Tar => vec![inv(&["cf", "./s.tar", "@"]), inv(&["cf", "@", "./s"]), inv(&["tf", "@"])],
3569            BehaviorHook::Sed => vec![inv(&["s/x/y/", "@"]), inv(&["-i", "s/x/y/", "@"])],
3570            BehaviorHook::Perl => {
3571                vec![inv(&["-pe", "s/x/y/", "@"]), inv(&["-pi", "-e", "s/x/y/", "@"])]
3572            }
3573        }
3574    }
3575
3576    /// Every RECURSIVE transfer refuses a source above the workspace.
3577    ///
3578    /// The shield tests a name; a recursive source is a root standing for files nobody named, so
3579    /// it cannot be cleared. `cp ~/.ssh/id_rsa ./x` was refused all along and `cp -r ~ ./x` was
3580    /// not — same theft, one flag apart — because the claim that makes a read unclearable was
3581    /// written twice and only one copy learned about sweeps.
3582    ///
3583    /// Enumerated from the registry rather than listed, so a transfer command that declares
3584    /// `recursive_flags` later is covered the day it lands and does not need anyone to remember
3585    /// this test exists.
3586    #[test]
3587    fn every_recursive_transfer_refuses_a_source_above_the_workspace() {
3588        use crate::engine::bridge::project;
3589        use crate::verdict::Verdict;
3590
3591        let mut covered = 0usize;
3592        for name in crate::registry::toml_command_names() {
3593            let Some(b) = crate::registry::command_behavior(name) else { continue };
3594            let Some(t) = b.transfer.as_ref() else { continue };
3595            for flag in &t.recursive_flags {
3596                covered += 1;
3597                let hot = vec![name.to_string(), flag.clone(), "~".to_string(), "./dest".to_string()];
3598                let refs: Vec<&str> = hot.iter().map(String::as_str).collect();
3599                if let Some(p) = resolve(&toks(&refs)) {
3600                    assert_eq!(project(&p), Verdict::Denied, "{hot:?}: a recursive read of home is unclearable");
3601                }
3602                // Non-vacuity: the same command and flag over the WORKTREE must still work, or
3603                // this would pass on a build that simply refused every recursive copy.
3604                let ok = vec![name.to_string(), flag.clone(), "./src".to_string(), "./dest".to_string()];
3605                let refs: Vec<&str> = ok.iter().map(String::as_str).collect();
3606                if let Some(p) = resolve(&toks(&refs)) {
3607                    assert_ne!(project(&p), Verdict::Denied, "{ok:?}: a worktree recursive copy must still allow");
3608                }
3609            }
3610        }
3611        assert!(covered >= 3, "only {covered} recursive transfer flags swept — the registry lookup is wrong");
3612    }
3613
3614    /// Fail-closed, enumerated over the REGISTRY: every `[command.behavior]` command denies an
3615    /// operand on a hot path (a secret, home, system, or unpinnable locus), AND a write-role
3616    /// command denies a write into the worktree-trusted rung (`.git/config`). Restores and
3617    /// generalizes `every_touched_path_operand_is_gated` for the declarative path — a command
3618    /// ported off Rust is covered automatically. Red→green: make `resolve_behavior` skip
3619    /// `classify_locus` and this fails on the first probe.
3620    #[test]
3621    fn every_behavior_command_gates_hot_operands() {
3622        use crate::engine::bridge::project;
3623        use crate::registry::types::PositionalRole;
3624        use crate::verdict::Verdict;
3625
3626        let deny = |cmd: &[String], why: &str| {
3627            let refs: Vec<&str> = cmd.iter().map(String::as_str).collect();
3628            let profile = resolve(&toks(&refs)).expect("behavior command resolves");
3629            assert_eq!(project(&profile), Verdict::Denied, "{cmd:?}: {why}");
3630        };
3631
3632        let mut path_bearing = 0usize;
3633        let mut hook_bearing = 0usize;
3634        for name in crate::registry::toml_command_names() {
3635            let Some(b) = crate::registry::command_behavior(name) else { continue };
3636            if !matches!(b.positionals, PositionalRole::None) {
3637                path_bearing += 1;
3638            }
3639            if b.hook.is_some() {
3640                hook_bearing += 1;
3641            }
3642            for hot in HOT_PATHS {
3643                for cmd in behavior_probes(name, b.positionals, hot) {
3644                    deny(&cmd, "touched hot path not gated");
3645                }
3646                // Hook commands (dd/tar/sed) have irregular operand syntax, so they are swept by
3647                // their own probe table — restoring the enumerated coverage the deleted RESOLVERS
3648                // sweep gave them.
3649                if let Some(hook) = b.hook {
3650                    for cmd in hook_probes(hook, name, hot) {
3651                        deny(&cmd, "hook: touched hot path not gated");
3652                    }
3653                }
3654            }
3655            // Worktree-trusted is a WRITE boundary only: reading `.git/config` (cat/grep) is
3656            // legitimately allowed, but a write/destroy/relocate into it must deny. Probe the
3657            // write face — the destination slot for a transfer, the operand for a plain write.
3658            let inv =
3659                |slots: &[&str]| -> Vec<String> { std::iter::once(name.to_string()).chain(slots.iter().map(|s| s.to_string())).collect() };
3660            match b.positionals {
3661                PositionalRole::Write => deny(&inv(&[".git/config"]), "write into worktree-trusted not gated"),
3662                PositionalRole::Transfer => deny(&inv(&["./safe", ".git/config"]), "transfer dest into worktree-trusted not gated"),
3663                _ => {}
3664            }
3665        }
3666        // Non-vacuity: every path-bearing AND every hook command on the roster was reached and
3667        // probed. Derived from the roster (not a magic number) — none-role printers (echo) don't
3668        // positionally gate; hook commands (dd/tar/sed) gate via `hook_probes`.
3669        let count = |pred: fn(&crate::registry::types::BehaviorSpec) -> bool| {
3670            EXPECTED_BEHAVIOR_COMMANDS
3671                .iter()
3672                .filter(|n| crate::registry::command_behavior(n).is_some_and(pred))
3673                .count()
3674        };
3675        assert_eq!(
3676            path_bearing,
3677            count(|b| !matches!(b.positionals, PositionalRole::None)),
3678            "path-bearing behavior commands: saw {path_bearing}"
3679        );
3680        assert_eq!(hook_bearing, count(|b| b.hook.is_some()), "hook behavior commands: saw {hook_bearing}");
3681    }
3682
3683    /// Fail-closed on unknown flags, enumerated over the REGISTRY: every DECLARATIVE flag-walking
3684    /// behavior command (a Read/Write/Transfer role, hookless) worst-cases an unrecognized flag —
3685    /// the `walk_positionals` → `worst` path. Exempt: `grep` (its hook treats an unknown `--token`
3686    /// as a search pattern — keyed on `BehaviorHook::Grep` SPECIFICALLY, not `hook.is_some()`, so a
3687    /// future hook variant is not auto-exempted), and none-role commands (echo prints its args;
3688    /// dd/tar/sed parse their own irregular syntax — all covered by their own resolver tests, and
3689    /// none-role commands take no positional path operands, so an unknown flag can't unlock danger).
3690    #[test]
3691    fn every_hookless_behavior_command_worst_cases_unknown_flags() {
3692        use crate::engine::bridge::project;
3693        use crate::registry::types::{BehaviorHook, PositionalRole};
3694        use crate::verdict::Verdict;
3695
3696        let exempt = |b: &crate::registry::types::BehaviorSpec| {
3697            matches!(b.hook, Some(BehaviorHook::Grep)) || matches!(b.positionals, PositionalRole::None)
3698        };
3699        let mut checked = 0usize;
3700        for name in crate::registry::toml_command_names() {
3701            let Some(b) = crate::registry::command_behavior(name) else { continue };
3702            if exempt(b) {
3703                continue;
3704            }
3705            let profile = resolve(&toks(&[name, "--xyzzy-unknown-42", "./safe"])).expect("resolves");
3706            assert_eq!(project(&profile), Verdict::Denied, "{name}: unknown flag not worst-cased");
3707            checked += 1;
3708        }
3709        let expected = EXPECTED_BEHAVIOR_COMMANDS
3710            .iter()
3711            .filter(|n| crate::registry::command_behavior(n).is_some_and(|b| !exempt(b)))
3712            .count();
3713        assert_eq!(checked, expected, "declarative flag-walking behavior commands: saw {checked}");
3714    }
3715
3716    /// Fail-closed authoring guard: `path_flag_caps` (which gates a valued flag's path VALUE, e.g.
3717    /// `touch -r REF`) runs ONLY on the declarative Read/Write/Transfer path — the None arm (echo)
3718    /// and the hook arm (grep/dd/tar/sed) both return before it. So a `[command.behavior.flags]`
3719    /// path-role declared on a none-role or hook command would be SILENTLY UNGATED — a fail-open.
3720    /// Assert no command does that. Red→green: add `kind = "read"` to a hook command's flags.
3721    #[test]
3722    fn no_none_or_hook_command_declares_ungated_path_flags() {
3723        use crate::registry::types::PositionalRole;
3724        for name in crate::registry::toml_command_names() {
3725            let Some(b) = crate::registry::command_behavior(name) else { continue };
3726            if b.path_flags.is_empty() {
3727                continue;
3728            }
3729            assert!(
3730                b.hook.is_none() && !matches!(b.positionals, PositionalRole::None),
3731                "{name}: behavior path-flags are gated only on the Read/Write/Transfer path; on a \
3732                 none-role or hook command they would be silently ungated (fail-open)"
3733            );
3734        }
3735    }
3736}