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