Skip to main content

safe_chains/registry/
mod.rs

1mod build;
2pub(crate) mod custom;
3mod cwd_writes;
4pub mod folder_config;
5pub use custom::fuzz_load_config;
6pub(crate) use cwd_writes::cwd_writes;
7#[cfg(test)]
8pub(crate) use cwd_writes::declared_writers;
9mod dispatch;
10mod docs;
11mod flag_sets;
12pub(crate) use flag_sets::{command_flag_sets, command_valued_flags, fallback_flag_sets, handler_policy_flag_sets, sub_valued_flags};
13mod glob_flags;
14mod operands;
15mod passthrough_gate;
16pub(crate) mod policy;
17pub(crate) mod types;
18
19#[cfg(test)]
20use std::cell::RefCell;
21use std::collections::HashMap;
22use std::sync::LazyLock;
23
24use crate::parse::Token;
25use crate::verdict::Verdict;
26
27pub use build::{build_registry, load_toml};
28pub(crate) use custom::user_config_level;
29pub use dispatch::dispatch_spec;
30pub use types::{CommandSpec, OwnedPolicy};
31
32use types::DispatchKind;
33
34type HandlerFn = fn(&[Token]) -> Verdict;
35
36static CMD_HANDLERS: LazyLock<HashMap<&'static str, HandlerFn>> = LazyLock::new(crate::handlers::custom_cmd_handlers);
37
38static SUB_HANDLERS: LazyLock<HashMap<&'static str, HandlerFn>> = LazyLock::new(crate::handlers::custom_sub_handlers);
39
40static TOML_REGISTRY: LazyLock<HashMap<String, CommandSpec>> = LazyLock::new(|| include!(concat!(env!("OUT_DIR"), "/toml_includes.rs")));
41
42static CUSTOM_REGISTRY: LazyLock<HashMap<String, CommandSpec>> = LazyLock::new(|| {
43    let mut map = HashMap::new();
44    custom::apply_custom(&mut map);
45    map
46});
47
48pub fn toml_dispatch(tokens: &[Token]) -> Option<Verdict> {
49    let cmd = crate::engine::resolve::invocation_name(&tokens[0]);
50    TOML_REGISTRY.get(cmd).map(|spec| dispatch_spec(tokens, spec))
51}
52
53/// Looks up the command in the runtime custom registry (project-local
54/// `.safe-chains.toml`, then user-level `~/.config/safe-chains.toml`).
55/// A match here wins over the built-in hardcoded handlers, which is how
56/// an override of `gh` takes effect.
57pub fn custom_dispatch(tokens: &[Token]) -> Option<Verdict> {
58    let cmd = crate::engine::resolve::invocation_name(&tokens[0]);
59    #[cfg(test)]
60    if let Some(verdict) = dispatch_test_command(tokens, cmd) {
61        return Some(verdict);
62    }
63    CUSTOM_REGISTRY.get(cmd).map(|spec| dispatch_spec(tokens, spec))
64}
65
66#[cfg(test)]
67thread_local! {
68    static TEST_COMMANDS: RefCell<HashMap<String, CommandSpec>> = RefCell::new(HashMap::new());
69}
70
71#[cfg(test)]
72pub(crate) fn with_test_commands<R>(source: &str, body: impl FnOnce() -> R) -> R {
73    let specs = load_toml(source, "test").unwrap_or_else(|e| panic!("test commands: {e}"));
74    TEST_COMMANDS.with(|slot| {
75        let mut map = slot.borrow_mut();
76        map.clear();
77        for spec in specs {
78            map.insert(spec.name.clone(), spec);
79        }
80    });
81    let _guard = TestCommandGuard;
82    body()
83}
84
85#[cfg(test)]
86struct TestCommandGuard;
87
88#[cfg(test)]
89impl Drop for TestCommandGuard {
90    fn drop(&mut self) {
91        TEST_COMMANDS.with(|slot| slot.borrow_mut().clear());
92    }
93}
94
95#[cfg(test)]
96fn dispatch_test_command(tokens: &[Token], cmd: &str) -> Option<Verdict> {
97    TEST_COMMANDS.with(|slot| {
98        let map = slot.borrow();
99        map.get(cmd).map(|spec| dispatch_spec(tokens, spec))
100    })
101}
102
103/// The canonical command name `cmd` resolves to via the registry's alias map (`gcat` → `cat`,
104/// `glink` → `ln`). Returns `cmd` unchanged when it is already canonical or unknown, so callers
105/// can canonicalize unconditionally. This is what lets the engine's path-gate dispatch reach an
106/// aliased invocation: without it, `gcat /etc/shadow` misses every resolver and falls through to
107/// the (ungated) legacy classifier. Custom registry first (an override may rename), then TOML.
108pub fn canonical_name(cmd: &str) -> &str {
109    CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd)).map_or(cmd, |spec| spec.name.as_str())
110}
111
112/// The command's own declared path-argument gate (`[command.path_gate]`), if any — consulted by
113/// `pathgate::should_deny` when a command isn't in `pathgates.toml`, so a path-bearing flag gates
114/// from the command's own definition. `cmd` is already canonicalized by the caller.
115pub(crate) fn command_path_gate(cmd: &str) -> Option<&'static crate::pathgate::RoleSpec> {
116    CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd)).and_then(|spec| spec.path_gate.as_ref())
117}
118
119/// The command's declarative facet behavior (`[command.behavior]`), if any — the engine's
120/// non-legacy classification path and the ONLY thing `engine::resolve::resolve` consults (the
121/// hardcoded `RESOLVERS` table is gone; every facet-classified command declares behavior).
122/// `cmd` is already canonicalized by the caller.
123pub(crate) fn command_behavior(cmd: &str) -> Option<&'static crate::registry::types::BehaviorSpec> {
124    CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd)).and_then(|spec| spec.behavior.as_ref())
125}
126
127/// What `cmd`'s stdout can name, when that has been researched and declared (`[command.output]`).
128/// `None` — the default for every command — keeps a `$(cmd …)` unpinnable.
129pub(crate) fn command_output_locus(cmd: &str) -> Option<&'static crate::registry::types::OutputSpec> {
130    CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd)).and_then(|spec| spec.output.as_ref())
131}
132
133/// What the SUBCOMMAND in `words` prints, when that sub has declared it
134/// (`[command.sub.output]`), plus the arguments left after the sub path.
135///
136/// Separate from `command_output_locus` because for a multi-command tool the claim belongs to the
137/// sub, not the program: `git diff --name-only` prints worktree paths while `git log` prints prose.
138/// Expressing that command-level would mean an `invalidated_by` naming every OTHER subcommand — a
139/// denylist, which fails open the next time git grows one.
140///
141/// Descends nested subs to the deepest declaring node, the same walk `is_eval_safe_invocation`
142/// does, so a claim can sit on `<resource> <action>`. `None` when no sub on the path declares one,
143/// which leaves the caller to fall back to the command-level claim (and then to unpinnable).
144/// `canonical` must be the CANONICALIZED command name (`registry::canonical_name` of the token's
145/// command name), the same key `command_output_locus` is given. Keying on the raw first word
146/// instead silently dropped the claim for a path-spelled or aliased command: `/usr/bin/git diff
147/// --name-only` is a trusted spelling of a trusted tool, and it lost the claim while bare `git` kept
148/// it — one operation, two spellings, two answers.
149pub(crate) fn sub_output_locus<'a>(
150    canonical: &str,
151    args: &'a [String],
152) -> Option<(&'static crate::registry::types::OutputSpec, &'a [String])> {
153    let mut rest = args;
154    let spec = CUSTOM_REGISTRY.get(canonical).or_else(|| TOML_REGISTRY.get(canonical))?;
155    let mut kind = &spec.kind;
156    let mut found: Option<(&'static crate::registry::types::OutputSpec, &'a [String])> = None;
157    loop {
158        let subs = match kind {
159            DispatchKind::Branching { subs, .. } | DispatchKind::Custom { subs, .. } => subs,
160            _ => return found,
161        };
162        let Some((arg, tail)) = rest.split_first() else { return found };
163        let Some(sub) = subs.iter().find(|s| s.name == *arg) else {
164            return found;
165        };
166        rest = tail;
167        // Deepest declaration wins. A shallower one is NOT inherited by a child that declares
168        // nothing: the claim is researched per node, and letting `<parent>`'s answer stand in for
169        // an unresearched `<parent> <child>` would be asserting something nobody checked. Reset so
170        // descending past a declaring node into a silent one falls back to unpinnable.
171        found = sub.output.as_ref().map(|o| (o, rest));
172        kind = &sub.kind;
173    }
174}
175
176/// The facet archetypes (`archetypes.toml`) the subcommand `tokens` resolve to — the Phase-1
177/// `profile = …` classification plus a capability for every present escalating `[[command.sub.flag]]`
178/// (`git push` → `[vcs-sync]`; `git push --force` → `[vcs-sync, remote-destroy-irreversible]`). The
179/// engine emits a Capability per name and the level algebra takes the max. Descends `Branching`/
180/// `Custom` subs to the DEEPEST profile-bearing sub (nested `<resource> <action>`). `None` when no
181/// matched sub declares a profile.
182pub(crate) fn sub_archetypes(tokens: &[Token]) -> Option<Vec<&'static str>> {
183    let cmd = canonical_name(tokens.first()?.command_name());
184    let spec = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd))?;
185    let sub = walk_to_profiled_sub(&tokens[1..], &spec.kind)?;
186    let mut out = vec![sub.profile.as_deref()?];
187    for flag in &sub.flags {
188        if flag_escalates(tokens, flag) {
189            out.push(flag.classifies.as_str());
190        }
191    }
192    // The profile fixes the TIER; it must not also decide what is ADMISSIBLE. Without this the
193    // archetype path bypassed the flag allowlist entirely and any flag rode along on the base
194    // profile — `git rebase --exec 'rm -rf /'` classified as an ordinary rebase. `unclassified` is
195    // the sanctioned fail-closed marker: it resolves to no archetype, so the engine emits a worst
196    // capability and the invocation denies.
197    if presents_unlisted_flag(tokens, sub) {
198        out.push("unclassified");
199    }
200    Some(out)
201}
202
203/// Whether `tokens` carry a flag the profiled `sub` does not declare. Mirrors the legacy flag walk:
204/// `--long` matched whole or as `--long=value`, single-dash tokens split into clustered shorts, `--`
205/// ends the flag region. A sub that declares NO flags at all is treated as "not yet enumerated"
206/// rather than "nothing permitted", so this tightens only where a list exists — the global
207/// enforcement of the empty case is staged separately (see the backfill guard).
208fn presents_unlisted_flag(tokens: &[Token], sub: &types::SubSpec) -> bool {
209    // A flag declared as an escalating `[[command.sub.flag]]` IS declared — it just carries a
210    // capability rather than sitting on the plain allowlist. Omitting it here would deny the very
211    // invocations the escalation exists to classify (`npm ci --ignore-scripts`, whose whole point is
212    // that its PRESENCE is the safe form).
213    let known = |f: &str| {
214        sub.allowed_standalone.iter().any(|a| a == f)
215            || sub.allowed_valued.iter().any(|a| a == f)
216            || sub.flags.iter().any(|d| d.name == f)
217            // An output-path flag is declared too — it names the write destination the engine
218            // path-gates (`supabase db dump -f dump.sql`), so it is admissible by construction.
219            || sub.output_path_flags.iter().any(|a| a == f)
220            || sub.destination_flag.as_deref() == Some(f)
221    };
222    for (idx, t) in tokens.iter().enumerate().skip(1) {
223        let s = t.as_str();
224        if s == "--" {
225            break;
226        }
227        if !s.starts_with('-') || s == "-" || crate::cst::opaque::probe_is_value(tokens, idx, &sub.allowed_valued) {
228            continue;
229        }
230        let head = s.split_once('=').map_or(s, |(f, _)| f);
231        // An endpoint flag is admitted only when it names THIS machine — see the identical rule on
232        // the glob path in `glob_presents_unlisted_flag`.
233        if sub.loopback_valued.iter().any(|a| a == head) {
234            let value = match s.split_once('=') {
235                Some((_, v)) => Some(v),
236                None => tokens.get(idx + 1).map(Token::as_str),
237            };
238            if value.is_some_and(crate::netloc::is_loopback) {
239                continue;
240            }
241            return true;
242        }
243        if known(head) {
244            continue;
245        }
246        // An explicitly declared tolerance keeps the sub open for the shape it names — the
247        // established way to say "this surface is genuinely unbounded" (a cloud API's per-service
248        // options). Declared in the TOML, so it is reviewable, unlike the silent default it replaces.
249        use crate::policy::UnknownTolerance as U;
250        let tolerated = if s.starts_with("--") {
251            matches!(sub.allowed_unknown, U::Long | U::Both)
252        } else {
253            matches!(sub.allowed_unknown, U::Short | U::Both)
254        };
255        if tolerated {
256            continue;
257        }
258        // A single-dash multi-char token may be clustered shorts (`-abc` = `-a -b -c`).
259        if !s.starts_with("--") && s.len() > 2 && s[1..].chars().all(|c| known(&format!("-{c}"))) {
260            continue;
261        }
262        return true;
263    }
264    false
265}
266
267/// The facet archetypes a flat command's PRESENT top-level classifying flags (`[[command.flag]]`)
268/// resolve to — the command-level analog of `sub_archetypes` for a flag-triggered mode (`age -d` →
269/// `[decrypt-read]`, `sops --decrypt` → `[decrypt-read]`). `None` when the command declares none or
270/// none are present, so `engine::resolve` falls through to the command's ordinary resolution (the
271/// bare/encrypt form of a bimodal tool). Uses the same `flag_escalates` predicate as the sub flags.
272pub(crate) fn command_flag_archetypes(tokens: &[Token]) -> Option<Vec<&'static str>> {
273    let cmd = canonical_name(tokens.first()?.command_name());
274    let spec = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd))?;
275    let present: Vec<&'static str> = spec
276        .archetype_flags
277        .iter()
278        .filter(|f| flag_escalates(tokens, f) || (!f.when_absent && spec.archetype_flags.may_hide_a_flag(tokens)))
279        .map(|f| f.classifies.as_str())
280        .collect();
281    (!present.is_empty()).then_some(present)
282}
283
284/// Whether `flag` escalates given `tokens`. A bare flag (no `value_prefix`) escalates on presence; a
285/// value-matched flag escalates only when its VALUE starts with the prefix — the space form
286/// (`-c core.sshCommand=…`) or the glued form (`--flag=core.sshCommand=…`). Scans the whole line;
287/// an escalator counts wherever it sits.
288fn flag_escalates(tokens: &[Token], flag: &types::FlagProvenance) -> bool {
289    if flag.when_absent {
290        // A SAFETY flag whose ABSENCE is the escalation (`npm ci` without `--ignore-scripts`).
291        // It must be AFFIRMATIVELY set — `--ignore-scripts=false` / `--no-ignore-scripts` re-ENABLE
292        // scripts, so they escalate exactly like the flag being missing (a fail-open otherwise).
293        return !flag_is_affirmatively_set(tokens, &flag.name);
294    }
295    let Some(prefix) = flag.value_prefix.as_deref() else {
296        return flag_present(tokens, &flag.name);
297    };
298    // space form: `NAME VALUE`, VALUE starting with the prefix
299    tokens.windows(2).any(|w| w[0].as_str() == flag.name && w[1].as_str().starts_with(prefix))
300        // glued form: `NAME=VALUE`, VALUE starting with the prefix
301        || tokens.iter().any(|t| {
302            t.as_str()
303                .strip_prefix(flag.name.as_str())
304                .and_then(|r| r.strip_prefix('='))
305                .is_some_and(|v| v.starts_with(prefix))
306        })
307}
308
309/// Whether a boolean flag is AFFIRMATIVELY enabled: bare `--flag`, or `--flag=<truthy>`. A
310/// `--flag=false/0/no/off` or a `--no-flag` DISABLES it (returns false), as does absence. Last
311/// occurrence wins, the CLI convention. Used by the `when_absent` escalator so a re-enabling spelling
312/// can't masquerade as the safety flag being set.
313fn flag_is_affirmatively_set(tokens: &[Token], flag: &str) -> bool {
314    let neg = format!("--no-{}", flag.trim_start_matches('-'));
315    let mut set = false;
316    for t in tokens {
317        let s = t.as_str();
318        if s == flag {
319            set = true;
320        } else if let Some(v) = s.strip_prefix(flag).and_then(|r| r.strip_prefix('=')) {
321            set = !matches!(v.to_ascii_lowercase().as_str(), "false" | "0" | "no" | "off" | "");
322        } else if s == neg {
323            set = false;
324        }
325    }
326    set
327}
328
329fn walk_to_profiled_sub(remaining: &[Token], kind: &'static DispatchKind) -> Option<&'static types::SubSpec> {
330    let subs = match kind {
331        DispatchKind::Branching { subs, .. } | DispatchKind::Custom { subs, .. } => subs,
332        _ => return None,
333    };
334    let arg = remaining.first()?;
335    let sub = subs.iter().find(|s| s.name == arg.as_str())?;
336    // Deepest profiled match wins: a nested action's profile overrides its resource sub's.
337    walk_to_profiled_sub(&remaining[1..], &sub.kind).or_else(|| sub.profile.is_some().then_some(sub))
338}
339
340/// Like `walk_to_profiled_sub`, but also returns the tokens AFTER the matched sub's name — the
341/// operands the engine still needs to inspect (the destination positional, for `network_destination`).
342fn walk_to_profiled_sub_rest<'a>(remaining: &'a [Token], kind: &'static DispatchKind) -> Option<(&'static types::SubSpec, &'a [Token])> {
343    let subs = match kind {
344        DispatchKind::Branching { subs, .. } | DispatchKind::Custom { subs, .. } => subs,
345        _ => return None,
346    };
347    let arg = remaining.first()?;
348    let sub = subs.iter().find(|s| s.name == arg.as_str())?;
349    let rest = &remaining[1..];
350    walk_to_profiled_sub_rest(rest, &sub.kind).or_else(|| sub.profile.is_some().then_some((sub, rest)))
351}
352
353/// For a profiled sub declaring `network_destination`, the first positional after it — the send
354/// TARGET (`git push origin` → `origin`; bare `git push` → `None`, the configured default). `None`
355/// (outer) when the resolved sub does not classify a destination. The engine maps the token's
356/// PROVENANCE onto `locus.provenance` (`resolve::destination_provenance`).
357///
358/// "First non-`-` token" is a heuristic: a VALUED flag's value sitting before the target
359/// (`git push -o $VAR origin`) is read as the destination. That only ever misreads CONSERVATIVELY —
360/// a stray value classifies to `literal`/`opaque` (equal-or-stricter than the real `established`
361/// target), never looser — so it can over-deny a rare form but never under-approve.
362pub(crate) fn sub_destination_token(tokens: &[Token]) -> Option<Option<&str>> {
363    let cmd = canonical_name(tokens.first()?.command_name());
364    let spec = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd))?;
365    let (sub, rest) = walk_to_profiled_sub_rest(&tokens[1..], &spec.kind)?;
366    if !sub.network_destination {
367        return None;
368    }
369    // A destination-carrying flag (`git push --repo=<dest>`) OVERRIDES the positional — else a
370    // `--repo=ext::sh` RCE would slip past a benign positional (`origin`). Scanned across the whole
371    // line since the flag may sit anywhere.
372    if let Some(flag) = sub.destination_flag.as_deref()
373        && let Some(v) = flag_value(tokens, flag)
374    {
375        return Some(Some(v));
376    }
377    Some(rest.iter().map(Token::as_str).find(|t| !t.starts_with('-')))
378}
379
380/// A flag's value, but only from the FLAG REGION — tokens after a `--` terminator are positionals,
381/// not flags.
382///
383/// Used where finding a value makes the classification MORE PERMISSIVE, which is where a
384/// disagreement with the tool costs something. `presents_unlisted_flag` already stops at `--`, so
385/// without this the two layers disagreed: `put-item ... -- --endpoint-url http://localhost:8000`
386/// passed admission (the walk never saw the flag) AND localized (the value lookup did), classifying
387/// a call to the real service as a write to this machine.
388///
389/// The restrictive lookups deliberately do NOT use this. For `output_path_flags`, finding a path
390/// ADDS a path-gated write capability, so scanning past `--` errs toward more gating; switching
391/// them here would relax them. Each direction fails closed, which is why the asymmetry stands.
392fn flag_value_in_flag_region<'a>(tokens: &'a [Token], flag: &str) -> Option<&'a str> {
393    let end = tokens.iter().position(|t| t.as_str() == "--").unwrap_or(tokens.len());
394    flag_value(&tokens[..end], flag)
395}
396
397/// A flag's value, glued (`--repo=VALUE`) or space-separated (`--repo VALUE`); `None` if absent.
398/// Scans the WHOLE token list — see `flag_value_in_flag_region` for the `--`-aware variant and why
399/// only the permissive callers use it.
400fn flag_value<'a>(tokens: &'a [Token], flag: &str) -> Option<&'a str> {
401    if let Some(v) = tokens.iter().find_map(|t| t.as_str().strip_prefix(flag).and_then(|r| r.strip_prefix('='))) {
402        return Some(v);
403    }
404    tokens.windows(2).find(|w| w[0].as_str() == flag).map(|w| w[1].as_str())
405}
406
407/// For a profiled `data-export` sub declaring `output_path_flags`, the output-file PATH one of them
408/// carries — or `None` when the export streams to stdout (no output flag present). The engine adds a
409/// path-gated write capability at this path's locus, so a dump to `/etc/cron.d/job` gates on locus
410/// exactly as a redirect there would. `None` (outer) when the resolved sub declares none.
411///
412/// Values are matched in every spelling the flag admits: `--file=X`, `--file X`, `-f X`, `-f=X`, and
413/// the glued short form `-fX` — the last mustn't be a bypass (`-f/etc/cron.d/job` reaching a system
414/// path would otherwise drop the write cap and auto-approve). A bare `-f` with no value is a
415/// malformed invocation the tool itself rejects, so a `None` there is harmless.
416/// Whether this invocation's declared endpoint flag names THIS machine, so `resolve` should clear
417/// the facets the destination determines. `false` covers "no endpoint flag", "points elsewhere",
418/// and "the sub never opted in".
419///
420/// Returning `false` for a non-loopback value is what keeps this independent of the admission
421/// check: even if `presents_unlisted_flag` were bypassed, the remote facets would still be the ones
422/// that classify.
423pub(crate) fn sub_loopback_localizes(tokens: &[Token]) -> bool {
424    let Some(cmd) = tokens.first().map(|t| canonical_name(t.command_name())) else {
425        return false;
426    };
427    let Some(spec) = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd)) else {
428        return false;
429    };
430    let Some((sub, _rest)) = walk_to_profiled_sub_rest(&tokens[1..], &spec.kind) else {
431        return false;
432    };
433    sub.loopback_effect == types::LoopbackEffect::Localizes
434        && sub
435            .loopback_valued
436            .iter()
437            .filter_map(|f| flag_value_in_flag_region(tokens, f))
438            .any(crate::netloc::is_loopback)
439}
440
441pub(crate) fn sub_output_path_token(tokens: &[Token]) -> Option<&str> {
442    let cmd = canonical_name(tokens.first()?.command_name());
443    let spec = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd))?;
444    let (sub, _rest) = walk_to_profiled_sub_rest(&tokens[1..], &spec.kind)?;
445    sub.output_path_flags.iter().find_map(|f| output_flag_value(tokens, f))
446}
447
448/// `flag_value`, plus the glued short form `-fVALUE` (a two-char `-x` flag with the value fused on).
449/// Kept separate from `flag_value` because a glued short is only unambiguous for the single-letter
450/// output flags this classifies (`-f`, `-r`); the destination-flag path (`--repo`) never needs it.
451fn output_flag_value<'a>(tokens: &'a [Token], flag: &'a str) -> Option<&'a str> {
452    if let Some(v) = flag_value(tokens, flag) {
453        return Some(v);
454    }
455    if flag.len() == 2 && flag.starts_with('-') && !flag.starts_with("--") {
456        return tokens.iter().find_map(|t| t.as_str().strip_prefix(flag).filter(|r| !r.is_empty()));
457    }
458    None
459}
460
461/// Whether `flag` appears anywhere in `tokens` — bare (`--force`), glued (`--flag=v`), or, for a SHORT
462/// single-char flag (`-d`), hidden inside a short CLUSTER (`-da`, `-vd`) for tools that combine short
463/// options. A flag is an escalator wherever it sits, so this scans the whole line. The flag ALLOWLIST
464/// cluster-expands, so this must too — otherwise a cluster admits the command while the classifier
465/// misses the dangerous flag inside it (a classifier/allowlist disagreement; a live bypass for any
466/// clustering tool with a classifying short flag).
467fn flag_present(tokens: &[Token], flag: &str) -> bool {
468    // A single-dash flag can appear in a cluster, `-X` or a longest-match `-XY` (zip's `-qTTcmd`); `--long` cannot.
469    let letters = flag.strip_prefix('-').filter(|l| !l.is_empty() && !l.starts_with('-'));
470    tokens.iter().any(|t| {
471        let s = t.as_str();
472        if s == flag || s.strip_prefix(flag).is_some_and(|rest| rest.starts_with('=')) {
473            return true;
474        }
475        // Short cluster `-<letters>` (single dash, not `--`): scan only the boolean-letter run BEFORE
476        // any `=value`, so a glued value (`-o=decrypted`) can't spuriously match the flag letters.
477        matches!(letters, Some(l)
478            if s.len() > 1 && s.as_bytes()[0] == b'-' && s.as_bytes()[1] != b'-'
479            && s[1..].split('=').next().is_some_and(|run| run.contains(l)))
480    })
481}
482
483pub fn toml_command_names() -> Vec<&'static str> {
484    TOML_REGISTRY.keys().map(|k| k.as_str()).collect()
485}
486
487/// EVERY declared stdout claim in the registry, command-level and sub-level alike, each paired with
488/// the invocation scope that carries it (`"fd"`, `"git diff"`).
489///
490/// The structural guards over `[command.output]` enumerate this rather than `toml_command_names`,
491/// so a sub-scoped claim is held to the same bar as a command-scoped one. Enumerating only commands
492/// would have let every `[command.sub.output]` ship unprobed — the claim is transitive (it widens
493/// whatever consumes the substitution), so an unguarded one is the worst kind to add.
494#[cfg(test)]
495pub(crate) fn output_claims() -> Vec<(String, &'static crate::registry::types::OutputSpec)> {
496    fn walk(prefix: &str, kind: &'static DispatchKind, out: &mut Vec<(String, &'static crate::registry::types::OutputSpec)>) {
497        let subs = match kind {
498            DispatchKind::Branching { subs, .. } | DispatchKind::Custom { subs, .. } => subs,
499            _ => return,
500        };
501        for sub in subs {
502            let scope = format!("{prefix} {}", sub.name);
503            if let Some(o) = sub.output.as_ref() {
504                out.push((scope.clone(), o));
505            }
506            walk(&scope, &sub.kind, out);
507        }
508    }
509
510    let mut out = Vec::new();
511    for (name, spec) in TOML_REGISTRY.iter() {
512        if let Some(o) = spec.output.as_ref() {
513            out.push((name.clone(), o));
514        }
515        walk(name, &spec.kind, &mut out);
516    }
517    out
518}
519
520/// Every command's canonical name with its declared `examples_safe` / `examples_denied`
521/// — the corpus the engine's never-looser corpus gate runs against.
522#[cfg(test)]
523pub(crate) fn corpus_examples() -> Vec<(&'static str, &'static [String], &'static [String])> {
524    TOML_REGISTRY
525        .iter()
526        .map(|(name, spec)| (name.as_str(), spec.examples_safe.as_slice(), spec.examples_denied.as_slice()))
527        .collect()
528}
529
530/// Look up `cmd_name`'s TOML-declared subs (set via `[[command.sub]]`
531/// blocks alongside `handler = "..."`) and dispatch the one whose name
532/// matches `tokens[1]`. Returns `None` if no sub matched, so the
533/// handler can fall through to its fallback grammar (or deny).
534pub fn try_sub_dispatch(cmd_name: &str, tokens: &[Token]) -> Option<Verdict> {
535    let spec = handler_spec(cmd_name)?;
536    let DispatchKind::Custom { subs, .. } = &spec.kind else {
537        return None;
538    };
539    let arg = tokens.get(1)?.as_str();
540    let sub = subs.iter().find(|s| s.name == arg)?;
541    Some(dispatch::dispatch_sub(&tokens[1..], sub))
542}
543
544/// Apply `cmd_name`'s TOML-declared `[command.fallback]` grammar.
545/// Returns `None` if no fallback is declared.
546pub fn try_fallback_grammar(cmd_name: &str, tokens: &[Token]) -> Option<Verdict> {
547    let spec = handler_spec(cmd_name)?;
548    let DispatchKind::Custom { fallback, .. } = &spec.kind else {
549        return None;
550    };
551    let f = fallback.as_ref()?;
552    Some(dispatch::dispatch_fallback(tokens, f))
553}
554
555/// Dispatch `tokens` against `cmd_name`'s `[[command.matrix]]`
556/// blocks. Looks at `tokens[1]` (parent) and `tokens[2]` (action),
557/// finds the first matrix whose `parents` contains the parent and
558/// whose `actions` map contains the action, then validates
559/// `tokens[2..]` against the named policy (and a guard flag if the
560/// matrix entry declared one). Returns `None` if no matrix matched —
561/// the handler can then fall through to its remaining special cases
562/// or deny.
563pub fn try_matrix_dispatch(cmd_name: &str, tokens: &[Token]) -> Option<Verdict> {
564    let spec = handler_spec(cmd_name)?;
565    let DispatchKind::Custom { matrices, handler_policies, .. } = &spec.kind else {
566        return None;
567    };
568    let parent = tokens.get(1)?.as_str();
569    let action = tokens.get(2)?.as_str();
570    for matrix in matrices {
571        if !matrix.parents.iter().any(|p| p == parent) {
572            continue;
573        }
574        let Some(action_spec) = matrix.actions.get(action) else {
575            continue;
576        };
577        if let Some(long) = action_spec.guard.as_deref()
578            && !crate::parse::has_flag(&tokens[2..], action_spec.guard_short.as_deref(), Some(long))
579        {
580            return Some(Verdict::Denied);
581        }
582        let Some(policy) = handler_policies.get(&action_spec.policy_key) else {
583            return Some(Verdict::Denied);
584        };
585        return Some(dispatch::dispatch_matrix_action(&tokens[2..], policy, matrix.level));
586    }
587    None
588}
589
590/// Validate `tokens` against `cmd_name`'s named flag policy declared
591/// in a `[command.handler_policy.KEY]` block. Returns `false` if no
592/// such policy is declared or the tokens fail it. Used by handlers
593/// whose dispatch logic genuinely can't move to TOML (e.g. gh's
594/// sub × action matrix) but whose per-policy WordSets should live
595/// in TOML rather than as Rust `WordSet` constants.
596pub fn check_handler_policy(cmd_name: &str, key: &str, tokens: &[Token]) -> bool {
597    let Some(spec) = handler_spec(cmd_name) else {
598        return false;
599    };
600    let DispatchKind::Custom { handler_policies, .. } = &spec.kind else {
601        return false;
602    };
603    let Some(policy) = handler_policies.get(key) else {
604        return false;
605    };
606    dispatch::check_handler_policy_owned(tokens, policy)
607}
608
609fn handler_spec(cmd_name: &str) -> Option<&'static CommandSpec> {
610    CUSTOM_REGISTRY.get(cmd_name).or_else(|| TOML_REGISTRY.get(cmd_name))
611}
612
613/// Returns true iff this invocation is tagged eval-safe — meaning its
614/// stdout is documented shell-init code that can safely be substituted
615/// inside `eval "$(...)"`.
616///
617/// The walker descends through `DispatchKind::Branching` AND
618/// `DispatchKind::Custom` matching subs token-by-token (handler-based
619/// commands such as `gh` can have tagged TOML-declared subs even though
620/// the handler does the actual dispatch). The leaf is the deepest matched
621/// node (where no further sub matches). `eval_safe` is checked only at
622/// the leaf — ancestor tags do NOT propagate. After confirming the leaf
623/// is tagged, every `-`-prefixed token in the remaining tail must appear
624/// in `eval_safe_flags`; positionals are unrestricted.
625///
626/// Tagged nodes are vetted manually per-command (see SAMPLE.toml). This
627/// function does not validate that `tokens` is syntactically allowed —
628/// callers must have already passed it through the regular dispatcher.
629pub fn is_eval_safe_invocation(tokens: &[Token]) -> bool {
630    if tokens.is_empty() {
631        return false;
632    }
633    let cmd = crate::engine::resolve::invocation_name(&tokens[0]);
634    let Some(spec) = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd)) else {
635        return false;
636    };
637    is_eval_safe_for_spec(spec, tokens)
638}
639
640/// Spec-local variant used by tests so they can build a `CommandSpec`
641/// via `load_toml` and exercise the walker without touching the global
642/// `TOML_REGISTRY`.
643pub(crate) fn is_eval_safe_for_spec(spec: &CommandSpec, tokens: &[Token]) -> bool {
644    if tokens.is_empty() {
645        return false;
646    }
647    walk_to_eval_safe_leaf(
648        &tokens[1..],
649        &spec.kind,
650        spec.eval_safe,
651        &spec.eval_safe_flags,
652        &spec.eval_safe_flag_values,
653        &spec.eval_safe_required_flags,
654    )
655}
656
657fn walk_to_eval_safe_leaf(
658    remaining: &[Token],
659    kind: &DispatchKind,
660    eval_safe: bool,
661    eval_safe_flags: &[String],
662    eval_safe_flag_values: &std::collections::HashMap<String, Vec<String>>,
663    eval_safe_required_flags: &[String],
664) -> bool {
665    let subs_opt = match kind {
666        DispatchKind::Branching { subs, .. } | DispatchKind::Custom { subs, .. } => Some(subs),
667        _ => None,
668    };
669    if let Some(subs) = subs_opt
670        && let Some(arg) = remaining.first()
671        && let Some(sub) = subs.iter().find(|s| s.name == arg.as_str())
672    {
673        return walk_to_eval_safe_leaf(
674            &remaining[1..],
675            &sub.kind,
676            sub.eval_safe,
677            &sub.eval_safe_flags,
678            &sub.eval_safe_flag_values,
679            &sub.eval_safe_required_flags,
680        );
681    }
682    if !eval_safe {
683        return false;
684    }
685    let mut i = 0;
686    let mut seen_required = false;
687    while i < remaining.len() {
688        let s = remaining[i].as_str();
689        if !s.starts_with('-') {
690            i += 1;
691            continue;
692        }
693        let (bare, eq_value) = match s.split_once('=') {
694            Some((k, v)) => (k, Some(v)),
695            None => (s, None),
696        };
697        if !eval_safe_flags.iter().any(|f| f == bare) {
698            return false;
699        }
700        if eval_safe_required_flags.iter().any(|f| f == bare) {
701            seen_required = true;
702        }
703        if let Some(allowed) = eval_safe_flag_values.get(bare) {
704            // Valued flag declared in eval_safe_flag_values. The value
705            // arrives either as `--flag=VALUE` (eq_value is Some) or as
706            // the next token (`--flag VALUE`); either way the walker
707            // consumes it because a flag in eval_safe_flag_values is
708            // structurally valued.
709            //
710            // `allowed` empty = explicit-unrestricted: contributor
711            // vetted that any bare-literal value preserves shell-init
712            // output. Non-empty = value must appear in the allowlist.
713            let value: &str = if let Some(v) = eq_value {
714                v
715            } else if let Some(next) = remaining.get(i + 1) {
716                let v = next.as_str();
717                i += 1;
718                v
719            } else {
720                return false;
721            };
722            // Empty value is denied even under the explicit-
723            // unrestricted (`= []`) posture: `--flag=` and an empty
724            // following token never represent a meaningful tool
725            // argument. The bare-literal alphabet check is per-char
726            // and vacuously passes empty strings, so the walker
727            // has to reject explicitly.
728            if value.is_empty() {
729                return false;
730            }
731            if !allowed.is_empty() && !allowed.iter().any(|av| av == value) {
732                return false;
733            }
734        }
735        i += 1;
736    }
737    if !eval_safe_required_flags.is_empty() && !seen_required {
738        return false;
739    }
740    true
741}
742
743pub fn toml_command_docs() -> Vec<crate::docs::CommandDoc> {
744    TOML_REGISTRY
745        .iter()
746        .filter(|(key, spec)| *key == &spec.name)
747        .map(|(_, spec)| spec.to_command_doc())
748        .collect()
749}
750
751#[cfg(test)]
752mod arity_tests;
753#[cfg(test)]
754mod gate_consistency;
755#[cfg(test)]
756mod glob_scope_tests;
757#[cfg(test)]
758mod guard_values;
759#[cfg(test)]
760mod overlap_tests;
761#[cfg(test)]
762mod tests;