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    /// This sub also matches with ONE arbitrary trailing `:segment`, which inherits this sub's
458    /// classification unchanged.
459    ///
460    /// For Rails' per-database rake tasks. A Rails 8 app has four databases out of the box
461    /// (solid_cache, solid_queue, solid_cable), and rake generates a variant of each schema task
462    /// per database: `db:migrate:primary`, `db:create:cache`, `db:drop:queue`. Fourteen base tasks
463    /// times four databases is 56 names, and enumerating them does not even work — the segment is
464    /// a key out of the app's own `config/database.yml`, so another app has `db:migrate:analytics`.
465    ///
466    /// Sound because the variant is strictly NARROWER than the base: `db:migrate:primary` migrates
467    /// one of the databases `db:migrate` migrates all of. Inheriting the base's classification is
468    /// therefore never a widening — `db:drop:cache` lands wherever `db:drop` already sits.
469    ///
470    /// Set it only where that containment argument holds. It is not a general "ignore the tail":
471    /// the suffix must be a single plain identifier, and a sub that means something DIFFERENT with
472    /// a suffix must keep declaring it separately.
473    #[serde(default)]
474    pub per_database: bool,
475    #[serde(default)]
476    pub candidate: Option<bool>,
477    /// A facet archetype name (`archetypes.toml`) — the Phase-1 successor to `candidate = true`:
478    /// instead of hand-marking the sub above the line, it declares which recurring capability
479    /// profile it is, and the engine DERIVES the verdict by projecting that profile through the
480    /// levels. See `docs/design/behavioral-taxonomy-archetypes.md`.
481    #[serde(default)]
482    pub profile: Option<String>,
483    /// Per-item research provenance for the classification (required when `profile` is set — the
484    /// `every_profiled_sub_has_provenance` guard). Three layers so a future researcher can act on
485    /// each precisely: `fact` = what the upstream tool DOCUMENTS (re-check `source` if it moves),
486    /// the `profile` itself = our inference (which archetype it maps to), `judgment` = our stance
487    /// where the source doesn't decide it (a policy call they may revisit). `source` cites the
488    /// upstream doc/section. See `docs/design/behavioral-taxonomy-archetypes.md` §3.
489    #[serde(default)]
490    pub fact: Option<String>,
491    #[serde(default)]
492    pub source: Option<String>,
493    #[serde(default)]
494    pub judgment: Option<String>,
495    #[serde(default)]
496    pub aliases: Vec<String>,
497    #[serde(default)]
498    pub level: Option<TomlLevel>,
499    #[serde(default)]
500    pub bare: Option<bool>,
501    #[serde(default)]
502    pub max_positional: Option<usize>,
503    /// Removed; see TomlCommand::positional_style.
504    #[serde(default)]
505    pub positional_style: Option<bool>,
506    #[serde(default)]
507    pub tolerate_unknown_short: Option<bool>,
508    #[serde(default)]
509    pub tolerate_unknown_long: Option<bool>,
510    #[serde(default)]
511    pub numeric_dash: Option<bool>,
512    #[serde(default)]
513    pub standalone: Vec<String>,
514    #[serde(default)]
515    pub valued: Vec<String>,
516    #[serde(default)]
517    pub guard: Option<String>,
518    #[serde(default)]
519    pub guard_short: Option<String>,
520    #[serde(default)]
521    pub allow_all: Option<bool>,
522    /// Reference a `[command.handler_policy.KEY]` block by name, copying
523    /// its standalone/valued/bare/etc. into this sub's effective policy.
524    /// Lets a single-sub form (search, browse, gh status) re-use the
525    /// same flag list a matrix entry would, without duplicating the
526    /// WordSets. Mutually exclusive with inline standalone/valued.
527    #[serde(default)]
528    pub policy: Option<String>,
529    #[serde(default)]
530    pub sub: Vec<TomlSub>,
531    /// Per-FLAG escalation + provenance (`[[command.sub.flag]]`): a flag that, when present, ADDS a
532    /// capability to this sub's resolved profile — `git push --force` (→ destroy), `-c
533    /// core.sshCommand=` (→ execution). The level algebra takes the max over the added capabilities,
534    /// so a benign base + a dangerous flag lands at the flag's tier. See
535    /// `docs/design/behavioral-taxonomy-archetypes.md` §3 (per-flag layer).
536    #[serde(default)]
537    pub flag: Vec<TomlSubFlag>,
538    /// `true` marks the sub's first positional as a NETWORK DESTINATION whose *provenance* the
539    /// engine classifies onto `locus.provenance` (established remote-name / literal URL / opaque
540    /// `$VAR`), and whose command-transport form (`ext::<cmd>`) worst-cases as RCE. For
541    /// `git push` and its kin (`scp`/`rsync`/`curl -d`). See `behavioral-taxonomy-exposure.md` §4.
542    #[serde(default)]
543    pub network_destination: Option<bool>,
544    /// A flag that ALSO carries the destination and OVERRIDES the positional (`git push
545    /// --repo=<dest>`). Classified with the same provenance rules — so `--repo=ext::sh` is caught as
546    /// RCE. Requires `network_destination`.
547    #[serde(default)]
548    pub destination_flag: Option<String>,
549    /// Flags whose VALUE is a local output-file path, for a `data-export` sub (`supabase db dump
550    /// -f`, `pg_dump --file`). When one is present the engine adds a path-gated write capability at
551    /// that file's locus — a dump to `./out.sql` is a worktree write, one to `/etc/cron.d/job` a
552    /// system write. Absent (the export goes to stdout) → no write, just the bulk remote read.
553    /// Requires `profile` (only a `data-export` sub has an output file). See
554    /// `behavioral-taxonomy-exposure.md`.
555    #[serde(default)]
556    pub output_path_flags: Vec<String>,
557    /// Flags naming a network endpoint that must be on THIS machine (`--endpoint-url
558    /// http://localhost:8000`). Two effects, both keyed on `netloc::is_loopback`: the flag is
559    /// admitted only with a loopback value, and a loopback value re-classifies the sub's
560    /// non-destroy capabilities as local (`resolve`'s loopback modifier). Declare only where a
561    /// local emulator is a researched workflow for that service.
562    #[serde(default)]
563    pub loopback_valued: Vec<String>,
564    /// Whether a `loopback_valued` flag naming this machine re-classifies the sub: `resolve` clears
565    /// the destination-determined facets (remote reach, net direction, payload, metered cost) and
566    /// leaves everything describing the operation alone. Absent = the sub keeps its remote
567    /// classification whatever the destination; mandatory for destroy archetypes, build-enforced.
568    #[serde(default)]
569    pub loopback_localizes: Option<bool>,
570    #[serde(default)]
571    pub nested_bare: Option<bool>,
572    #[serde(default)]
573    pub require_any: Vec<String>,
574    #[serde(default)]
575    pub first_arg: Vec<String>,
576    /// Flags a `first_arg` GLOB family accepts. The glob admits an invocation on its first
577    /// positional alone, so without these it never examines the flags at all and
578    /// `--endpoint-url http://evil.com` rides along on a read. Empty = family not yet researched
579    /// (permissive, grandfathered — see `no_new_unresearched_first_arg_family`).
580    #[serde(default)]
581    pub first_arg_standalone: Vec<String>,
582    #[serde(default)]
583    pub first_arg_valued: Vec<String>,
584    /// Flags admitted only when their VALUE names this machine (`--endpoint-url
585    /// http://localhost:8000`). Same arity as `first_arg_valued`; the value is classified by
586    /// `netloc::is_loopback`, and anything not positively recognized as loopback denies.
587    #[serde(default)]
588    pub first_arg_loopback_valued: Vec<String>,
589    /// First-positional globs (`secret`, `secret/*`) that make this sub a CREDENTIAL-READ: matching
590    /// denies, before the allow-glob. The value-dependent complement to `profile=credential-read`
591    /// (whole sub) — `kubectl get secret/x`, `aws configure get aws_secret_access_key`.
592    #[serde(default)]
593    pub credential_first_arg: Vec<String>,
594    #[serde(default)]
595    pub write_flags: Vec<String>,
596    #[serde(default)]
597    pub delegate_after: Option<String>,
598    #[serde(default)]
599    pub delegate_skip: Option<usize>,
600    /// `"file"` (first positional is the executor path — `go run ./cmd`) or `"project"`
601    /// (the current project is the executor — `cargo run`). Gates via the execution-origin
602    /// engine instead of a flat level. See `DispatchKind::Executor`.
603    #[serde(default)]
604    pub executor: Option<String>,
605    /// A valued flag whose value redirects the executor out of the project
606    /// (`cargo run --manifest-path DIR/Cargo.toml`); its value is locus-gated. `Project` only.
607    #[serde(default)]
608    pub executor_redirect_flag: Option<String>,
609    /// Predicate the executor path must satisfy (`"go-package"`), else deny. `File` only.
610    #[serde(default)]
611    pub positional_shape: Option<String>,
612    #[serde(default)]
613    pub handler: Option<String>,
614    #[serde(default)]
615    pub doc_body: Option<String>,
616    /// Marks this sub's leaf invocation as safe inside
617    /// `eval "$(CMD SUB ...)"`. The leaf is the deepest matched dispatch
618    /// node — if this sub has nested sub-subs and the invocation matches
619    /// deeper, the tag does NOT apply; the sub-sub must be tagged itself.
620    /// Unset = not eval-safe (the default).
621    #[serde(default)]
622    pub eval_safe: Option<bool>,
623    /// Flag allowlist that extends `eval_safe = true` — these `-`-prefixed
624    /// tokens are also permitted inside the substitution. Default empty,
625    /// meaning only the bare form plus positionals are eval-safe.
626    /// Build panics if this is set without `eval_safe = true`.
627    #[serde(default)]
628    pub eval_safe_flags: Vec<String>,
629    /// Per-valued-flag value allowlist (same semantics as the
630    /// command-level field). Maps each valued flag (which MUST also
631    /// appear in `eval_safe_flags`) to its permitted values.
632    #[serde(default)]
633    pub eval_safe_flag_values: std::collections::HashMap<String, Vec<String>>,
634    /// Flags where AT LEAST ONE must appear (same semantics as the
635    /// command-level field).
636    #[serde(default)]
637    pub eval_safe_required_flags: Vec<String>,
638    /// `[command.sub.output]` — what THIS SUB's stdout can name (same shape and
639    /// semantics as the command-level `[command.output]`).
640    ///
641    /// Sub-scoped because the claim rarely holds for a whole multi-command tool:
642    /// `git diff --name-only` prints worktree paths, while `git log` prints prose
643    /// and `git config --get` prints whatever was configured. A command-level
644    /// claim would have to be voided by an `invalidated_by` list naming every
645    /// other subcommand, which is a denylist and fails open on the next one git
646    /// adds.
647    #[serde(default)]
648    pub output: Option<TomlOutput>,
649}
650
651#[derive(Debug, Clone, Copy, Deserialize)]
652pub(super) enum TomlLevel {
653    Inert,
654    SafeRead,
655    SafeWrite,
656}
657
658impl From<TomlLevel> for SafetyLevel {
659    fn from(l: TomlLevel) -> Self {
660        match l {
661            TomlLevel::Inert => SafetyLevel::Inert,
662            TomlLevel::SafeRead => SafetyLevel::SafeRead,
663            TomlLevel::SafeWrite => SafetyLevel::SafeWrite,
664        }
665    }
666}
667
668#[derive(Debug)]
669pub struct CommandSpec {
670    pub name: String,
671    pub description: String,
672    pub aliases: Vec<String>,
673    pub url: String,
674    pub category: String,
675    /// Upstream version of the underlying tool that was researched
676    /// when this spec was last updated. Free-form string — e.g.
677    /// `"1.9.0"`, `"v5.10.3"`, `"2026-05-08 master"`,
678    /// `"@northflank/cli 0.10.15"`. Internal-only: not rendered in
679    /// docs or used at runtime. Surfaces in tests and as a tripwire
680    /// when researching newer versions of the same tool.
681    pub researched_version: Option<String>,
682    /// Sample invocations that the registry test runs through `is_safe_command`.
683    /// Each `examples_safe` entry must produce `Verdict::Allowed`.
684    pub examples_safe: Vec<String>,
685    /// Sample invocations that must be denied. Use these to lock in security
686    /// boundaries (e.g. `srb tc --metrics-file=/etc/passwd` should always
687    /// be denied; recording it here catches regressions).
688    pub examples_denied: Vec<String>,
689    /// True when this command's bare invocation (no sub) is tagged as
690    /// safe-to-eval. Walked by `registry::is_eval_safe_invocation()`.
691    pub eval_safe: bool,
692    /// Flag allowlist extending `eval_safe` — flags permitted in the
693    /// substituted invocation when the walker stops at this node.
694    pub eval_safe_flags: Vec<String>,
695    /// Per-valued-flag value allowlist. When the walker hits a flag
696    /// listed here, the value following the flag (separated by `=` or
697    /// space) must be in this list.
698    pub eval_safe_flag_values: std::collections::HashMap<String, Vec<String>>,
699    /// Flags where at least one must appear in the substituted
700    /// invocation. Empty = no required-flag constraint.
701    pub eval_safe_required_flags: Vec<String>,
702    /// The command's own path-argument gate (`[command.path_gate]`), if declared. Read by
703    /// `registry::command_path_gate` → `pathgate::should_deny`.
704    pub(super) path_gate: Option<crate::pathgate::RoleSpec>,
705    /// Top-level classifying flags (`[[command.flag]]`), lowered from `TomlSubFlag`. A present flag
706    /// classifies the whole invocation as its archetype — read by `registry::command_flag_archetypes`
707    /// → `engine::resolve::resolve` (the flat-command analog of a profiled sub's escalating flags).
708    pub(super) archetype_flags: Vec<FlagProvenance>,
709    /// Declarative facet behavior (`[command.behavior]`), lowered to typed facet enums. Read
710    /// by `registry::command_behavior` → `engine::resolve::resolve_behavior`. When present,
711    /// the engine classifies this command from its declared facets instead of a Rust resolver.
712    pub(super) behavior: Option<BehaviorSpec>,
713    /// Lowered `[command.output]` — read by `registry::command_output_locus` →
714    /// `engine::resolve::substitution_locus`, which decides whether a `$(…)` around this command
715    /// yields a bounded path instead of the unpinnable sentinel.
716    pub(super) output: Option<OutputSpec>,
717    /// True when the command's `NAME=VALUE` positionals become environment variables (`export`,
718    /// `declare -x`). `dispatch_spec` then classifies each through `envvars::assignment_verdict`
719    /// and combines the result, so `export LD_PRELOAD=/tmp/evil.so` denies as
720    /// `LD_PRELOAD=/tmp/evil.so ls` does.
721    pub(super) env_assignment_positionals: bool,
722    pub(super) kind: DispatchKind,
723}
724
725/// A command's declarative facet behavior, lowered from `[command.behavior]` (`TomlBehavior`)
726/// with every facet string resolved to its enum at build time. The generic resolver reads this
727/// plus the tokens and builds a `Profile`. Clone so it can be attached uniformly across the
728/// `build_command` construction sites.
729#[derive(Debug, Clone)]
730pub(crate) struct BehaviorSpec {
731    pub operation: crate::engine::facet::Operation,
732    pub positionals: PositionalRole,
733    pub scale: ScaleModel,
734    /// Behavior's own flag grammar, pre-split for the shared `walk_positionals`.
735    pub short: Vec<u8>,
736    pub valued_short: Vec<u8>,
737    pub long: Vec<String>,
738    pub valued_long: Vec<String>,
739    pub numeric_shorthand: bool,
740    /// Flags whose presence widens the scale to unbounded (`rm -r`, `grep -r`).
741    pub unbounded_flags: Vec<String>,
742    /// Valued flags whose VALUE is a path to gate (`touch -r REF` reads REF), with its role.
743    pub path_flags: Vec<PathFlag>,
744    pub hook: Option<BehaviorHook>,
745    /// Transfer semantics, present iff `positionals == Transfer`.
746    pub transfer: Option<TransferSpec>,
747}
748
749/// A valued flag whose value is a path safe-chains gates by locus. One spelling per entry (a
750/// flag with both short and long forms is two entries); the resolver scans for each.
751#[derive(Debug, Clone)]
752pub(crate) struct PathFlag {
753    pub short: Option<u8>,
754    pub long: Option<String>,
755    pub role: PathRole,
756}
757
758/// The role a path-flag's value plays — read (gated by read locus) or write (by write locus).
759#[derive(Debug, Clone, Copy, PartialEq, Eq)]
760pub(crate) enum PathRole {
761    Read,
762    Write,
763}
764
765/// Lowered `[command.behavior.transfer]` — the per-command transfer knobs, terms resolved.
766#[derive(Debug, Clone)]
767pub(crate) struct TransferSpec {
768    pub source: TransferSource,
769    /// Whether the DESTINATION operand is a rebind rather than an ordinary write: `ln` makes the
770    /// destination name refer to somewhere else, while `cp` and `mv` put bytes at or under it.
771    /// Both are `create`/`transfer` to the engine, so the operation cannot tell them apart.
772    pub rebinds_destination: bool,
773    pub no_clobber_flags: Vec<String>,
774    pub clobber_flags: Vec<String>,
775    pub recursive_flags: Vec<String>,
776}
777
778/// The source-operand operation of a transfer command.
779#[derive(Debug, Clone, Copy, PartialEq, Eq)]
780pub(crate) enum TransferSource {
781    /// cp/ln: read the source into the destination/link (no disclosure to the model).
782    Observe,
783    /// mv: remove the source from its old location (trivially reversible).
784    Relocate,
785}
786
787/// The closed set of operand-role shapes (§ design doc: the `Operands` enum, as data).
788#[derive(Debug, Clone, Copy, PartialEq, Eq)]
789pub(crate) enum PositionalRole {
790    None,
791    Read,
792    Write,
793    PatternThenRead,
794    Transfer,
795}
796
797/// How a command's `Scale` is computed from its operands.
798#[derive(Debug, Clone, Copy, PartialEq, Eq)]
799pub(crate) enum ScaleModel {
800    /// Every operation is a single item regardless of operand count (cat/head).
801    Single,
802    /// Count, glob, or a recursion flag widen it (`breadth_scale`) — rm/mkdir.
803    Breadth,
804}
805
806/// Runtime form of `[command.output]`: how to derive the locus of a command's stdout.
807#[derive(Debug, Clone)]
808pub(crate) struct OutputSpec {
809    pub locus_from: OutputLocus,
810    /// Flags that void the claim (see `TomlOutput::invalidated_by`).
811    pub invalidated_by: Vec<String>,
812    /// Value-taking flags (see `TomlOutput::valued`).
813    pub valued: Vec<String>,
814    /// Flags of which at least one must be present (see `TomlOutput::requires`).
815    pub requires: Vec<String>,
816}
817
818#[derive(Debug, Clone, Copy, PartialEq, Eq)]
819pub(crate) enum OutputLocus {
820    /// Beneath the command's own path operands — the worst `read_locus` over them, or the cwd
821    /// when it has none (`fd pattern` with no root searches `.`).
822    Operands,
823    /// The working directory itself (`pwd`).
824    Cwd,
825    /// A subset of what it was piped (`head -1`, `sort`, `uniq`) — so the locus is the PREVIOUS
826    /// pipeline stage's. Only when the command has no path operand: `head f.txt` prints the
827    /// contents of a file rather than filtering a stream, and contents are not paths.
828    Stdin,
829    /// The output words are ATOMS: they carry no path separator, so splicing one into a path
830    /// cannot move which directory the path names. `seq` prints integers; `basename` prints a
831    /// single component by definition.
832    ///
833    /// This is a different KIND of claim from the others, which all answer "which locus does this
834    /// output name". An atom names no locus at all — the point is that it cannot CHANGE one. That
835    /// is what makes `for i in $(seq 1 4); do … > "$SP/dx_$i.txt"; done` confinable: the prefix is
836    /// literal, and an atom spliced into the leaf cannot escape it.
837    ///
838    /// Separator-freedom alone is not sufficient — an atom that IS a whole component could be
839    /// `..`. Confinement additionally requires the interpolation to be flanked by literal text
840    /// within its component, which is a property of the PATH, not of this declaration. See
841    /// `docs/design/behavioral-taxonomy-*` and the plan recorded in TODO.md.
842    Atom,
843}
844
845/// A named thin resolver hook for irreducible token logic a declaration can't express — a
846/// command whose operand syntax is not getopt positional (grep's pattern disambiguation, dd's
847/// `key=value`, tar's dashless mode bundles, sed's mini-language script). The hook parses the
848/// tokens; the facets still come from the declaration + the builders.
849#[derive(Debug, Clone, Copy, PartialEq, Eq)]
850pub(crate) enum BehaviorHook {
851    Grep,
852    Dd,
853    Tar,
854    Sed,
855    Perl,
856}
857
858/// Runtime form of a `[[command.sub.flag]]` — the engine-relevant part of an escalating flag: its
859/// `name` (matched against the tokens) and the archetype it `classifies` as when present. Its
860/// research provenance (`fact`/`source`/`judgment`) lives on the TOML side and is validated at build
861/// time, not carried here.
862#[derive(Debug, Clone)]
863pub(super) struct FlagProvenance {
864    pub name: String,
865    pub classifies: String,
866    /// See `TomlSubFlag::value_prefix` — `None` = escalate on presence; `Some` = only when the
867    /// flag's value starts with this.
868    pub value_prefix: Option<String>,
869    /// See `TomlSubFlag::when_absent` — escalate when the flag is ABSENT (a safety flag whose
870    /// absence is the risk).
871    pub when_absent: bool,
872}
873
874/// How a sub's declared name is matched. An enum rather than a bool because the two are genuinely
875/// different matching MODES, and because a third boolean on `SubSpec` is the point at which the
876/// struct stops being readable — `name_match: WithDatabaseSuffix` says what `per_database: true`
877/// only implied.
878#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
879pub(super) enum NameMatch {
880    #[default]
881    Exact,
882    /// Also matches `name:<dbname>` for one plain identifier — see `TomlSub::per_database`.
883    WithDatabaseSuffix,
884}
885
886#[derive(Debug, Clone)]
887pub(super) struct SubSpec {
888    pub name: String,
889    pub kind: DispatchKind,
890    /// How this sub's name is matched against an argument.
891    pub name_match: NameMatch,
892    /// The facet archetype this sub is classified as (`archetypes.toml`), if declared via
893    /// `profile = …`. The engine resolves the sub to this archetype's static capability profile
894    /// (`registry::sub_archetype`), deriving the verdict rather than taking a hand-marked level.
895    /// (Its research provenance — `fact`/`source`/`judgment` — lives on the TOML side only and is
896    /// validated at build time; it is not carried on the runtime spec.)
897    pub profile: Option<String>,
898    /// Escalating flags: each, when present, adds `classifies`'s capability to the resolved profile.
899    pub flags: Vec<FlagProvenance>,
900    /// The sub's DECLARED flag allowlist, preserved for a PROFILED sub. Its legacy `kind` is forced
901    /// to deny-all at build time, but the engine classifies a profiled sub straight from its
902    /// archetype and never reaches that kind — so without keeping the lists here the declaration
903    /// would be discarded and ANY flag would ride along on the profile. That was a fail-OPEN:
904    /// `git rebase --exec 'rm -rf /'` and `supabase db dump --frobnicate` both classified as their
905    /// benign base profile. `sub_archetypes` validates presented flags against these.
906    pub allowed_standalone: Vec<String>,
907    pub allowed_valued: Vec<String>,
908    /// The sub's declared tolerance for flags it does not enumerate — the existing, explicit way to
909    /// say "this tool's flag surface is genuinely unbounded" (a cloud API's per-service options).
910    /// Preserved alongside the allowlist so the profiled path honors it: a sub that declares it stays
911    /// open BY DECLARATION (reviewable in the TOML) rather than by a silent engine default, and a sub
912    /// that does not — `git rebase`, where a flag changes the operation — enforces.
913    pub allowed_unknown: crate::policy::UnknownTolerance,
914    /// If this sub was declared with `policy = "key"`, the referenced
915    /// handler_policy name is preserved for docs rendering so a sub
916    /// that points at a policy also shown in **Shared flag sets** can
917    /// render as a reference rather than duplicating the flag list.
918    pub policy_ref: Option<String>,
919    /// True when this sub's leaf invocation is tagged as safe-to-eval.
920    /// Walked by `registry::is_eval_safe_invocation()`.
921    pub eval_safe: bool,
922    /// Flag allowlist extending `eval_safe` — flags permitted in the
923    /// substituted invocation when the walker stops at this sub.
924    pub eval_safe_flags: Vec<String>,
925    /// Per-valued-flag value allowlist (same semantics as on
926    /// `CommandSpec`).
927    pub eval_safe_flag_values: std::collections::HashMap<String, Vec<String>>,
928    /// Lowered `[command.sub.output]` — this sub's own stdout claim, consulted by
929    /// `registry::sub_output_locus` before the command-level one.
930    pub output: Option<OutputSpec>,
931    /// Flags where at least one must appear in the substituted
932    /// invocation (same semantics as on `CommandSpec`).
933    pub eval_safe_required_flags: Vec<String>,
934    /// `true` = classify this sub's first positional as a network destination onto
935    /// `locus.provenance` (see `TomlSub::network_destination`).
936    pub network_destination: bool,
937    /// A flag that overrides the positional destination (`git push --repo=…`); see
938    /// `TomlSub::destination_flag`.
939    pub destination_flag: Option<String>,
940    /// Output-file flags for a `data-export` sub; a present one adds a path-gated write capability
941    /// at the file's locus (see `TomlSub::output_path_flags`).
942    pub output_path_flags: Vec<String>,
943    /// Endpoint flags gated on naming this machine; see `TomlSub::loopback_valued`.
944    pub loopback_valued: Vec<String>,
945    /// What a loopback endpoint buys this sub; see `TomlSub::loopback_localizes`.
946    pub loopback_effect: LoopbackEffect,
947}
948
949/// What a recognized loopback destination buys a sub. Gating the FLAG and re-classifying the
950/// OPERATION are separate powers: a read only needs the former (it already passes), while a write
951/// needs the latter to stop looking like a call to a cloud service.
952#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
953pub(super) enum LoopbackEffect {
954    /// The endpoint flag is admissible when local; the classification is untouched.
955    #[default]
956    AdmitOnly,
957    /// Also clears the facets the destination determines (remote reach, net direction, payload,
958    /// metered cost), leaving the ones describing the operation alone.
959    Localizes,
960}
961
962#[derive(Debug, Clone)]
963pub(super) enum DispatchKind {
964    Policy {
965        policy: OwnedPolicy,
966        level: SafetyLevel,
967    },
968    FirstArg {
969        patterns: Vec<String>,
970        level: SafetyLevel,
971        /// Flags the glob family accepts. Empty = not yet researched (grandfathered); see
972        /// `glob_presents_unlisted_flag`.
973        standalone: Vec<String>,
974        valued: Vec<String>,
975        /// Flags admitted only when their value is a loopback endpoint.
976        loopback_valued: Vec<String>,
977    },
978    RequireAny {
979        require_any: Vec<String>,
980        policy: OwnedPolicy,
981        level: SafetyLevel,
982        accept_bare_help: bool,
983    },
984    Branching {
985        subs: Vec<SubSpec>,
986        bare_flags: Vec<String>,
987        bare_ok: bool,
988        pre_standalone: Vec<String>,
989        pre_valued: Vec<String>,
990        first_arg: Vec<String>,
991        first_arg_level: SafetyLevel,
992        /// Flags the `first_arg` glob family accepts, as in `DispatchKind::FirstArg`.
993        first_arg_standalone: Vec<String>,
994        first_arg_valued: Vec<String>,
995        first_arg_loopback_valued: Vec<String>,
996        /// First-positional globs that classify the invocation as a credential-read (deny), checked
997        /// after explicit subs and before the allow-glob. Empty for almost every command.
998        credential_first_arg: Vec<String>,
999        /// Accept one leading rustup toolchain selector (`cargo +nightly build`), stripped before
1000        /// sub dispatch. From `[command.wrapper] toolchain_selector = true`.
1001        toolchain_selector: bool,
1002    },
1003    WriteFlagged {
1004        policy: OwnedPolicy,
1005        base_level: SafetyLevel,
1006        write_flags: Vec<String>,
1007    },
1008    DelegateAfterSeparator {
1009        separator: String,
1010    },
1011    DelegateSkip {
1012        skip: usize,
1013    },
1014    Wrapper {
1015        standalone: Vec<String>,
1016        valued: Vec<String>,
1017        positional_skip: usize,
1018        separator: Option<String>,
1019        bare_ok: bool,
1020    },
1021    /// A `verb-chain` grammar (`mlr`): a strict main-flag region + a `then`-chain of
1022    /// allowlisted verbs. See `dispatch::dispatch_verb_chain`.
1023    VerbChain(VerbChainSpec),
1024    /// A code-execution command whose verdict is the execution-origin gate (worktree code
1025    /// allows, foreign denies), not a flat level. See `dispatch::dispatch_executor` and
1026    /// docs/design/behavioral-taxonomy-execution-origin.md.
1027    Executor {
1028        policy: OwnedPolicy,
1029        /// Verdict for a flag-only invocation with no executor (`python3 --version`).
1030        level: SafetyLevel,
1031        kind: ExecutorKind,
1032        /// A valued flag whose value REDIRECTS the executor out of the project
1033        /// (`cargo run --manifest-path DIR/Cargo.toml`) — its value is locus-gated like a
1034        /// file executor. Only meaningful for `ExecutorKind::Project`.
1035        redirect_flag: Option<String>,
1036        /// A predicate the executor path must satisfy, else deny (`ExecutorKind::File`).
1037        /// `go run` uses `go-package` so a remote import path (`rsc.io/x@latest`) is not
1038        /// treated as a worktree executor.
1039        shape: Option<crate::policy::PositionalShape>,
1040    },
1041    Custom {
1042        #[allow(dead_code)]
1043        handler_name: String,
1044        doc_body: Option<String>,
1045        /// TOML-declared subs the handler may consult via
1046        /// `registry::try_sub_dispatch()`. Empty unless the handler
1047        /// uses the helper.
1048        subs: Vec<SubSpec>,
1049        /// TOML-declared alternate grammar the handler may consult
1050        /// via `registry::try_fallback_grammar()`. `None` unless the
1051        /// handler uses the helper.
1052        fallback: Option<FallbackSpec>,
1053        /// Named flag policies the handler consults via
1054        /// `registry::check_handler_policy()`. Empty unless the handler
1055        /// has dispatch logic that picks a policy by name at runtime.
1056        handler_policies: std::collections::HashMap<String, OwnedPolicy>,
1057        /// Sub × action matrices the handler walks via
1058        /// `registry::try_matrix_dispatch()`.
1059        matrices: Vec<MatrixSpec>,
1060    },
1061}
1062
1063/// How a code-execution command locates its executor. `File`: the first positional is the
1064/// executor path (`bash x.sh`, `python3 x.py`, `go run ./cmd`). `Project`: the current
1065/// project is the executor and there is no path operand (`cargo run`, `dotnet run`).
1066#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1067pub(super) enum ExecutorKind {
1068    File,
1069    Project,
1070}
1071
1072impl ExecutorKind {
1073    pub(super) fn from_name(name: &str) -> Option<Self> {
1074        match name {
1075            "file" => Some(Self::File),
1076            "project" => Some(Self::Project),
1077            _ => None,
1078        }
1079    }
1080}
1081
1082#[derive(Debug, Clone)]
1083pub struct OwnedPolicy {
1084    pub standalone: Vec<String>,
1085    pub valued: Vec<String>,
1086    pub bare: bool,
1087    pub max_positional: Option<usize>,
1088    pub tolerance: crate::policy::FlagTolerance,
1089}
1090
1091#[derive(Debug, Clone)]
1092pub(super) struct MatrixSpec {
1093    pub parents: Vec<String>,
1094    pub level: SafetyLevel,
1095    pub actions: std::collections::HashMap<String, MatrixAction>,
1096}
1097
1098#[derive(Debug, Clone)]
1099pub(super) struct MatrixAction {
1100    pub policy_key: String,
1101    pub guard: Option<String>,
1102    pub guard_short: Option<String>,
1103}
1104
1105#[derive(Debug, Clone)]
1106pub(super) struct VerbChainSpec {
1107    pub level: SafetyLevel,
1108    pub separator: String,
1109    pub main_standalone: Vec<String>,
1110    pub main_valued: Vec<String>,
1111    pub main_variadic: Vec<String>,
1112    pub verbs: std::collections::HashSet<String>,
1113}
1114
1115#[derive(Debug, Clone)]
1116pub(super) struct FallbackSpec {
1117    pub policy: OwnedPolicy,
1118    pub level: SafetyLevel,
1119    pub positional_shape: Option<crate::policy::PositionalShape>,
1120    /// When set, the first positional is an EXECUTOR (a script/package the command runs),
1121    /// gated by the execution-origin engine instead of the flat `level`. `ExecutorKind::File`
1122    /// is the only form used by fallbacks (interpreters). See `dispatch::dispatch_executor`.
1123    pub executor: Option<ExecutorKind>,
1124    /// See `DispatchKind::Executor::redirect_flag`. Unused for `File` fallbacks.
1125    pub executor_redirect_flag: Option<String>,
1126}