Skip to main content

safe_chains/registry/
types.rs

1pub(crate) use super::dispatch::delegate::DelegateAfter;
2use serde::Deserialize;
3
4use crate::verdict::SafetyLevel;
5
6#[path = "types_behavior.rs"]
7mod behavior;
8#[path = "shapes.rs"]
9mod shapes;
10#[path = "types_sub.rs"]
11mod sub;
12#[path = "types_tables.rs"]
13mod tables;
14#[path = "transfer.rs"]
15mod transfer;
16pub(crate) use behavior::*;
17pub(super) use shapes::{misshapen, sub_shape};
18pub(super) use sub::*;
19pub(super) use tables::*;
20pub(super) use transfer::TomlTransfer;
21pub(crate) use transfer::{TransferSource, TransferSpec};
22mod hooks;
23pub(super) use hooks::SpecHooks;
24
25#[derive(Debug, Deserialize)]
26pub(super) struct TomlFile {
27    // Defaulted so a user config that contains only `[[trusted]]` (the repo-pin
28    // list, parsed separately) is valid. Unknown tables like `[[trusted]]` are
29    // ignored here.
30    #[serde(default)]
31    pub command: Vec<TomlCommand>,
32}
33
34#[derive(Debug, Deserialize)]
35pub(super) struct TomlCommand {
36    pub name: String,
37    #[serde(default)]
38    pub description: Option<String>,
39    #[serde(default)]
40    pub candidate: Option<bool>,
41    #[serde(default)]
42    pub aliases: Vec<String>,
43    #[serde(default)]
44    pub url: String,
45    #[serde(default)]
46    pub level: Option<TomlLevel>,
47    #[serde(default)]
48    pub bare: Option<bool>,
49    #[serde(default)]
50    pub max_positional: Option<usize>,
51    /// This command PUTS ITS `NAME=VALUE` POSITIONALS INTO THE ENVIRONMENT (`export`, `declare -x`), each classified through
52    /// `envvars.toml` as the `VAR=value cmd` prefix form is (`exported_assignments_verdict`).
53    #[serde(default)]
54    pub env_assignment_positionals: Option<bool>,
55    /// Lowered into [`LineChecks::flag_value_shapes`].
56    #[serde(default)]
57    pub flag_value_shapes: std::collections::BTreeMap<String, String>,
58    /// Lowered into [`SpecHooks`]: the command is built with GHC, so any `+RTS` argument is refused.
59    #[serde(default)]
60    pub ghc_rts: Option<bool>,
61    /// Removed for `tolerate_unknown_short`/`_long`; build panics if a TOML sets it, naming the command (SAMPLE.toml migrates).
62    #[serde(default)]
63    pub positional_style: Option<bool>,
64    #[serde(default)]
65    pub tolerate_unknown_short: Option<bool>,
66    #[serde(default)]
67    pub tolerate_unknown_long: Option<bool>,
68    #[serde(default)]
69    pub numeric_dash: Option<bool>,
70    #[serde(default)]
71    pub single_dash_words: Option<bool>,
72    #[serde(default)]
73    pub reads_commands_from: Vec<String>,
74    #[serde(default)]
75    pub standalone: Vec<String>,
76    #[serde(default)]
77    pub valued: Vec<String>,
78    /// Flags that take a value OPTIONALLY: `--long` and `--long=27` are both real spellings.
79    /// See `build_policy` for why this compiles down to the other two lists rather than adding
80    /// a state to the walk.
81    #[serde(default)]
82    pub optional_valued: Vec<String>,
83    #[serde(default)]
84    pub bare_flags: Vec<String>,
85    #[serde(default)]
86    pub sub: Vec<TomlSub>,
87    #[serde(default)]
88    pub handler: Option<String>,
89    #[serde(default)]
90    pub doc_body: Option<String>,
91    #[serde(default)]
92    pub require_any: Vec<String>,
93    #[serde(default)]
94    pub first_arg: Vec<String>,
95    /// Flags a `first_arg` GLOB family accepts. The glob admits an invocation on its first
96    /// positional alone, so without these it never examines the flags at all and
97    /// `--endpoint-url http://evil.com` rides along on a read. Empty = family not yet researched
98    /// (permissive, grandfathered — see `no_new_unresearched_first_arg_family`).
99    #[serde(default)]
100    pub first_arg_standalone: Vec<String>,
101    #[serde(default)]
102    pub first_arg_valued: Vec<String>,
103    /// Flags admitted only when their VALUE names this machine (`--endpoint-url
104    /// http://localhost:8000`). Same arity as `first_arg_valued`; the value is classified by
105    /// `netloc::is_loopback`, and anything not positively recognized as loopback denies.
106    #[serde(default)]
107    pub first_arg_loopback_valued: Vec<String>,
108    #[serde(default)]
109    pub credential_first_arg: Vec<String>,
110    /// Top-level classifying flags (`[[command.flag]]`): a flag whose PRESENCE classifies the WHOLE
111    /// invocation as an archetype — the flat-command analog of `[[command.sub.flag]]`. For a bimodal
112    /// tool where a mode flag flips the operation: `age -d` / `sops --decrypt` reveal plaintext to the
113    /// model (`decrypt-read`), while the bare/encrypt form is an ordinary local write. Resolved by
114    /// `engine::resolve` via `registry::command_flag_archetypes`; each flag's `classifies` must name a
115    /// known archetype and carry `fact`/`source` provenance (the `assert_command_flag_provenance` guard).
116    #[serde(default)]
117    pub flag: Vec<TomlSubFlag>,
118    #[serde(default)]
119    pub flag_valued: Vec<String>,
120    #[serde(default)]
121    pub wrapper: Option<TomlWrapper>,
122    #[serde(default)]
123    pub write_flags: Vec<String>,
124    /// Path-argument gate co-located with the command (`[command.path_gate]`): the read/write
125    /// role of each path-bearing flag value and of bare positionals. Consulted by
126    /// `pathgate::should_deny` so a `--output`/`-i` path can't ship ungated. Same shape as
127    /// `pathgates.toml`'s `[roles.X]`.
128    #[serde(default)]
129    pub path_gate: Option<crate::pathgate::RoleSpec>,
130    #[serde(default)]
131    pub researched_version: Option<String>,
132    /// Sample invocations that double as test fixtures.
133    /// `examples_safe` must validate as Allowed; `examples_denied` must validate as Denied.
134    /// Use these to exercise aliases and canonical forms (e.g. `mise use` and `mise u`)
135    /// so drift between the TOML and runtime dispatch fails the test suite.
136    #[serde(default)]
137    pub examples_safe: Vec<String>,
138    #[serde(default)]
139    pub examples_denied: Vec<String>,
140    /// Marks this command's leaf invocation as safe inside
141    /// `eval "$(CMD ...)"`. Set on flat commands whose stdout is documented
142    /// shell-init code (e.g. `ssh-agent`). The leaf is the deepest matched
143    /// dispatch node — tagging here does NOT propagate to subs; each sub
144    /// must be tagged independently. Unset = not eval-safe (the default).
145    #[serde(default)]
146    pub eval_safe: Option<bool>,
147    /// Flag allowlist that extends `eval_safe = true` — these `-`-prefixed
148    /// tokens are also permitted inside the substitution. Default empty,
149    /// meaning only the bare form plus positionals are eval-safe.
150    /// Build panics if this is set without `eval_safe = true`.
151    #[serde(default)]
152    pub eval_safe_flags: Vec<String>,
153    /// Per-valued-flag value allowlist. Maps each valued flag (which
154    /// MUST also appear in `eval_safe_flags`) to the set of values
155    /// permitted in eval substitutions. Use for tools where the flag's
156    /// value determines stdout shape (`aws --format env` vs
157    /// `--format json`). Default empty = no value restriction beyond
158    /// the bare-literal alphabet.
159    #[serde(default)]
160    pub eval_safe_flag_values: std::collections::HashMap<String, Vec<String>>,
161    /// Flags where AT LEAST ONE must appear in the eval substitution.
162    /// Use for tools whose bare invocation isn't shell-init code:
163    /// `fzf` is interactive without `--bash|--zsh|--fish|--nushell`.
164    /// Every entry must also appear in `eval_safe_flags`. Default
165    /// empty = no required flags (bare invocation is fine).
166    #[serde(default)]
167    pub eval_safe_required_flags: Vec<String>,
168    /// Shortcut: every invocation of this command is denied. Used in custom
169    /// TOMLs to lock down a built-in (e.g. `name = "gh", deny = true` in
170    /// `.safe-chains.toml` denies every gh form for that project).
171    #[serde(default)]
172    pub deny: Option<bool>,
173    /// Alternate grammar engaged when standard sub-dispatch finds no match.
174    /// Only meaningful for handler-using commands (e.g. tilt's Ruby template
175    /// engine fallback when no Kubernetes tilt sub matches). The handler is
176    /// responsible for invoking it via `registry::try_fallback_grammar()`.
177    #[serde(default)]
178    pub fallback: Option<TomlFallback>,
179    /// Named flag policies the handler references by string key. Used when
180    /// a handler's dispatch logic genuinely can't move to TOML (e.g. gh's
181    /// sub × action matrix) but the per-policy WordSets are still data that
182    /// should live in TOML. The handler reads them via
183    /// `registry::check_handler_policy(cmd, key, tokens)`.
184    #[serde(default)]
185    pub handler_policy: std::collections::HashMap<String, TomlHandlerPolicy>,
186    /// Parent × action → policy matrices. One block declares: "for
187    /// these parent subcommand names, each of these action verbs maps
188    /// to a named `handler_policy` and validates at this safety level."
189    /// Lets handlers express their dispatch tables as data instead of
190    /// `match` arms. Walked by `registry::try_matrix_dispatch()`.
191    #[serde(default)]
192    pub matrix: Vec<TomlMatrix>,
193    /// A `verb-chain` grammar (`mlr`): a strict main-flag region followed by a
194    /// `then`-chain of allowlisted verbs. Fully declarative — no handler needed.
195    #[serde(default)]
196    pub verb_chain: Option<TomlVerbChain>,
197    /// Declarative facet behavior (`[command.behavior]`) — the non-legacy classification
198    /// path. When present, the engine resolves this command by building a `Profile` from the
199    /// declared operation + operand-role + flags (see `engine::resolve::resolve_behavior`),
200    /// retiring a hardcoded `RESOLVERS` entry. The legacy `level` remains only as the
201    /// fallback the engine already overrides.
202    #[serde(default)]
203    pub behavior: Option<TomlBehavior>,
204    /// What this command's STDOUT can name (`[command.output]`) — the axis that decides whether a
205    /// `$(…)` around it yields a bounded path or an unknowable one. Absent (the default) means
206    /// unpinnable: the substitution worst-cases exactly as it always has. See
207    /// docs/design/behavioral-taxonomy-substitution-locus.md.
208    #[serde(default)]
209    pub output: Option<TomlOutput>,
210    /// What this command writes in its folder without naming a path; as on a sub.
211    #[serde(default)]
212    pub writes_cwd: Option<String>,
213    #[serde(default)]
214    pub output_dirs: Vec<String>,
215}
216
217/// `[command.output]` — a researched claim about where this command's stdout can POINT. It is a
218/// separate axis from every facet: how safe a command is to RUN says nothing about what its output
219/// names (`echo` is inert and `$(echo /etc/shadow)` names a credential file), so this is declared
220/// per command or not at all.
221#[derive(Debug, Deserialize)]
222#[serde(deny_unknown_fields)]
223pub(super) struct TomlOutput {
224    /// `operands` — output names paths beneath the command's own path operands (`fd`, `git
225    /// ls-files`); `cwd` — output names the working directory (`pwd`).
226    pub locus_from: String,
227    /// Flags under which the claim does NOT hold, because they change what stdout CONTAINS.
228    /// `fd -x cat {}` prints file contents rather than paths, and `fd -l` prints `ls -l` rows —
229    /// neither is a path any more, so the locus rule cannot describe them. Any of these present
230    /// makes the substitution unpinnable again.
231    #[serde(default)]
232    pub invalidated_by: Vec<String>,
233    /// Value-taking flags, so their VALUE is not mistaken for an operand (`head -n 5` takes no
234    /// file). Carried here rather than read off the legacy top-level `valued` for the same reason
235    /// `[command.behavior]` carries its own grammar: this claim is researched as a unit, and a
236    /// silently-shared list would let an unrelated edit change what counts as a root.
237    #[serde(default)]
238    pub valued: Vec<String>,
239    /// Flags of which at least ONE must be present, or the claim does not hold. The inverse of
240    /// `invalidated_by`, and needed by any command whose default output is not paths at all:
241    /// `git diff` prints a PATCH, and only `--name-only` turns it into a list of paths. Empty
242    /// (the normal case) means the claim holds for the bare invocation.
243    #[serde(default)]
244    pub requires: Vec<String>,
245}
246
247/// A command's declarative facet behavior (`[command.behavior]`). Field values that name a
248/// facet term are the kebab strings from `engine::facet` (`operation = "observe"`); the build
249/// maps them via `FacetTerm::from_term` and PANICS (naming the command) on an unknown term, so
250/// a typo can't silently mis-classify. The behavior carries its OWN flag grammar
251/// (`standalone`/`valued`), independent of the legacy top-level `standalone` — `rm`'s legacy
252/// flag set is restricted to `--help`/`--version` (so the legacy fallback can't fail-open on
253/// `rm -rf`), while its behavior grammar is the full destructive set.
254#[derive(Debug, Deserialize)]
255#[serde(deny_unknown_fields)]
256pub(super) struct TomlBehavior {
257    /// The act each operand capability performs — an `Operation` term
258    /// (`observe`/`create`/`mutate`/`destroy`/…).
259    pub operation: String,
260    /// How bare positionals are touched: `none` | `read` | `write` | `pattern-then-read` |
261    /// `transfer` (the closed set the `Operands` enum encodes).
262    pub positionals: String,
263    /// Scale model: `single` (every read is one item — cat/head) or `breadth`
264    /// (count/glob/recursion widen it — rm/mkdir). Defaults to `single`.
265    #[serde(default)]
266    pub scale: Option<String>,
267    /// Boolean flags this command accepts (behavior's own grammar). Single-dash single-char
268    /// tokens (`-r`) cluster; `--long` tokens are matched whole.
269    #[serde(default)]
270    pub standalone: Vec<String>,
271    /// Value-taking flags (consume the next token or a glued `=value`).
272    #[serde(default)]
273    pub valued: Vec<String>,
274    /// Accept the obsolete `-NUM` count shorthand (`head -20`).
275    #[serde(default)]
276    pub numeric_shorthand: Option<bool>,
277    /// Per-flag facet deltas — a flag whose presence widens scale (`"-r" = { scale =
278    /// "unbounded" }`), consumes a path value, or supplies a pattern.
279    #[serde(default)]
280    pub flags: std::collections::HashMap<String, TomlBehaviorFlag>,
281    /// Thin custom hook for the irreducible token logic a declaration can't express
282    /// (`grep`'s pattern-vs-file disambiguation). Composes: it returns the classified operand
283    /// set; the facets + level projection stay declarative. Absent = pure declarative.
284    #[serde(default)]
285    pub hook: Option<String>,
286    /// Transfer semantics (`[command.behavior.transfer]`), REQUIRED when `positionals =
287    /// "transfer"` — the source-operand operation and the clobber/recursion flag sets that a
288    /// `cp`/`mv`/`ln`-shaped command differs on.
289    #[serde(default)]
290    pub transfer: Option<TomlTransfer>,
291}
292
293/// One flag's contribution to a `[command.behavior]` profile: a scale bump when present, and/or
294/// a path role on the flag's VALUE (a valued flag whose value is a path safe-chains must gate,
295/// e.g. `touch -r REF` reads REF's timestamp — folds the `[command.path_gate]` idea into behavior).
296#[derive(Debug, Deserialize)]
297#[serde(deny_unknown_fields)]
298pub(super) struct TomlBehaviorFlag {
299    /// Scale bump when present (`"-r" = { scale = "unbounded" }`).
300    #[serde(default)]
301    pub scale: Option<String>,
302    /// The flag's VALUE is a path with this role: `read` (gated by its read locus) or `write`
303    /// (gated by its write locus). The flag must be a valued flag (in `valued`).
304    #[serde(default)]
305    pub kind: Option<String>,
306}
307
308/// A `verb-chain` command grammar: `CMD [main-flags…] verb [args…] then verb [args…] …`
309/// (`mlr`). The main-flag region is a STRICT allowlist (an unlisted flag denies — so a
310/// mutating flag like mlr's `-I`/`--in-place`, omitted, is caught by omission); the verb
311/// region is a `then`-chain where every verb NAME must be on the `verbs` allowlist (verb
312/// ARGS are open-ended and not inspected — a pure verb has no shell/file escape).
313#[derive(Debug, Deserialize)]
314#[serde(deny_unknown_fields)]
315pub(super) struct TomlVerbChain {
316    #[serde(default)]
317    pub level: Option<TomlLevel>,
318    /// The chain separator keyword (mlr: `then`). Defaults to `then`.
319    #[serde(default)]
320    pub separator: Option<String>,
321    /// Boolean main flags (no value). SAFETY: every value-TAKING main flag must go in
322    /// `main_valued` instead, or the walk mistakes its value for the verb boundary and a
323    /// later mutating flag slips past in verb-land.
324    #[serde(default)]
325    pub main_standalone: Vec<String>,
326    /// Value-taking main flags (`--from FILE`, `--ifs ,`), each consuming the next token.
327    #[serde(default)]
328    pub main_valued: Vec<String>,
329    /// Variadic main flags (mlr `--mfrom A B …`) that consume tokens until a `--` terminator.
330    #[serde(default)]
331    pub main_variadic: Vec<String>,
332    /// The allowlist of verb names permitted in every `then`-segment.
333    #[serde(default)]
334    pub verbs: Vec<String>,
335}
336
337#[derive(Debug, Deserialize)]
338#[serde(deny_unknown_fields)]
339pub(super) struct TomlMatrix {
340    pub parents: Vec<String>,
341    pub level: TomlLevel,
342    pub actions: std::collections::HashMap<String, TomlMatrixAction>,
343}
344
345#[derive(Debug, Deserialize)]
346#[serde(untagged)]
347pub(super) enum TomlMatrixAction {
348    /// Shorthand: `list = "policy_name"` — references handler_policy by
349    /// name; no guard required.
350    Policy(String),
351    /// Detailed form: `download = { policy = "release_download", guard
352    /// = "--output", guard_short = "-O" }`. The guard flag must be
353    /// present in the action's args for the dispatch to succeed.
354    Detailed(TomlMatrixActionDetailed),
355}
356
357#[derive(Debug, Deserialize)]
358#[serde(deny_unknown_fields)]
359pub(super) struct TomlMatrixActionDetailed {
360    pub policy: String,
361    #[serde(default)]
362    pub guard: Option<String>,
363    #[serde(default)]
364    pub guard_short: Option<String>,
365}
366
367#[derive(Debug, Clone, Copy, Deserialize)]
368pub(super) enum TomlLevel {
369    Inert,
370    SafeRead,
371    SafeWrite,
372}
373
374impl From<TomlLevel> for SafetyLevel {
375    fn from(l: TomlLevel) -> Self {
376        match l {
377            TomlLevel::Inert => SafetyLevel::Inert,
378            TomlLevel::SafeRead => SafetyLevel::SafeRead,
379            TomlLevel::SafeWrite => SafetyLevel::SafeWrite,
380        }
381    }
382}
383
384#[derive(Debug)]
385pub struct CommandSpec {
386    pub name: String,
387    pub description: String,
388    pub aliases: Vec<String>,
389    pub url: String,
390    pub category: String,
391    /// Upstream version of the underlying tool that was researched
392    /// when this spec was last updated. Free-form string — e.g.
393    /// `"1.9.0"`, `"v5.10.3"`, `"2026-05-08 master"`,
394    /// `"@northflank/cli 0.10.15"`. Internal-only: not rendered in
395    /// docs or used at runtime. Surfaces in tests and as a tripwire
396    /// when researching newer versions of the same tool.
397    pub researched_version: Option<String>,
398    /// Sample invocations that the registry test runs through `is_safe_command`.
399    /// Each `examples_safe` entry must produce `Verdict::Allowed`.
400    pub examples_safe: Vec<String>,
401    /// Sample invocations that must be denied. Use these to lock in security
402    /// boundaries (e.g. `srb tc --metrics-file=/etc/passwd` should always
403    /// be denied; recording it here catches regressions).
404    pub examples_denied: Vec<String>,
405    /// True when this command's bare invocation (no sub) is tagged as
406    /// safe-to-eval. Walked by `registry::is_eval_safe_invocation()`.
407    pub eval_safe: bool,
408    /// Flag allowlist extending `eval_safe` — flags permitted in the
409    /// substituted invocation when the walker stops at this node.
410    pub eval_safe_flags: Vec<String>,
411    /// Per-valued-flag value allowlist. When the walker hits a flag
412    /// listed here, the value following the flag (separated by `=` or
413    /// space) must be in this list.
414    pub eval_safe_flag_values: std::collections::HashMap<String, Vec<String>>,
415    /// Flags where at least one must appear in the substituted
416    /// invocation. Empty = no required-flag constraint.
417    pub eval_safe_required_flags: Vec<String>,
418    /// The command's own path-argument gate (`[command.path_gate]`), if declared. Read by
419    /// `registry::command_path_gate` → `pathgate::should_deny`.
420    pub(super) path_gate: Option<crate::pathgate::RoleSpec>,
421    /// `[[command.flag]]`, read by `registry::command_flag_archetypes` → `engine::resolve::resolve`.
422    pub(super) archetype_flags: super::build::ArchetypeFlags,
423    /// Declarative facet behavior (`[command.behavior]`), lowered to typed facet enums. Read
424    /// by `registry::command_behavior` → `engine::resolve::resolve_behavior`. When present,
425    /// the engine classifies this command from its declared facets instead of a Rust resolver.
426    pub(super) behavior: Option<BehaviorSpec>,
427    /// Lowered `[command.output]` — read by `registry::command_output_locus` →
428    /// `engine::resolve::substitution_locus`, which decides whether a `$(…)` around this command
429    /// yields a bounded path instead of the unpinnable sentinel.
430    pub(super) output: Option<OutputSpec>,
431    pub(super) writes_cwd: Option<crate::pathctx::anchor::Anchor>,
432    pub(super) line_checks: LineChecks,
433    pub(super) hooks: SpecHooks,
434    pub(super) kind: DispatchKind,
435}
436
437#[derive(Debug, Clone)]
438pub(super) enum DispatchKind {
439    Policy {
440        policy: OwnedPolicy,
441        level: SafetyLevel,
442        /// A predicate the first positional must meet, from the sub's `positional_shape`.
443        shape: Option<crate::policy::PositionalShape>,
444    },
445    FirstArg {
446        patterns: Vec<String>,
447        level: SafetyLevel,
448        /// Flags the glob family accepts. Empty = not yet researched (grandfathered); see
449        /// `glob_presents_unlisted_flag`.
450        standalone: Vec<String>,
451        valued: Vec<String>,
452        /// Flags admitted only when their value is a loopback endpoint.
453        loopback_valued: Vec<String>,
454    },
455    RequireAny {
456        require_any: Vec<String>,
457        policy: OwnedPolicy,
458        level: SafetyLevel,
459        accept_bare_help: bool,
460    },
461    Branching {
462        subs: Vec<SubSpec>,
463        bare_flags: Vec<String>,
464        bare_ok: bool,
465        pre_standalone: Vec<String>,
466        pre_valued: Vec<String>,
467        first_arg: Vec<String>,
468        first_arg_level: SafetyLevel,
469        /// Flags the `first_arg` glob family accepts, as in `DispatchKind::FirstArg`.
470        first_arg_standalone: Vec<String>,
471        first_arg_valued: Vec<String>,
472        first_arg_loopback_valued: Vec<String>,
473        /// First-positional globs that classify the invocation as a credential-read (deny), checked
474        /// after explicit subs and before the allow-glob. Empty for almost every command.
475        credential_first_arg: Vec<String>,
476        /// Accept one leading rustup toolchain selector (`cargo +nightly build`), stripped before
477        /// sub dispatch. From `[command.wrapper] toolchain_selector = true`.
478        toolchain_selector: bool,
479    },
480    WriteFlagged {
481        policy: OwnedPolicy,
482        base_level: SafetyLevel,
483        write_flags: Vec<String>,
484    },
485    DelegateAfterSeparator(DelegateAfter),
486    DelegateSkip {
487        skip: usize,
488        shape: Option<crate::policy::PositionalShape>,
489    },
490    Wrapper {
491        standalone: Vec<String>,
492        valued: Vec<String>,
493        positional_skip: usize,
494        separator: Option<String>,
495        bare_ok: bool,
496    },
497    /// A `verb-chain` grammar (`mlr`): a strict main-flag region + a `then`-chain of
498    /// allowlisted verbs. See `dispatch::dispatch_verb_chain`.
499    VerbChain(VerbChainSpec),
500    /// A code-execution command whose verdict is the execution-origin gate (worktree code
501    /// allows, foreign denies), not a flat level. See `dispatch::dispatch_executor` and
502    /// docs/design/behavioral-taxonomy-execution-origin.md.
503    Executor {
504        policy: OwnedPolicy,
505        /// Verdict for a flag-only invocation with no executor (`python3 --version`).
506        level: SafetyLevel,
507        kind: ExecutorKind,
508        /// A valued flag whose value REDIRECTS the executor out of the project
509        /// (`cargo run --manifest-path DIR/Cargo.toml`) — its value is locus-gated like a
510        /// file executor. Only meaningful for `ExecutorKind::Project`.
511        redirect_flag: Option<String>,
512        /// A predicate the executor path must satisfy, else deny (`ExecutorKind::File`).
513        /// `go run` uses `go-package` so a remote import path (`rsc.io/x@latest`) is not
514        /// treated as a worktree executor.
515        shape: Option<crate::policy::PositionalShape>,
516        /// Whether the tokens AFTER the executor path are the SCRIPT's argv rather than this
517        /// command's own arguments. `python3 ./task.py --flag arg` passes them; `karma start
518        /// ./a.conf.js` does not, and a second path there is a second CONFIG it will load.
519        ///
520        /// Decides how much of the invocation the flag policy governs, so it defaults to FALSE —
521        /// the enforcing answer. See `dispatch::dispatch_executor`.
522        passes_argv: bool,
523    },
524    Custom {
525        #[allow(dead_code)]
526        handler_name: String,
527        doc_body: Option<String>,
528        /// TOML-declared subs the handler may consult via
529        /// `registry::try_sub_dispatch()`. Empty unless the handler
530        /// uses the helper.
531        subs: Vec<SubSpec>,
532        /// TOML-declared alternate grammar the handler may consult
533        /// via `registry::try_fallback_grammar()`. `None` unless the
534        /// handler uses the helper.
535        fallback: Option<FallbackSpec>,
536        /// Named flag policies the handler consults via
537        /// `registry::check_handler_policy()`. Empty unless the handler
538        /// has dispatch logic that picks a policy by name at runtime.
539        handler_policies: std::collections::HashMap<String, OwnedPolicy>,
540        /// Sub × action matrices the handler walks via
541        /// `registry::try_matrix_dispatch()`.
542        matrices: Vec<MatrixSpec>,
543    },
544}
545
546/// How a code-execution command locates its executor. `File`: the first positional is the
547/// executor path (`bash x.sh`, `python3 x.py`, `go run ./cmd`). `Project`: the current
548/// project is the executor and there is no path operand (`cargo run`, `dotnet run`).
549#[derive(Debug, Clone, Copy, PartialEq, Eq)]
550pub(super) enum ExecutorKind {
551    File,
552    Project,
553}
554
555pub use super::policy::OwnedPolicy;
556
557#[derive(Debug, Clone)]
558pub(super) struct MatrixSpec {
559    pub parents: Vec<String>,
560    pub level: SafetyLevel,
561    pub actions: std::collections::HashMap<String, MatrixAction>,
562}
563
564#[derive(Debug, Clone)]
565pub(super) struct VerbChainSpec {
566    pub level: SafetyLevel,
567    pub separator: String,
568    pub main_standalone: Vec<String>,
569    pub main_valued: Vec<String>,
570    pub main_variadic: Vec<String>,
571    pub verbs: std::collections::HashSet<String>,
572}
573
574#[derive(Debug, Clone)]
575pub(super) struct FallbackSpec {
576    pub policy: OwnedPolicy,
577    pub level: SafetyLevel,
578    pub positional_shape: Option<crate::policy::PositionalShape>,
579    /// When set, the first positional is an EXECUTOR (a script/package the command runs),
580    /// gated by the execution-origin engine instead of the flat `level`. `ExecutorKind::File`
581    /// is the only form used by fallbacks (interpreters). See `dispatch::dispatch_executor`.
582    pub executor: Option<ExecutorKind>,
583    /// See `DispatchKind::Executor::redirect_flag` (unused for `File` fallbacks).
584    pub executor_redirect_flag: Option<String>,
585    /// See `DispatchKind::Executor::passes_argv`, set by interpreters, whose trailing tokens are argv.
586    pub passes_argv: bool,
587    pub write_flags: Vec<String>,
588}