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