use std::collections::HashMap;
use crate::policy::{FlagTolerance, UnknownTolerance};
use crate::verdict::SafetyLevel;
use super::types::*;
macro_rules! fail {
($($arg:tt)*) => { return Err(format!($($arg)*)) };
}
macro_rules! ensure {
($cond:expr, $($arg:tt)*) => {
if !($cond) {
return Err(format!($($arg)*));
}
};
}
#[path = "build_archetype_flags.rs"]
mod archetype_flags;
#[path = "build_lower.rs"]
mod lower;
pub(crate) use archetype_flags::ArchetypeFlags;
use lower::{lower_behavior, lower_output};
pub(super) fn build_policy(
standalone: Vec<String>,
valued: Vec<String>,
optional_valued: Vec<String>,
bare: Option<bool>,
max_positional: Option<usize>,
tolerate_unknown_short: Option<bool>,
tolerate_unknown_long: Option<bool>,
numeric_dash: Option<bool>,
) -> OwnedPolicy {
let (mut standalone, mut valued) = (standalone, valued);
for flag in optional_valued {
standalone.push(flag.clone());
valued.push(flag);
}
let unknown = match (tolerate_unknown_short.unwrap_or(false), tolerate_unknown_long.unwrap_or(false)) {
(false, false) => UnknownTolerance::Strict,
(true, false) => UnknownTolerance::Short,
(false, true) => UnknownTolerance::Long,
(true, true) => UnknownTolerance::Both,
};
OwnedPolicy {
standalone,
valued,
bare: bare.unwrap_or(true),
max_positional,
min_positional: None,
tolerance: FlagTolerance { unknown, numeric_dash: numeric_dash.unwrap_or(false), single_dash_words: false },
passthrough: None,
}
}
fn build_matrix(toml: TomlMatrix) -> MatrixSpec {
let actions = toml
.actions
.into_iter()
.map(|(name, action)| {
let built = match action {
TomlMatrixAction::Policy(policy_key) => MatrixAction { policy_key, guard: None, guard_short: None },
TomlMatrixAction::Detailed(d) => MatrixAction { policy_key: d.policy, guard: d.guard, guard_short: d.guard_short },
};
(name, built)
})
.collect();
MatrixSpec { parents: toml.parents, level: toml.level.into(), actions }
}
fn build_handler_policy(toml: TomlHandlerPolicy) -> OwnedPolicy {
build_policy(
toml.standalone, toml.valued, toml.optional_valued, toml.bare, toml.max_positional, toml.tolerate_unknown_short,
toml.tolerate_unknown_long, toml.numeric_dash,
)
}
fn build_verb_chain(toml: TomlVerbChain) -> VerbChainSpec {
VerbChainSpec {
level: toml.level.unwrap_or(TomlLevel::Inert).into(),
separator: toml.separator.unwrap_or_else(|| "then".to_string()),
main_standalone: toml.main_standalone,
main_valued: toml.main_valued,
main_variadic: toml.main_variadic,
verbs: toml.verbs.into_iter().collect(),
}
}
fn build_fallback(parent: &str, toml: TomlFallback) -> Result<FallbackSpec, String> {
let policy = build_policy(
toml.standalone, toml.valued, toml.optional_valued, toml.bare, toml.max_positional, toml.tolerate_unknown_short,
toml.tolerate_unknown_long, toml.numeric_dash,
);
let level: SafetyLevel = toml.level.unwrap_or(TomlLevel::Inert).into();
let positional_shape = crate::policy::PositionalShape::from_toml(toml.positional_shape.as_deref(), &format!("{parent} fallback"))?;
let executor = match toml.executor.as_deref() {
None => None,
Some(name) => match ExecutorKind::from_name(name) {
Some(kind) => Some(kind),
None => fail!("{parent}: unknown fallback executor `{name}` (known: file, project)"),
},
};
Ok(FallbackSpec {
policy,
level,
positional_shape,
executor,
executor_redirect_flag: toml.executor_redirect_flag,
passes_argv: toml.passes_argv.unwrap_or(false),
write_flags: toml.write_flags,
})
}
fn check_no_legacy_positional_style(name: &str, ps: Option<bool>) -> Result<(), String> {
if ps.is_some() {
fail!(
"command '{name}': `positional_style` was removed. Use \
`tolerate_unknown_short = true` for tools with single-dash \
flags (pdftotext -help, sample -mayDie). Use \
`tolerate_unknown_long = true` ONLY for tools whose \
double-dash flag surface is genuinely unbounded (AWS CLI \
style); double-dash unknowns silently pass when this is \
on, which has caused safety bugs. Most tools need neither."
);
}
Ok(())
}
fn filter_candidates(subs: Vec<TomlSub>) -> Result<impl Iterator<Item = TomlSub>, String> {
for s in &subs {
ensure!(
!s.candidate.unwrap_or(false) || s.sub.is_empty(),
"sub `{}`: a `candidate` sub is filtered out, so its nested subs are dead — drop the \
nested subs, or drop `candidate` if the sub is meant to be live",
s.name,
);
}
for s in &subs {
if !s.per_database {
continue;
}
let clash = subs.iter().find(|o| o.name.starts_with(&format!("{}:", s.name)));
ensure!(
clash.is_none(),
"sub `{}`: `per_database` is unsound on a task that prefixes another (`{}`) — a \
suffix cannot be told from a subtask name. Enumerate the variants, or drop the flag",
s.name,
clash.map(|c| c.name.as_str()).unwrap_or(""),
);
}
Ok(subs.into_iter().filter(|s| !s.candidate.unwrap_or(false)))
}
fn first_arg_matches(name: &str, patterns: &[String]) -> bool {
patterns.iter().any(|p| match p.strip_suffix('*') {
Some(prefix) => name.starts_with(prefix),
None => p == name,
})
}
fn assert_no_candidate_shadowed_by_glob(parent: &str, subs: &[TomlSub], first_arg: &[String]) -> Result<(), String> {
if first_arg.is_empty() {
return Ok(());
}
for s in subs {
if s.candidate.unwrap_or(false) && first_arg_matches(&s.name, first_arg) {
fail!(
"'{parent}' sub `{}` is `candidate = true` but its name is MATCHED by the sibling \
first_arg glob {first_arg:?} — it would fall through the filter and AUTO-APPROVE \
(a silent deny→allow inversion). Use `profile`/an explicit sub-sub to deny it, or \
drop it from the glob.",
s.name,
);
}
}
Ok(())
}
pub(super) fn build_subs(
parent: &str,
toml: TomlSub,
handler_policies: &std::collections::HashMap<String, OwnedPolicy>,
) -> Result<Vec<SubSpec>, String> {
let aliases = toml.aliases.clone();
let canonical = build_sub(parent, toml, handler_policies)?;
let mut out = Vec::with_capacity(1 + aliases.len());
for alias in aliases {
out.push(SubSpec {
name: alias,
kind: canonical.kind.clone(),
name_match: canonical.name_match,
policy_ref: canonical.policy_ref.clone(),
profile: canonical.profile.clone(),
flags: canonical.flags.clone(),
allowed_standalone: canonical.allowed_standalone.clone(),
allowed_valued: canonical.allowed_valued.clone(),
allowed_unknown: canonical.allowed_unknown,
eval_safe: canonical.eval_safe,
eval_safe_flags: canonical.eval_safe_flags.clone(),
eval_safe_flag_values: canonical.eval_safe_flag_values.clone(),
eval_safe_required_flags: canonical.eval_safe_required_flags.clone(),
output: canonical.output.clone(),
network_destination: canonical.network_destination,
destination_flag: canonical.destination_flag.clone(),
loopback_valued: canonical.loopback_valued.clone(),
loopback_effect: canonical.loopback_effect,
output_path_flags: canonical.output_path_flags.clone(),
writes_cwd: canonical.writes_cwd,
});
}
out.push(canonical);
Ok(out)
}
fn assert_sub_provenance(parent: &str, toml: &TomlSub) -> Result<(), String> {
let cited = |o: &Option<String>| o.as_deref().is_some_and(|s| !s.trim().is_empty());
let judged = |o: &Option<String>| o.as_deref().is_none_or(|s| !s.trim().is_empty());
if let Some(p) = &toml.profile {
ensure!(
crate::engine::archetype::archetype(p).is_some(),
"{parent} sub `{}`: profile `{p}` is not a known archetype (archetypes.toml)",
toml.name,
);
ensure!(cited(&toml.fact), "{parent} sub `{}`: `profile` requires a `fact`", toml.name);
ensure!(cited(&toml.source), "{parent} sub `{}`: `profile` requires a `source`", toml.name);
ensure!(judged(&toml.judgment), "{parent} sub `{}`: `judgment`, if given, must not be blank", toml.name);
ensure!(
!toml.standalone.is_empty()
|| !toml.valued.is_empty()
|| toml.tolerate_unknown_short == Some(true)
|| toml.tolerate_unknown_long == Some(true)
|| !toml.flag.is_empty(),
"{parent} sub `{}`: a profiled sub must declare its flag surface — list `standalone`/\
`valued`, or set `tolerate_unknown_long = true` if it is genuinely unbounded",
toml.name,
);
ensure!(toml.sub.is_empty(), "{parent} sub `{}`: a profiled sub must be a leaf (no nested subs)", toml.name);
}
ensure!(
toml.network_destination != Some(true) || toml.profile.is_some(),
"{parent} sub `{}`: `network_destination` requires a `profile`",
toml.name,
);
ensure!(
toml.destination_flag.is_none() || toml.network_destination == Some(true),
"{parent} sub `{}`: `destination_flag` requires `network_destination`",
toml.name,
);
ensure!(
toml.output_path_flags.is_empty() || toml.profile.is_some(),
"{parent} sub `{}`: `output_path_flags` requires a `profile`",
toml.name,
);
for f in &toml.flag {
ensure!(
f.classifies == "unclassified" || crate::engine::archetype::archetype(&f.classifies).is_some(),
"{parent} sub `{}` flag `{}`: classifies `{}` is not a known archetype",
toml.name,
f.name,
f.classifies,
);
ensure!(cited(&f.fact), "{parent} sub `{}` flag `{}`: requires a `fact`", toml.name, f.name);
ensure!(cited(&f.source), "{parent} sub `{}` flag `{}`: requires a `source`", toml.name, f.name);
ensure!(judged(&f.judgment), "{parent} sub `{}` flag `{}`: `judgment`, if given, must not be blank", toml.name, f.name);
ensure!(
!(f.when_absent == Some(true) && f.value_prefix.is_some()),
"{parent} sub `{}` flag `{}`: `when_absent` and `value_prefix` are mutually exclusive",
toml.name,
f.name,
);
}
Ok(())
}
fn assert_loopback_localizes_is_coherent(parent: &str, name: &str, toml: &TomlSub) -> Result<(), String> {
ensure!(
toml.loopback_valued.is_empty() || toml.profile.is_some(),
"{parent} sub `{name}`: `loopback_valued` needs `profile` — the gate is only consulted on \
a profiled sub, so here it would do nothing at all",
);
if !toml.loopback_localizes.unwrap_or(false) {
return Ok(());
}
ensure!(
!toml.loopback_valued.is_empty(),
"{parent} sub `{name}`: `loopback_localizes` requires a `loopback_valued` flag — without \
one nothing can establish that the destination is this machine",
);
let profile = toml.profile.as_deref().unwrap_or_default();
let operation = crate::engine::archetype::archetype(profile).map(|c| c.operation);
ensure!(
operation != Some(crate::engine::facet::Operation::Destroy),
"{parent} sub `{name}`: `profile = \"{profile}\"` carries `operation = destroy` and may \
not set `loopback_localizes` — a loopback endpoint cannot be verified (an SSH tunnel makes \
localhost mean production), and that is only unrecoverable for destroy",
);
Ok(())
}
pub(super) fn build_sub(
parent: &str,
mut toml: TomlSub,
handler_policies: &std::collections::HashMap<String, OwnedPolicy>,
) -> Result<SubSpec, String> {
check_no_legacy_positional_style(&toml.name, toml.positional_style)?;
let name = toml.name.clone();
let policy_ref = toml.policy.clone();
let profile = toml.profile.clone();
assert_sub_provenance(parent, &toml)?;
assert_no_candidate_shadowed_by_glob(&format!("{parent} {}", toml.name), &toml.sub, &toml.first_arg)?;
let flags = std::mem::take(&mut toml.flag)
.into_iter()
.map(|f| crate::registry::types::FlagProvenance {
name: f.name,
classifies: f.classifies,
value_prefix: f.value_prefix,
when_absent: f.when_absent.unwrap_or(false),
})
.collect();
let (allowed_standalone, allowed_valued) = (toml.standalone.clone(), toml.valued.clone());
let allowed_unknown = match (toml.tolerate_unknown_short.unwrap_or(false), toml.tolerate_unknown_long.unwrap_or(false)) {
(false, false) => UnknownTolerance::Strict,
(true, false) => UnknownTolerance::Short,
(false, true) => UnknownTolerance::Long,
(true, true) => UnknownTolerance::Both,
};
if profile.is_some() {
toml.bare = Some(false);
toml.standalone = Vec::new();
toml.valued = Vec::new();
toml.max_positional = Some(0);
}
let eval_safe = toml.eval_safe.unwrap_or(false);
let eval_safe_flags = std::mem::take(&mut toml.eval_safe_flags);
let eval_safe_flag_values = std::mem::take(&mut toml.eval_safe_flag_values);
let eval_safe_required_flags = std::mem::take(&mut toml.eval_safe_required_flags);
let network_destination = toml.network_destination.unwrap_or(false);
let destination_flag = toml.destination_flag.clone();
let output_path_flags = toml.output_path_flags.clone();
let loopback_valued = toml.loopback_valued.clone();
let loopback_effect = if toml.loopback_localizes.unwrap_or(false) { LoopbackEffect::Localizes } else { LoopbackEffect::AdmitOnly };
assert_loopback_localizes_is_coherent(parent, &name, &toml)?;
let valued_for_check = toml.valued.clone();
assert_eval_safe_flags_require_tag(parent, &name, eval_safe, &eval_safe_flags)?;
assert_eval_safe_flag_values_consistent(parent, &name, &eval_safe_flags, &eval_safe_flag_values)?;
assert_eval_safe_valued_flags_declared(parent, &name, &eval_safe_flags, &valued_for_check, &eval_safe_flag_values)?;
assert_eval_safe_required_flags_consistent(parent, &name, &eval_safe_flags, &eval_safe_required_flags)?;
assert_sub_eval_safe_only_on_leaf(parent, &toml)?;
let writes_cwd = super::cwd_writes::lower(parent, &name, toml.writes_cwd.as_deref(), &toml.output_dirs, toml.executor.as_deref())?;
let output = lower_output(&format!("{parent} {name}"), toml.output.as_ref())?;
Ok(SubSpec {
name,
output,
writes_cwd,
name_match: if toml.per_database { NameMatch::WithDatabaseSuffix } else { NameMatch::Exact },
kind: super::passthrough_gate::build_sub_kind(parent, toml, handler_policies)?,
policy_ref,
profile,
flags,
allowed_standalone,
allowed_valued,
allowed_unknown,
eval_safe,
eval_safe_flags,
eval_safe_flag_values,
eval_safe_required_flags,
network_destination,
destination_flag,
loopback_valued,
loopback_effect,
output_path_flags,
})
}
fn assert_eval_safe_flag_values_consistent(
parent: &str,
name: &str,
eval_safe_flags: &[String],
eval_safe_flag_values: &std::collections::HashMap<String, Vec<String>>,
) -> Result<(), String> {
for (flag, values) in eval_safe_flag_values {
if !eval_safe_flags.iter().any(|f| f == flag) {
fail!(
"command '{parent}' sub `{name}` lists `{flag}` in \
`eval_safe_flag_values` but not in `eval_safe_flags`. \
A value allowlist only takes effect when the flag itself \
is allowed. Add `{flag}` to `eval_safe_flags` or remove \
the value entry."
);
}
for value in values {
if value.is_empty() || !value.chars().all(is_bare_literal_char) {
fail!(
"command '{parent}' sub `{name}` has eval_safe_flag_values \
for `{flag}` containing value `{value:?}` with characters \
outside `[a-zA-Z0-9_./=-]`. The allowed-value set must \
itself be bare-literal so it can never embed a shell-\
expansion trigger into the substituted invocation."
);
}
}
}
Ok(())
}
fn is_bare_literal_char(c: char) -> bool {
c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | '=')
}
fn assert_eval_safe_required_flags_consistent(
parent: &str,
name: &str,
eval_safe_flags: &[String],
eval_safe_required_flags: &[String],
) -> Result<(), String> {
for flag in eval_safe_required_flags {
if !eval_safe_flags.iter().any(|f| f == flag) {
fail!(
"command '{parent}' sub `{name}` lists `{flag}` in \
`eval_safe_required_flags` but not in `eval_safe_flags`. \
A required-flag constraint must be a subset of the \
allowed-flag set — otherwise the flag is required AND \
immediately denied. Add `{flag}` to `eval_safe_flags` or \
remove it from `eval_safe_required_flags`."
);
}
}
Ok(())
}
fn assert_eval_safe_valued_flags_declared(
parent: &str,
name: &str,
eval_safe_flags: &[String],
valued: &[String],
eval_safe_flag_values: &std::collections::HashMap<String, Vec<String>>,
) -> Result<(), String> {
for flag in eval_safe_flags {
if !valued.iter().any(|v| v == flag) {
continue;
}
if !eval_safe_flag_values.contains_key(flag) {
fail!(
"command '{parent}' sub `{name}` lists `{flag}` in \
`eval_safe_flags` AND in `valued`, but `{flag}` has no \
entry in `eval_safe_flag_values`. Every valued flag \
tagged eval-safe must declare its value posture: \
either a concrete allowlist of safe values \
(`{flag} = [\"value-a\", \"value-b\"]`) or the \
explicit-unrestricted form (`{flag} = []`) signaling \
the contributor vetted that any value preserves shell-\
init output. Omitting an entry means the walker can't \
tell whether the value-following-flag is supposed to \
be checked, and a future short alias of `{flag}` \
could silently widen the eval-safe surface."
);
}
}
Ok(())
}
fn assert_eval_safe_flags_require_tag(parent: &str, name: &str, eval_safe: bool, flags: &[String]) -> Result<(), String> {
if !flags.is_empty() && !eval_safe {
fail!(
"command '{parent}' sub `{name}` declares `eval_safe_flags` without \
`eval_safe = true`. The flag allowlist only takes effect when the \
sub is tagged eval-safe. Add `eval_safe = true` or drop \
`eval_safe_flags`."
);
}
Ok(())
}
fn assert_sub_eval_safe_only_on_leaf(parent: &str, toml: &TomlSub) -> Result<(), String> {
if toml.eval_safe != Some(true) {
return Ok(());
}
if !toml.sub.is_empty() {
fail!(
"command '{parent}' sub `{}` sets `eval_safe = true` AND has \
nested [[command.sub.sub]] blocks. eval_safe must be tagged on \
a leaf node — move the tag onto the specific sub-sub that emits \
shell-init code. Otherwise the walker accepts any unmatched \
sub-sub name as a positional, which is counter-intuitive.",
toml.name,
);
}
if toml.handler.is_some() {
fail!(
"command '{parent}' sub `{}` sets `eval_safe = true` AND \
`handler = \"...\"`. Handler-based subs run Rust dispatch logic \
whose shape the eval walker cannot introspect — eval-safety \
requires a declarative leaf the registry can reason about.",
toml.name,
);
}
if toml.delegate_after.is_some() || toml.delegate_skip.is_some() {
fail!(
"command '{parent}' sub `{}` sets `eval_safe = true` AND \
delegates to an inner command (delegate_after / delegate_skip). \
The inner command's output is unrelated to this sub's vetting \
— drop `eval_safe`.",
toml.name,
);
}
Ok(())
}
fn assert_eval_safe_tagged_command_has_researched_version(toml: &TomlCommand) -> Result<(), String> {
let command_tagged = toml.eval_safe == Some(true);
let any_sub_tagged = toml_has_any_eval_safe_sub(&toml.sub);
if !command_tagged && !any_sub_tagged {
return Ok(());
}
if toml.researched_version.is_none() {
fail!(
"command '{}' has `eval_safe = true` (on the command or a sub) \
but no `researched_version`. eval-safe tags pin a per-tag trust \
claim against a specific upstream snapshot — add the version \
you researched (e.g. `researched_version = \"v2026.5.3\"`) so \
the next contributor knows what to diff against.",
toml.name,
);
}
Ok(())
}
fn toml_has_any_eval_safe_sub(subs: &[TomlSub]) -> bool {
subs.iter().any(|s| s.eval_safe == Some(true) || toml_has_any_eval_safe_sub(&s.sub))
}
fn assert_command_eval_safe_only_on_leaf(toml: &TomlCommand) -> Result<(), String> {
if toml.eval_safe != Some(true) {
return Ok(());
}
if !toml.sub.is_empty() {
fail!(
"command '{}' sets `eval_safe = true` at the command level AND \
has [[command.sub]] blocks. Move the tag onto the specific \
sub that emits shell-init code (e.g. `mise activate`) — \
command-level tagging on a structured command is counter-\
intuitive.",
toml.name,
);
}
if toml.wrapper.is_some() {
fail!(
"command '{}' sets `eval_safe = true` AND `[command.wrapper]`. \
Wrappers forward to an inner command — tagging the wrapper \
would tag every wrapped invocation. Drop `eval_safe`.",
toml.name,
);
}
if toml.deny.unwrap_or(false) {
fail!(
"command '{}' sets both `deny = true` and `eval_safe = true`. \
These are contradictory — deny silently dominates. Drop one.",
toml.name,
);
}
Ok(())
}
pub(super) fn build_sub_kind_unchecked(
parent: &str,
toml: TomlSub,
handler_policies: &std::collections::HashMap<String, OwnedPolicy>,
) -> Result<DispatchKind, String> {
let policy_free = toml.handler.is_some() || toml.allow_all.is_some() || toml.delegate_after.is_some() || toml.delegate_skip.is_some();
super::policy::min_positional_fits(parent, &toml, policy_free)?;
if let Some(handler_name) = toml.handler {
return Ok(DispatchKind::Custom {
handler_name,
doc_body: toml.doc_body,
subs: Vec::new(),
fallback: None,
handler_policies: std::collections::HashMap::new(),
matrices: Vec::new(),
});
}
if toml.allow_all.unwrap_or(false) {
return Ok(DispatchKind::Policy { policy: OwnedPolicy::allow_all(), level: toml.level.unwrap_or(TomlLevel::Inert).into() });
}
if let Some(sep) = toml.delegate_after {
return Ok(DispatchKind::DelegateAfterSeparator { separator: sep });
}
if let Some(skip) = toml.delegate_skip {
let shape = crate::policy::PositionalShape::from_toml(
toml.positional_shape.as_deref(),
&format!("command '{parent}' sub `{}`", toml.name),
)?;
if shape.is_some() && skip < 2 {
fail!("command '{parent}' sub `{}`: positional_shape needs delegate_skip of 2 or more", toml.name);
}
return Ok(DispatchKind::DelegateSkip { skip, shape });
}
if !toml.sub.is_empty() || !toml.credential_first_arg.is_empty() {
let first_arg_level = toml.level.unwrap_or(TomlLevel::Inert).into();
return Ok(DispatchKind::Branching {
subs: filter_candidates(toml.sub)?
.map(|s| build_subs(parent, s, handler_policies))
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.flatten()
.collect(),
bare_flags: Vec::new(),
bare_ok: toml.nested_bare.unwrap_or(false),
pre_standalone: toml.standalone,
pre_valued: toml.valued,
first_arg: toml.first_arg,
first_arg_level,
first_arg_standalone: toml.first_arg_standalone,
first_arg_valued: toml.first_arg_valued,
first_arg_loopback_valued: toml.first_arg_loopback_valued,
credential_first_arg: toml.credential_first_arg,
toolchain_selector: false,
});
}
build_policy_sub_kind(parent, toml, handler_policies)
}
fn build_policy_sub_kind(
parent: &str,
toml: TomlSub,
handler_policies: &std::collections::HashMap<String, OwnedPolicy>,
) -> Result<DispatchKind, String> {
let mut policy = if let Some(key) = &toml.policy {
if !toml.standalone.is_empty() || !toml.valued.is_empty() {
fail!(
"command '{parent}' sub `{}` sets both `policy = \"{}\"` and \
inline standalone/valued — pick one. Either drop the inline \
lists (and rely on the referenced handler_policy) or drop \
the `policy` field.",
toml.name,
key,
);
}
match handler_policies.get(key).cloned() {
Some(p) => p,
None => fail!(
"command '{parent}' sub `{}` references handler_policy \
`{key}` which is not declared. Add a \
[command.handler_policy.{key}] block or fix the typo.",
toml.name,
),
}
} else {
build_policy(
toml.standalone, toml.valued, toml.optional_valued, toml.bare, toml.max_positional, toml.tolerate_unknown_short,
toml.tolerate_unknown_long, toml.numeric_dash,
)
};
policy.min_positional = toml.min_positional;
policy.passthrough = toml.passthrough.map(super::policy::build_passthrough);
let level: SafetyLevel = toml.level.unwrap_or(TomlLevel::Inert).into();
if let Some(name) = toml.executor.as_deref() {
let Some(kind) = ExecutorKind::from_name(name) else {
fail!("command '{parent}' sub `{}`: unknown executor `{name}` (known: file, project)", toml.name)
};
let shape = crate::policy::PositionalShape::from_toml(
toml.positional_shape.as_deref(),
&format!("command '{parent}' sub `{}`", toml.name),
)?;
return Ok(DispatchKind::Executor {
policy,
level,
kind,
redirect_flag: toml.executor_redirect_flag,
shape,
passes_argv: toml.passes_argv.unwrap_or(false),
});
}
if !toml.write_flags.is_empty() {
return Ok(DispatchKind::WriteFlagged { policy, base_level: level, write_flags: toml.write_flags });
}
if let Some(guard) = toml.guard {
let mut require_any = vec![guard];
if let Some(short) = toml.guard_short {
require_any.push(short);
}
return Ok(DispatchKind::RequireAny { require_any, policy, level, accept_bare_help: true });
}
if !toml.first_arg.is_empty() {
return Ok(DispatchKind::FirstArg {
patterns: toml.first_arg,
level,
standalone: toml.first_arg_standalone,
valued: toml.first_arg_valued,
loopback_valued: toml.first_arg_loopback_valued,
});
}
if !toml.require_any.is_empty() {
return Ok(DispatchKind::RequireAny { require_any: toml.require_any, policy, level, accept_bare_help: false });
}
Ok(DispatchKind::Policy { policy, level })
}
fn assert_flat_or_structured(toml: &TomlCommand) -> Result<(), String> {
if toml.sub.is_empty() {
return Ok(());
}
let mut conflicts = Vec::new();
if !toml.standalone.is_empty() {
conflicts.push("standalone");
}
if !toml.valued.is_empty() {
conflicts.push("valued");
}
if toml.max_positional.is_some() {
conflicts.push("max_positional");
}
if toml.tolerate_unknown_short.is_some() {
conflicts.push("tolerate_unknown_short");
}
if toml.tolerate_unknown_long.is_some() {
conflicts.push("tolerate_unknown_long");
}
if toml.numeric_dash.is_some() {
conflicts.push("numeric_dash");
}
if toml.single_dash_words.is_some() {
conflicts.push("single_dash_words");
}
if !conflicts.is_empty() {
fail!(
"command '{}' mixes flat-style top-level fields ({}) with [[command.sub]] blocks. \
When subs are present these fields are silently dropped. \
Either drop the subs (if the command is flat) or move global \
flags into a [command.wrapper] block.",
toml.name,
conflicts.join(", "),
);
}
Ok(())
}
fn assert_matrix_policy_keys_exist(toml: &TomlCommand) -> Result<(), String> {
if toml.matrix.is_empty() {
return Ok(());
}
for matrix in &toml.matrix {
for (action_name, action) in &matrix.actions {
let policy_key = match action {
TomlMatrixAction::Policy(k) => k,
TomlMatrixAction::Detailed(d) => &d.policy,
};
if !toml.handler_policy.contains_key(policy_key) {
fail!(
"command '{}' matrix action `{}` references \
handler_policy `{}` which is not declared. \
Add a [command.handler_policy.{}] block or fix the typo.",
toml.name,
action_name,
policy_key,
policy_key,
);
}
}
}
Ok(())
}
fn assert_matrix_no_duplicate_parent_action(toml: &TomlCommand) -> Result<(), String> {
if toml.matrix.len() < 2 {
return Ok(());
}
let mut seen: std::collections::HashSet<(String, String)> = std::collections::HashSet::new();
for matrix in &toml.matrix {
for parent in &matrix.parents {
for action in matrix.actions.keys() {
let key = (parent.clone(), action.clone());
if !seen.insert(key) {
fail!(
"command '{}' matrix has duplicate (parent, action) pair \
(`{}`, `{}`). The first match would silently win — \
consolidate into one matrix block or remove the duplicate.",
toml.name,
parent,
action,
);
}
}
}
}
Ok(())
}
fn assert_fallback_requires_handler(toml: &TomlCommand) -> Result<(), String> {
if toml.fallback.is_some() && toml.handler.is_none() {
fail!(
"command '{}' declares [command.fallback] without a handler. \
Fallback grammars are only consulted via \
registry::try_fallback_grammar() from a Rust handler — without \
handler = \"...\" the block is silently dropped. \
Either set handler or remove [command.fallback].",
toml.name,
);
}
Ok(())
}
#[allow(clippy::too_many_lines)]
pub(super) fn build_command(toml: TomlCommand, category: &str) -> Result<CommandSpec, String> {
assert_flat_or_structured(&toml)?;
assert_fallback_requires_handler(&toml)?;
assert_matrix_policy_keys_exist(&toml)?;
assert_no_candidate_shadowed_by_glob(&toml.name, &toml.sub, &toml.first_arg)?;
assert_matrix_no_duplicate_parent_action(&toml)?;
assert_command_eval_safe_only_on_leaf(&toml)?;
assert_eval_safe_tagged_command_has_researched_version(&toml)?;
check_no_legacy_positional_style(&toml.name, toml.positional_style)?;
let cat = category.to_string();
let desc = toml.description.unwrap_or_default();
let researched_version = toml.researched_version;
let examples_safe = toml.examples_safe;
let examples_denied = toml.examples_denied;
let eval_safe = toml.eval_safe.unwrap_or(false);
let eval_safe_flags = toml.eval_safe_flags;
let eval_safe_flag_values = toml.eval_safe_flag_values;
let eval_safe_required_flags = toml.eval_safe_required_flags;
if !eval_safe_flags.is_empty() && !eval_safe {
fail!(
"command '{}' declares `eval_safe_flags` without `eval_safe = true`. \
The flag allowlist only takes effect when the command is tagged \
eval-safe. Add `eval_safe = true` or drop `eval_safe_flags`.",
toml.name,
);
}
assert_eval_safe_flag_values_consistent(&toml.name, "<command>", &eval_safe_flags, &eval_safe_flag_values)?;
assert_eval_safe_valued_flags_declared(&toml.name, "<command>", &eval_safe_flags, &toml.valued, &eval_safe_flag_values)?;
assert_eval_safe_required_flags_consistent(&toml.name, "<command>", &eval_safe_flags, &eval_safe_required_flags)?;
let behavior = lower_behavior(&toml.name, toml.behavior.as_ref())?;
let output = lower_output(&toml.name, toml.output.as_ref())?;
let writes_cwd = super::cwd_writes::lower(&toml.name, "<command>", toml.writes_cwd.as_deref(), &toml.output_dirs, None)?;
let line_checks = LineChecks::lower(&toml.name, toml.env_assignment_positionals, &toml.flag_value_shapes)?;
let archetype_flags = archetype_flags::lower(&toml.name, toml.flag, &toml.flag_valued, &toml.valued, toml.wrapper.as_ref())?;
if toml.deny.unwrap_or(false) {
return Ok(CommandSpec {
name: toml.name,
description: desc,
aliases: toml.aliases,
url: toml.url,
category: cat,
researched_version,
examples_safe,
examples_denied,
eval_safe,
eval_safe_flags: eval_safe_flags.clone(),
eval_safe_flag_values: eval_safe_flag_values.clone(),
eval_safe_required_flags: eval_safe_required_flags.clone(),
path_gate: toml.path_gate,
archetype_flags: archetype_flags.clone(),
behavior: behavior.clone(),
output,
writes_cwd,
line_checks: line_checks.clone(),
kind: DispatchKind::Policy { policy: OwnedPolicy::deny_all(), level: SafetyLevel::Inert },
});
}
if let Some(vc) = toml.verb_chain {
return Ok(CommandSpec {
name: toml.name,
description: desc,
aliases: toml.aliases,
url: toml.url,
category: cat,
researched_version,
examples_safe,
examples_denied,
eval_safe,
eval_safe_flags: eval_safe_flags.clone(),
eval_safe_flag_values: eval_safe_flag_values.clone(),
eval_safe_required_flags: eval_safe_required_flags.clone(),
path_gate: toml.path_gate,
archetype_flags: archetype_flags.clone(),
behavior: behavior.clone(),
output,
writes_cwd,
line_checks: line_checks.clone(),
kind: DispatchKind::VerbChain(build_verb_chain(vc)),
});
}
if let Some(handler_name) = toml.handler {
let handler_policies: std::collections::HashMap<String, OwnedPolicy> =
toml.handler_policy.into_iter().map(|(k, v)| (k, build_handler_policy(v))).collect();
let parent_name = toml.name.clone();
let subs: Vec<SubSpec> = filter_candidates(toml.sub)?
.map(|s| build_subs(&parent_name, s, &handler_policies))
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.flatten()
.collect();
let fallback = toml.fallback.map(|f| build_fallback(&toml.name, f)).transpose()?;
let matrices = toml.matrix.into_iter().map(build_matrix).collect();
return Ok(CommandSpec {
name: toml.name,
description: desc,
aliases: toml.aliases,
url: toml.url,
category: cat,
researched_version,
examples_safe,
examples_denied,
eval_safe,
eval_safe_flags: eval_safe_flags.clone(),
eval_safe_flag_values: eval_safe_flag_values.clone(),
eval_safe_required_flags: eval_safe_required_flags.clone(),
path_gate: toml.path_gate,
archetype_flags: archetype_flags.clone(),
behavior: behavior.clone(),
output,
writes_cwd,
line_checks: line_checks.clone(),
kind: DispatchKind::Custom { handler_name, doc_body: toml.doc_body, subs, fallback, handler_policies, matrices },
});
}
if let Some(w) = toml.wrapper {
if !toml.sub.is_empty() || !toml.bare_flags.is_empty() {
let first_arg_level = toml.level.unwrap_or(TomlLevel::Inert).into();
let parent_name = toml.name.clone();
return Ok(CommandSpec {
name: toml.name,
description: desc,
aliases: toml.aliases,
url: toml.url,
category: cat,
researched_version,
examples_safe,
examples_denied,
eval_safe,
eval_safe_flags: eval_safe_flags.clone(),
eval_safe_flag_values: eval_safe_flag_values.clone(),
eval_safe_required_flags: eval_safe_required_flags.clone(),
path_gate: toml.path_gate,
archetype_flags: archetype_flags.clone(),
behavior: behavior.clone(),
output,
writes_cwd,
line_checks: line_checks.clone(),
kind: DispatchKind::Branching {
bare_flags: toml.bare_flags,
subs: filter_candidates(toml.sub)?
.map(|s| build_subs(&parent_name, s, &std::collections::HashMap::new()))
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.flatten()
.collect(),
pre_standalone: w.standalone,
pre_valued: w.valued,
bare_ok: toml.bare.unwrap_or(false),
first_arg: toml.first_arg,
first_arg_standalone: toml.first_arg_standalone,
first_arg_valued: toml.first_arg_valued,
first_arg_loopback_valued: toml.first_arg_loopback_valued,
first_arg_level,
credential_first_arg: toml.credential_first_arg,
toolchain_selector: w.toolchain_selector.unwrap_or(false),
},
});
}
return Ok(CommandSpec {
name: toml.name,
description: desc,
aliases: toml.aliases,
url: toml.url,
category: cat,
researched_version,
examples_safe,
examples_denied,
eval_safe,
eval_safe_flags: eval_safe_flags.clone(),
eval_safe_flag_values: eval_safe_flag_values.clone(),
eval_safe_required_flags: eval_safe_required_flags.clone(),
path_gate: toml.path_gate,
archetype_flags: archetype_flags.clone(),
behavior: behavior.clone(),
output,
writes_cwd,
line_checks: line_checks.clone(),
kind: DispatchKind::Wrapper {
standalone: w.standalone,
valued: w.valued,
positional_skip: w.positional_skip.unwrap_or(0),
separator: w.separator,
bare_ok: w.bare_ok.unwrap_or(false),
},
});
}
if !toml.sub.is_empty() || !toml.bare_flags.is_empty() {
let first_arg_level = toml.level.unwrap_or(TomlLevel::Inert).into();
let parent_name = toml.name.clone();
return Ok(CommandSpec {
name: toml.name,
description: desc,
aliases: toml.aliases,
url: toml.url,
category: cat,
researched_version,
examples_safe,
examples_denied,
eval_safe,
eval_safe_flags: eval_safe_flags.clone(),
eval_safe_flag_values: eval_safe_flag_values.clone(),
eval_safe_required_flags: eval_safe_required_flags.clone(),
path_gate: toml.path_gate,
archetype_flags: archetype_flags.clone(),
behavior: behavior.clone(),
output,
writes_cwd,
line_checks: line_checks.clone(),
kind: DispatchKind::Branching {
bare_flags: toml.bare_flags,
subs: filter_candidates(toml.sub)?
.map(|s| build_subs(&parent_name, s, &std::collections::HashMap::new()))
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.flatten()
.collect(),
pre_standalone: Vec::new(),
pre_valued: Vec::new(),
bare_ok: toml.bare.unwrap_or(false),
first_arg: toml.first_arg,
first_arg_level,
first_arg_standalone: toml.first_arg_standalone,
first_arg_valued: toml.first_arg_valued,
first_arg_loopback_valued: toml.first_arg_loopback_valued,
credential_first_arg: toml.credential_first_arg,
toolchain_selector: false,
},
});
}
let mut policy = build_policy(
toml.standalone, toml.valued, toml.optional_valued, toml.bare, toml.max_positional, toml.tolerate_unknown_short,
toml.tolerate_unknown_long, toml.numeric_dash,
);
policy.tolerance.single_dash_words = toml.single_dash_words.unwrap_or(false);
let level = toml.level.unwrap_or(TomlLevel::Inert).into();
if !toml.first_arg.is_empty() {
return Ok(CommandSpec {
name: toml.name,
description: desc,
aliases: toml.aliases,
url: toml.url,
category: cat,
researched_version,
examples_safe,
examples_denied,
eval_safe,
eval_safe_flags: eval_safe_flags.clone(),
eval_safe_flag_values: eval_safe_flag_values.clone(),
eval_safe_required_flags: eval_safe_required_flags.clone(),
path_gate: toml.path_gate,
archetype_flags: archetype_flags.clone(),
behavior: behavior.clone(),
output,
writes_cwd,
line_checks: line_checks.clone(),
kind: DispatchKind::FirstArg {
patterns: toml.first_arg,
level,
standalone: toml.first_arg_standalone,
valued: toml.first_arg_valued,
loopback_valued: toml.first_arg_loopback_valued,
},
});
}
if !toml.write_flags.is_empty() {
return Ok(CommandSpec {
name: toml.name,
description: desc,
aliases: toml.aliases,
url: toml.url,
category: cat,
researched_version,
examples_safe,
examples_denied,
eval_safe,
eval_safe_flags: eval_safe_flags.clone(),
eval_safe_flag_values: eval_safe_flag_values.clone(),
eval_safe_required_flags: eval_safe_required_flags.clone(),
path_gate: toml.path_gate,
archetype_flags: archetype_flags.clone(),
behavior: behavior.clone(),
output,
writes_cwd,
line_checks: line_checks.clone(),
kind: DispatchKind::WriteFlagged { policy, base_level: level, write_flags: toml.write_flags },
});
}
if !toml.require_any.is_empty() {
return Ok(CommandSpec {
name: toml.name,
description: desc,
aliases: toml.aliases,
url: toml.url,
category: cat,
researched_version,
examples_safe,
examples_denied,
eval_safe,
eval_safe_flags: eval_safe_flags.clone(),
eval_safe_flag_values: eval_safe_flag_values.clone(),
eval_safe_required_flags: eval_safe_required_flags.clone(),
path_gate: toml.path_gate,
archetype_flags: archetype_flags.clone(),
behavior: behavior.clone(),
output,
writes_cwd,
line_checks: line_checks.clone(),
kind: DispatchKind::RequireAny { require_any: toml.require_any, policy, level, accept_bare_help: false },
});
}
Ok(CommandSpec {
line_checks: line_checks.clone(),
name: toml.name,
description: desc,
aliases: toml.aliases,
url: toml.url,
category: cat,
researched_version,
examples_safe,
examples_denied,
eval_safe,
eval_safe_flags,
eval_safe_flag_values,
eval_safe_required_flags,
path_gate: toml.path_gate,
archetype_flags,
behavior,
output,
writes_cwd,
kind: DispatchKind::Policy { policy, level },
})
}
pub fn load_toml(source: &str, category: &str) -> Result<Vec<CommandSpec>, String> {
let file: TomlFile = match toml::from_str(source) {
Ok(f) => f,
Err(e) => {
let preview: String = source.chars().take(80).collect();
fail!("invalid TOML command definition: {e}\n source begins: {preview}");
}
};
file.command
.into_iter()
.filter(|cmd| !cmd.candidate.unwrap_or(false))
.map(|cmd| build_command(cmd, category))
.collect()
}
pub fn build_registry(specs: Vec<CommandSpec>) -> HashMap<String, CommandSpec> {
let mut map = HashMap::new();
for spec in specs {
insert_spec(&mut map, spec);
}
map
}
pub fn insert_spec(map: &mut HashMap<String, CommandSpec>, spec: CommandSpec) {
map.retain(|_, s| s.name != spec.name);
for alias in &spec.aliases {
map.insert(
alias.clone(),
CommandSpec {
line_checks: spec.line_checks.clone(),
name: spec.name.clone(),
description: spec.description.clone(),
aliases: vec![],
url: spec.url.clone(),
category: spec.category.clone(),
researched_version: spec.researched_version.clone(),
examples_safe: vec![],
examples_denied: vec![],
eval_safe: spec.eval_safe,
eval_safe_flags: spec.eval_safe_flags.clone(),
eval_safe_flag_values: spec.eval_safe_flag_values.clone(),
eval_safe_required_flags: spec.eval_safe_required_flags.clone(),
path_gate: None,
archetype_flags: ArchetypeFlags::default(),
behavior: None,
output: None,
writes_cwd: None,
kind: spec.kind.clone(),
},
);
}
map.insert(spec.name.clone(), spec);
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
#[test]
fn single_dash_words_on_a_structured_command_is_rejected() {
crate::registry::tests::assert_rejected(
"[[command]]\nname = \"tc\"\nsingle_dash_words = true\n[[command.sub]]\nname = \"ls\"\n",
"single_dash_words",
);
}
fn flag_name() -> impl Strategy<Value = String> {
"[a-zA-Z][a-zA-Z0-9_-]{0,8}".prop_map(String::from)
}
fn opt_bool() -> impl Strategy<Value = Option<bool>> {
proptest::option::of(any::<bool>())
}
fn oracle_first_arg_matches(name: &str, patterns: &[String]) -> bool {
patterns.iter().any(|p| match p.strip_suffix('*') {
Some(prefix) => name.starts_with(prefix),
None => p == name,
})
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn build_policy_optional_valued_mechanism_appends_to_both_lists(
standalone in proptest::collection::vec(flag_name(), 0..5),
valued in proptest::collection::vec(flag_name(), 0..5),
optional_valued in proptest::collection::vec(flag_name(), 0..5),
bare in opt_bool(),
max_positional in proptest::option::of(any::<usize>()),
tolerate_unknown_short in opt_bool(),
tolerate_unknown_long in opt_bool(),
numeric_dash in opt_bool(),
) {
let p = build_policy(
standalone.clone(),
valued.clone(),
optional_valued.clone(),
bare,
max_positional,
tolerate_unknown_short,
tolerate_unknown_long,
numeric_dash,
);
let unique: std::collections::BTreeSet<String> =
optional_valued.iter().cloned().collect();
for flag in &unique {
let sa = p.standalone.iter().filter(|f| f.as_str() == flag.as_str()).count();
let va = p.valued.iter().filter(|f| f.as_str() == flag.as_str()).count();
let s_orig = standalone.iter().filter(|f| f.as_str() == flag.as_str()).count();
let v_orig = valued.iter().filter(|f| f.as_str() == flag.as_str()).count();
let s_ov = optional_valued.iter().filter(|f| f.as_str() == flag.as_str()).count();
prop_assert_eq!(
sa,
s_orig + s_ov,
"optional_valued entry {} ended up {} times in standalone (expected originals {} + ov {})",
flag, sa, s_orig, s_ov,
);
prop_assert_eq!(
va,
v_orig + s_ov,
"optional_valued entry {} ended up {} times in valued (expected originals {} + ov {})",
flag, va, v_orig, s_ov,
);
}
prop_assert!(
p.standalone.starts_with(&standalone),
"standalone prefix not preserved: {:?}", p.standalone,
);
prop_assert!(
p.valued.starts_with(&valued),
"valued prefix not preserved: {:?}", p.valued,
);
}
#[test]
fn build_policy_unknown_tolerance_tracks_the_boolean_pair(
short in any::<bool>(),
long in any::<bool>(),
) {
let p = build_policy(
Vec::new(),
Vec::new(),
Vec::new(),
Some(true),
None,
Some(short),
Some(long),
None,
);
let expected = match (short, long) {
(false, false) => UnknownTolerance::Strict,
(true, false) => UnknownTolerance::Short,
(false, true) => UnknownTolerance::Long,
(true, true) => UnknownTolerance::Both,
};
prop_assert_eq!(p.tolerance.unknown, expected);
}
#[test]
fn first_arg_matches_agrees_with_a_simple_reference(
name in "[a-zA-Z0-9][a-zA-Z0-9._:-]{0,12}",
patterns in proptest::collection::vec(
"(-\\*|[a-zA-Z][a-zA-Z0-9._:-]{0,8}(\\*)?)",
0..6,
),
) {
let patterns: Vec<String> = patterns;
prop_assert_eq!(
first_arg_matches(&name, &patterns),
oracle_first_arg_matches(&name, &patterns),
);
}
/// MONOTONICITY (`first_arg_matches`). The function tests `any` over the pattern
/// list, so adding a matching pattern can never turn a hit into a miss — the
/// property holds for a synthetic name (forced not to match any base pattern) and a
/// single `*`-suffixed pattern whose prefix the name starts with. A regression that
/// replaced `any` with `all`, or that re-applied the loop on each pattern's match
/// to update some shared state, would break the monotonicity direction on the second
/// assertion: matches on a pattern that was already a miss would need a flip, and
/// that's exactly the failure mode the property isolates.
#[test]
fn first_arg_matches_is_monotone_in_adding_a_matching_pattern(
base in proptest::collection::vec(
"[a-zA-Z][a-zA-Z0-9._:-]{0,8}",
0..4,
),
prefix in "[a-zA-Z][a-zA-Z0-9._:-]{0,4}",
tail in "[a-zA-Z0-9._:-]{1,6}",
) {
let name = format!("{}{}", prefix, tail);
// The base patterns do NOT match `name` (no pattern starts with `prefix*`, and
// none equals `name`). The added pattern `prefix*` does.
prop_assume!(!base.iter().any(|p| p == &name
|| (p.ends_with('*') && name.starts_with(&p[..p.len() - 1]))));
let before = first_arg_matches(&name, &base);
let mut extended = base.clone();
extended.push(format!("{}*", prefix));
let after = first_arg_matches(&name, &extended);
prop_assert!(!before, "base should not match: base={:?} name={}", base, name);
prop_assert!(after, "adding matching pattern should have flipped to true");
}
}
}