Skip to main content

safe_chains/registry/
types.rs

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