Skip to main content

safe_chains/registry/
types.rs

1use serde::Deserialize;
2
3use crate::verdict::SafetyLevel;
4
5#[derive(Debug, Deserialize)]
6pub(super) struct TomlFile {
7    // Defaulted so a user config that contains only `[[trusted]]` (the repo-pin
8    // list, parsed separately) is valid. Unknown tables like `[[trusted]]` are
9    // ignored here.
10    #[serde(default)]
11    pub command: Vec<TomlCommand>,
12}
13
14#[derive(Debug, Deserialize)]
15pub(super) struct TomlCommand {
16    pub name: String,
17    #[serde(default)]
18    pub description: Option<String>,
19    #[serde(default)]
20    pub candidate: Option<bool>,
21    #[serde(default)]
22    pub aliases: Vec<String>,
23    #[serde(default)]
24    pub url: String,
25    #[serde(default)]
26    pub level: Option<TomlLevel>,
27    #[serde(default)]
28    pub bare: Option<bool>,
29    #[serde(default)]
30    pub max_positional: Option<usize>,
31    /// This command PUTS ITS `NAME=VALUE` POSITIONALS INTO THE ENVIRONMENT (`export`, `declare -x`).
32    /// Each one is classified through `envvars.toml`, exactly as the `VAR=value cmd` prefix form is,
33    /// so the two spellings of one capability cannot disagree.
34    #[serde(default)]
35    pub env_assignment_positionals: Option<bool>,
36    /// Removed in favor of `tolerate_unknown_short` / `tolerate_unknown_long`.
37    /// Build panics if any TOML still sets this — see SAMPLE.toml for the
38    /// migration guidance. Kept on the deserializer struct so the panic
39    /// message can name the offending command instead of a serde error.
40    #[serde(default)]
41    pub positional_style: Option<bool>,
42    #[serde(default)]
43    pub tolerate_unknown_short: Option<bool>,
44    #[serde(default)]
45    pub tolerate_unknown_long: Option<bool>,
46    #[serde(default)]
47    pub numeric_dash: Option<bool>,
48    #[serde(default)]
49    pub standalone: Vec<String>,
50    #[serde(default)]
51    pub valued: Vec<String>,
52    #[serde(default)]
53    pub bare_flags: Vec<String>,
54    #[serde(default)]
55    pub sub: Vec<TomlSub>,
56    #[serde(default)]
57    pub handler: Option<String>,
58    #[serde(default)]
59    pub doc_body: Option<String>,
60    #[serde(default)]
61    pub require_any: Vec<String>,
62    #[serde(default)]
63    pub first_arg: Vec<String>,
64    /// Flags a `first_arg` GLOB family accepts. The glob admits an invocation on its first
65    /// positional alone, so without these it never examines the flags at all and
66    /// `--endpoint-url http://evil.com` rides along on a read. Empty = family not yet researched
67    /// (permissive, grandfathered — see `no_new_unresearched_first_arg_family`).
68    #[serde(default)]
69    pub first_arg_standalone: Vec<String>,
70    #[serde(default)]
71    pub first_arg_valued: Vec<String>,
72    /// Flags admitted only when their VALUE names this machine (`--endpoint-url
73    /// http://localhost:8000`). Same arity as `first_arg_valued`; the value is classified by
74    /// `netloc::is_loopback`, and anything not positively recognized as loopback denies.
75    #[serde(default)]
76    pub first_arg_loopback_valued: Vec<String>,
77    #[serde(default)]
78    pub credential_first_arg: Vec<String>,
79    /// Top-level classifying flags (`[[command.flag]]`): a flag whose PRESENCE classifies the WHOLE
80    /// invocation as an archetype — the flat-command analog of `[[command.sub.flag]]`. For a bimodal
81    /// tool where a mode flag flips the operation: `age -d` / `sops --decrypt` reveal plaintext to the
82    /// model (`decrypt-read`), while the bare/encrypt form is an ordinary local write. Resolved by
83    /// `engine::resolve` via `registry::command_flag_archetypes`; each flag's `classifies` must name a
84    /// known archetype and carry `fact`/`source` provenance (the `assert_command_flag_provenance` guard).
85    #[serde(default)]
86    pub flag: Vec<TomlSubFlag>,
87    #[serde(default)]
88    pub wrapper: Option<TomlWrapper>,
89    #[serde(default)]
90    pub write_flags: Vec<String>,
91    /// Path-argument gate co-located with the command (`[command.path_gate]`): the read/write
92    /// role of each path-bearing flag value and of bare positionals. Consulted by
93    /// `pathgate::should_deny` so a `--output`/`-i` path can't ship ungated. Same shape as
94    /// `pathgates.toml`'s `[roles.X]`.
95    #[serde(default)]
96    pub path_gate: Option<crate::pathgate::RoleSpec>,
97    #[serde(default)]
98    pub researched_version: Option<String>,
99    /// Sample invocations that double as test fixtures.
100    /// `examples_safe` must validate as Allowed; `examples_denied` must validate as Denied.
101    /// Use these to exercise aliases and canonical forms (e.g. `mise use` and `mise u`)
102    /// so drift between the TOML and runtime dispatch fails the test suite.
103    #[serde(default)]
104    pub examples_safe: Vec<String>,
105    #[serde(default)]
106    pub examples_denied: Vec<String>,
107    /// Marks this command's leaf invocation as safe inside
108    /// `eval "$(CMD ...)"`. Set on flat commands whose stdout is documented
109    /// shell-init code (e.g. `ssh-agent`). The leaf is the deepest matched
110    /// dispatch node — tagging here does NOT propagate to subs; each sub
111    /// must be tagged independently. Unset = not eval-safe (the default).
112    #[serde(default)]
113    pub eval_safe: Option<bool>,
114    /// Flag allowlist that extends `eval_safe = true` — these `-`-prefixed
115    /// tokens are also permitted inside the substitution. Default empty,
116    /// meaning only the bare form plus positionals are eval-safe.
117    /// Build panics if this is set without `eval_safe = true`.
118    #[serde(default)]
119    pub eval_safe_flags: Vec<String>,
120    /// Per-valued-flag value allowlist. Maps each valued flag (which
121    /// MUST also appear in `eval_safe_flags`) to the set of values
122    /// permitted in eval substitutions. Use for tools where the flag's
123    /// value determines stdout shape (`aws --format env` vs
124    /// `--format json`). Default empty = no value restriction beyond
125    /// the bare-literal alphabet.
126    #[serde(default)]
127    pub eval_safe_flag_values: std::collections::HashMap<String, Vec<String>>,
128    /// Flags where AT LEAST ONE must appear in the eval substitution.
129    /// Use for tools whose bare invocation isn't shell-init code:
130    /// `fzf` is interactive without `--bash|--zsh|--fish|--nushell`.
131    /// Every entry must also appear in `eval_safe_flags`. Default
132    /// empty = no required flags (bare invocation is fine).
133    #[serde(default)]
134    pub eval_safe_required_flags: Vec<String>,
135    /// Shortcut: every invocation of this command is denied. Used in custom
136    /// TOMLs to lock down a built-in (e.g. `name = "gh", deny = true` in
137    /// `.safe-chains.toml` denies every gh form for that project).
138    #[serde(default)]
139    pub deny: Option<bool>,
140    /// Alternate grammar engaged when standard sub-dispatch finds no match.
141    /// Only meaningful for handler-using commands (e.g. tilt's Ruby template
142    /// engine fallback when no Kubernetes tilt sub matches). The handler is
143    /// responsible for invoking it via `registry::try_fallback_grammar()`.
144    #[serde(default)]
145    pub fallback: Option<TomlFallback>,
146    /// Named flag policies the handler references by string key. Used when
147    /// a handler's dispatch logic genuinely can't move to TOML (e.g. gh's
148    /// sub × action matrix) but the per-policy WordSets are still data that
149    /// should live in TOML. The handler reads them via
150    /// `registry::check_handler_policy(cmd, key, tokens)`.
151    #[serde(default)]
152    pub handler_policy: std::collections::HashMap<String, TomlHandlerPolicy>,
153    /// Parent × action → policy matrices. One block declares: "for
154    /// these parent subcommand names, each of these action verbs maps
155    /// to a named `handler_policy` and validates at this safety level."
156    /// Lets handlers express their dispatch tables as data instead of
157    /// `match` arms. Walked by `registry::try_matrix_dispatch()`.
158    #[serde(default)]
159    pub matrix: Vec<TomlMatrix>,
160    /// A `verb-chain` grammar (`mlr`): a strict main-flag region followed by a
161    /// `then`-chain of allowlisted verbs. Fully declarative — no handler needed.
162    #[serde(default)]
163    pub verb_chain: Option<TomlVerbChain>,
164    /// Declarative facet behavior (`[command.behavior]`) — the non-legacy classification
165    /// path. When present, the engine resolves this command by building a `Profile` from the
166    /// declared operation + operand-role + flags (see `engine::resolve::resolve_behavior`),
167    /// retiring a hardcoded `RESOLVERS` entry. The legacy `level` remains only as the
168    /// fallback the engine already overrides.
169    #[serde(default)]
170    pub behavior: Option<TomlBehavior>,
171    /// What this command's STDOUT can name (`[command.output]`) — the axis that decides whether a
172    /// `$(…)` around it yields a bounded path or an unknowable one. Absent (the default) means
173    /// unpinnable: the substitution worst-cases exactly as it always has. See
174    /// docs/design/behavioral-taxonomy-substitution-locus.md.
175    #[serde(default)]
176    pub output: Option<TomlOutput>,
177}
178
179/// `[command.output]` — a researched claim about where this command's stdout can POINT. It is a
180/// separate axis from every facet: how safe a command is to RUN says nothing about what its output
181/// names (`echo` is inert and `$(echo /etc/shadow)` names a credential file), so this is declared
182/// per command or not at all.
183#[derive(Debug, Deserialize)]
184#[serde(deny_unknown_fields)]
185pub(super) struct TomlOutput {
186    /// `operands` — output names paths beneath the command's own path operands (`fd`, `git
187    /// ls-files`); `cwd` — output names the working directory (`pwd`).
188    pub locus_from: String,
189    /// Flags under which the claim does NOT hold, because they change what stdout CONTAINS.
190    /// `fd -x cat {}` prints file contents rather than paths, and `fd -l` prints `ls -l` rows —
191    /// neither is a path any more, so the locus rule cannot describe them. Any of these present
192    /// makes the substitution unpinnable again.
193    #[serde(default)]
194    pub invalidated_by: Vec<String>,
195    /// Value-taking flags, so their VALUE is not mistaken for an operand (`head -n 5` takes no
196    /// file). Carried here rather than read off the legacy top-level `valued` for the same reason
197    /// `[command.behavior]` carries its own grammar: this claim is researched as a unit, and a
198    /// silently-shared list would let an unrelated edit change what counts as a root.
199    #[serde(default)]
200    pub valued: Vec<String>,
201    /// Flags of which at least ONE must be present, or the claim does not hold. The inverse of
202    /// `invalidated_by`, and needed by any command whose default output is not paths at all:
203    /// `git diff` prints a PATCH, and only `--name-only` turns it into a list of paths. Empty
204    /// (the normal case) means the claim holds for the bare invocation.
205    #[serde(default)]
206    pub requires: Vec<String>,
207}
208
209/// A command's declarative facet behavior (`[command.behavior]`). Field values that name a
210/// facet term are the kebab strings from `engine::facet` (`operation = "observe"`); the build
211/// maps them via `FacetTerm::from_term` and PANICS (naming the command) on an unknown term, so
212/// a typo can't silently mis-classify. The behavior carries its OWN flag grammar
213/// (`standalone`/`valued`), independent of the legacy top-level `standalone` — `rm`'s legacy
214/// flag set is restricted to `--help`/`--version` (so the legacy fallback can't fail-open on
215/// `rm -rf`), while its behavior grammar is the full destructive set.
216#[derive(Debug, Deserialize)]
217#[serde(deny_unknown_fields)]
218pub(super) struct TomlBehavior {
219    /// The act each operand capability performs — an `Operation` term
220    /// (`observe`/`create`/`mutate`/`destroy`/…).
221    pub operation: String,
222    /// How bare positionals are touched: `none` | `read` | `write` | `pattern-then-read` |
223    /// `transfer` (the closed set the `Operands` enum encodes).
224    pub positionals: String,
225    /// Scale model: `single` (every read is one item — cat/head) or `breadth`
226    /// (count/glob/recursion widen it — rm/mkdir). Defaults to `single`.
227    #[serde(default)]
228    pub scale: Option<String>,
229    /// Boolean flags this command accepts (behavior's own grammar). Single-dash single-char
230    /// tokens (`-r`) cluster; `--long` tokens are matched whole.
231    #[serde(default)]
232    pub standalone: Vec<String>,
233    /// Value-taking flags (consume the next token or a glued `=value`).
234    #[serde(default)]
235    pub valued: Vec<String>,
236    /// Accept the obsolete `-NUM` count shorthand (`head -20`).
237    #[serde(default)]
238    pub numeric_shorthand: Option<bool>,
239    /// Per-flag facet deltas — a flag whose presence widens scale (`"-r" = { scale =
240    /// "unbounded" }`), consumes a path value, or supplies a pattern.
241    #[serde(default)]
242    pub flags: std::collections::HashMap<String, TomlBehaviorFlag>,
243    /// Thin custom hook for the irreducible token logic a declaration can't express
244    /// (`grep`'s pattern-vs-file disambiguation). Composes: it returns the classified operand
245    /// set; the facets + level projection stay declarative. Absent = pure declarative.
246    #[serde(default)]
247    pub hook: Option<String>,
248    /// Transfer semantics (`[command.behavior.transfer]`), REQUIRED when `positionals =
249    /// "transfer"` — the source-operand operation and the clobber/recursion flag sets that a
250    /// `cp`/`mv`/`ln`-shaped command differs on.
251    #[serde(default)]
252    pub transfer: Option<TomlTransfer>,
253}
254
255/// The differing knobs of a transfer command (`cp`/`mv`/`ln`): every source operand is read at
256/// its own locus and the destination is a create/overwrite at its locus, but the source
257/// *operation* and the clobber/recursion flags differ per command.
258#[derive(Debug, Deserialize)]
259#[serde(deny_unknown_fields)]
260pub(super) struct TomlTransfer {
261    /// The source-operand operation: `observe` (cp/ln read the source into the dest/link) or
262    /// `relocate` (mv removes the source from its old location).
263    pub source: String,
264    /// True when the destination operand is REBOUND rather than written through: `ln` points the
265    /// destination name at something else. Defaults false (cp/mv write bytes at the destination).
266    #[serde(default)]
267    pub rebinds_destination: bool,
268    /// Flags whose PRESENCE means the destination will not be overwritten (`cp`/`mv`: `-n`,
269    /// `--no-clobber`). Mutually exclusive with `clobber_flags`.
270    #[serde(default)]
271    pub no_clobber_flags: Vec<String>,
272    /// Flags whose PRESENCE means the destination WILL be overwritten, the default being
273    /// no-clobber (`ln`: `-f`, `--force`). Mutually exclusive with `no_clobber_flags`.
274    #[serde(default)]
275    pub clobber_flags: Vec<String>,
276    /// Flags whose presence widens the scale to unbounded (`cp`: `-r`/`-R`/`-a`).
277    #[serde(default)]
278    pub recursive_flags: Vec<String>,
279}
280
281/// One flag's contribution to a `[command.behavior]` profile: a scale bump when present, and/or
282/// a path role on the flag's VALUE (a valued flag whose value is a path safe-chains must gate,
283/// e.g. `touch -r REF` reads REF's timestamp — folds the `[command.path_gate]` idea into behavior).
284#[derive(Debug, Deserialize)]
285#[serde(deny_unknown_fields)]
286pub(super) struct TomlBehaviorFlag {
287    /// Scale bump when present (`"-r" = { scale = "unbounded" }`).
288    #[serde(default)]
289    pub scale: Option<String>,
290    /// The flag's VALUE is a path with this role: `read` (gated by its read locus) or `write`
291    /// (gated by its write locus). The flag must be a valued flag (in `valued`).
292    #[serde(default)]
293    pub kind: Option<String>,
294}
295
296/// A `verb-chain` command grammar: `CMD [main-flags…] verb [args…] then verb [args…] …`
297/// (`mlr`). The main-flag region is a STRICT allowlist (an unlisted flag denies — so a
298/// mutating flag like mlr's `-I`/`--in-place`, omitted, is caught by omission); the verb
299/// region is a `then`-chain where every verb NAME must be on the `verbs` allowlist (verb
300/// ARGS are open-ended and not inspected — a pure verb has no shell/file escape).
301#[derive(Debug, Deserialize)]
302#[serde(deny_unknown_fields)]
303pub(super) struct TomlVerbChain {
304    #[serde(default)]
305    pub level: Option<TomlLevel>,
306    /// The chain separator keyword (mlr: `then`). Defaults to `then`.
307    #[serde(default)]
308    pub separator: Option<String>,
309    /// Boolean main flags (no value). SAFETY: every value-TAKING main flag must go in
310    /// `main_valued` instead, or the walk mistakes its value for the verb boundary and a
311    /// later mutating flag slips past in verb-land.
312    #[serde(default)]
313    pub main_standalone: Vec<String>,
314    /// Value-taking main flags (`--from FILE`, `--ifs ,`), each consuming the next token.
315    #[serde(default)]
316    pub main_valued: Vec<String>,
317    /// Variadic main flags (mlr `--mfrom A B …`) that consume tokens until a `--` terminator.
318    #[serde(default)]
319    pub main_variadic: Vec<String>,
320    /// The allowlist of verb names permitted in every `then`-segment.
321    #[serde(default)]
322    pub verbs: Vec<String>,
323}
324
325#[derive(Debug, Deserialize)]
326#[serde(deny_unknown_fields)]
327pub(super) struct TomlMatrix {
328    pub parents: Vec<String>,
329    pub level: TomlLevel,
330    pub actions: std::collections::HashMap<String, TomlMatrixAction>,
331}
332
333#[derive(Debug, Deserialize)]
334#[serde(untagged)]
335pub(super) enum TomlMatrixAction {
336    /// Shorthand: `list = "policy_name"` — references handler_policy by
337    /// name; no guard required.
338    Policy(String),
339    /// Detailed form: `download = { policy = "release_download", guard
340    /// = "--output", guard_short = "-O" }`. The guard flag must be
341    /// present in the action's args for the dispatch to succeed.
342    Detailed(TomlMatrixActionDetailed),
343}
344
345#[derive(Debug, Deserialize)]
346#[serde(deny_unknown_fields)]
347pub(super) struct TomlMatrixActionDetailed {
348    pub policy: String,
349    #[serde(default)]
350    pub guard: Option<String>,
351    #[serde(default)]
352    pub guard_short: Option<String>,
353}
354
355#[derive(Debug, Deserialize)]
356pub(super) struct TomlHandlerPolicy {
357    #[serde(default)]
358    pub standalone: Vec<String>,
359    #[serde(default)]
360    pub valued: Vec<String>,
361    #[serde(default)]
362    pub bare: Option<bool>,
363    #[serde(default)]
364    pub max_positional: Option<usize>,
365    #[serde(default)]
366    pub tolerate_unknown_short: Option<bool>,
367    #[serde(default)]
368    pub tolerate_unknown_long: Option<bool>,
369    #[serde(default)]
370    pub numeric_dash: Option<bool>,
371}
372
373#[derive(Debug, Deserialize)]
374pub(super) struct TomlFallback {
375    #[serde(default)]
376    pub level: Option<TomlLevel>,
377    #[serde(default)]
378    pub bare: Option<bool>,
379    #[serde(default)]
380    pub max_positional: Option<usize>,
381    #[serde(default)]
382    pub standalone: Vec<String>,
383    #[serde(default)]
384    pub valued: Vec<String>,
385    #[serde(default)]
386    pub tolerate_unknown_short: Option<bool>,
387    #[serde(default)]
388    pub tolerate_unknown_long: Option<bool>,
389    #[serde(default)]
390    pub numeric_dash: Option<bool>,
391    /// Named predicate the handler applies to the first positional arg.
392    /// Currently the only value is `"path"` — accepts a token shaped like
393    /// a file path (contains `/`, `.`, or is `-` for stdin). Adding new
394    /// shapes is a one-line `PositionalShape` enum addition plus a match
395    /// arm in `policy::positional_matches_shape()`.
396    #[serde(default)]
397    pub positional_shape: Option<String>,
398    /// `"file"` gates the first positional as an EXECUTOR through the execution-origin
399    /// engine (worktree-local code allows, foreign denies) rather than the flat `level`.
400    /// For interpreters run as `python3 ./s.py` / `ruby s.rb`. (`"project"` exists for subs
401    /// but is not used on fallbacks.)
402    #[serde(default)]
403    pub executor: Option<String>,
404    #[serde(default)]
405    pub executor_redirect_flag: Option<String>,
406}
407
408#[derive(Debug, Deserialize)]
409pub(super) struct TomlWrapper {
410    #[serde(default)]
411    pub standalone: Vec<String>,
412    #[serde(default)]
413    pub valued: Vec<String>,
414    #[serde(default)]
415    pub positional_skip: Option<usize>,
416    #[serde(default)]
417    pub separator: Option<String>,
418    #[serde(default)]
419    pub bare_ok: Option<bool>,
420    /// Accept one leading rustup toolchain selector (`cargo +nightly build`). A `+name` token is
421    /// not a flag, so `standalone` cannot express it, and the name is variable, so it cannot be
422    /// enumerated. Only meaningful on a structured (sub-dispatching) command.
423    #[serde(default)]
424    pub toolchain_selector: Option<bool>,
425}
426
427/// One `[[command.sub.flag]]`: a flag that escalates its sub's classification when present.
428#[derive(Debug, Deserialize)]
429pub(super) struct TomlSubFlag {
430    pub name: String,
431    /// The archetype (`archetypes.toml`) this flag's presence ADDS to the profile — or
432    /// `"unclassified"` to worst-case (fail-closed) a flag whose effect we can't yet name.
433    pub classifies: String,
434    /// Optional value-match: escalate only when the flag's VALUE starts with this prefix (space
435    /// form `-c core.sshCommand=…` or glued `--flag=core.sshCommand=…`). Absent = escalate on the
436    /// flag's mere PRESENCE (a bare flag like `--force`). This is what lets ONE valued flag be
437    /// benign for most values and dangerous for a specific key (`git -c core.sshCommand=` = exec).
438    #[serde(default)]
439    pub value_prefix: Option<String>,
440    /// `true` INVERTS the trigger: escalate when the flag is ABSENT, not present. For a SAFETY flag
441    /// whose absence is the risk — `npm ci` runs lifecycle scripts UNLESS `--ignore-scripts` is
442    /// given, so its base profile (local-install-pinned) escalates to supply-chain-build when
443    /// `--ignore-scripts` is missing. Mutually exclusive with `value_prefix`.
444    #[serde(default)]
445    pub when_absent: Option<bool>,
446    #[serde(default)]
447    pub fact: Option<String>,
448    #[serde(default)]
449    pub source: Option<String>,
450    #[serde(default)]
451    pub judgment: Option<String>,
452}
453
454#[derive(Debug, Deserialize)]
455pub(super) struct TomlSub {
456    pub name: String,
457    #[serde(default)]
458    pub candidate: Option<bool>,
459    /// A facet archetype name (`archetypes.toml`) — the Phase-1 successor to `candidate = true`:
460    /// instead of hand-marking the sub above the line, it declares which recurring capability
461    /// profile it is, and the engine DERIVES the verdict by projecting that profile through the
462    /// levels. See `docs/design/behavioral-taxonomy-archetypes.md`.
463    #[serde(default)]
464    pub profile: Option<String>,
465    /// Per-item research provenance for the classification (required when `profile` is set — the
466    /// `every_profiled_sub_has_provenance` guard). Three layers so a future researcher can act on
467    /// each precisely: `fact` = what the upstream tool DOCUMENTS (re-check `source` if it moves),
468    /// the `profile` itself = our inference (which archetype it maps to), `judgment` = our stance
469    /// where the source doesn't decide it (a policy call they may revisit). `source` cites the
470    /// upstream doc/section. See `docs/design/behavioral-taxonomy-archetypes.md` §3.
471    #[serde(default)]
472    pub fact: Option<String>,
473    #[serde(default)]
474    pub source: Option<String>,
475    #[serde(default)]
476    pub judgment: Option<String>,
477    #[serde(default)]
478    pub aliases: Vec<String>,
479    #[serde(default)]
480    pub level: Option<TomlLevel>,
481    #[serde(default)]
482    pub bare: Option<bool>,
483    #[serde(default)]
484    pub max_positional: Option<usize>,
485    /// Removed; see TomlCommand::positional_style.
486    #[serde(default)]
487    pub positional_style: Option<bool>,
488    #[serde(default)]
489    pub tolerate_unknown_short: Option<bool>,
490    #[serde(default)]
491    pub tolerate_unknown_long: Option<bool>,
492    #[serde(default)]
493    pub numeric_dash: Option<bool>,
494    #[serde(default)]
495    pub standalone: Vec<String>,
496    #[serde(default)]
497    pub valued: Vec<String>,
498    #[serde(default)]
499    pub guard: Option<String>,
500    #[serde(default)]
501    pub guard_short: Option<String>,
502    #[serde(default)]
503    pub allow_all: Option<bool>,
504    /// Reference a `[command.handler_policy.KEY]` block by name, copying
505    /// its standalone/valued/bare/etc. into this sub's effective policy.
506    /// Lets a single-sub form (search, browse, gh status) re-use the
507    /// same flag list a matrix entry would, without duplicating the
508    /// WordSets. Mutually exclusive with inline standalone/valued.
509    #[serde(default)]
510    pub policy: Option<String>,
511    #[serde(default)]
512    pub sub: Vec<TomlSub>,
513    /// Per-FLAG escalation + provenance (`[[command.sub.flag]]`): a flag that, when present, ADDS a
514    /// capability to this sub's resolved profile — `git push --force` (→ destroy), `-c
515    /// core.sshCommand=` (→ execution). The level algebra takes the max over the added capabilities,
516    /// so a benign base + a dangerous flag lands at the flag's tier. See
517    /// `docs/design/behavioral-taxonomy-archetypes.md` §3 (per-flag layer).
518    #[serde(default)]
519    pub flag: Vec<TomlSubFlag>,
520    /// `true` marks the sub's first positional as a NETWORK DESTINATION whose *provenance* the
521    /// engine classifies onto `locus.provenance` (established remote-name / literal URL / opaque
522    /// `$VAR`), and whose command-transport form (`ext::<cmd>`) worst-cases as RCE. For
523    /// `git push` and its kin (`scp`/`rsync`/`curl -d`). See `behavioral-taxonomy-exposure.md` §4.
524    #[serde(default)]
525    pub network_destination: Option<bool>,
526    /// A flag that ALSO carries the destination and OVERRIDES the positional (`git push
527    /// --repo=<dest>`). Classified with the same provenance rules — so `--repo=ext::sh` is caught as
528    /// RCE. Requires `network_destination`.
529    #[serde(default)]
530    pub destination_flag: Option<String>,
531    /// Flags whose VALUE is a local output-file path, for a `data-export` sub (`supabase db dump
532    /// -f`, `pg_dump --file`). When one is present the engine adds a path-gated write capability at
533    /// that file's locus — a dump to `./out.sql` is a worktree write, one to `/etc/cron.d/job` a
534    /// system write. Absent (the export goes to stdout) → no write, just the bulk remote read.
535    /// Requires `profile` (only a `data-export` sub has an output file). See
536    /// `behavioral-taxonomy-exposure.md`.
537    #[serde(default)]
538    pub output_path_flags: Vec<String>,
539    /// Flags naming a network endpoint that must be on THIS machine (`--endpoint-url
540    /// http://localhost:8000`). Two effects, both keyed on `netloc::is_loopback`: the flag is
541    /// admitted only with a loopback value, and a loopback value re-classifies the sub's
542    /// non-destroy capabilities as local (`resolve`'s loopback modifier). Declare only where a
543    /// local emulator is a researched workflow for that service.
544    #[serde(default)]
545    pub loopback_valued: Vec<String>,
546    /// Whether a `loopback_valued` flag naming this machine re-classifies the sub: `resolve` clears
547    /// the destination-determined facets (remote reach, net direction, payload, metered cost) and
548    /// leaves everything describing the operation alone. Absent = the sub keeps its remote
549    /// classification whatever the destination; mandatory for destroy archetypes, build-enforced.
550    #[serde(default)]
551    pub loopback_localizes: Option<bool>,
552    #[serde(default)]
553    pub nested_bare: Option<bool>,
554    #[serde(default)]
555    pub require_any: Vec<String>,
556    #[serde(default)]
557    pub first_arg: Vec<String>,
558    /// Flags a `first_arg` GLOB family accepts. The glob admits an invocation on its first
559    /// positional alone, so without these it never examines the flags at all and
560    /// `--endpoint-url http://evil.com` rides along on a read. Empty = family not yet researched
561    /// (permissive, grandfathered — see `no_new_unresearched_first_arg_family`).
562    #[serde(default)]
563    pub first_arg_standalone: Vec<String>,
564    #[serde(default)]
565    pub first_arg_valued: Vec<String>,
566    /// Flags admitted only when their VALUE names this machine (`--endpoint-url
567    /// http://localhost:8000`). Same arity as `first_arg_valued`; the value is classified by
568    /// `netloc::is_loopback`, and anything not positively recognized as loopback denies.
569    #[serde(default)]
570    pub first_arg_loopback_valued: Vec<String>,
571    /// First-positional globs (`secret`, `secret/*`) that make this sub a CREDENTIAL-READ: matching
572    /// denies, before the allow-glob. The value-dependent complement to `profile=credential-read`
573    /// (whole sub) — `kubectl get secret/x`, `aws configure get aws_secret_access_key`.
574    #[serde(default)]
575    pub credential_first_arg: Vec<String>,
576    #[serde(default)]
577    pub write_flags: Vec<String>,
578    #[serde(default)]
579    pub delegate_after: Option<String>,
580    #[serde(default)]
581    pub delegate_skip: Option<usize>,
582    /// `"file"` (first positional is the executor path — `go run ./cmd`) or `"project"`
583    /// (the current project is the executor — `cargo run`). Gates via the execution-origin
584    /// engine instead of a flat level. See `DispatchKind::Executor`.
585    #[serde(default)]
586    pub executor: Option<String>,
587    /// A valued flag whose value redirects the executor out of the project
588    /// (`cargo run --manifest-path DIR/Cargo.toml`); its value is locus-gated. `Project` only.
589    #[serde(default)]
590    pub executor_redirect_flag: Option<String>,
591    /// Predicate the executor path must satisfy (`"go-package"`), else deny. `File` only.
592    #[serde(default)]
593    pub positional_shape: Option<String>,
594    #[serde(default)]
595    pub handler: Option<String>,
596    #[serde(default)]
597    pub doc_body: Option<String>,
598    /// Marks this sub's leaf invocation as safe inside
599    /// `eval "$(CMD SUB ...)"`. The leaf is the deepest matched dispatch
600    /// node — if this sub has nested sub-subs and the invocation matches
601    /// deeper, the tag does NOT apply; the sub-sub must be tagged itself.
602    /// Unset = not eval-safe (the default).
603    #[serde(default)]
604    pub eval_safe: Option<bool>,
605    /// Flag allowlist that extends `eval_safe = true` — these `-`-prefixed
606    /// tokens are also permitted inside the substitution. Default empty,
607    /// meaning only the bare form plus positionals are eval-safe.
608    /// Build panics if this is set without `eval_safe = true`.
609    #[serde(default)]
610    pub eval_safe_flags: Vec<String>,
611    /// Per-valued-flag value allowlist (same semantics as the
612    /// command-level field). Maps each valued flag (which MUST also
613    /// appear in `eval_safe_flags`) to its permitted values.
614    #[serde(default)]
615    pub eval_safe_flag_values: std::collections::HashMap<String, Vec<String>>,
616    /// Flags where AT LEAST ONE must appear (same semantics as the
617    /// command-level field).
618    #[serde(default)]
619    pub eval_safe_required_flags: Vec<String>,
620    /// `[command.sub.output]` — what THIS SUB's stdout can name (same shape and
621    /// semantics as the command-level `[command.output]`).
622    ///
623    /// Sub-scoped because the claim rarely holds for a whole multi-command tool:
624    /// `git diff --name-only` prints worktree paths, while `git log` prints prose
625    /// and `git config --get` prints whatever was configured. A command-level
626    /// claim would have to be voided by an `invalidated_by` list naming every
627    /// other subcommand, which is a denylist and fails open on the next one git
628    /// adds.
629    #[serde(default)]
630    pub output: Option<TomlOutput>,
631}
632
633#[derive(Debug, Clone, Copy, Deserialize)]
634pub(super) enum TomlLevel {
635    Inert,
636    SafeRead,
637    SafeWrite,
638}
639
640impl From<TomlLevel> for SafetyLevel {
641    fn from(l: TomlLevel) -> Self {
642        match l {
643            TomlLevel::Inert => SafetyLevel::Inert,
644            TomlLevel::SafeRead => SafetyLevel::SafeRead,
645            TomlLevel::SafeWrite => SafetyLevel::SafeWrite,
646        }
647    }
648}
649
650#[derive(Debug)]
651pub struct CommandSpec {
652    pub name: String,
653    pub description: String,
654    pub aliases: Vec<String>,
655    pub url: String,
656    pub category: String,
657    /// Upstream version of the underlying tool that was researched
658    /// when this spec was last updated. Free-form string — e.g.
659    /// `"1.9.0"`, `"v5.10.3"`, `"2026-05-08 master"`,
660    /// `"@northflank/cli 0.10.15"`. Internal-only: not rendered in
661    /// docs or used at runtime. Surfaces in tests and as a tripwire
662    /// when researching newer versions of the same tool.
663    pub researched_version: Option<String>,
664    /// Sample invocations that the registry test runs through `is_safe_command`.
665    /// Each `examples_safe` entry must produce `Verdict::Allowed`.
666    pub examples_safe: Vec<String>,
667    /// Sample invocations that must be denied. Use these to lock in security
668    /// boundaries (e.g. `srb tc --metrics-file=/etc/passwd` should always
669    /// be denied; recording it here catches regressions).
670    pub examples_denied: Vec<String>,
671    /// True when this command's bare invocation (no sub) is tagged as
672    /// safe-to-eval. Walked by `registry::is_eval_safe_invocation()`.
673    pub eval_safe: bool,
674    /// Flag allowlist extending `eval_safe` — flags permitted in the
675    /// substituted invocation when the walker stops at this node.
676    pub eval_safe_flags: Vec<String>,
677    /// Per-valued-flag value allowlist. When the walker hits a flag
678    /// listed here, the value following the flag (separated by `=` or
679    /// space) must be in this list.
680    pub eval_safe_flag_values: std::collections::HashMap<String, Vec<String>>,
681    /// Flags where at least one must appear in the substituted
682    /// invocation. Empty = no required-flag constraint.
683    pub eval_safe_required_flags: Vec<String>,
684    /// The command's own path-argument gate (`[command.path_gate]`), if declared. Read by
685    /// `registry::command_path_gate` → `pathgate::should_deny`.
686    pub(super) path_gate: Option<crate::pathgate::RoleSpec>,
687    /// Top-level classifying flags (`[[command.flag]]`), lowered from `TomlSubFlag`. A present flag
688    /// classifies the whole invocation as its archetype — read by `registry::command_flag_archetypes`
689    /// → `engine::resolve::resolve` (the flat-command analog of a profiled sub's escalating flags).
690    pub(super) archetype_flags: Vec<FlagProvenance>,
691    /// Declarative facet behavior (`[command.behavior]`), lowered to typed facet enums. Read
692    /// by `registry::command_behavior` → `engine::resolve::resolve_behavior`. When present,
693    /// the engine classifies this command from its declared facets instead of a Rust resolver.
694    pub(super) behavior: Option<BehaviorSpec>,
695    /// Lowered `[command.output]` — read by `registry::command_output_locus` →
696    /// `engine::resolve::substitution_locus`, which decides whether a `$(…)` around this command
697    /// yields a bounded path instead of the unpinnable sentinel.
698    pub(super) output: Option<OutputSpec>,
699    /// True when the command's `NAME=VALUE` positionals become environment variables (`export`,
700    /// `declare -x`). `dispatch_spec` then classifies each through `envvars::assignment_verdict`
701    /// and combines the result, so `export LD_PRELOAD=/tmp/evil.so` denies as
702    /// `LD_PRELOAD=/tmp/evil.so ls` does.
703    pub(super) env_assignment_positionals: bool,
704    pub(super) kind: DispatchKind,
705}
706
707/// A command's declarative facet behavior, lowered from `[command.behavior]` (`TomlBehavior`)
708/// with every facet string resolved to its enum at build time. The generic resolver reads this
709/// plus the tokens and builds a `Profile`. Clone so it can be attached uniformly across the
710/// `build_command` construction sites.
711#[derive(Debug, Clone)]
712pub(crate) struct BehaviorSpec {
713    pub operation: crate::engine::facet::Operation,
714    pub positionals: PositionalRole,
715    pub scale: ScaleModel,
716    /// Behavior's own flag grammar, pre-split for the shared `walk_positionals`.
717    pub short: Vec<u8>,
718    pub valued_short: Vec<u8>,
719    pub long: Vec<String>,
720    pub valued_long: Vec<String>,
721    pub numeric_shorthand: bool,
722    /// Flags whose presence widens the scale to unbounded (`rm -r`, `grep -r`).
723    pub unbounded_flags: Vec<String>,
724    /// Valued flags whose VALUE is a path to gate (`touch -r REF` reads REF), with its role.
725    pub path_flags: Vec<PathFlag>,
726    pub hook: Option<BehaviorHook>,
727    /// Transfer semantics, present iff `positionals == Transfer`.
728    pub transfer: Option<TransferSpec>,
729}
730
731/// A valued flag whose value is a path safe-chains gates by locus. One spelling per entry (a
732/// flag with both short and long forms is two entries); the resolver scans for each.
733#[derive(Debug, Clone)]
734pub(crate) struct PathFlag {
735    pub short: Option<u8>,
736    pub long: Option<String>,
737    pub role: PathRole,
738}
739
740/// The role a path-flag's value plays — read (gated by read locus) or write (by write locus).
741#[derive(Debug, Clone, Copy, PartialEq, Eq)]
742pub(crate) enum PathRole {
743    Read,
744    Write,
745}
746
747/// Lowered `[command.behavior.transfer]` — the per-command transfer knobs, terms resolved.
748#[derive(Debug, Clone)]
749pub(crate) struct TransferSpec {
750    pub source: TransferSource,
751    /// Whether the DESTINATION operand is a rebind rather than an ordinary write: `ln` makes the
752    /// destination name refer to somewhere else, while `cp` and `mv` put bytes at or under it.
753    /// Both are `create`/`transfer` to the engine, so the operation cannot tell them apart.
754    pub rebinds_destination: bool,
755    pub no_clobber_flags: Vec<String>,
756    pub clobber_flags: Vec<String>,
757    pub recursive_flags: Vec<String>,
758}
759
760/// The source-operand operation of a transfer command.
761#[derive(Debug, Clone, Copy, PartialEq, Eq)]
762pub(crate) enum TransferSource {
763    /// cp/ln: read the source into the destination/link (no disclosure to the model).
764    Observe,
765    /// mv: remove the source from its old location (trivially reversible).
766    Relocate,
767}
768
769/// The closed set of operand-role shapes (§ design doc: the `Operands` enum, as data).
770#[derive(Debug, Clone, Copy, PartialEq, Eq)]
771pub(crate) enum PositionalRole {
772    None,
773    Read,
774    Write,
775    PatternThenRead,
776    Transfer,
777}
778
779/// How a command's `Scale` is computed from its operands.
780#[derive(Debug, Clone, Copy, PartialEq, Eq)]
781pub(crate) enum ScaleModel {
782    /// Every operation is a single item regardless of operand count (cat/head).
783    Single,
784    /// Count, glob, or a recursion flag widen it (`breadth_scale`) — rm/mkdir.
785    Breadth,
786}
787
788/// Runtime form of `[command.output]`: how to derive the locus of a command's stdout.
789#[derive(Debug, Clone)]
790pub(crate) struct OutputSpec {
791    pub locus_from: OutputLocus,
792    /// Flags that void the claim (see `TomlOutput::invalidated_by`).
793    pub invalidated_by: Vec<String>,
794    /// Value-taking flags (see `TomlOutput::valued`).
795    pub valued: Vec<String>,
796    /// Flags of which at least one must be present (see `TomlOutput::requires`).
797    pub requires: Vec<String>,
798}
799
800#[derive(Debug, Clone, Copy, PartialEq, Eq)]
801pub(crate) enum OutputLocus {
802    /// Beneath the command's own path operands — the worst `read_locus` over them, or the cwd
803    /// when it has none (`fd pattern` with no root searches `.`).
804    Operands,
805    /// The working directory itself (`pwd`).
806    Cwd,
807    /// A subset of what it was piped (`head -1`, `sort`, `uniq`) — so the locus is the PREVIOUS
808    /// pipeline stage's. Only when the command has no path operand: `head f.txt` prints the
809    /// contents of a file rather than filtering a stream, and contents are not paths.
810    Stdin,
811    /// The output words are ATOMS: they carry no path separator, so splicing one into a path
812    /// cannot move which directory the path names. `seq` prints integers; `basename` prints a
813    /// single component by definition.
814    ///
815    /// This is a different KIND of claim from the others, which all answer "which locus does this
816    /// output name". An atom names no locus at all — the point is that it cannot CHANGE one. That
817    /// is what makes `for i in $(seq 1 4); do … > "$SP/dx_$i.txt"; done` confinable: the prefix is
818    /// literal, and an atom spliced into the leaf cannot escape it.
819    ///
820    /// Separator-freedom alone is not sufficient — an atom that IS a whole component could be
821    /// `..`. Confinement additionally requires the interpolation to be flanked by literal text
822    /// within its component, which is a property of the PATH, not of this declaration. See
823    /// `docs/design/behavioral-taxonomy-*` and the plan recorded in TODO.md.
824    Atom,
825}
826
827/// A named thin resolver hook for irreducible token logic a declaration can't express — a
828/// command whose operand syntax is not getopt positional (grep's pattern disambiguation, dd's
829/// `key=value`, tar's dashless mode bundles, sed's mini-language script). The hook parses the
830/// tokens; the facets still come from the declaration + the builders.
831#[derive(Debug, Clone, Copy, PartialEq, Eq)]
832pub(crate) enum BehaviorHook {
833    Grep,
834    Dd,
835    Tar,
836    Sed,
837    Perl,
838}
839
840/// Runtime form of a `[[command.sub.flag]]` — the engine-relevant part of an escalating flag: its
841/// `name` (matched against the tokens) and the archetype it `classifies` as when present. Its
842/// research provenance (`fact`/`source`/`judgment`) lives on the TOML side and is validated at build
843/// time, not carried here.
844#[derive(Debug, Clone)]
845pub(super) struct FlagProvenance {
846    pub name: String,
847    pub classifies: String,
848    /// See `TomlSubFlag::value_prefix` — `None` = escalate on presence; `Some` = only when the
849    /// flag's value starts with this.
850    pub value_prefix: Option<String>,
851    /// See `TomlSubFlag::when_absent` — escalate when the flag is ABSENT (a safety flag whose
852    /// absence is the risk).
853    pub when_absent: bool,
854}
855
856#[derive(Debug, Clone)]
857pub(super) struct SubSpec {
858    pub name: String,
859    pub kind: DispatchKind,
860    /// The facet archetype this sub is classified as (`archetypes.toml`), if declared via
861    /// `profile = …`. The engine resolves the sub to this archetype's static capability profile
862    /// (`registry::sub_archetype`), deriving the verdict rather than taking a hand-marked level.
863    /// (Its research provenance — `fact`/`source`/`judgment` — lives on the TOML side only and is
864    /// validated at build time; it is not carried on the runtime spec.)
865    pub profile: Option<String>,
866    /// Escalating flags: each, when present, adds `classifies`'s capability to the resolved profile.
867    pub flags: Vec<FlagProvenance>,
868    /// The sub's DECLARED flag allowlist, preserved for a PROFILED sub. Its legacy `kind` is forced
869    /// to deny-all at build time, but the engine classifies a profiled sub straight from its
870    /// archetype and never reaches that kind — so without keeping the lists here the declaration
871    /// would be discarded and ANY flag would ride along on the profile. That was a fail-OPEN:
872    /// `git rebase --exec 'rm -rf /'` and `supabase db dump --frobnicate` both classified as their
873    /// benign base profile. `sub_archetypes` validates presented flags against these.
874    pub allowed_standalone: Vec<String>,
875    pub allowed_valued: Vec<String>,
876    /// The sub's declared tolerance for flags it does not enumerate — the existing, explicit way to
877    /// say "this tool's flag surface is genuinely unbounded" (a cloud API's per-service options).
878    /// Preserved alongside the allowlist so the profiled path honors it: a sub that declares it stays
879    /// open BY DECLARATION (reviewable in the TOML) rather than by a silent engine default, and a sub
880    /// that does not — `git rebase`, where a flag changes the operation — enforces.
881    pub allowed_unknown: crate::policy::UnknownTolerance,
882    /// If this sub was declared with `policy = "key"`, the referenced
883    /// handler_policy name is preserved for docs rendering so a sub
884    /// that points at a policy also shown in **Shared flag sets** can
885    /// render as a reference rather than duplicating the flag list.
886    pub policy_ref: Option<String>,
887    /// True when this sub's leaf invocation is tagged as safe-to-eval.
888    /// Walked by `registry::is_eval_safe_invocation()`.
889    pub eval_safe: bool,
890    /// Flag allowlist extending `eval_safe` — flags permitted in the
891    /// substituted invocation when the walker stops at this sub.
892    pub eval_safe_flags: Vec<String>,
893    /// Per-valued-flag value allowlist (same semantics as on
894    /// `CommandSpec`).
895    pub eval_safe_flag_values: std::collections::HashMap<String, Vec<String>>,
896    /// Lowered `[command.sub.output]` — this sub's own stdout claim, consulted by
897    /// `registry::sub_output_locus` before the command-level one.
898    pub output: Option<OutputSpec>,
899    /// Flags where at least one must appear in the substituted
900    /// invocation (same semantics as on `CommandSpec`).
901    pub eval_safe_required_flags: Vec<String>,
902    /// `true` = classify this sub's first positional as a network destination onto
903    /// `locus.provenance` (see `TomlSub::network_destination`).
904    pub network_destination: bool,
905    /// A flag that overrides the positional destination (`git push --repo=…`); see
906    /// `TomlSub::destination_flag`.
907    pub destination_flag: Option<String>,
908    /// Output-file flags for a `data-export` sub; a present one adds a path-gated write capability
909    /// at the file's locus (see `TomlSub::output_path_flags`).
910    pub output_path_flags: Vec<String>,
911    /// Endpoint flags gated on naming this machine; see `TomlSub::loopback_valued`.
912    pub loopback_valued: Vec<String>,
913    /// What a loopback endpoint buys this sub; see `TomlSub::loopback_localizes`.
914    pub loopback_effect: LoopbackEffect,
915}
916
917/// What a recognized loopback destination buys a sub. Gating the FLAG and re-classifying the
918/// OPERATION are separate powers: a read only needs the former (it already passes), while a write
919/// needs the latter to stop looking like a call to a cloud service.
920#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
921pub(super) enum LoopbackEffect {
922    /// The endpoint flag is admissible when local; the classification is untouched.
923    #[default]
924    AdmitOnly,
925    /// Also clears the facets the destination determines (remote reach, net direction, payload,
926    /// metered cost), leaving the ones describing the operation alone.
927    Localizes,
928}
929
930#[derive(Debug, Clone)]
931pub(super) enum DispatchKind {
932    Policy {
933        policy: OwnedPolicy,
934        level: SafetyLevel,
935    },
936    FirstArg {
937        patterns: Vec<String>,
938        level: SafetyLevel,
939        /// Flags the glob family accepts. Empty = not yet researched (grandfathered); see
940        /// `glob_presents_unlisted_flag`.
941        standalone: Vec<String>,
942        valued: Vec<String>,
943        /// Flags admitted only when their value is a loopback endpoint.
944        loopback_valued: Vec<String>,
945    },
946    RequireAny {
947        require_any: Vec<String>,
948        policy: OwnedPolicy,
949        level: SafetyLevel,
950        accept_bare_help: bool,
951    },
952    Branching {
953        subs: Vec<SubSpec>,
954        bare_flags: Vec<String>,
955        bare_ok: bool,
956        pre_standalone: Vec<String>,
957        pre_valued: Vec<String>,
958        first_arg: Vec<String>,
959        first_arg_level: SafetyLevel,
960        /// Flags the `first_arg` glob family accepts, as in `DispatchKind::FirstArg`.
961        first_arg_standalone: Vec<String>,
962        first_arg_valued: Vec<String>,
963        first_arg_loopback_valued: Vec<String>,
964        /// First-positional globs that classify the invocation as a credential-read (deny), checked
965        /// after explicit subs and before the allow-glob. Empty for almost every command.
966        credential_first_arg: Vec<String>,
967        /// Accept one leading rustup toolchain selector (`cargo +nightly build`), stripped before
968        /// sub dispatch. From `[command.wrapper] toolchain_selector = true`.
969        toolchain_selector: bool,
970    },
971    WriteFlagged {
972        policy: OwnedPolicy,
973        base_level: SafetyLevel,
974        write_flags: Vec<String>,
975    },
976    DelegateAfterSeparator {
977        separator: String,
978    },
979    DelegateSkip {
980        skip: usize,
981    },
982    Wrapper {
983        standalone: Vec<String>,
984        valued: Vec<String>,
985        positional_skip: usize,
986        separator: Option<String>,
987        bare_ok: bool,
988    },
989    /// A `verb-chain` grammar (`mlr`): a strict main-flag region + a `then`-chain of
990    /// allowlisted verbs. See `dispatch::dispatch_verb_chain`.
991    VerbChain(VerbChainSpec),
992    /// A code-execution command whose verdict is the execution-origin gate (worktree code
993    /// allows, foreign denies), not a flat level. See `dispatch::dispatch_executor` and
994    /// docs/design/behavioral-taxonomy-execution-origin.md.
995    Executor {
996        policy: OwnedPolicy,
997        /// Verdict for a flag-only invocation with no executor (`python3 --version`).
998        level: SafetyLevel,
999        kind: ExecutorKind,
1000        /// A valued flag whose value REDIRECTS the executor out of the project
1001        /// (`cargo run --manifest-path DIR/Cargo.toml`) — its value is locus-gated like a
1002        /// file executor. Only meaningful for `ExecutorKind::Project`.
1003        redirect_flag: Option<String>,
1004        /// A predicate the executor path must satisfy, else deny (`ExecutorKind::File`).
1005        /// `go run` uses `go-package` so a remote import path (`rsc.io/x@latest`) is not
1006        /// treated as a worktree executor.
1007        shape: Option<crate::policy::PositionalShape>,
1008    },
1009    Custom {
1010        #[allow(dead_code)]
1011        handler_name: String,
1012        doc_body: Option<String>,
1013        /// TOML-declared subs the handler may consult via
1014        /// `registry::try_sub_dispatch()`. Empty unless the handler
1015        /// uses the helper.
1016        subs: Vec<SubSpec>,
1017        /// TOML-declared alternate grammar the handler may consult
1018        /// via `registry::try_fallback_grammar()`. `None` unless the
1019        /// handler uses the helper.
1020        fallback: Option<FallbackSpec>,
1021        /// Named flag policies the handler consults via
1022        /// `registry::check_handler_policy()`. Empty unless the handler
1023        /// has dispatch logic that picks a policy by name at runtime.
1024        handler_policies: std::collections::HashMap<String, OwnedPolicy>,
1025        /// Sub × action matrices the handler walks via
1026        /// `registry::try_matrix_dispatch()`.
1027        matrices: Vec<MatrixSpec>,
1028    },
1029}
1030
1031/// How a code-execution command locates its executor. `File`: the first positional is the
1032/// executor path (`bash x.sh`, `python3 x.py`, `go run ./cmd`). `Project`: the current
1033/// project is the executor and there is no path operand (`cargo run`, `dotnet run`).
1034#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1035pub(super) enum ExecutorKind {
1036    File,
1037    Project,
1038}
1039
1040impl ExecutorKind {
1041    pub(super) fn from_name(name: &str) -> Option<Self> {
1042        match name {
1043            "file" => Some(Self::File),
1044            "project" => Some(Self::Project),
1045            _ => None,
1046        }
1047    }
1048}
1049
1050#[derive(Debug, Clone)]
1051pub struct OwnedPolicy {
1052    pub standalone: Vec<String>,
1053    pub valued: Vec<String>,
1054    pub bare: bool,
1055    pub max_positional: Option<usize>,
1056    pub tolerance: crate::policy::FlagTolerance,
1057}
1058
1059#[derive(Debug, Clone)]
1060pub(super) struct MatrixSpec {
1061    pub parents: Vec<String>,
1062    pub level: SafetyLevel,
1063    pub actions: std::collections::HashMap<String, MatrixAction>,
1064}
1065
1066#[derive(Debug, Clone)]
1067pub(super) struct MatrixAction {
1068    pub policy_key: String,
1069    pub guard: Option<String>,
1070    pub guard_short: Option<String>,
1071}
1072
1073#[derive(Debug, Clone)]
1074pub(super) struct VerbChainSpec {
1075    pub level: SafetyLevel,
1076    pub separator: String,
1077    pub main_standalone: Vec<String>,
1078    pub main_valued: Vec<String>,
1079    pub main_variadic: Vec<String>,
1080    pub verbs: std::collections::HashSet<String>,
1081}
1082
1083#[derive(Debug, Clone)]
1084pub(super) struct FallbackSpec {
1085    pub policy: OwnedPolicy,
1086    pub level: SafetyLevel,
1087    pub positional_shape: Option<crate::policy::PositionalShape>,
1088    /// When set, the first positional is an EXECUTOR (a script/package the command runs),
1089    /// gated by the execution-origin engine instead of the flat `level`. `ExecutorKind::File`
1090    /// is the only form used by fallbacks (interpreters). See `dispatch::dispatch_executor`.
1091    pub executor: Option<ExecutorKind>,
1092    /// See `DispatchKind::Executor::redirect_flag`. Unused for `File` fallbacks.
1093    pub executor_redirect_flag: Option<String>,
1094}