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