Skip to main content

kaish_types/
tool.rs

1//! Tool schema and argument types.
2
3use std::collections::{BTreeMap, HashSet};
4
5use crate::value::Value;
6
7fn default_consumes() -> usize {
8    1
9}
10
11/// Schema for a tool parameter.
12#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
13#[non_exhaustive]
14pub struct ParamSchema {
15    /// Parameter name.
16    pub name: String,
17    /// Type hint (string, int, bool, array, object, any).
18    pub param_type: String,
19    /// Whether this parameter is required.
20    pub required: bool,
21    /// Default value if not required.
22    pub default: Option<Value>,
23    /// Description for help text.
24    pub description: String,
25    /// Alternative names/flags for this parameter (e.g., "-r", "-R" for "recursive").
26    pub aliases: Vec<String>,
27    /// Number of positional tokens this non-bool flag consumes per occurrence.
28    ///
29    /// Default 1 (standard `--flag value`). Set to 2 for `--flag NAME VALUE`
30    /// patterns such as jq's `--arg` / `--argjson`. When `consumes > 1`, the
31    /// kernel collects each occurrence as an inner array and accumulates
32    /// repeated occurrences under the same `named` key — the tool sees a
33    /// `Value::Json(Array(Array(...)))` listing every (N-tuple) occurrence.
34    #[serde(default = "default_consumes")]
35    pub consumes: usize,
36    /// True when this flag may appear more than once and each occurrence
37    /// should be kept (clap's `ArgAction::Append`, i.e. a `Vec<_>` value flag
38    /// like sed's `-e`). When set, the kernel accumulates every occurrence
39    /// under the same `named` key as a `Value::Json(Array(...))` instead of
40    /// letting the last write win — the "no silent drop" contract for repeated
41    /// flags. Orthogonal to `consumes`: `consumes` is values-per-occurrence,
42    /// `repeatable` is occurrences-per-invocation.
43    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
44    pub repeatable: bool,
45    /// True for positional arguments (`cat foo.txt`), false for flags
46    /// (`grep --ignore-case`). The validator matches positional params
47    /// against `args.positional` by their order *among positionals only*,
48    /// independent of where they sit in the clap struct. Default false so
49    /// hand-built `ParamSchema::required(...)` constructors keep flag
50    /// semantics; clap-reflected positionals set it via
51    /// `arg.get_index().is_some()`.
52    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
53    pub positional: bool,
54}
55
56impl ParamSchema {
57    /// Create a required parameter.
58    pub fn required(name: impl Into<String>, param_type: impl Into<String>, description: impl Into<String>) -> Self {
59        Self {
60            name: name.into(),
61            param_type: param_type.into(),
62            required: true,
63            default: None,
64            description: description.into(),
65            aliases: Vec::new(),
66            consumes: 1,
67            repeatable: false,
68            positional: false,
69        }
70    }
71
72    /// Create an optional parameter with a default value.
73    pub fn optional(name: impl Into<String>, param_type: impl Into<String>, default: Value, description: impl Into<String>) -> Self {
74        Self {
75            name: name.into(),
76            param_type: param_type.into(),
77            required: false,
78            default: Some(default),
79            description: description.into(),
80            aliases: Vec::new(),
81            consumes: 1,
82            repeatable: false,
83            positional: false,
84        }
85    }
86
87    /// Create a minimal parameter (not required, no default, empty
88    /// description, `consumes` 1, flag — not positional). Chain the `with_*`
89    /// setters to fill in fields. Use this when each field is computed
90    /// independently (e.g. reflected from clap) rather than fitting the
91    /// `required`/`optional` shortcuts. Keeps construction working across the
92    /// `#[non_exhaustive]` boundary.
93    pub fn new(name: impl Into<String>, param_type: impl Into<String>) -> Self {
94        Self {
95            name: name.into(),
96            param_type: param_type.into(),
97            required: false,
98            default: None,
99            description: String::new(),
100            aliases: Vec::new(),
101            consumes: 1,
102            repeatable: false,
103            positional: false,
104        }
105    }
106
107    /// Set the human-readable description.
108    pub fn with_description(mut self, description: impl Into<String>) -> Self {
109        self.description = description.into();
110        self
111    }
112
113    /// Set whether the parameter is required.
114    pub fn with_required(mut self, required: bool) -> Self {
115        self.required = required;
116        self
117    }
118
119    /// Set the default value (used when the parameter is omitted).
120    pub fn with_default(mut self, default: Option<Value>) -> Self {
121        self.default = default;
122        self
123    }
124
125    /// Set the positional flag from a computed boolean (the parameterless
126    /// [`positional`](Self::positional) sets it unconditionally to `true`).
127    pub fn with_positional(mut self, positional: bool) -> Self {
128        self.positional = positional;
129        self
130    }
131
132    /// Mark this parameter as positional (matched by argv order rather than
133    /// by name). Used by `params_from_clap` for clap args with an assigned
134    /// index, and by hand-written schemas for positional parameters like
135    /// jq's `filter`.
136    pub fn positional(mut self) -> Self {
137        self.positional = true;
138        self
139    }
140
141    /// Add alternative names/flags for this parameter.
142    ///
143    /// Aliases are used for short flags like `-r`, `-R` that map to `recursive`.
144    pub fn with_aliases(mut self, aliases: impl IntoIterator<Item = impl Into<String>>) -> Self {
145        self.aliases = aliases.into_iter().map(Into::into).collect();
146        self
147    }
148
149    /// Declare how many positional tokens this non-bool flag consumes per
150    /// occurrence (`--flag v1 v2 ...`). Default is 1. Panics on 0 — a flag
151    /// that consumes nothing is a bool flag, not a schema-typed param.
152    pub fn consumes(mut self, n: usize) -> Self {
153        assert!(n >= 1, "ParamSchema::consumes requires n >= 1 (use a bool param for flags that take no value)");
154        self.consumes = n;
155        self
156    }
157
158    /// Mark this flag as repeatable: each occurrence is accumulated rather than
159    /// overwritten (see [`repeatable`](Self::repeatable)). Set from a computed
160    /// boolean so clap reflection can pass `ArgAction::Append` directly.
161    pub fn with_repeatable(mut self, repeatable: bool) -> Self {
162        self.repeatable = repeatable;
163        self
164    }
165
166    /// Check if a flag name matches this parameter or any of its aliases.
167    pub fn matches_flag(&self, flag: &str) -> bool {
168        if self.name == flag {
169            return true;
170        }
171        self.aliases.iter().any(|a| a == flag)
172    }
173}
174
175/// An example showing how to use a tool.
176#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
177pub struct Example {
178    /// Short description of what the example demonstrates.
179    pub description: String,
180    /// The example command/code.
181    pub code: String,
182}
183
184impl Example {
185    /// Create a new example.
186    pub fn new(description: impl Into<String>, code: impl Into<String>) -> Self {
187        Self {
188            description: description.into(),
189            code: code.into(),
190        }
191    }
192}
193
194/// How the kernel's argv binder hands a tool its arguments.
195///
196/// The default split into [`ToolArgs::positional`], [`ToolArgs::named`] and
197/// [`ToolArgs::flags`] is set-shaped, which suits most tools but cannot serve a
198/// subcommand tree: `kj block list --limit 5` renders back as
199/// `--limit=5 -- block list`, which clap rejects because `--limit` belongs to
200/// `list`, not the root. Order and multiplicity are gone by then.
201///
202/// A third binding is plausible, so this enum is `#[non_exhaustive]` from the
203/// day it ships: adding the attribute later is itself a breaking change. Match
204/// with a wildcard arm that fails loudly, never a silent default.
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
206#[serde(rename_all = "lowercase")]
207#[non_exhaustive]
208pub enum ArgBinding {
209    /// Decompose into `positional`/`named`/`flags`. The default; every tool
210    /// that does not ask for something else gets this.
211    #[default]
212    Typed,
213    /// Hand the tool every word after its name, in source order, as
214    /// [`ToolArgs::words`]. See [`ToolSchema::with_verbatim_argv`].
215    Verbatim,
216}
217
218impl ArgBinding {
219    /// True for the default binding. `skip_serializing_if` reads this so a
220    /// typed tool's schema carries no `"arg_binding"` key at all.
221    pub fn is_typed(&self) -> bool {
222        matches!(self, ArgBinding::Typed)
223    }
224}
225
226/// Schema describing a tool's interface.
227#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
228#[non_exhaustive]
229pub struct ToolSchema {
230    /// Tool name.
231    pub name: String,
232    /// Short description.
233    pub description: String,
234    /// Parameter definitions.
235    pub params: Vec<ParamSchema>,
236    /// Whether `$(tool)` binds this tool's `.data` as a typed value rather
237    /// than binding its text. See [`ToolSchema::with_typed_substitution`].
238    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
239    pub typed_substitution: bool,
240    /// Usage examples.
241    pub examples: Vec<Example>,
242    /// Map remaining positional args to named params by schema order.
243    /// Only for MCP/external tools that expect named JSON params.
244    /// Builtins handle their own positionals and should leave this false.
245    pub map_positionals: bool,
246    /// Child schemas for subcommand-aware tools (`kj context list`, …).
247    ///
248    /// Empty for flat tools (`cat`, `grep`, `ls`) — they take the flat binding
249    /// path. When non-empty, the kernel walks leading positionals to pick the
250    /// active leaf and binds flags against *that leaf's* `params` (see
251    /// `select_leaf` in the kernel).
252    ///
253    /// `skip_serializing_if` keeps the wire compact for the many flat tools
254    /// (no `"subcommands":[]` noise); `default` is then required so a flat
255    /// tool's payload (key absent) deserializes back to empty.
256    #[serde(default, skip_serializing_if = "Vec::is_empty")]
257    pub subcommands: Vec<ToolSchema>,
258    /// Command-level aliases (`ls` → `list`, `rm` → `remove`), matched when
259    /// routing a positional to a child. Distinct from [`ParamSchema::aliases`],
260    /// which name *flags*.
261    #[serde(default, skip_serializing_if = "Vec::is_empty")]
262    pub aliases: Vec<String>,
263    /// The tool renders its **own** output, including `--json` — the kernel
264    /// must not re-format its `ExecResult` through `apply_output_format`.
265    ///
266    /// Default false: a tool returns typed [`crate::OutputData`] and the kernel
267    /// renders the requested format uniformly. Set true for tools with bespoke
268    /// JSON envelopes (e.g. an embedder's `kj`): they consume `--json`
269    /// themselves and emit final bytes. See [`ToolSchema::with_owned_output`].
270    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
271    pub owns_output: bool,
272    /// The tool wants its argv **in source order, with types preserved** — the
273    /// binder must NOT split flags into the unordered `flags` set. When true,
274    /// every argument is bound to `positional` in the order written (operators
275    /// like `-f`/`=`/`!` as strings, operands keeping their `Value` type), and
276    /// `named`/`flags` stay empty.
277    ///
278    /// Default false: normal tools get the clap-style order-independent split
279    /// (`-la` == `-al`). Set true for the rare *position-sensitive* command
280    /// whose operands may themselves look like flags — POSIX `test`, where
281    /// `test $x = -n` and `test 0 -gt -5` must see `-n`/`-5` as literal
282    /// operands. See [`ToolSchema::with_raw_argv`].
283    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
284    pub raw_argv: bool,
285    /// How the binder hands this tool its arguments. See [`ArgBinding`].
286    #[serde(default, skip_serializing_if = "ArgBinding::is_typed")]
287    pub arg_binding: ArgBinding,
288    /// The tool consumes glob patterns **as data** — the argv binder must pass
289    /// a bare glob pattern through as literal text instead of expanding it to
290    /// matching paths.
291    ///
292    /// Default false: shell semantics — `cat *.rs` sees matching files and
293    /// zero matches is a bind-time error. Set true for a tool whose input *is*
294    /// the pattern (`glob`), so the natural unquoted spelling
295    /// (`glob **/*.rs`) hands the pattern text to the tool instead of walking
296    /// the tree at bind time and binding the first match as the "pattern".
297    /// See [`ToolSchema::with_glob_passthrough`].
298    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
299    pub glob_passthrough: bool,
300    /// Dotted effect ids this tool declares (`fs.remove`, `fs.overwrite`,
301    /// …) — what an embedder reads off `tools --json` to learn a tool's
302    /// destructive effects instead of recognizing tool names. Empty for a
303    /// tool with no destructive effect. A flat tool with several behaviors
304    /// behind one schema (`kaish-trash`'s `list`/`restore`/`config`/`empty`)
305    /// lists every effect any of its behaviors has, not just the ones the
306    /// current invocation will reach — the schema is reflected once, before
307    /// argv says which behavior runs. See [`ToolSchema::with_operations`].
308    #[serde(default, skip_serializing_if = "Vec::is_empty")]
309    pub operations: Vec<String>,
310}
311
312impl ToolSchema {
313    /// Create a new tool schema.
314    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
315        Self {
316            name: name.into(),
317            description: description.into(),
318            params: Vec::new(),
319            examples: Vec::new(),
320            map_positionals: false,
321            subcommands: Vec::new(),
322            aliases: Vec::new(),
323            owns_output: false,
324            raw_argv: false,
325            arg_binding: ArgBinding::Typed,
326            glob_passthrough: false,
327            typed_substitution: false,
328            operations: Vec::new(),
329        }
330    }
331
332    /// Declare that this tool wants its argv in source order with types
333    /// preserved (no flag/positional split). See [`ToolSchema::raw_argv`].
334    ///
335    /// Setting this and [`ToolSchema::with_verbatim_argv`] together is a
336    /// mistake; verbatim wins.
337    pub fn with_raw_argv(mut self) -> Self {
338        self.raw_argv = true;
339        self
340    }
341
342    /// Declare that this tool parses its own argv: the binder fills
343    /// [`ToolArgs::words`] with every word after the tool name, in source
344    /// order, post-expansion, and leaves the split empty. See [`ArgBinding`]
345    /// for when to use it. [`ToolArgs::to_argv`] cannot put
346    /// them back — a verbatim tool builds its argv from `words` with no
347    /// inversion at all ([`ToolArgs::words_argv`] does the rendering).
348    ///
349    /// The kernel still owns the global flags: `--json` is removed from
350    /// `words` wherever it appears and applied to the output format, so a
351    /// verbatim tool never sees it and cannot get it wrong. The schema is
352    /// unchanged either way — it still supplies help, completion and the
353    /// parameter list.
354    ///
355    /// Distinct from [`ToolSchema::with_raw_argv`], which also keeps source
356    /// order but binds into `positional` and does not lift the global flags.
357    /// Setting both is a mistake; verbatim wins.
358    ///
359    /// With [`ToolSchema::with_owned_output`] the tool keeps `--json` in its
360    /// own words — the kernel renders nothing for such a tool, so lifting the
361    /// flag would leave it handled by no one.
362    pub fn with_verbatim_argv(mut self) -> Self {
363        self.arg_binding = ArgBinding::Verbatim;
364        self
365    }
366
367    /// Declare that this tool's `.data` IS its value, so `$(tool)` binds it
368    /// typed instead of binding the text it printed.
369    ///
370    /// `.data` does three jobs: it feeds `--json`, it is the pipeline's
371    /// structured sideband, and it is what a command substitution binds. Only
372    /// the third is a question of taste, and answering it from "does this tool
373    /// set `.data`" got it wrong: `cut -f2 f` bound `["b"]` while
374    /// `awk '{print $2}' f`, doing the identical job, bound text.
375    ///
376    /// Declare it when the structured thing IS the answer — `fromjson`, `jq`,
377    /// `keys`, `values`. Leave it off when `.data` is a structured VIEW of
378    /// text the tool already printed, which is every tool with a POSIX
379    /// counterpart: those read as their POSIX selves, and a caller who wants
380    /// types asks with `--json`.
381    ///
382    /// Not inferable from the constructor: `jq` and `cut` both build with
383    /// `success_with_data` and belong on opposite sides.
384    pub fn with_typed_substitution(mut self) -> Self {
385        self.typed_substitution = true;
386        self
387    }
388
389    /// Declare that this tool consumes glob patterns as data: the argv binder
390    /// passes bare patterns through as literal text instead of expanding them.
391    /// See [`ToolSchema::glob_passthrough`].
392    pub fn with_glob_passthrough(mut self) -> Self {
393        self.glob_passthrough = true;
394        self
395    }
396
397    /// Declare the dotted effect ids this tool carries. See
398    /// [`ToolSchema::operations`].
399    pub fn with_operations(mut self, operations: impl IntoIterator<Item = impl Into<String>>) -> Self {
400        self.operations = operations.into_iter().map(Into::into).collect();
401        self
402    }
403
404    /// Enable positional->named parameter mapping for MCP/external tools.
405    pub fn with_positional_mapping(mut self) -> Self {
406        self.map_positionals = true;
407        self
408    }
409
410    /// Add a parameter to the schema.
411    pub fn param(mut self, param: ParamSchema) -> Self {
412        self.params.push(param);
413        self
414    }
415
416    /// Add an example to the schema.
417    pub fn example(mut self, description: impl Into<String>, code: impl Into<String>) -> Self {
418        self.examples.push(Example::new(description, code));
419        self
420    }
421
422    /// Add a child schema, making this a subcommand-aware tool.
423    pub fn subcommand(mut self, child: ToolSchema) -> Self {
424        self.subcommands.push(child);
425        self
426    }
427
428    /// Set command-level aliases (e.g. `ls` for a `list` subcommand). These
429    /// name the *command*, not its flags; flag aliases live on each
430    /// [`ParamSchema`].
431    pub fn with_command_aliases(mut self, aliases: impl IntoIterator<Item = impl Into<String>>) -> Self {
432        self.aliases = aliases.into_iter().map(Into::into).collect();
433        self
434    }
435
436    /// True if `word` names this command — its `name` or any of its
437    /// command-level `aliases`. Used when routing a positional to a child.
438    pub fn matches_command(&self, word: &str) -> bool {
439        self.name == word || self.aliases.iter().any(|a| a == word)
440    }
441
442    /// Declare that this tool renders its own output (including `--json`), so
443    /// the kernel won't re-format its result.
444    ///
445    /// Applies to the whole tree: every subcommand is marked too, and a `json`
446    /// param is advertised on each node that doesn't already declare one.
447    /// Reflection skips `json` as the kernel-global output flag, so this
448    /// re-advertises it for tools that genuinely own it — closing the loop so
449    /// `help <tool> <sub>` lists `--json` where the tool actually handles it.
450    pub fn with_owned_output(mut self) -> Self {
451        self.mark_owned_output();
452        self
453    }
454
455    fn mark_owned_output(&mut self) {
456        self.owns_output = true;
457        if !self.params.iter().any(|p| p.name == "json") {
458            self.params.push(
459                ParamSchema::new("json", "bool").with_description("Render output as JSON"),
460            );
461        }
462        for child in &mut self.subcommands {
463            child.mark_owned_output();
464        }
465    }
466}
467
468/// Parsed arguments ready for tool execution.
469#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
470#[non_exhaustive]
471pub struct ToolArgs {
472    /// Positional arguments in order.
473    pub positional: Vec<Value>,
474    /// Named arguments by key.
475    pub named: BTreeMap<String, Value>,
476    /// Boolean flags (e.g., -l, --force).
477    pub flags: HashSet<String>,
478    /// Every word after the tool name, in source order, post-expansion —
479    /// `Some` only for an [`ArgBinding::Verbatim`] tool, `None` for every
480    /// other tool.
481    ///
482    /// A text word arrives as [`Value::String`]; a heredoc- or pipe-bound word
483    /// keeps its [`Value::Bytes`]. `positional` and `named` are empty when this
484    /// is `Some`; `flags` holds only the global flags the binder lifted out
485    /// (today just `json`), so `has_flag("json")` still answers.
486    ///
487    /// Render it to a clap argv with [`ToolArgs::words_argv`].
488    #[serde(default, skip_serializing_if = "Option::is_none")]
489    pub words: Option<Vec<Value>>,
490}
491
492impl ToolArgs {
493    /// Create empty args.
494    pub fn new() -> Self {
495        Self::default()
496    }
497
498    /// Render [`words`](Self::words) into argv tokens for a verbatim tool's
499    /// own parser. Empty when the tool is not verbatim.
500    ///
501    /// A [`Value::Bytes`] word renders as an inert placeholder token, as
502    /// [`to_argv`](Self::to_argv) does for a binary positional; the real bytes
503    /// stay at the matching index in `words`.
504    pub fn words_argv(&self) -> Vec<String> {
505        self.words
506            .as_deref()
507            .unwrap_or_default()
508            .iter()
509            .map(value_to_argv_token)
510            .collect()
511    }
512
513    /// Get a positional argument by index.
514    pub fn get_positional(&self, index: usize) -> Option<&Value> {
515        self.positional.get(index)
516    }
517
518    /// Get a named argument by key.
519    pub fn get_named(&self, key: &str) -> Option<&Value> {
520        self.named.get(key)
521    }
522
523    /// Get a named argument or positional fallback.
524    ///
525    /// Useful for tools that accept both `cat file.txt` and `cat path=file.txt`.
526    pub fn get(&self, name: &str, positional_index: usize) -> Option<&Value> {
527        self.named.get(name).or_else(|| self.positional.get(positional_index))
528    }
529
530    /// Get a string value from args.
531    pub fn get_string(&self, name: &str, positional_index: usize) -> Option<String> {
532        self.get(name, positional_index).and_then(|v| match v {
533            Value::String(s) => Some(s.clone()),
534            Value::Int(i) => Some(i.to_string()),
535            Value::Float(f) => Some(f.to_string()),
536            Value::Bool(b) => Some(b.to_string()),
537            _ => None,
538        })
539    }
540
541    /// Get a boolean value from args.
542    pub fn get_bool(&self, name: &str, positional_index: usize) -> Option<bool> {
543        self.get(name, positional_index).and_then(|v| match v {
544            Value::Bool(b) => Some(*b),
545            Value::String(s) => match s.as_str() {
546                "true" | "yes" | "1" => Some(true),
547                "false" | "no" | "0" => Some(false),
548                _ => None,
549            },
550            Value::Int(i) => Some(*i != 0),
551            _ => None,
552        })
553    }
554
555    /// Check if a flag is set (in flags set, or named bool).
556    pub fn has_flag(&self, name: &str) -> bool {
557        // Check the flags set first (from -x or --name syntax)
558        if self.flags.contains(name) {
559            return true;
560        }
561        // Fall back to checking named args (from name=true syntax)
562        self.named.get(name).is_some_and(|v| match v {
563            Value::Bool(b) => *b,
564            Value::String(s) => !s.is_empty() && s != "false" && s != "0",
565            _ => true,
566        })
567    }
568
569    /// Move bool entries from `named` into the appropriate set so a downstream
570    /// clap parser (with `#[arg(...)] field: bool`) accepts them.
571    ///
572    /// Tests routinely seed `args.named.insert(K, Value::Bool(true))` for the
573    /// schema-pre-clap path; `to_argv()` would emit those as `--K=true`, which
574    /// clap rejects for `bool` fields. Promote to:
575    /// - `Bool(true)` → presence in `flags` (clap sees `--K`).
576    /// - `Bool(false)` → dropped (clap treats absent flag and explicit false
577    ///   the same; preserving it would only resurface as `--K=false` and break
578    ///   the same parser).
579    ///
580    /// A `Value::Bool` parked under a key the `schema` declares as a *value-taking*
581    /// flag is the flag's literal value, not a bare bool flag — `spawn --command
582    /// true` binds `command = Bool(true)`. Those keys are left in `named` so
583    /// `to_argv()` renders `--command=true` and clap's `Option<String>` field
584    /// accepts it; collapsing them to a bare `--command` drops the value and
585    /// makes clap error "a value is required".
586    ///
587    /// Idempotent. Non-bool named entries are left alone.
588    pub fn flagify_bool_named(&mut self, schema: &ToolSchema) {
589        // Keys (param names + aliases) the schema declares as non-bool, non-positional
590        // flags — i.e. flags that take a value.
591        let value_keys: HashSet<&str> = schema
592            .params
593            .iter()
594            .filter(|p| !p.positional && !is_bool_param_type(&p.param_type))
595            .flat_map(|p| {
596                std::iter::once(p.name.as_str())
597                    .chain(p.aliases.iter().map(|a| a.trim_start_matches('-')))
598            })
599            .collect();
600
601        let bool_keys: Vec<String> = self
602            .named
603            .iter()
604            .filter(|(k, v)| matches!(v, Value::Bool(_)) && !value_keys.contains(k.as_str()))
605            .map(|(k, _)| k.clone())
606            .collect();
607        for k in bool_keys {
608            // Remove unconditionally so Bool(false) doesn't linger and break
609            // a `--K=false` rejection in clap. Only Bool(true) re-enters as a
610            // flag presence.
611            if let Some(Value::Bool(true)) = self.named.remove(&k) {
612                self.flags.insert(k);
613            }
614        }
615    }
616
617    /// Reconstruct a clap-friendly argv vector from already-parsed ToolArgs.
618    ///
619    /// kaish has already done shell parsing (variables expanded, globs expanded,
620    /// `$(...)` substituted, schema-driven flag/value splitting). `to_argv`
621    /// rebuilds a flat token stream suitable for `Parser::parse_from(std::iter::once("<tool>").chain(args.to_argv()?))`.
622    ///
623    /// Layout: flags first (as `--<name>`), then named values (as
624    /// `--<name>=<value>`), then positionals — separated from earlier sections
625    /// by `--` so trailing-passthrough builtins still see them as positionals
626    /// even if a value happens to begin with `-`.
627    ///
628    /// # Errors
629    ///
630    /// Returns [`ToolArgvError`] when a **named/flag** value is
631    /// [`Value::Bytes`] — binary can't cross the argv/text stringification
632    /// boundary (GH #164, closing the root cause behind GH #120's stringified
633    /// `[binary: N bytes]` placeholder). A **positional** `Value::Bytes` does
634    /// NOT error here; see `value_to_argv_token`'s doc comment for why.
635    ///
636    /// See the clap builtin pattern in CLAUDE.md (Contributor conventions).
637    ///
638    /// Equivalent to [`to_argv_excluding`](Self::to_argv_excluding)`(&[])` —
639    /// same rendering path, nothing excluded.
640    pub fn to_argv(&self) -> Result<Vec<String>, ToolArgvError> {
641        self.to_argv_excluding(&[])
642    }
643
644    /// Like [`to_argv`](Self::to_argv), but skips the given **named** keys
645    /// entirely — neither the key's flag token nor its value appears in the
646    /// rendered argv, and (crucially) a `Value::Bytes` under an excluded key
647    /// is never passed to `render_named_value`, so it can never trip
648    /// [`ToolArgvError::BinaryNamedValue`].
649    ///
650    /// Use this when a builtin deliberately reads one of its own named
651    /// parameters raw off `ToolArgs` (e.g. `args.named.get("content")`)
652    /// instead of the clap-parsed field, specifically to preserve a
653    /// typed/binary value that must not cross the argv/text stringification
654    /// boundary — while still wanting the *rest* of its arguments bound
655    /// through the normal clap path. `write`'s `content` param is the
656    /// motivating case (GH #218, a follow-up from the GH #164 / #215
657    /// review): before this helper, the builtin cloned the whole `ToolArgs`
658    /// and called `named.remove("content")` by hand, which silently stops
659    /// covering a *second* Bytes-capable named param the moment one is added.
660    /// Naming the excluded keys here instead makes the exemption a
661    /// greppable, drift-resistant idiom.
662    ///
663    /// Only **named** keys are excludable — not flags or positionals, by
664    /// design. A bool flag carries no value to protect, so there is nothing
665    /// to exempt. A positional's clap-reflected field is already a
666    /// validation-only sink nobody reads (see CLAUDE.md's clap-builtin
667    /// convention), so a positional `Value::Bytes` never needed an
668    /// exemption in the first place — `value_to_argv_token` renders it as
669    /// an inert placeholder rather than erroring. If a future case needs to
670    /// exclude a flag or positional too, that is new design, not an
671    /// extension of this helper.
672    pub fn to_argv_excluding(&self, exclude: &[&str]) -> Result<Vec<String>, ToolArgvError> {
673        let mut argv = Vec::with_capacity(
674            self.flags.len() + self.named.len() * 2 + self.positional.len() + 1,
675        );
676
677        // Flags are unordered (HashSet); sort for deterministic argv so tests
678        // and snapshots stay stable. Single-char keys emit short form (`-n`)
679        // so clap's natural `#[arg(short = 'n', long = "no_newline")]` derive
680        // accepts them without needing visible_alias gymnastics.
681        let mut flags: Vec<&String> = self.flags.iter().collect();
682        flags.sort();
683        for flag in flags {
684            argv.push(flag_token(flag));
685        }
686
687        // Named values: emit `-k=value` for single-char keys and `--key=value`
688        // for multi-char keys. `=` form keeps parsing unambiguous when the
689        // value begins with `-`. Multi-value (`consumes > 1`) params are
690        // stored as Value::Json(Array(Array(...))) — one entry per occurrence.
691        // An excluded key is skipped before its value is ever inspected, so a
692        // Value::Bytes there can't reach render_named_value's Bytes guard.
693        for (key, value) in &self.named {
694            if exclude.contains(&key.as_str()) {
695                continue;
696            }
697            for rendered in render_named_value(key, value)? {
698                argv.push(format!("{}={}", flag_token(key), rendered));
699            }
700        }
701
702        // `--` terminator so clap treats positionals as positionals even if
703        // they begin with `-` (e.g. `echo -- -n` should print `-n`).
704        if !self.positional.is_empty() {
705            argv.push("--".to_string());
706            for value in &self.positional {
707                argv.push(value_to_argv_token(value));
708            }
709        }
710
711        Ok(argv)
712    }
713}
714
715/// Error raised by [`ToolArgs::to_argv`] when a **named or flag** argument
716/// cannot cross the argv/text stringification boundary.
717///
718/// The only offending [`Value`] variant is [`Value::Bytes`] — every other
719/// variant has a lossless text form. Binary crossing this boundary used to
720/// silently render as a `[binary: N bytes]` placeholder text token, which a
721/// downstream clap-parsed field (`parsed.separator`, `parsed.algo`, …) would
722/// then see as if it were the user's real value — GH #120's root cause,
723/// deferred as "Phase 2" at the time and closed here (GH #164).
724///
725/// Deliberately does **not** cover positional `Value::Bytes` — see
726/// `value_to_argv_token`'s doc comment for why a positional binary value
727/// stays safe to render as a placeholder rather than error.
728#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
729#[non_exhaustive]
730pub enum ToolArgvError {
731    /// A named/flag argument held [`Value::Bytes`].
732    #[error(
733        "argument `{key}` holds {byte_len} binary bytes, which cannot cross the argv/text \
734         boundary — read it from the raw ToolArgs value (e.g. `args.get(\"{key}\", ..)`) \
735         instead of the clap-parsed field"
736    )]
737    BinaryNamedValue {
738        /// The named argument's key (the schema name, e.g. `"separator"` —
739        /// not the `-`/`--`-prefixed flag_token form).
740        key: String,
741        /// The number of binary bytes it held. Never the bytes themselves —
742        /// this error message must stay safe to log.
743        byte_len: usize,
744    },
745}
746
747fn flag_token(name: &str) -> String {
748    if name.chars().count() == 1 {
749        format!("-{name}")
750    } else {
751        format!("--{name}")
752    }
753}
754
755/// Whether a `ParamSchema::param_type` names a boolean flag.
756fn is_bool_param_type(param_type: &str) -> bool {
757    param_type.eq_ignore_ascii_case("bool") || param_type.eq_ignore_ascii_case("boolean")
758}
759
760/// Render one named argument's value into its `to_argv()` token(s).
761///
762/// `key` is only used to attribute a [`ToolArgvError`] to the argument that
763/// held it — it does not affect rendering of any other variant.
764fn render_named_value(key: &str, value: &Value) -> Result<Vec<String>, ToolArgvError> {
765    match value {
766        // `consumes > 1` lands as Json(Array(Array(...))) — one inner array per
767        // occurrence. Flatten each inner array into space-joined tokens; clap
768        // can split on `=` further if needed.
769        Value::Json(serde_json::Value::Array(outer)) if outer.iter().all(|v| v.is_array()) => {
770            Ok(outer
771                .iter()
772                .map(|inner| {
773                    inner
774                        .as_array()
775                        .map(|a| a.iter().map(json_value_to_token).collect::<Vec<_>>().join(" "))
776                        .unwrap_or_default()
777                })
778                .collect())
779        }
780        // A named/flag value is commonly read straight off the clap-parsed
781        // field (`parsed.separator`, `parsed.algo`, …) rather than the raw
782        // `ToolArgs`, so silently stringifying binary here — as the old
783        // `[binary: N bytes]` placeholder did — hands a builtin's clap struct
784        // a value that looks textual but isn't the user's real data (GH #120's
785        // root cause). Loud instead: see `ToolArgvError`.
786        Value::Bytes(data) => Err(ToolArgvError::BinaryNamedValue {
787            key: key.to_string(),
788            byte_len: data.len(),
789        }),
790        _ => Ok(vec![value_to_argv_token(value)]),
791    }
792}
793
794/// Render one **positional** argument's value into its `to_argv()` token.
795///
796/// `Value::Bytes` renders as a visible placeholder rather than erroring —
797/// unlike the named-value path in [`render_named_value`]. This is safe only
798/// because a clap-reflected positional field is a validation-only sink (see
799/// CLAUDE.md's clap-builtin convention): no builtin reads a positional's
800/// *value* off the parsed clap struct, every one of them reads the typed
801/// `Value` straight off `args.positional` instead (e.g. `push`'s `rest:
802/// Vec<String>` sink, or `write`'s content positional, which accepts real
803/// `Value::Bytes` content byte-for-byte via `args.positional`, never via
804/// `parsed`). A placeholder token here only has to satisfy clap's parse (argv
805/// shape / arity), never carry real data anywhere — so it can never leak
806/// unlike the named case this function's sibling guards against.
807fn value_to_argv_token(value: &Value) -> String {
808    match value {
809        Value::Null => String::new(),
810        Value::Bool(b) => b.to_string(),
811        Value::Int(i) => i.to_string(),
812        Value::Float(f) => f.to_string(),
813        Value::String(s) => s.clone(),
814        Value::Json(j) => j.to_string(),
815        Value::Bytes(data) => format!("[binary: {} bytes]", data.len()),
816    }
817}
818
819/// Is a kernel-owned global flag written as `--flag=VALUE` on?
820///
821/// Off for the empty string, `false`, `0`, and a numeric zero; on for
822/// everything else, including a value the kernel could not evaluate. `--json`
823/// is bound by three different binders — typed, `raw_argv`, and `verbatim` —
824/// and each one asks this question. Asking it in one place is what keeps
825/// `--json=0` meaning the same thing on all three.
826///
827/// This is deliberately NOT [`ToolArgs::has_flag`]'s rule. `has_flag` answers
828/// "was this key provided", which is what a value-taking flag needs
829/// (`head -n 0` provided `-n`), so it treats a numeric zero as present. A
830/// global flag has no value of its own to carry, so for it zero means off.
831///
832/// ```
833/// use kaish_types::{global_flag_value_is_truthy, Value};
834///
835/// assert!(global_flag_value_is_truthy(&Value::String("yes".into())));
836/// assert!(!global_flag_value_is_truthy(&Value::Int(0)));
837/// assert!(!global_flag_value_is_truthy(&Value::String("0".into())));
838/// ```
839pub fn global_flag_value_is_truthy(value: &Value) -> bool {
840    match value {
841        Value::Bool(b) => *b,
842        Value::Int(i) => *i != 0,
843        Value::Float(f) => *f != 0.0,
844        Value::String(s) => !s.is_empty() && s != "false" && s != "0",
845        // A collection, JSON payload, or binary blob is not a spelling of
846        // "off" — treat the flag as given rather than silently dropping it.
847        _ => true,
848    }
849}
850
851fn json_value_to_token(value: &serde_json::Value) -> String {
852    match value {
853        serde_json::Value::Null => String::new(),
854        serde_json::Value::Bool(b) => b.to_string(),
855        serde_json::Value::Number(n) => n.to_string(),
856        serde_json::Value::String(s) => s.clone(),
857        other => other.to_string(),
858    }
859}
860
861#[cfg(test)]
862mod schema_serde_tests {
863    use super::*;
864
865    /// A flat tool (no subcommands/aliases) must serialize byte-identically to
866    /// the pre-subcommand wire format: the two new fields are skipped entirely.
867    #[test]
868    fn flat_schema_omits_new_fields_on_wire() {
869        let schema = ToolSchema::new("cat", "concatenate")
870            .param(ParamSchema::required("path", "string", "file to read").positional());
871        let json = serde_json::to_value(&schema).expect("serialize");
872        let obj = json.as_object().expect("object");
873        assert!(!obj.contains_key("subcommands"), "flat tool leaks subcommands: {json}");
874        assert!(!obj.contains_key("aliases"), "flat tool leaks command aliases: {json}");
875    }
876
877    /// Round-trip the skip: a flat tool serializes *without* the keys, so the
878    /// deserializer must `default` them back to empty. (This is what lets us
879    /// skip-serialize empties without breaking our own flat tools' payloads.)
880    #[test]
881    fn flat_wire_form_deserializes_to_empty() {
882        let flat = serde_json::json!({
883            "name": "cat",
884            "description": "concatenate",
885            "params": [],
886            "examples": [],
887            "map_positionals": false
888        });
889        let schema: ToolSchema = serde_json::from_value(flat).expect("deserialize flat form");
890        assert!(schema.subcommands.is_empty());
891        assert!(schema.aliases.is_empty());
892    }
893
894    /// `with_owned_output` marks the whole tree and advertises `json` on each
895    /// node that didn't already declare it.
896    #[test]
897    fn with_owned_output_marks_tree_and_advertises_json() {
898        let schema = ToolSchema::new("kj", "kaijutsu")
899            .subcommand(
900                ToolSchema::new("context", "ctx")
901                    .subcommand(ToolSchema::new("list", "list contexts")),
902            )
903            .with_owned_output();
904
905        assert!(schema.owns_output, "root marked");
906        assert!(schema.params.iter().any(|p| p.name == "json"), "root advertises json");
907        let context = &schema.subcommands[0];
908        assert!(context.owns_output, "child marked");
909        let list = &context.subcommands[0];
910        assert!(list.owns_output, "grandchild marked");
911        assert!(list.params.iter().any(|p| p.name == "json"), "leaf advertises json");
912    }
913
914    /// `with_owned_output` doesn't duplicate an already-declared `json` param.
915    #[test]
916    fn with_owned_output_does_not_double_add_json() {
917        let schema = ToolSchema::new("kj", "kaijutsu")
918            .param(ParamSchema::new("json", "bool"))
919            .with_owned_output();
920        let json_count = schema.params.iter().filter(|p| p.name == "json").count();
921        assert_eq!(json_count, 1, "json should appear exactly once");
922    }
923
924    /// `owns_output` round-trips and is omitted from the wire when false.
925    #[test]
926    fn owns_output_serde() {
927        let flat = ToolSchema::new("ls", "list");
928        let json = serde_json::to_value(&flat).expect("serialize");
929        let obj = json.as_object().expect("object");
930        assert!(!obj.contains_key("owns_output"), "false omitted: {json}");
931
932        let owned = ToolSchema::new("kj", "kaijutsu").with_owned_output();
933        let wire = serde_json::to_string(&owned).expect("serialize");
934        let back: ToolSchema = serde_json::from_str(&wire).expect("deserialize");
935        assert!(back.owns_output);
936    }
937
938    /// A subcommand tree round-trips through serde with names and aliases intact.
939    #[test]
940    fn subcommand_tree_round_trips() {
941        let schema = ToolSchema::new("kj", "kaijutsu")
942            .subcommand(
943                ToolSchema::new("context", "context ops")
944                    .with_command_aliases(["ctx"])
945                    .subcommand(ToolSchema::new("list", "list contexts").with_command_aliases(["ls"])),
946            );
947        let json = serde_json::to_string(&schema).expect("serialize");
948        let back: ToolSchema = serde_json::from_str(&json).expect("deserialize");
949        assert_eq!(back.subcommands.len(), 1);
950        let context = &back.subcommands[0];
951        assert!(context.matches_command("context"));
952        assert!(context.matches_command("ctx"));
953        assert_eq!(context.subcommands.len(), 1);
954        assert!(context.subcommands[0].matches_command("ls"));
955    }
956}
957
958#[cfg(test)]
959mod to_argv_tests {
960    use super::*;
961
962    #[test]
963    fn empty_args_produce_empty_argv() {
964        assert!(ToolArgs::new().to_argv().unwrap().is_empty());
965    }
966
967    #[test]
968    fn positionals_emitted_after_double_dash() {
969        let mut args = ToolArgs::new();
970        args.positional.push(Value::String("hello".into()));
971        args.positional.push(Value::String("world".into()));
972        assert_eq!(args.to_argv().unwrap(), vec!["--", "hello", "world"]);
973    }
974
975    #[test]
976    fn single_char_flags_emit_short_form() {
977        let mut args = ToolArgs::new();
978        args.flags.insert("n".into());
979        args.flags.insert("verbose".into());
980        // Sorted: "n" then "verbose"
981        assert_eq!(args.to_argv().unwrap(), vec!["-n", "--verbose"]);
982    }
983
984    #[test]
985    fn named_values_use_equals_form() {
986        let mut args = ToolArgs::new();
987        args.named.insert("count".into(), Value::Int(5));
988        args.named.insert("name".into(), Value::String("foo".into()));
989        // BTreeMap iterates in key order, so "count" before "name"
990        assert_eq!(args.to_argv().unwrap(), vec!["--count=5", "--name=foo"]);
991    }
992
993    #[test]
994    fn single_char_named_emits_short_equals() {
995        let mut args = ToolArgs::new();
996        args.named.insert("n".into(), Value::Int(5));
997        assert_eq!(args.to_argv().unwrap(), vec!["-n=5"]);
998    }
999
1000    #[test]
1001    fn positional_with_leading_dash_survives_double_dash() {
1002        let mut args = ToolArgs::new();
1003        args.positional.push(Value::String("-n".into()));
1004        // `echo -- -n` should round-trip as `-- -n`, not be reparsed as a flag.
1005        assert_eq!(args.to_argv().unwrap(), vec!["--", "-n"]);
1006    }
1007
1008    #[test]
1009    fn mixed_flags_named_positionals() {
1010        let mut args = ToolArgs::new();
1011        args.flags.insert("verbose".into());
1012        args.named.insert("limit".into(), Value::Int(10));
1013        args.positional.push(Value::String("file.txt".into()));
1014        assert_eq!(
1015            args.to_argv().unwrap(),
1016            vec!["--verbose", "--limit=10", "--", "file.txt"]
1017        );
1018    }
1019
1020    /// GH #164: a named/flag `Value::Bytes` must error loudly instead of
1021    /// silently stringifying to the `[binary: N bytes]` placeholder — that
1022    /// placeholder is exactly what a downstream clap-parsed field
1023    /// (`parsed.separator`, `parsed.algo`, …) would otherwise see as if it
1024    /// were the user's real value (GH #120's root cause).
1025    #[test]
1026    fn named_bytes_value_errors_loudly() {
1027        let mut args = ToolArgs::new();
1028        args.named.insert("separator".into(), Value::Bytes(vec![0xff, 0x00, 0xfe]));
1029
1030        let err = args.to_argv().expect_err("named Bytes must error");
1031        // The message must name the key and the byte count.
1032        let message = err.to_string();
1033        assert!(message.contains("separator"));
1034        assert!(message.contains('3'));
1035        let ToolArgvError::BinaryNamedValue { key, byte_len } = err;
1036        assert_eq!(key, "separator");
1037        assert_eq!(byte_len, 3);
1038    }
1039
1040    /// A single-char named key (e.g. `-a`) gets the same loud treatment.
1041    #[test]
1042    fn single_char_named_bytes_value_errors_loudly() {
1043        let mut args = ToolArgs::new();
1044        args.named.insert("a".into(), Value::Bytes(vec![1, 2]));
1045
1046        let err = args.to_argv().expect_err("named Bytes must error");
1047        let ToolArgvError::BinaryNamedValue { key, byte_len } = err;
1048        assert_eq!(key, "a");
1049        assert_eq!(byte_len, 2);
1050    }
1051
1052    /// Positional `Value::Bytes`, by contrast, does NOT error — see
1053    /// `value_to_argv_token`'s doc comment. The clap-reflected positional
1054    /// field is a validation-only sink; no builtin ever reads its *value* off
1055    /// the parsed struct (they read the typed `Value` straight off
1056    /// `args.positional`), so a placeholder token here is inert, not
1057    /// corruption. This is the load-bearing decision behind builtins like
1058    /// `push`/`write` accepting real binary content through positionals.
1059    #[test]
1060    fn positional_bytes_value_renders_placeholder_not_error() {
1061        let mut args = ToolArgs::new();
1062        args.positional.push(Value::Bytes(vec![0xff, 0x00, 0xfe]));
1063
1064        let argv = args.to_argv().expect("positional Bytes must not error");
1065        assert_eq!(argv, vec!["--", "[binary: 3 bytes]"]);
1066    }
1067
1068    /// Mixed case: a named Bytes error takes priority even when a positional
1069    /// Bytes value is also present (the loud path must not be starved by
1070    /// iteration order silently succeeding on the positional half first).
1071    #[test]
1072    fn named_bytes_errors_even_with_positional_bytes_present() {
1073        let mut args = ToolArgs::new();
1074        args.named.insert("check".into(), Value::Bytes(vec![9, 9]));
1075        args.positional.push(Value::Bytes(vec![1, 2, 3]));
1076
1077        let err = args.to_argv().expect_err("named Bytes must still error");
1078        let ToolArgvError::BinaryNamedValue { key, .. } = err;
1079        assert_eq!(key, "check");
1080    }
1081
1082    // ── GH #218: ToolArgs::to_argv_excluding ────────────────────────────
1083    //
1084    // write.rs reads its own `content` named param raw off `ToolArgs` to
1085    // preserve `Value::Bytes`, then needs the *rest* of its args through the
1086    // normal clap/to_argv path — these tests pin the helper that replaces the
1087    // ad hoc "clone ToolArgs, remove the key, call to_argv()" dance.
1088
1089    /// A named `Value::Bytes` under an excluded key must not error and must
1090    /// not appear anywhere in the rendered argv — this is the whole point:
1091    /// `write`'s `content` carries real binary and must never reach argv.
1092    #[test]
1093    fn to_argv_excluding_skips_excluded_named_bytes_without_error() {
1094        let mut args = ToolArgs::new();
1095        args.named.insert("content".into(), Value::Bytes(vec![0xff, 0x00, 0xfe]));
1096        args.named.insert("path".into(), Value::String("dest.bin".into()));
1097
1098        let argv = args
1099            .to_argv_excluding(&["content"])
1100            .expect("excluded named Bytes must not error");
1101        assert_eq!(argv, vec!["--path=dest.bin"]);
1102        assert!(
1103            argv.iter().all(|tok| !tok.contains("content")),
1104            "excluded key must not appear in argv at all: {argv:?}"
1105        );
1106    }
1107
1108    /// A named `Value::Bytes` under a key that is NOT excluded still errors
1109    /// loudly, same as plain `to_argv()` — excluding one key must not blanket
1110    /// the whole named map.
1111    #[test]
1112    fn to_argv_excluding_still_errors_on_non_excluded_named_bytes() {
1113        let mut args = ToolArgs::new();
1114        args.named.insert("content".into(), Value::Bytes(vec![1, 2, 3]));
1115        args.named.insert("separator".into(), Value::Bytes(vec![9, 9]));
1116
1117        let err = args
1118            .to_argv_excluding(&["content"])
1119            .expect_err("non-excluded named Bytes must still error");
1120        let ToolArgvError::BinaryNamedValue { key, .. } = err;
1121        assert_eq!(key, "separator");
1122    }
1123
1124    /// Excluding a key that isn't a `Value::Bytes` at all (the common case —
1125    /// most invocations of `write` carry plain string content) still drops it
1126    /// from argv. The exclusion is unconditional on the key, not conditional
1127    /// on the value being binary.
1128    #[test]
1129    fn to_argv_excluding_drops_excluded_key_regardless_of_value_type() {
1130        let mut args = ToolArgs::new();
1131        args.named.insert("content".into(), Value::String("hello".into()));
1132        args.named.insert("path".into(), Value::String("dest.txt".into()));
1133
1134        let argv = args.to_argv_excluding(&["content"]).expect("no error expected");
1135        assert_eq!(argv, vec!["--path=dest.txt"]);
1136    }
1137
1138    /// An empty exclude list must behave *exactly* like `to_argv()` — same
1139    /// tokens, same order — across flags, named values, and positionals, on
1140    /// args that don't touch the Bytes edge case at all. `to_argv()` itself
1141    /// delegates to this with an empty slice, so this is also the guard that
1142    /// the delegation didn't change plain `to_argv()` behavior.
1143    #[test]
1144    fn to_argv_excluding_empty_list_matches_to_argv() {
1145        let mut args = ToolArgs::new();
1146        args.flags.insert("verbose".into());
1147        args.flags.insert("n".into());
1148        args.named.insert("limit".into(), Value::Int(10));
1149        args.named.insert("name".into(), Value::String("foo".into()));
1150        args.positional.push(Value::String("file.txt".into()));
1151        args.positional.push(Value::String("-weird".into()));
1152
1153        assert_eq!(
1154            args.to_argv_excluding(&[]).unwrap(),
1155            args.to_argv().unwrap(),
1156            "empty exclude list must be indistinguishable from to_argv()"
1157        );
1158    }
1159
1160    #[test]
1161    fn flagify_bool_named_promotes_true_to_flag() {
1162        let mut args = ToolArgs::new();
1163        args.named.insert("recursive".into(), Value::Bool(true));
1164        args.named.insert("limit".into(), Value::Int(5));
1165
1166        args.flagify_bool_named(&ToolSchema::new("t", ""));
1167
1168        assert!(args.flags.contains("recursive"));
1169        assert!(!args.named.contains_key("recursive"));
1170        // Non-bool entries are untouched.
1171        assert_eq!(args.named.get("limit"), Some(&Value::Int(5)));
1172    }
1173
1174    #[test]
1175    fn flagify_bool_named_drops_false() {
1176        let mut args = ToolArgs::new();
1177        args.named.insert("recursive".into(), Value::Bool(false));
1178
1179        args.flagify_bool_named(&ToolSchema::new("t", ""));
1180
1181        assert!(!args.flags.contains("recursive"));
1182        assert!(!args.named.contains_key("recursive"));
1183    }
1184
1185    #[test]
1186    fn flagify_bool_named_is_idempotent() {
1187        let mut args = ToolArgs::new();
1188        args.named.insert("recursive".into(), Value::Bool(true));
1189        args.flagify_bool_named(&ToolSchema::new("t", ""));
1190        args.flagify_bool_named(&ToolSchema::new("t", ""));
1191        assert!(args.flags.contains("recursive"));
1192    }
1193
1194    /// Regression guard: argv emitted after flagify must round-trip through
1195    /// a clap parser without `--K=true` showing up.
1196    #[test]
1197    fn flagify_bool_named_round_trips_through_to_argv() {
1198        let mut args = ToolArgs::new();
1199        args.named.insert("R".into(), Value::Bool(true));
1200        args.flagify_bool_named(&ToolSchema::new("t", ""));
1201        let argv = args.to_argv().unwrap();
1202        assert!(argv.contains(&"-R".to_string()), "expected -R, got {:?}", argv);
1203        assert!(!argv.iter().any(|s| s.contains('=')), "no =value should appear, got {:?}", argv);
1204    }
1205
1206    /// A `Bool(true)` parked under a schema-declared value-taking flag is the
1207    /// flag's literal value (`spawn --command true`), not a bare bool flag — it
1208    /// stays in `named` and renders as `--K=true`, not a value-less `--K`.
1209    #[test]
1210    fn flagify_bool_named_keeps_value_flag_value() {
1211        let mut schema = ToolSchema::new("spawn", "");
1212        schema.params.push(ParamSchema::new("command", "string"));
1213
1214        let mut args = ToolArgs::new();
1215        args.named.insert("command".into(), Value::Bool(true));
1216        args.flagify_bool_named(&schema);
1217
1218        assert!(!args.flags.contains("command"), "value flag must not collapse to a bare flag");
1219        assert_eq!(args.named.get("command"), Some(&Value::Bool(true)));
1220        let argv = args.to_argv().unwrap();
1221        assert!(
1222            argv.iter().any(|s| s == "--command=true"),
1223            "expected --command=true, got {:?}",
1224            argv
1225        );
1226    }
1227
1228    /// One schema carrying both a bool flag and a value-taking flag: the bool
1229    /// flag still flagifies, the value flag keeps its value. Proves
1230    /// `is_bool_param_type` actually distinguishes the two (an empty-schema test
1231    /// can't — it flagifies everything regardless).
1232    #[test]
1233    fn flagify_bool_named_distinguishes_bool_from_value_param() {
1234        let mut schema = ToolSchema::new("t", "");
1235        schema.params.push(ParamSchema::new("verbose", "bool"));
1236        schema.params.push(ParamSchema::new("command", "string"));
1237
1238        let mut args = ToolArgs::new();
1239        args.named.insert("verbose".into(), Value::Bool(true));
1240        args.named.insert("command".into(), Value::Bool(true));
1241        args.flagify_bool_named(&schema);
1242
1243        // Bool flag → promoted to a bare flag.
1244        assert!(args.flags.contains("verbose"));
1245        assert!(!args.named.contains_key("verbose"));
1246        // Value flag → value retained.
1247        assert!(!args.flags.contains("command"));
1248        assert_eq!(args.named.get("command"), Some(&Value::Bool(true)));
1249    }
1250}
1251
1252#[cfg(test)]
1253mod verbatim_words_tests {
1254    use super::*;
1255
1256    /// A typed tool never receives words, so the argv rendering is empty
1257    /// rather than a stringified decomposition.
1258    #[test]
1259    fn typed_args_render_no_words() {
1260        let mut args = ToolArgs::new();
1261        args.positional.push(Value::String("hello".into()));
1262        assert!(args.words.is_none());
1263        assert!(args.words_argv().is_empty());
1264    }
1265
1266    /// Order, multiplicity and non-string types all survive into argv — the
1267    /// three things the typed decomposition drops for a subcommand tree.
1268    #[test]
1269    fn words_render_in_order_with_repeats() {
1270        let mut args = ToolArgs::new();
1271        args.words = Some(vec![
1272            Value::String("block".into()),
1273            Value::String("list".into()),
1274            Value::String("--limit".into()),
1275            Value::Int(5),
1276            Value::String("--include".into()),
1277            Value::String("a".into()),
1278            Value::String("--include".into()),
1279            Value::String("b".into()),
1280        ]);
1281        assert_eq!(
1282            args.words_argv(),
1283            vec!["block", "list", "--limit", "5", "--include", "a", "--include", "b"],
1284        );
1285    }
1286
1287    /// A binary word keeps its bytes in `words` and renders as an inert
1288    /// placeholder token, so the tool's parser sees an argv-shaped stream
1289    /// while the real data stays reachable at the same index.
1290    #[test]
1291    fn binary_word_renders_as_a_placeholder_and_keeps_its_bytes() {
1292        let mut args = ToolArgs::new();
1293        args.words = Some(vec![
1294            Value::String("write".into()),
1295            Value::Bytes(vec![0, 159, 146, 150]),
1296        ]);
1297        let argv = args.words_argv();
1298        assert_eq!(argv[0], "write");
1299        assert_ne!(argv[1], "", "a binary word still needs an argv token");
1300        assert!(
1301            !argv[1].as_bytes().contains(&0),
1302            "the placeholder must be text, not the raw bytes; got {:?}",
1303            argv[1],
1304        );
1305        let words = args.words.as_deref().expect("words");
1306        assert_eq!(words[1], Value::Bytes(vec![0, 159, 146, 150]));
1307    }
1308}