Skip to main content

agent_first_data/cli_spec/
resolve.rs

1use super::error::{
2    InvocationReadError, InvocationReadProblem, duplicate_error, invalid_value, missing_value,
3};
4use super::help::{HelpCatalog, combination_usage};
5use super::*;
6use std::collections::{BTreeMap, BTreeSet};
7use std::ffi::OsString;
8use std::path::{Path, PathBuf};
9
10/// Validated registry used for resolution and help generation.
11#[derive(Clone, Debug, PartialEq)]
12pub struct BuiltCliSpec {
13    pub(super) spec: CliSpec,
14    pub(super) hidden_help_defaults: BTreeMap<Vec<String>, BTreeSet<String>>,
15}
16
17impl BuiltCliSpec {
18    pub(crate) fn hide_help_defaults(&mut self, hide: impl Fn(&ArgSpec) -> bool) {
19        self.hidden_help_defaults = self
20            .spec
21            .commands
22            .iter()
23            .filter_map(|command| {
24                let hidden: BTreeSet<_> = command
25                    .arguments
26                    .iter()
27                    .filter(|argument| argument.default.is_some() && hide(argument))
28                    .map(|argument| argument.argument_id.clone())
29                    .collect();
30                (!hidden.is_empty()).then(|| (command.command_path.clone(), hidden))
31            })
32            .collect();
33    }
34
35    pub fn spec(&self) -> &CliSpec {
36        &self.spec
37    }
38
39    pub fn resolve_from<I, S>(&self, args: I) -> Result<CliOutcome, CliError>
40    where
41        I: IntoIterator<Item = S>,
42        S: Into<OsString>,
43    {
44        let raw: Vec<OsString> = args.into_iter().map(Into::into).collect();
45        self.resolve_os(&raw)
46    }
47
48    /// Generate type-correct argv for every combination and every fixed
49    /// `one_of` member. These fixtures exercise the same normalized shapes
50    /// used by help rendering without pretending help placeholders are argv.
51    pub fn synthetic_invocations(&self) -> Vec<SyntheticInvocation> {
52        let mut fixtures = Vec::new();
53        for command in &self.spec.commands {
54            for combination in &command.combinations {
55                let mut variants = vec![vec![self.spec.name.clone()]];
56                for part in &command.command_path {
57                    for argv in &mut variants {
58                        argv.push(part.clone());
59                    }
60                }
61                for argument in &command.arguments {
62                    let values: Vec<String> =
63                        if let Some(fixed) = combination.fixed.get(&argument.argument_id) {
64                            fixed.values().to_vec()
65                        } else if combination
66                            .required
67                            .iter()
68                            .any(|id| id == &argument.argument_id)
69                        {
70                            vec![synthetic_value(argument)]
71                        } else {
72                            continue;
73                        };
74                    let mut expanded = Vec::new();
75                    for argv in variants {
76                        for value in &values {
77                            let mut candidate = argv.clone();
78                            append_synthetic_argument(&mut candidate, argument, value);
79                            expanded.push(candidate);
80                        }
81                    }
82                    variants = expanded;
83                }
84                fixtures.extend(variants.into_iter().map(|argv| SyntheticInvocation {
85                    command_path: command.command_path.clone(),
86                    combination_id: combination.combination_id.clone(),
87                    argv,
88                }));
89            }
90        }
91        fixtures
92    }
93
94    /// The help model for one command.
95    ///
96    /// The same model `--help` returns, reachable in-process. Build-time
97    /// tooling — an offline reference renderer, for example — needs the whole
98    /// registry, and this is how it consumes it without a full-spec dump on
99    /// the agent's discovery path.
100    pub fn help(&self, command_path: &[String]) -> Option<CliHelpV2> {
101        let command = self
102            .spec
103            .commands
104            .iter()
105            .find(|candidate| candidate.command_path == command_path)?;
106        Some(self.help_catalog(command, true).into_help_model())
107    }
108
109    /// Check exact action coverage and return an executable binding.
110    pub fn bind_actions<R, I, S>(&self, handlers: I) -> Result<BoundCliSpec<R>, CliSpecError>
111    where
112        I: IntoIterator<Item = (S, fn(&ResolvedInvocation) -> R)>,
113        S: Into<String>,
114    {
115        let expected: BTreeSet<&str> = self
116            .spec
117            .commands
118            .iter()
119            .flat_map(|command| command.combinations.iter())
120            .map(|combination| combination.action_id.as_str())
121            .collect();
122        let mut actual = BTreeMap::new();
123        for (action_id, handler) in handlers {
124            let action_id = action_id.into();
125            if actual.insert(action_id.clone(), handler).is_some() {
126                return Err(CliSpecError::new(
127                    "duplicate_action_handler",
128                    format!("action `{action_id}` has more than one handler"),
129                ));
130            }
131        }
132        let actual_ids: BTreeSet<&str> = actual.keys().map(String::as_str).collect();
133        if expected != actual_ids {
134            let missing: Vec<&str> = expected.difference(&actual_ids).copied().collect();
135            let extra: Vec<&str> = actual_ids.difference(&expected).copied().collect();
136            return Err(CliSpecError::new(
137                "action_handler_coverage",
138                format!("handler coverage mismatch; missing={missing:?}, extra={extra:?}"),
139            ));
140        }
141        Ok(BoundCliSpec {
142            cli: self.clone(),
143            handlers: actual,
144        })
145    }
146
147    fn resolve_os(&self, raw: &[OsString]) -> Result<CliOutcome, CliError> {
148        let mut utf8 = Vec::with_capacity(raw.len());
149        for token in raw {
150            let Some(token) = token.to_str() else {
151                return Err(CliError::new(
152                    CliErrorRule::InvalidUtf8,
153                    self.spec.name.clone(),
154                    "argv contains a token that is not valid UTF-8",
155                ));
156            };
157            utf8.push(token.to_string());
158        }
159        let argv = if utf8.is_empty() { &[][..] } else { &utf8[1..] };
160        let (command, consumed) = self.select_command(argv)?;
161        let command_path = self.display_command_path(command);
162        let parsed = tokenize(
163            command,
164            &argv[consumed..],
165            &command_path,
166            &self.spec.commands,
167        )?;
168
169        if parsed.control_count() > 0 {
170            if parsed.control_count() != 1 || !parsed.application_values.is_empty() {
171                return Err(CliError::unregistered(command_path));
172            }
173            // `--docs` renders the whole registry, which is raw bytes, not
174            // protocol events. It therefore gets its own contract instead of
175            // `lifecycle_output`, and must be settled before the shared
176            // protocol plan below would wrongly accept `--output`.
177            if parsed.docs {
178                // Root-only, like `--version` below: past the command path the
179                // spelling belongs to the application, and where it declared
180                // one, `tokenize` bound the token to that argument and never
181                // set this flag at all.
182                if !command.command_path.is_empty() {
183                    return Err(CliError::unregistered(command_path));
184                }
185                let contract = OutputSpec::raw()
186                    .file_sinks(self.spec.lifecycle_output.file_sinks_ref().to_vec());
187                let output = resolve_output(&contract, &parsed.output, &command_path)?;
188                return Ok(CliOutcome::Docs(ResolvedDocs {
189                    output,
190                    registry: self.clone(),
191                }));
192            }
193            let output =
194                resolve_output(&self.spec.lifecycle_output, &parsed.output, &command_path)?;
195            if parsed.help {
196                return Ok(CliOutcome::Help(ResolvedHelp {
197                    model: self.help_catalog(command, true).into_help_model(),
198                    output,
199                }));
200            }
201            if parsed.version {
202                if !command.command_path.is_empty() {
203                    return Err(CliError::unregistered(command_path));
204                }
205                return Ok(CliOutcome::Version(ResolvedVersion {
206                    name: self.spec.name.clone(),
207                    version: self.spec.version.clone(),
208                    display_name: self.spec.display_name.clone(),
209                    build: self.spec.build.clone(),
210                    output,
211                }));
212            }
213        }
214
215        let matching: Vec<&Combination> = command
216            .combinations
217            .iter()
218            .filter(|combination| combination_matches(command, combination, &parsed))
219            .collect();
220        let Some(combination) = matching.first().copied() else {
221            return Err(CliError::unregistered(command_path));
222        };
223        if matching.len() != 1 {
224            return Err(CliError::new(
225                CliErrorRule::UnregisteredCombination,
226                command_path,
227                "arguments match more than one registered CLI combination",
228            ));
229        }
230        let output = resolve_output(&combination.output, &parsed.output, &command_path)?;
231        let projected = project_values(command, combination, &parsed);
232        Ok(CliOutcome::Run(ResolvedInvocation {
233            command_path: command.command_path.clone(),
234            action_id: combination.action_id.clone(),
235            combination_id: combination.combination_id.clone(),
236            values: projected.values,
237            sources: projected.sources,
238            declared: projected.declared,
239            explicit_argument_ids: parsed.explicit_application_ids,
240            output,
241            strict_reads: false,
242        }))
243    }
244
245    fn select_command<'a>(&'a self, argv: &[String]) -> Result<(&'a CommandSpec, usize), CliError> {
246        let mut commands: Vec<&CommandSpec> = self.spec.commands.iter().collect();
247        commands.sort_by_key(|command| std::cmp::Reverse(command.command_path.len()));
248        if let Some(command) = commands.iter().copied().find(|command| {
249            command.command_path.len() <= argv.len()
250                && command
251                    .command_path
252                    .iter()
253                    .zip(argv)
254                    .all(|(expected, actual)| expected == actual)
255        }) {
256            let remaining = &argv[command.command_path.len()..];
257            let has_children = self.spec.commands.iter().any(|candidate| {
258                candidate.command_path.len() > command.command_path.len()
259                    && candidate.command_path.starts_with(&command.command_path)
260            });
261            if remaining
262                .first()
263                .is_some_and(|token| !token.starts_with('-'))
264                && has_children
265            {
266                return Err(CliError::new(
267                    CliErrorRule::UnknownCommand,
268                    self.display_command_path(command),
269                    "unknown command",
270                ));
271            }
272            return Ok((command, command.command_path.len()));
273        }
274        Err(CliError::new(
275            CliErrorRule::UnknownCommand,
276            self.spec.name.clone(),
277            "unknown command",
278        ))
279    }
280
281    fn display_command_path(&self, command: &CommandSpec) -> String {
282        std::iter::once(self.spec.name.as_str())
283            .chain(command.command_path.iter().map(String::as_str))
284            .collect::<Vec<_>>()
285            .join(" ")
286    }
287
288    fn child_help_commands(&self, command: &CommandSpec) -> Vec<String> {
289        let mut children: Vec<Vec<String>> = self
290            .spec
291            .commands
292            .iter()
293            .filter(|candidate| {
294                candidate.command_path.len() == command.command_path.len() + 1
295                    && candidate.command_path.starts_with(&command.command_path)
296            })
297            .map(|candidate| candidate.command_path.clone())
298            .collect();
299        children.sort();
300        children
301            .into_iter()
302            .map(|path| format!("{} {} --help", self.spec.name, path.join(" ")))
303            .collect()
304    }
305
306    pub(crate) fn help_catalog(
307        &self,
308        command: &CommandSpec,
309        include_output_usage: bool,
310    ) -> HelpCatalog {
311        let command_path = self.display_command_path(command);
312        let mut shapes = Vec::new();
313        let mut notes = BTreeMap::new();
314        let mut shape_defaults = Vec::new();
315        let hidden_defaults = self.hidden_help_defaults.get(&command.command_path);
316        for combination in &command.combinations {
317            let (usage, shape_notes, defaults) = combination_usage(
318                command,
319                combination,
320                &command_path,
321                hidden_defaults,
322                include_output_usage,
323            );
324            shapes.push(CliShape {
325                id: combination.combination_id.clone(),
326                // With one shape there is nothing to tell apart, so the
327                // command's own description already covers it.
328                about: if command.combinations.len() == 1 {
329                    None
330                } else {
331                    combination.about.clone()
332                },
333                usage,
334            });
335            notes.extend(shape_notes);
336            shape_defaults.push(defaults);
337        }
338        let defaults: BTreeMap<_, _> = shape_defaults
339            .first()
340            .into_iter()
341            .flatten()
342            .filter(|(name, value)| {
343                shape_defaults
344                    .iter()
345                    .all(|defaults| defaults.get(*name) == Some(*value))
346            })
347            .map(|(name, value)| (name.clone(), value.clone()))
348            .collect();
349        for specific in &mut shape_defaults {
350            specific.retain(|name, _| !defaults.contains_key(name));
351        }
352        let model = CliHelpV2 {
353            schema: "cli-help-v2".to_string(),
354            command_path,
355            // The root command has no description of its own — the registry's
356            // does double duty, and without this fallback an agent's first
357            // discovery call learns every subcommand but never what the tool is.
358            about: command.about.clone().or_else(|| {
359                command
360                    .command_path
361                    .is_empty()
362                    .then(|| self.spec.about.clone())
363                    .flatten()
364            }),
365            shapes,
366            subcommands: self.child_help_commands(command),
367            notes,
368            defaults,
369        };
370        HelpCatalog {
371            model,
372            shape_defaults,
373        }
374    }
375}
376
377/// Type-correct argv generated from a registered shape.
378#[derive(Clone, Debug, PartialEq, Eq)]
379pub struct SyntheticInvocation {
380    pub command_path: Vec<String>,
381    pub combination_id: String,
382    pub argv: Vec<String>,
383}
384
385/// A built registry with exactly one handler per action.
386pub struct BoundCliSpec<R> {
387    cli: BuiltCliSpec,
388    handlers: BTreeMap<String, fn(&ResolvedInvocation) -> R>,
389}
390
391impl<R> BoundCliSpec<R> {
392    /// Resolve argv against this registry, binding the run branch to its
393    /// handler as it goes.
394    ///
395    /// The handler is attached here, where `bind_actions` has already proved
396    /// one exists for every action, which is what makes
397    /// [`BoundInvocation::run`] infallible. Resolving through the registry that
398    /// owns the handlers also removes the possibility of dispatching an
399    /// invocation from a *different* registry: there is no longer a step that
400    /// takes one.
401    pub fn resolve_from<I, S>(&self, args: I) -> Result<BoundOutcome<R>, CliError>
402    where
403        I: IntoIterator<Item = S>,
404        S: Into<OsString>,
405    {
406        Ok(match self.cli.resolve_from(args)? {
407            CliOutcome::Run(invocation) => BoundOutcome::Run(self.bind(invocation)),
408            CliOutcome::Help(help) => BoundOutcome::Help(help),
409            CliOutcome::Version(version) => BoundOutcome::Version(version),
410            CliOutcome::Docs(docs) => BoundOutcome::Docs(docs),
411        })
412    }
413
414    /// Call every declared combination's handler with strict argument reads,
415    /// returning each combination id with what its handler produced.
416    ///
417    /// **This runs your handlers.** Every one of them, on synthetic argv, in
418    /// whatever order the registry declares them. Use it only where a handler
419    /// is a pure projection of argv into a command value. Where the handler
420    /// *is* the command, this will do whatever the command does — bind a port
421    /// and never return, open a terminal, write files, or uninstall something.
422    /// The name of this method is not a promise that it is safe to call; the
423    /// shape of your handlers is.
424    ///
425    /// Where it does fit, it is the other half of the typed reads on
426    /// [`ResolvedInvocation`]. A handler that reads an argument id its
427    /// combination does not declare, or reads one as the wrong type, gets an
428    /// [`InvocationReadError`] in production — reported as a program defect,
429    /// and exactly the class of typo no compiler catches. Here the read itself
430    /// panics naming the combination and the id, driven by the same
431    /// synthetic invocations [`BuiltCliSpec::synthetic_invocations`] generates
432    /// for help and docs. Production code carries no branch for a case it
433    /// cannot reach, and the case is still caught before it ships.
434    ///
435    /// If your handlers are not callable here, that is worth reading as a
436    /// design signal rather than a limitation of this method: separating "parse
437    /// argv into a typed command" from "carry the command out" makes the check
438    /// available and is the better shape independently.
439    ///
440    /// The results are returned rather than discarded because a handler that
441    /// returns a `Result` has a second thing worth checking — that every
442    /// combination actually *builds* — and a caller that had to write its own
443    /// loop for that would be back to hand-rolling the half this replaces.
444    /// Ignore the return when the handler's output says nothing useful.
445    // This method exists to fail loudly from a test; diverging is the whole
446    // point, and the doc above says so. The allow records that rather than
447    // reshaping a deliberate abort into a value nobody can act on.
448    #[allow(clippy::panic)]
449    pub fn call_every_combination(&self) -> Vec<(String, R)> {
450        let mut results = Vec::new();
451        for fixture in self.cli.synthetic_invocations() {
452            // A fixture that does not resolve to a run is a registry defect, and
453            // skipping it would let this method report success while covering
454            // nothing — the one failure a check like this must not have.
455            let outcome = self.cli.resolve_from(fixture.argv.clone());
456            let Ok(CliOutcome::Run(mut invocation)) = outcome else {
457                panic!(
458                    "combination `{}` generated argv {:?}, which does not resolve to a run",
459                    fixture.combination_id, fixture.argv
460                );
461            };
462            invocation.strict_reads = true;
463            let combination = invocation.combination_id.clone();
464            results.push((combination, self.bind(invocation).run()));
465        }
466        assert!(
467            !results.is_empty(),
468            "no combination was called; a registry with no runnable combination cannot be verified"
469        );
470        results
471    }
472
473    fn bind(&self, invocation: ResolvedInvocation) -> BoundInvocation<R> {
474        // `bind_actions` rejected any registry whose action ids and handler ids
475        // differ, and `action_id` can only come from a combination in that same
476        // registry. The allow records that proof once, here, instead of making
477        // every caller carry a branch for it.
478        #[allow(clippy::expect_used)]
479        let handler = *self
480            .handlers
481            .get(invocation.action_id())
482            .expect("bind_actions guarantees one handler per action id");
483        BoundInvocation {
484            invocation,
485            handler,
486        }
487    }
488}
489
490/// What an argv resolved to, with the run branch already bound to its handler.
491pub enum BoundOutcome<R> {
492    Run(BoundInvocation<R>),
493    Help(ResolvedHelp),
494    Version(ResolvedVersion),
495    Docs(ResolvedDocs),
496}
497
498impl<R> BoundOutcome<R> {
499    /// The resolved sink plan, available before lifecycle handling or domain I/O.
500    pub fn output_plan(&self) -> &OutputPlan {
501        match self {
502            Self::Run(invocation) => invocation.output_plan(),
503            Self::Docs(docs) => docs.output_plan(),
504            Self::Help(help) => help.output_plan(),
505            Self::Version(version) => version.output_plan(),
506        }
507    }
508}
509
510impl<R> std::fmt::Debug for BoundOutcome<R> {
511    /// Written by hand so it does not require `R: Debug`: `R` is whatever the
512    /// application's handlers return, and demanding `Debug` of it would make
513    /// this enum unusable in a test that wants to assert on the outcome.
514    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
515        match self {
516            Self::Run(invocation) => formatter.debug_tuple("Run").field(invocation).finish(),
517            Self::Help(help) => formatter.debug_tuple("Help").field(help).finish(),
518            Self::Version(version) => formatter.debug_tuple("Version").field(version).finish(),
519            Self::Docs(docs) => formatter.debug_tuple("Docs").field(docs).finish(),
520        }
521    }
522}
523
524/// A resolved invocation together with the handler that will run it.
525///
526/// Running cannot fail: the handler was looked up at resolution, by the
527/// registry that owns it.
528pub struct BoundInvocation<R> {
529    invocation: ResolvedInvocation,
530    handler: fn(&ResolvedInvocation) -> R,
531}
532
533impl<R> BoundInvocation<R> {
534    /// The output contract, readable before the handler runs so a caller can
535    /// install redirection first.
536    pub fn output_plan(&self) -> &OutputPlan {
537        self.invocation.output_plan()
538    }
539
540    /// The resolved invocation, for a caller that needs more than the plan.
541    pub fn invocation(&self) -> &ResolvedInvocation {
542        &self.invocation
543    }
544
545    /// Run the bound handler.
546    pub fn run(self) -> R {
547        (self.handler)(&self.invocation)
548    }
549
550    /// Run the bound handler and give the invocation back.
551    ///
552    /// For a caller that still needs the resolved values afterwards — a command
553    /// path, or globals read once the handler has produced its command. Without
554    /// this the only way to keep them past [`run`](Self::run) is to clone the
555    /// value maps before calling it.
556    pub fn run_with_invocation(self) -> (R, ResolvedInvocation) {
557        let result = (self.handler)(&self.invocation);
558        (result, self.invocation)
559    }
560}
561
562impl<R> std::fmt::Debug for BoundInvocation<R> {
563    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
564        formatter
565            .debug_struct("BoundInvocation")
566            .field("invocation", &self.invocation)
567            .finish_non_exhaustive()
568    }
569}
570
571/// What an argv resolved to.
572#[derive(Clone, Debug, PartialEq)]
573pub enum CliOutcome {
574    Run(ResolvedInvocation),
575    Help(ResolvedHelp),
576    Version(ResolvedVersion),
577    Docs(ResolvedDocs),
578}
579
580/// One legal invocation, projected onto the shape that matched it.
581///
582/// Read it through the typed accessors — [`text`](Self::text),
583/// [`flag`](Self::flag), [`integer`](Self::integer), [`source`](Self::source)
584/// and their optional and repeated forms. Each one checks the read against
585/// what the matched combination declares, and a mismatch is an
586/// [`InvocationReadError`]: a defect in the program, reported as
587/// `cli_invocation_invalid` at exit 1. There is no untyped read, so no handler
588/// can mistake "not declared" for a legitimate `false` or an empty string.
589#[derive(Clone, Debug, PartialEq)]
590pub struct ResolvedInvocation {
591    pub(super) command_path: Vec<String>,
592    pub(super) action_id: String,
593    pub(super) combination_id: String,
594    pub(super) values: BTreeMap<String, InvocationValue>,
595    pub(super) sources: BTreeMap<String, Vec<ValueSource>>,
596    pub(super) declared: BTreeMap<String, DeclaredArgument>,
597    pub(super) explicit_argument_ids: BTreeSet<String>,
598    pub(super) output: OutputPlan,
599    /// Set only by [`BoundCliSpec::call_every_combination`]. A read the
600    /// registry refuses is a defect in the handler, and this is the mode that
601    /// fails the test at the read that made it, naming combination and id.
602    pub(super) strict_reads: bool,
603}
604
605/// What the matched combination declares about one argument id.
606#[derive(Clone, Debug, PartialEq, Eq)]
607pub(super) struct DeclaredArgument {
608    pub(super) value_type: ArgValueType,
609    pub(super) repeatable: bool,
610    pub(super) sourced: bool,
611}
612
613/// A parsed argument value, independent of registry default serialization.
614#[derive(Clone, Debug, PartialEq)]
615pub(super) enum InvocationValue {
616    Bool(bool),
617    String(String),
618    I64(i64),
619    FiniteF64(f64),
620    Json(String),
621    List(Vec<InvocationValue>),
622}
623
624impl InvocationValue {
625    fn as_bool(&self) -> Option<bool> {
626        match self {
627            Self::Bool(value) => Some(*value),
628            _ => None,
629        }
630    }
631
632    fn as_str(&self) -> Option<&str> {
633        match self {
634            Self::String(value) => Some(value),
635            _ => None,
636        }
637    }
638
639    fn as_i64(&self) -> Option<i64> {
640        match self {
641            Self::I64(value) => Some(*value),
642            _ => None,
643        }
644    }
645
646    fn as_f64(&self) -> Option<f64> {
647        match self {
648            Self::FiniteF64(value) => Some(*value),
649            _ => None,
650        }
651    }
652
653    /// The raw, still-unparsed JSON source text of a `json` argument.
654    fn as_json_str(&self) -> Option<&str> {
655        match self {
656            Self::Json(value) => Some(value),
657            _ => None,
658        }
659    }
660
661    fn as_list(&self) -> Option<&[InvocationValue]> {
662        match self {
663            Self::List(values) => Some(values),
664            _ => None,
665        }
666    }
667}
668
669impl From<CliValue> for InvocationValue {
670    fn from(value: CliValue) -> Self {
671        match value {
672            CliValue::Bool(value) => Self::Bool(value),
673            CliValue::String(value) => Self::String(value),
674            CliValue::I64(value) => Self::I64(value),
675            CliValue::FiniteF64(value) => Self::FiniteF64(value),
676            CliValue::Json(value) => Self::Json(value),
677            CliValue::List(items) => Self::List(items.into_iter().map(Self::from).collect()),
678        }
679    }
680}
681
682/// The value types a text read accepts: every type whose value is a string.
683const TEXT_TYPES: &[ArgValueType] = &[ArgValueType::String, ArgValueType::Enum, ArgValueType::Uuid];
684
685impl ResolvedInvocation {
686    pub fn command_path(&self) -> &[String] {
687        &self.command_path
688    }
689
690    pub fn action_id(&self) -> &str {
691        &self.action_id
692    }
693
694    pub fn combination_id(&self) -> &str {
695        &self.combination_id
696    }
697
698    pub fn output_plan(&self) -> &OutputPlan {
699        &self.output
700    }
701
702    /// Whether the caller wrote this argument, as opposed to inheriting it
703    /// from the shape's fixed value or the argument's default.
704    pub fn was_explicit(&self, argument_id: &str) -> Result<bool, InvocationReadError> {
705        self.declaration(argument_id, "explicit argument")?;
706        Ok(self.explicit_argument_ids.contains(argument_id))
707    }
708
709    /// Whether the matched combination declares `argument_id` at all.
710    ///
711    /// For a handler bound to an action several combinations share, where only
712    /// some of them accept an argument: ask, then read. Reading an undeclared id
713    /// is still an [`InvocationReadError`].
714    pub fn declares(&self, argument_id: &str) -> bool {
715        self.declared.contains_key(argument_id)
716    }
717
718    /// A string, enum or UUID value the combination always supplies: required,
719    /// fixed, or defaulted.
720    pub fn text(&self, argument_id: &str) -> Result<&str, InvocationReadError> {
721        let value = self.single(argument_id, TEXT_TYPES, "text")?;
722        self.required_value(argument_id, value, "text")?
723            .as_str()
724            .ok_or_else(|| self.refuse(argument_id, "text", InvocationReadProblem::WrongType))
725    }
726
727    /// A string, enum or UUID value the caller may omit.
728    pub fn optional_text(&self, argument_id: &str) -> Result<Option<&str>, InvocationReadError> {
729        Ok(self
730            .single(argument_id, TEXT_TYPES, "optional text")?
731            .and_then(InvocationValue::as_str))
732    }
733
734    /// Every value of a repeatable string, enum or UUID argument, in argv order.
735    pub fn texts(&self, argument_id: &str) -> Result<Vec<&str>, InvocationReadError> {
736        Ok(self
737            .list(argument_id, TEXT_TYPES, "repeated text")?
738            .iter()
739            .filter_map(InvocationValue::as_str)
740            .collect())
741    }
742
743    /// Whether a flag was given. An absent flag the combination declares is a
744    /// legitimate `false`; an undeclared one is a read error, never `false`.
745    pub fn flag(&self, argument_id: &str) -> Result<bool, InvocationReadError> {
746        let value = self.single(argument_id, &[ArgValueType::Flag], "flag")?;
747        Ok(value.and_then(InvocationValue::as_bool).unwrap_or(false))
748    }
749
750    /// The raw source text of a `json` argument the combination always supplies.
751    pub fn json_text(&self, argument_id: &str) -> Result<&str, InvocationReadError> {
752        let value = self.single(argument_id, &[ArgValueType::Json], "json text")?;
753        self.required_value(argument_id, value, "json text")?
754            .as_json_str()
755            .ok_or_else(|| self.refuse(argument_id, "json text", InvocationReadProblem::WrongType))
756    }
757
758    /// The raw source text of a `json` argument the caller may omit.
759    pub fn optional_json_text(
760        &self,
761        argument_id: &str,
762    ) -> Result<Option<&str>, InvocationReadError> {
763        Ok(self
764            .single(argument_id, &[ArgValueType::Json], "optional json text")?
765            .and_then(InvocationValue::as_json_str))
766    }
767
768    /// An `i64` argument converted to the integer type the handler works in.
769    ///
770    /// A value that does not fit `T` is a read error: the registry's
771    /// [`ArgSpec::range`] is where the bound belongs, so the caller gets a
772    /// usage error at exit 2 instead of a handler-side check.
773    pub fn integer<T: TryFrom<i64>>(&self, argument_id: &str) -> Result<T, InvocationReadError> {
774        let expected = integer_read("integer", std::any::type_name::<T>());
775        let value = self.single(argument_id, &[ArgValueType::I64], &expected)?;
776        let number = self
777            .required_value(argument_id, value, &expected)?
778            .as_i64()
779            .ok_or_else(|| self.refuse(argument_id, &expected, InvocationReadProblem::WrongType))?;
780        T::try_from(number)
781            .map_err(|_| self.refuse(argument_id, &expected, InvocationReadProblem::OutOfRange))
782    }
783
784    /// An `i64` argument the caller may omit, converted as [`integer`](Self::integer).
785    pub fn optional_integer<T: TryFrom<i64>>(
786        &self,
787        argument_id: &str,
788    ) -> Result<Option<T>, InvocationReadError> {
789        let expected = integer_read("optional integer", std::any::type_name::<T>());
790        let Some(number) = self
791            .single(argument_id, &[ArgValueType::I64], &expected)?
792            .and_then(InvocationValue::as_i64)
793        else {
794            return Ok(None);
795        };
796        T::try_from(number)
797            .map(Some)
798            .map_err(|_| self.refuse(argument_id, &expected, InvocationReadProblem::OutOfRange))
799    }
800
801    /// Every value of a repeatable `i64` argument, each converted as
802    /// [`integer`](Self::integer).
803    pub fn integers<T: TryFrom<i64>>(
804        &self,
805        argument_id: &str,
806    ) -> Result<Vec<T>, InvocationReadError> {
807        let expected = integer_read("repeated integers", std::any::type_name::<T>());
808        self.list(argument_id, &[ArgValueType::I64], &expected)?
809            .iter()
810            .filter_map(InvocationValue::as_i64)
811            .map(|number| {
812                T::try_from(number).map_err(|_| {
813                    self.refuse(argument_id, &expected, InvocationReadProblem::OutOfRange)
814                })
815            })
816            .collect()
817    }
818
819    /// A finite `f64` argument the combination always supplies.
820    pub fn number(&self, argument_id: &str) -> Result<f64, InvocationReadError> {
821        let value = self.single(argument_id, &[ArgValueType::FiniteF64], "number")?;
822        self.required_value(argument_id, value, "number")?
823            .as_f64()
824            .ok_or_else(|| self.refuse(argument_id, "number", InvocationReadProblem::WrongType))
825    }
826
827    /// A finite `f64` argument the caller may omit.
828    pub fn optional_number(&self, argument_id: &str) -> Result<Option<f64>, InvocationReadError> {
829        Ok(self
830            .single(argument_id, &[ArgValueType::FiniteF64], "optional number")?
831            .and_then(InvocationValue::as_f64))
832    }
833
834    /// A `KEY=VALUE` argument the combination always supplies, split at the
835    /// first `=`.
836    pub fn key_value(&self, argument_id: &str) -> Result<(&str, &str), InvocationReadError> {
837        let value = self.single(argument_id, &[ArgValueType::KeyValue], "key-value pair")?;
838        self.required_value(argument_id, value, "key-value pair")?
839            .as_str()
840            .and_then(split_pair)
841            .ok_or_else(|| {
842                self.refuse(
843                    argument_id,
844                    "key-value pair",
845                    InvocationReadProblem::WrongType,
846                )
847            })
848    }
849
850    /// A `KEY=VALUE` argument the caller may omit.
851    pub fn optional_key_value(
852        &self,
853        argument_id: &str,
854    ) -> Result<Option<(&str, &str)>, InvocationReadError> {
855        Ok(self
856            .single(
857                argument_id,
858                &[ArgValueType::KeyValue],
859                "optional key-value pair",
860            )?
861            .and_then(InvocationValue::as_str)
862            .and_then(split_pair))
863    }
864
865    /// Every pair of a repeatable `KEY=VALUE` argument, in argv order.
866    pub fn key_values(&self, argument_id: &str) -> Result<Vec<(&str, &str)>, InvocationReadError> {
867        Ok(self
868            .list(
869                argument_id,
870                &[ArgValueType::KeyValue],
871                "repeated key-value pairs",
872            )?
873            .iter()
874            .filter_map(InvocationValue::as_str)
875            .filter_map(split_pair)
876            .collect())
877    }
878
879    /// Where a sourced argument's value is, as the parser classified it.
880    ///
881    /// Classification is syntax only: nothing has been read. Call
882    /// [`ValueSource::read`](crate::value_source) or `read_secret` when the
883    /// value is actually needed, so a variable or file that does not exist is
884    /// a failure of the command that needed it, not of argv.
885    pub fn source(&self, argument_id: &str) -> Result<&ValueSource, InvocationReadError> {
886        let sources = self.sourced(argument_id, false, "source")?;
887        sources
888            .first()
889            .ok_or_else(|| self.refuse(argument_id, "source", InvocationReadProblem::Absent))
890    }
891
892    /// A sourced argument the caller may omit.
893    pub fn optional_source(
894        &self,
895        argument_id: &str,
896    ) -> Result<Option<&ValueSource>, InvocationReadError> {
897        Ok(self.sourced(argument_id, false, "optional source")?.first())
898    }
899
900    /// Every source of a repeatable sourced argument, in argv order.
901    pub fn sources(&self, argument_id: &str) -> Result<&[ValueSource], InvocationReadError> {
902        self.sourced(argument_id, true, "repeated sources")
903    }
904
905    fn declaration(
906        &self,
907        argument_id: &str,
908        expected: &str,
909    ) -> Result<&DeclaredArgument, InvocationReadError> {
910        self.declared
911            .get(argument_id)
912            .ok_or_else(|| self.refuse(argument_id, expected, InvocationReadProblem::Undeclared))
913    }
914
915    /// The value of a non-repeatable, non-sourced argument of one of `types`.
916    fn single(
917        &self,
918        argument_id: &str,
919        types: &[ArgValueType],
920        expected: &str,
921    ) -> Result<Option<&InvocationValue>, InvocationReadError> {
922        let declared = self.declaration(argument_id, expected)?;
923        if declared.repeatable || declared.sourced || !types.contains(&declared.value_type) {
924            return Err(self.refuse(argument_id, expected, InvocationReadProblem::WrongType));
925        }
926        Ok(self.values.get(argument_id))
927    }
928
929    /// The values of a repeatable, non-sourced argument of one of `types`.
930    fn list(
931        &self,
932        argument_id: &str,
933        types: &[ArgValueType],
934        expected: &str,
935    ) -> Result<&[InvocationValue], InvocationReadError> {
936        let declared = self.declaration(argument_id, expected)?;
937        if !declared.repeatable || declared.sourced || !types.contains(&declared.value_type) {
938            return Err(self.refuse(argument_id, expected, InvocationReadProblem::WrongType));
939        }
940        Ok(self
941            .values
942            .get(argument_id)
943            .and_then(InvocationValue::as_list)
944            .unwrap_or(&[]))
945    }
946
947    fn sourced(
948        &self,
949        argument_id: &str,
950        repeatable: bool,
951        expected: &str,
952    ) -> Result<&[ValueSource], InvocationReadError> {
953        let declared = self.declaration(argument_id, expected)?;
954        if !declared.sourced || declared.repeatable != repeatable {
955            return Err(self.refuse(argument_id, expected, InvocationReadProblem::WrongType));
956        }
957        Ok(self.sources.get(argument_id).map_or(&[][..], Vec::as_slice))
958    }
959
960    fn required_value<'a>(
961        &self,
962        argument_id: &str,
963        value: Option<&'a InvocationValue>,
964        expected: &str,
965    ) -> Result<&'a InvocationValue, InvocationReadError> {
966        value.ok_or_else(|| self.refuse(argument_id, expected, InvocationReadProblem::Absent))
967    }
968
969    // Diverging here is the point of strict mode: the test fails at the read
970    // that is wrong, naming the combination and the id.
971    #[allow(clippy::panic)]
972    fn refuse(
973        &self,
974        argument_id: &str,
975        expected: &str,
976        problem: InvocationReadProblem,
977    ) -> InvocationReadError {
978        let error = InvocationReadError {
979            combination_id: self.combination_id.clone(),
980            argument_id: argument_id.to_string(),
981            expected: expected.to_string(),
982            problem,
983        };
984        if self.strict_reads {
985            panic!("{error}");
986        }
987        error
988    }
989}
990
991fn integer_read(read: &str, type_name: &str) -> String {
992    format!(
993        "{read} as {}",
994        type_name.rsplit("::").next().unwrap_or(type_name)
995    )
996}
997
998fn split_pair(text: &str) -> Option<(&str, &str)> {
999    text.split_once('=').filter(|(key, _)| !key.is_empty())
1000}
1001
1002/// Where a resolved call's output goes, and in what form.
1003#[derive(Clone, Debug, PartialEq, Eq)]
1004pub enum OutputPlan {
1005    Raw {
1006        stdout_file: Option<PathBuf>,
1007        stderr_file: Option<PathBuf>,
1008    },
1009    Protocol {
1010        lifecycle: OutputLifecycle,
1011        format: OutputFormat,
1012        destination: OutputTo,
1013        stdout_file: Option<PathBuf>,
1014        stderr_file: Option<PathBuf>,
1015    },
1016}
1017
1018impl OutputPlan {
1019    /// Structured output format, or `None` for a raw-byte command.
1020    pub const fn output_format(&self) -> Option<OutputFormat> {
1021        match self {
1022            Self::Raw { .. } => None,
1023            Self::Protocol { format, .. } => Some(*format),
1024        }
1025    }
1026
1027    /// Structured output routing, or `None` for a raw-byte command.
1028    pub const fn output_to(&self) -> Option<OutputTo> {
1029        match self {
1030            Self::Raw { .. } => None,
1031            Self::Protocol { destination, .. } => Some(*destination),
1032        }
1033    }
1034
1035    pub fn stdout_file(&self) -> Option<&Path> {
1036        match self {
1037            Self::Raw { stdout_file, .. } | Self::Protocol { stdout_file, .. } => {
1038                stdout_file.as_deref()
1039            }
1040        }
1041    }
1042
1043    pub fn stderr_file(&self) -> Option<&Path> {
1044        match self {
1045            Self::Raw { stderr_file, .. } | Self::Protocol { stderr_file, .. } => {
1046                stderr_file.as_deref()
1047            }
1048        }
1049    }
1050}
1051
1052#[derive(Default)]
1053struct ParsedArgs {
1054    application_values: BTreeMap<String, Vec<InvocationValue>>,
1055    /// The classified source of every value of a sourced argument, in argv
1056    /// order, beside its raw text in `application_values`.
1057    application_sources: BTreeMap<String, Vec<ValueSource>>,
1058    explicit_application_ids: BTreeSet<String>,
1059    output: ParsedOutput,
1060    help: bool,
1061    version: bool,
1062    docs: bool,
1063}
1064
1065impl ParsedArgs {
1066    fn control_count(&self) -> usize {
1067        usize::from(self.help) + usize::from(self.version) + usize::from(self.docs)
1068    }
1069}
1070
1071#[derive(Default)]
1072struct ParsedOutput {
1073    format: Option<String>,
1074    destination: Option<String>,
1075    stdout_file: Option<PathBuf>,
1076    stderr_file: Option<PathBuf>,
1077}
1078
1079fn tokenize(
1080    command: &CommandSpec,
1081    tokens: &[String],
1082    command_path: &str,
1083    all_commands: &[CommandSpec],
1084) -> Result<ParsedArgs, CliError> {
1085    let longs: BTreeMap<&str, &ArgSpec> = command
1086        .arguments
1087        .iter()
1088        .filter_map(|argument| match &argument.syntax {
1089            ArgSyntax::Long { name } => Some((name.as_str(), argument)),
1090            ArgSyntax::Positional { .. } => None,
1091        })
1092        .collect();
1093    let mut positionals: Vec<&ArgSpec> = command
1094        .arguments
1095        .iter()
1096        .filter(|argument| matches!(argument.syntax, ArgSyntax::Positional { .. }))
1097        .collect();
1098    positionals.sort_by_key(|argument| match argument.syntax {
1099        ArgSyntax::Positional { index } => index,
1100        ArgSyntax::Long { .. } => usize::MAX,
1101    });
1102
1103    let mut parsed = ParsedArgs::default();
1104    let mut index = 0;
1105    let mut positional_index = 0;
1106    let mut options_done = false;
1107    while index < tokens.len() {
1108        let token = &tokens[index];
1109        if !options_done && token == "--" {
1110            options_done = true;
1111            index += 1;
1112            continue;
1113        }
1114        if !options_done && token.starts_with("--") {
1115            let (name, inline_value) = token
1116                .split_once('=')
1117                .map_or((token.as_str(), None), |(name, value)| (name, Some(value)));
1118            if let Some(argument) = longs.get(name).copied() {
1119                let display = name.to_string();
1120                let raw_value = if argument.value_type == ArgValueType::Flag {
1121                    if inline_value.is_some() {
1122                        return Err(invalid_value(
1123                            command_path,
1124                            display,
1125                            "flags do not accept values",
1126                        ));
1127                    }
1128                    None
1129                } else {
1130                    Some(take_value(
1131                        tokens,
1132                        &mut index,
1133                        inline_value,
1134                        Some(argument),
1135                        &longs,
1136                        name,
1137                        command_path,
1138                    )?)
1139                };
1140                let value = match raw_value {
1141                    Some(value) => parse_value(argument, value).map_err(|message| {
1142                        invalid_value(command_path, display.clone(), &message)
1143                    })?,
1144                    None => InvocationValue::Bool(true),
1145                };
1146                insert_application(&mut parsed, argument, value, display, command_path)?;
1147                index += 1;
1148                continue;
1149            }
1150            match name {
1151                "--help" => {
1152                    reject_inline_value(inline_value, name, command_path)?;
1153                    set_once(&mut parsed.help, name, command_path)?;
1154                }
1155                "--version" => {
1156                    reject_inline_value(inline_value, name, command_path)?;
1157                    set_once(&mut parsed.version, name, command_path)?;
1158                }
1159                "--docs" => {
1160                    reject_inline_value(inline_value, name, command_path)?;
1161                    set_once(&mut parsed.docs, name, command_path)?;
1162                }
1163                "--output" => {
1164                    parsed.output.format = Some(set_output_value(
1165                        parsed.output.format.as_ref(),
1166                        take_value(
1167                            tokens,
1168                            &mut index,
1169                            inline_value,
1170                            None,
1171                            &longs,
1172                            name,
1173                            command_path,
1174                        )?,
1175                        name,
1176                        command_path,
1177                    )?);
1178                }
1179                "--output-to" => {
1180                    parsed.output.destination = Some(set_output_value(
1181                        parsed.output.destination.as_ref(),
1182                        take_value(
1183                            tokens,
1184                            &mut index,
1185                            inline_value,
1186                            None,
1187                            &longs,
1188                            name,
1189                            command_path,
1190                        )?,
1191                        name,
1192                        command_path,
1193                    )?);
1194                }
1195                "--stdout-file" => {
1196                    parsed.output.stdout_file = Some(PathBuf::from(set_output_value(
1197                        parsed.output.stdout_file.as_ref(),
1198                        take_value(
1199                            tokens,
1200                            &mut index,
1201                            inline_value,
1202                            None,
1203                            &longs,
1204                            name,
1205                            command_path,
1206                        )?,
1207                        name,
1208                        command_path,
1209                    )?));
1210                }
1211                "--stderr-file" => {
1212                    parsed.output.stderr_file = Some(PathBuf::from(set_output_value(
1213                        parsed.output.stderr_file.as_ref(),
1214                        take_value(
1215                            tokens,
1216                            &mut index,
1217                            inline_value,
1218                            None,
1219                            &longs,
1220                            name,
1221                            command_path,
1222                        )?,
1223                        name,
1224                        command_path,
1225                    )?));
1226                }
1227                _ => {
1228                    let mut error = CliError::new(
1229                        CliErrorRule::UnknownArgument,
1230                        command_path.to_string(),
1231                        "unknown long argument",
1232                    );
1233                    error.hint = format!(
1234                        "run `{command_path} --help` for supported options, or pass `--` before a positional value that starts with `-`"
1235                    );
1236                    return Err(error);
1237                }
1238            }
1239            index += 1;
1240            continue;
1241        }
1242        if !options_done && token.starts_with('-') && token != "-" {
1243            let positional_accepts_value = positionals
1244                .get(positional_index)
1245                .is_some_and(|argument| accepts_hyphen_prefixed_value(argument, token));
1246            if !positional_accepts_value {
1247                let mut error = CliError::new(
1248                    CliErrorRule::UnknownArgument,
1249                    command_path.to_string(),
1250                    "unknown short argument",
1251                );
1252                error.hint = format!(
1253                    "flags are long-only; pass `--` before a positional value that starts with `-`, or run `{command_path} --help`"
1254                );
1255                return Err(error);
1256            }
1257        }
1258        let Some(argument) = positionals.get(positional_index).copied() else {
1259            // A registered command name here is almost always a caller who put
1260            // the command after its arguments. Saying only "unexpected
1261            // positional argument" is true and useless: the fix is an ordering
1262            // one, and nothing else in the message would suggest it.
1263            let message = if is_registered_command_segment(token, all_commands) {
1264                "command name must come before its arguments"
1265            } else {
1266                "unexpected positional argument"
1267            };
1268            return Err(CliError::new(
1269                CliErrorRule::UnexpectedPositional,
1270                command_path.to_string(),
1271                message,
1272            ));
1273        };
1274        let value = parse_value(argument, token).map_err(|message| {
1275            invalid_value(command_path, argument.argument_id.clone(), &message)
1276        })?;
1277        insert_application(
1278            &mut parsed,
1279            argument,
1280            value,
1281            argument.argument_id.clone(),
1282            command_path,
1283        )?;
1284        if !argument.repeatable {
1285            positional_index += 1;
1286        }
1287        index += 1;
1288    }
1289    Ok(parsed)
1290}
1291
1292fn take_value<'a>(
1293    tokens: &'a [String],
1294    index: &mut usize,
1295    inline_value: Option<&'a str>,
1296    argument: Option<&ArgSpec>,
1297    longs: &BTreeMap<&str, &ArgSpec>,
1298    name: &str,
1299    command_path: &str,
1300) -> Result<&'a str, CliError> {
1301    if let Some(value) = inline_value {
1302        if value.is_empty() && argument.is_none() {
1303            return Err(missing_value(command_path, name));
1304        }
1305        return Ok(value);
1306    }
1307    let Some(value) = tokens.get(*index + 1) else {
1308        return Err(missing_value(command_path, name));
1309    };
1310    if value.starts_with('-')
1311        && value != "-"
1312        && !argument.is_some_and(|argument| accepts_hyphen_prefixed_value(argument, value))
1313    {
1314        let mut error = missing_value(command_path, name);
1315        // A registered flag next is a value left out, not a value that happens
1316        // to start with `-`; the `=` spelling would only pass the flag's name
1317        // off as the value.
1318        if !names_registered_flag(longs, value) {
1319            error.hint = format!("write `{name}=VALUE` for a value that starts with `-`");
1320        }
1321        return Err(error);
1322    }
1323    *index += 1;
1324    Ok(value)
1325}
1326
1327/// Whether `token` (with or without an inline `=VALUE`) names one of the
1328/// command's own long flags or a control flag every command accepts.
1329fn names_registered_flag(longs: &BTreeMap<&str, &ArgSpec>, token: &str) -> bool {
1330    let name = token.split_once('=').map_or(token, |(name, _)| name);
1331    longs.contains_key(name)
1332        || matches!(
1333            name,
1334            "--help"
1335                | "--version"
1336                | "--docs"
1337                | "--output"
1338                | "--output-to"
1339                | "--stdout-file"
1340                | "--stderr-file"
1341        )
1342}
1343
1344/// Whether a `-`-prefixed token is this argument's value rather than a flag.
1345///
1346/// Deliberately a *syntax* question, not a validity one. Asking `parse_value`
1347/// would fold semantic constraints in, so `--limit -1` against a `1..=1000`
1348/// range would be read as "no value supplied" — reporting a missing argument
1349/// for a value the caller plainly typed. Range and enum membership are checked
1350/// after the token is claimed, where they can say what is actually wrong.
1351///
1352/// A free-form string takes a negative number too: flags are long-only, so
1353/// `-5` can only ever be a value, and a config value or default is routinely
1354/// one (`set n -5 --value-type number`, `--default -1`).
1355fn accepts_hyphen_prefixed_value(argument: &ArgSpec, value: &str) -> bool {
1356    match argument.value_type {
1357        ArgValueType::I64 => value.parse::<i64>().is_ok(),
1358        ArgValueType::FiniteF64 => value.parse::<f64>().is_ok_and(f64::is_finite),
1359        ArgValueType::String => {
1360            value.parse::<i64>().is_ok() || value.parse::<f64>().is_ok_and(f64::is_finite)
1361        }
1362        ArgValueType::Json => serde_json::from_str::<serde::de::IgnoredAny>(value).is_ok(),
1363        _ => false,
1364    }
1365}
1366
1367fn reject_inline_value(
1368    inline_value: Option<&str>,
1369    name: &str,
1370    command_path: &str,
1371) -> Result<(), CliError> {
1372    if inline_value.is_some() {
1373        return Err(invalid_value(
1374            command_path,
1375            name.to_string(),
1376            "control flags do not accept values",
1377        ));
1378    }
1379    Ok(())
1380}
1381
1382fn set_once(value: &mut bool, name: &str, command_path: &str) -> Result<(), CliError> {
1383    if *value {
1384        return Err(duplicate_error(command_path, name));
1385    }
1386    *value = true;
1387    Ok(())
1388}
1389
1390fn set_output_value<T>(
1391    existing: Option<&T>,
1392    value: &str,
1393    name: &str,
1394    command_path: &str,
1395) -> Result<String, CliError> {
1396    if existing.is_some() {
1397        return Err(duplicate_error(command_path, name));
1398    }
1399    if value.is_empty() && matches!(name, "--stdout-file" | "--stderr-file") {
1400        return Err(invalid_value(
1401            command_path,
1402            name.to_string(),
1403            "expected a nonempty file path",
1404        ));
1405    }
1406    Ok(value.to_string())
1407}
1408
1409fn insert_application(
1410    parsed: &mut ParsedArgs,
1411    argument: &ArgSpec,
1412    value: InvocationValue,
1413    display: String,
1414    command_path: &str,
1415) -> Result<(), CliError> {
1416    let values = parsed
1417        .application_values
1418        .entry(argument.argument_id.clone())
1419        .or_default();
1420    if !argument.repeatable && !values.is_empty() {
1421        return Err(duplicate_error(command_path, &display));
1422    }
1423    if let (Some(sources), InvocationValue::String(raw)) = (&argument.sources, &value) {
1424        // Classify the source once without reading it.
1425        let source = sources
1426            .parse(raw)
1427            .map_err(|error| invalid_value(command_path, display.clone(), error.message()))?;
1428        parsed
1429            .application_sources
1430            .entry(argument.argument_id.clone())
1431            .or_default()
1432            .push(source);
1433    }
1434    values.push(value);
1435    parsed
1436        .explicit_application_ids
1437        .insert(argument.argument_id.clone());
1438    Ok(())
1439}
1440
1441fn parse_value(argument: &ArgSpec, raw: &str) -> Result<InvocationValue, String> {
1442    match argument.value_type {
1443        ArgValueType::Flag => Ok(InvocationValue::Bool(true)),
1444        ArgValueType::String | ArgValueType::Enum => {
1445            if argument.value_type == ArgValueType::Enum
1446                && !argument.enum_values.iter().any(|value| value == raw)
1447            {
1448                return Err(format!(
1449                    "expected one of {}",
1450                    argument.enum_values.join(", ")
1451                ));
1452            }
1453            Ok(InvocationValue::String(raw.to_string()))
1454        }
1455        ArgValueType::KeyValue => match raw.split_once('=') {
1456            Some((key, _)) if !key.is_empty() => Ok(InvocationValue::String(raw.to_string())),
1457            Some(_) => Err("expected KEY=VALUE with a non-empty KEY".to_string()),
1458            None => Err("expected KEY=VALUE".to_string()),
1459        },
1460        ArgValueType::I64 => {
1461            let value = raw
1462                .parse::<i64>()
1463                .map_err(|_| "expected an i64 integer".to_string())?;
1464            if let Some([minimum, maximum]) = argument.range
1465                && !(minimum..=maximum).contains(&value)
1466            {
1467                return Err(format!("expected an integer in {minimum}..={maximum}"));
1468            }
1469            Ok(InvocationValue::I64(value))
1470        }
1471        ArgValueType::Uuid => {
1472            if is_canonical_uuid(raw) {
1473                Ok(InvocationValue::String(raw.to_string()))
1474            } else {
1475                Err("expected a UUID (8-4-4-4-12 hexadecimal digits)".to_string())
1476            }
1477        }
1478        ArgValueType::FiniteF64 => raw
1479            .parse::<f64>()
1480            .ok()
1481            .filter(|value| value.is_finite())
1482            .map(InvocationValue::FiniteF64)
1483            .ok_or_else(|| "expected a finite f64 number".to_string()),
1484        // Validate that `raw` is exactly one JSON value, then keep the source
1485        // text. `IgnoredAny` checks the grammar without building a
1486        // `serde_json::Value`, so the core never commits to a number
1487        // representation on the caller's behalf.
1488        ArgValueType::Json => serde_json::from_str::<serde::de::IgnoredAny>(raw)
1489            .map(|_| InvocationValue::Json(raw.to_string()))
1490            .map_err(|_| "expected one valid JSON value".to_string()),
1491    }
1492}
1493
1494pub(super) fn validate_value_type(argument: &ArgSpec, value: &CliValue) -> Result<(), String> {
1495    match (&argument.value_type, value) {
1496        (ArgValueType::Flag, CliValue::Bool(_))
1497        | (ArgValueType::String, CliValue::String(_))
1498        | (ArgValueType::Json, CliValue::Json(_)) => Ok(()),
1499        // A default or fixed value is held to the same range as one typed on
1500        // the command line. Checking only the type would let a registry ship a
1501        // default its own argument rejects — a contradiction nothing downstream
1502        // could report, because the value never passes through the parser.
1503        (ArgValueType::I64, CliValue::I64(number)) => match argument.range {
1504            Some([minimum, maximum]) if !(minimum..=maximum).contains(number) => Err(format!(
1505                "value {number} is outside the argument's {minimum}..={maximum} range"
1506            )),
1507            _ => Ok(()),
1508        },
1509        (ArgValueType::Uuid, CliValue::String(text)) if is_canonical_uuid(text) => Ok(()),
1510        (ArgValueType::Uuid, CliValue::String(_)) => {
1511            Err("value is not a UUID (8-4-4-4-12 hexadecimal digits)".to_string())
1512        }
1513        (ArgValueType::FiniteF64, CliValue::FiniteF64(value)) if value.is_finite() => Ok(()),
1514        (ArgValueType::KeyValue, CliValue::String(text))
1515            if text.split_once('=').is_some_and(|(key, _)| !key.is_empty()) =>
1516        {
1517            Ok(())
1518        }
1519        (ArgValueType::KeyValue, CliValue::String(_)) => {
1520            Err("value is not KEY=VALUE with a non-empty KEY".to_string())
1521        }
1522        (ArgValueType::Enum, CliValue::String(value)) if argument.enum_values.contains(value) => {
1523            Ok(())
1524        }
1525        _ => Err("value type does not match the argument".to_string()),
1526    }
1527}
1528
1529fn combination_matches(
1530    command: &CommandSpec,
1531    combination: &Combination,
1532    parsed: &ParsedArgs,
1533) -> bool {
1534    let allowed: BTreeSet<&str> = combination
1535        .fixed
1536        .keys()
1537        .map(String::as_str)
1538        .chain(combination.required.iter().map(String::as_str))
1539        .chain(combination.optional.iter().map(String::as_str))
1540        .collect();
1541    if parsed
1542        .explicit_application_ids
1543        .iter()
1544        .any(|id| !allowed.contains(id.as_str()))
1545        || combination
1546            .required
1547            .iter()
1548            .any(|id| !parsed.explicit_application_ids.contains(id))
1549    {
1550        return false;
1551    }
1552    combination.fixed.iter().all(|(id, fixed)| {
1553        let argument = command
1554            .arguments
1555            .iter()
1556            .find(|argument| argument.argument_id == *id);
1557        let effective = parsed
1558            .application_values
1559            .get(id)
1560            .and_then(|values| values.first())
1561            .and_then(InvocationValue::as_str)
1562            .or_else(|| {
1563                argument
1564                    .and_then(|arg| arg.default.as_ref())
1565                    .and_then(CliValue::as_str)
1566            });
1567        effective.is_some_and(|value| fixed.values().iter().any(|fixed| fixed == value))
1568    })
1569}
1570
1571/// What the matched combination supplies, split by how a handler reads it.
1572struct Projected {
1573    values: BTreeMap<String, InvocationValue>,
1574    sources: BTreeMap<String, Vec<ValueSource>>,
1575    declared: BTreeMap<String, DeclaredArgument>,
1576}
1577
1578fn project_values(
1579    command: &CommandSpec,
1580    combination: &Combination,
1581    parsed: &ParsedArgs,
1582) -> Projected {
1583    let allowed: BTreeSet<&str> = combination
1584        .fixed
1585        .keys()
1586        .map(String::as_str)
1587        .chain(combination.required.iter().map(String::as_str))
1588        .chain(combination.optional.iter().map(String::as_str))
1589        .collect();
1590    let mut projected = Projected {
1591        values: BTreeMap::new(),
1592        sources: BTreeMap::new(),
1593        declared: BTreeMap::new(),
1594    };
1595    for argument in command
1596        .arguments
1597        .iter()
1598        .filter(|argument| allowed.contains(argument.argument_id.as_str()))
1599    {
1600        let id = argument.argument_id.clone();
1601        projected.declared.insert(
1602            id.clone(),
1603            DeclaredArgument {
1604                value_type: argument.value_type.clone(),
1605                repeatable: argument.repeatable,
1606                sourced: argument.sources.is_some(),
1607            },
1608        );
1609        // The parser has already classified a sourced argument; hand that
1610        // classification over instead of the raw text it came from, so no
1611        // handler parses the same grammar a second time.
1612        if argument.sources.is_some() {
1613            if let Some(sources) = parsed.application_sources.get(&id) {
1614                projected.sources.insert(id, sources.clone());
1615            }
1616            continue;
1617        }
1618        let value = parsed
1619            .application_values
1620            .get(&id)
1621            .map(|values| {
1622                if argument.repeatable {
1623                    InvocationValue::List(values.clone())
1624                } else {
1625                    values[0].clone()
1626                }
1627            })
1628            .or_else(|| {
1629                argument
1630                    .default
1631                    .clone()
1632                    .map(InvocationValue::from)
1633                    .map(|default| {
1634                        if argument.repeatable {
1635                            InvocationValue::List(vec![default])
1636                        } else {
1637                            default
1638                        }
1639                    })
1640            })
1641            .or_else(|| {
1642                (argument.value_type == ArgValueType::Flag).then_some(InvocationValue::Bool(false))
1643            });
1644        if let Some(value) = value {
1645            projected.values.insert(id, value);
1646        }
1647    }
1648    projected
1649}
1650
1651fn resolve_output(
1652    spec: &OutputSpec,
1653    parsed: &ParsedOutput,
1654    command_path: &str,
1655) -> Result<OutputPlan, CliError> {
1656    match spec {
1657        OutputSpec::Raw { file_sinks } => {
1658            if parsed.format.is_some() || parsed.destination.is_some() {
1659                return Err(CliError::unregistered(command_path.to_string()));
1660            }
1661            ensure_sinks(file_sinks, parsed, command_path)?;
1662            Ok(OutputPlan::Raw {
1663                stdout_file: parsed.stdout_file.clone(),
1664                stderr_file: parsed.stderr_file.clone(),
1665            })
1666        }
1667        OutputSpec::Protocol {
1668            lifecycle,
1669            formats,
1670            destinations,
1671            default_format,
1672            default_destination,
1673            file_sinks,
1674        } => {
1675            ensure_sinks(file_sinks, parsed, command_path)?;
1676            let format = parsed.format.as_ref().unwrap_or(default_format);
1677            if !formats.contains(format) {
1678                return Err(invalid_value(
1679                    command_path,
1680                    "--output".to_string(),
1681                    &format!("expected one of {}", formats.join(", ")),
1682                ));
1683            }
1684            let destination = parsed.destination.as_ref().unwrap_or(default_destination);
1685            if !destinations.contains(destination) {
1686                return Err(invalid_value(
1687                    command_path,
1688                    "--output-to".to_string(),
1689                    &format!("expected one of {}", destinations.join(", ")),
1690                ));
1691            }
1692            let output_format = format.parse::<OutputFormat>().map_err(|_| {
1693                invalid_value(
1694                    command_path,
1695                    "--output".to_string(),
1696                    "expected one of json, yaml, plain",
1697                )
1698            })?;
1699            let output_to = destination.parse::<OutputTo>().map_err(|_| {
1700                invalid_value(
1701                    command_path,
1702                    "--output-to".to_string(),
1703                    "expected one of split, stdout, stderr",
1704                )
1705            })?;
1706            // Every protocol event is routed to stderr, so nothing is ever
1707            // written to stdout: a file sink for it would be created and stay
1708            // empty. Refuse the contradiction instead of leaving the file behind.
1709            // (The reverse is not one: stderr also carries what the emitter does
1710            // not, such as a panic, so a stderr file has a use under stdout.)
1711            if !stdout_file_allowed(destination) && parsed.stdout_file.is_some() {
1712                let mut error = CliError::new(
1713                    CliErrorRule::UnregisteredCombination,
1714                    command_path.to_string(),
1715                    "--stdout-file cannot be combined with --output-to stderr",
1716                );
1717                let alternatives: Vec<_> = destinations
1718                    .iter()
1719                    .filter(|destination| stdout_file_allowed(destination))
1720                    .map(String::as_str)
1721                    .collect();
1722                error.hint = if alternatives.is_empty() {
1723                    "drop --stdout-file".into()
1724                } else {
1725                    format!(
1726                        "drop --stdout-file or choose --output-to {}",
1727                        alternatives.join(" or ")
1728                    )
1729                };
1730                return Err(error);
1731            }
1732            Ok(OutputPlan::Protocol {
1733                lifecycle: *lifecycle,
1734                format: output_format,
1735                destination: output_to,
1736                stdout_file: parsed.stdout_file.clone(),
1737                stderr_file: parsed.stderr_file.clone(),
1738            })
1739        }
1740    }
1741}
1742
1743fn ensure_sinks(
1744    allowed: &[String],
1745    parsed: &ParsedOutput,
1746    command_path: &str,
1747) -> Result<(), CliError> {
1748    if (parsed.stdout_file.is_some() && !allowed.iter().any(|sink| sink == "stdout"))
1749        || (parsed.stderr_file.is_some() && !allowed.iter().any(|sink| sink == "stderr"))
1750    {
1751        return Err(CliError::unregistered(command_path.to_string()));
1752    }
1753    Ok(())
1754}
1755
1756/// Whether `token` names a segment of some registered command path.
1757///
1758/// Used only to sharpen a diagnosis, so a plain containment test is enough: the
1759/// point is to recognise that the caller typed a command where a value was
1760/// expected, not to work out which command they meant.
1761fn is_registered_command_segment(token: &str, all_commands: &[CommandSpec]) -> bool {
1762    all_commands
1763        .iter()
1764        .any(|command| command.command_path.iter().any(|segment| segment == token))
1765}
1766
1767/// Whether `raw` is a canonical 8-4-4-4-12 hexadecimal UUID.
1768///
1769/// Hand-written rather than pulled from a crate: the check has to be something
1770/// another language can reimplement from `cli-spec-v1` alone, and it keeps the
1771/// core free of a dependency for one argument shape.
1772fn is_canonical_uuid(raw: &str) -> bool {
1773    const GROUPS: [usize; 5] = [8, 4, 4, 4, 12];
1774    let mut parts = raw.split('-');
1775    for width in GROUPS {
1776        let Some(part) = parts.next() else {
1777            return false;
1778        };
1779        if part.len() != width || !part.bytes().all(|byte| byte.is_ascii_hexdigit()) {
1780            return false;
1781        }
1782    }
1783    parts.next().is_none()
1784}
1785
1786fn synthetic_value(argument: &ArgSpec) -> String {
1787    match argument.value_type {
1788        ArgValueType::Flag => String::new(),
1789        ArgValueType::String => {
1790            if argument.sensitive {
1791                "synthetic-sensitive".to_string()
1792            } else {
1793                "value".to_string()
1794            }
1795        }
1796        ArgValueType::I64 => argument
1797            .range
1798            .map_or_else(|| "1".to_string(), |[minimum, _]| minimum.to_string()),
1799        ArgValueType::Uuid => "00000000-0000-0000-0000-000000000000".to_string(),
1800        ArgValueType::FiniteF64 => "1.5".to_string(),
1801        ArgValueType::Enum => argument.enum_values.first().cloned().unwrap_or_default(),
1802        ArgValueType::Json => "{}".to_string(),
1803        ArgValueType::KeyValue => "key=value".to_string(),
1804    }
1805}
1806
1807fn append_synthetic_argument(argv: &mut Vec<String>, argument: &ArgSpec, value: &str) {
1808    match &argument.syntax {
1809        ArgSyntax::Long { name } => {
1810            argv.push(name.clone());
1811            if argument.value_type != ArgValueType::Flag {
1812                argv.push(value.to_string());
1813            }
1814        }
1815        ArgSyntax::Positional { .. } => argv.push(value.to_string()),
1816    }
1817}