Skip to main content

safe_chains/registry/
types.rs

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