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