fledge 1.1.1

Dev lifecycle CLI. One tool for the dev loop, any language.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use anyhow::Result;
use clap::{Arg, Command};
use serde::Serialize;

/// Current schema version of `fledge introspect --json` output. Bumped only on
/// breaking changes to the JSON shape; additive fields do not require a bump.
pub const INTROSPECT_SCHEMA_VERSION: u32 = 1;

pub struct IntrospectOptions {
    pub json: bool,
}

#[derive(Debug, Serialize)]
struct IntrospectOutput {
    schema_version: u32,
    #[serde(flatten)]
    root: CommandNode,
}

pub fn run(opts: IntrospectOptions, cmd: Command) -> Result<()> {
    let tree = build_tree(&cmd);
    if opts.json {
        let output = IntrospectOutput {
            schema_version: INTROSPECT_SCHEMA_VERSION,
            root: tree,
        };
        println!("{}", serde_json::to_string_pretty(&output)?);
    } else {
        render_pretty(&tree, 0);
    }
    Ok(())
}

#[derive(Debug, Serialize)]
pub struct CommandNode {
    pub name: String,
    pub about: Option<String>,
    pub aliases: Vec<String>,
    pub args: Vec<ArgNode>,
    pub subcommands: Vec<CommandNode>,
}

#[derive(Clone, Debug, Serialize)]
pub struct ArgNode {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub long: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub short: Option<char>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub aliases: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub help: Option<String>,
    pub required: bool,
    pub takes_value: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value_name: Option<String>,
    pub global: bool,
}

fn build_tree(cmd: &Command) -> CommandNode {
    build_tree_with_inherited(cmd, &[])
}

/// Walk the clap tree, threading inherited `global = true` args down through
/// each subcommand. Each node's `args` is the union of the args declared on
/// that command and any inherited globals from ancestors (deduplicated by
/// name — a child re-declaring an arg keeps its own copy). Inherited args
/// retain `global: true` so agents can distinguish them from locally-declared
/// args if they want to.
fn build_tree_with_inherited(cmd: &Command, inherited: &[ArgNode]) -> CommandNode {
    let own_args: Vec<ArgNode> = cmd
        .get_arguments()
        .filter(|a| {
            // Skip the implicit `--help` / `--version` globals — they're
            // on every command and add noise.
            let id = a.get_id().as_str();
            id != "help" && id != "version"
        })
        .map(build_arg)
        .collect();

    let mut all_args = own_args;
    for inherited_arg in inherited {
        if !all_args.iter().any(|a| a.name == inherited_arg.name) {
            all_args.push(inherited_arg.clone());
        }
    }

    // Globals to pass to children: every arg currently visible at this level
    // that is itself global. Locally-declared globals start propagating here;
    // ancestor globals continue propagating.
    let next_inherited: Vec<ArgNode> = all_args.iter().filter(|a| a.global).cloned().collect();

    CommandNode {
        name: cmd.get_name().to_string(),
        about: cmd.get_about().map(|s| s.to_string()),
        aliases: cmd.get_visible_aliases().map(|s| s.to_string()).collect(),
        args: all_args,
        subcommands: cmd
            .get_subcommands()
            .filter(|s| s.get_name() != "help")
            .map(|s| build_tree_with_inherited(s, &next_inherited))
            .collect(),
    }
}

fn build_arg(arg: &Arg) -> ArgNode {
    // Detect value-taking args via the explicit `ArgAction`. `get_num_args()`
    // returns `None` for the vast majority of clap-derive args (it's only set
    // when the user wrote `#[arg(num_args = ...)]` themselves), so the
    // previous `unwrap_or(false)` made every `Option<String>` / `PathBuf` /
    // `Vec<String>` flag look like a boolean. Positive-matching on `Set` and
    // `Append` is the correct probe and is conservative against future
    // `ArgAction` variants — a new variant would default to "doesn't take a
    // value" rather than silently flipping the contract.
    let takes_value = matches!(
        arg.get_action(),
        clap::ArgAction::Set | clap::ArgAction::Append
    );
    let mut aliases: Vec<String> = arg
        .get_visible_aliases()
        .map(|v| v.into_iter().map(|s| s.to_string()).collect())
        .unwrap_or_default();
    if let Some(short_aliases) = arg.get_visible_short_aliases() {
        for c in short_aliases {
            aliases.push(c.to_string());
        }
    }
    ArgNode {
        name: arg.get_id().as_str().to_string(),
        long: arg.get_long().map(|s| s.to_string()),
        short: arg.get_short(),
        aliases,
        help: arg.get_help().map(|s| s.to_string()),
        required: arg.is_required_set(),
        takes_value,
        // Only expose value_name when the arg actually takes a value —
        // clap synthesizes uppercase names for bool flags, which is noise
        // for agents trying to generate invocations.
        value_name: if takes_value {
            arg.get_value_names()
                .and_then(|v| v.first().map(|s| s.to_string()))
        } else {
            None
        },
        global: arg.is_global_set(),
    }
}

fn render_pretty(node: &CommandNode, indent: usize) {
    let pad = "  ".repeat(indent);
    let alias_suffix = if node.aliases.is_empty() {
        String::new()
    } else {
        format!(" (aliases: {})", node.aliases.join(", "))
    };
    println!("{pad}{}{}", node.name, alias_suffix);
    if let Some(about) = &node.about {
        println!("{pad}  {about}");
    }
    for arg in &node.args {
        let flags = match (arg.long.as_deref(), arg.short) {
            (Some(long), Some(short)) => format!("-{short}, --{long}"),
            (Some(long), None) => format!("--{long}"),
            (None, Some(short)) => format!("-{short}"),
            (None, None) => format!("<{}>", arg.name),
        };
        let value = arg
            .value_name
            .as_deref()
            .map(|v| format!(" <{v}>"))
            .unwrap_or_default();
        let required_marker = if arg.required { "*" } else { "" };
        println!("{pad}  {required_marker}{flags}{value}");
    }
    for sub in &node.subcommands {
        render_pretty(sub, indent + 1);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::CommandFactory;

    // Minimal test CLI so we don't depend on the real Cli struct.
    #[derive(clap::Parser)]
    #[command(name = "testcli", about = "Test CLI")]
    struct TestCli {
        #[arg(long, global = true)]
        verbose: bool,

        #[command(subcommand)]
        command: TestCommands,
    }

    #[derive(clap::Subcommand)]
    enum TestCommands {
        /// Say hi
        Hello {
            /// Name to greet
            name: String,
            /// Output JSON
            #[arg(long)]
            json: bool,
        },
    }

    #[test]
    fn build_tree_captures_top_level() {
        let cmd = TestCli::command();
        let tree = build_tree(&cmd);
        assert_eq!(tree.name, "testcli");
        assert_eq!(tree.about.as_deref(), Some("Test CLI"));
    }

    #[test]
    fn build_tree_captures_global_args() {
        let cmd = TestCli::command();
        let tree = build_tree(&cmd);
        let verbose = tree.args.iter().find(|a| a.name == "verbose").unwrap();
        assert!(verbose.global);
        assert_eq!(verbose.long.as_deref(), Some("verbose"));
    }

    #[test]
    fn global_args_propagate_to_subcommands() {
        // Locks the introspect contract: a `global = true` arg declared on a
        // parent command appears on every descendant subcommand's `args`,
        // marked `global: true`. Agents reading any node's args see the full
        // set of flags accepted at that level.
        let cmd = TestCli::command();
        let tree = build_tree(&cmd);
        let hello = tree.subcommands.iter().find(|s| s.name == "hello").unwrap();
        let verbose = hello
            .args
            .iter()
            .find(|a| a.name == "verbose")
            .expect("inherited global should appear on subcommand");
        assert!(verbose.global);
    }

    #[derive(clap::Parser)]
    #[command(name = "deepcli")]
    struct DeepCli {
        #[arg(long, global = true)]
        root_global: bool,

        #[command(subcommand)]
        command: DeepMid,
    }

    #[derive(clap::Subcommand)]
    enum DeepMid {
        Mid {
            #[arg(long, global = true)]
            mid_global: bool,

            #[command(subcommand)]
            action: DeepLeaf,
        },
    }

    #[derive(clap::Subcommand)]
    enum DeepLeaf {
        Leaf {
            #[arg(long)]
            leaf_local: bool,
        },
    }

    #[test]
    fn globals_propagate_through_multiple_levels() {
        let cmd = DeepCli::command();
        let tree = build_tree(&cmd);
        let mid = tree.subcommands.iter().find(|s| s.name == "mid").unwrap();
        let leaf = mid.subcommands.iter().find(|s| s.name == "leaf").unwrap();

        // Leaf sees: its own arg, mid's global, root's global
        assert!(leaf.args.iter().any(|a| a.name == "leaf_local"));
        assert!(leaf.args.iter().any(|a| a.name == "mid_global" && a.global));
        assert!(leaf
            .args
            .iter()
            .any(|a| a.name == "root_global" && a.global));
    }

    #[derive(clap::Parser)]
    #[command(name = "shadowcli")]
    struct ShadowCli {
        #[arg(long, global = true)]
        json: bool,

        #[command(subcommand)]
        command: ShadowSub,
    }

    #[derive(clap::Subcommand)]
    enum ShadowSub {
        /// Subcommand that redeclares `--json` with its own settings
        Sub {
            #[arg(long, help = "child's own json flag")]
            json: bool,
        },
    }

    #[test]
    fn child_redeclaration_does_not_duplicate_inherited_arg() {
        let cmd = ShadowCli::command();
        let tree = build_tree(&cmd);
        let sub = tree.subcommands.iter().find(|s| s.name == "sub").unwrap();
        let json_args: Vec<&ArgNode> = sub.args.iter().filter(|a| a.name == "json").collect();
        assert_eq!(
            json_args.len(),
            1,
            "child redeclaring an inherited arg should not produce a duplicate, got: {:?}",
            json_args
        );
        // The child's local declaration wins; help text comes from the child.
        assert_eq!(json_args[0].help.as_deref(), Some("child's own json flag"));
    }

    #[test]
    fn build_tree_captures_subcommand_with_required_arg() {
        let cmd = TestCli::command();
        let tree = build_tree(&cmd);
        let hello = tree.subcommands.iter().find(|s| s.name == "hello").unwrap();
        assert_eq!(hello.about.as_deref(), Some("Say hi"));
        let name_arg = hello.args.iter().find(|a| a.name == "name").unwrap();
        assert!(name_arg.required);
        let json_arg = hello.args.iter().find(|a| a.name == "json").unwrap();
        assert!(!json_arg.required);
        assert_eq!(json_arg.long.as_deref(), Some("json"));
    }

    #[test]
    fn build_tree_skips_help_and_version_args() {
        let cmd = TestCli::command();
        let tree = build_tree(&cmd);
        assert!(!tree.args.iter().any(|a| a.name == "help"));
        assert!(!tree.args.iter().any(|a| a.name == "version"));
    }

    #[test]
    fn build_tree_skips_help_subcommand() {
        let cmd = TestCli::command();
        let tree = build_tree(&cmd);
        assert!(!tree.subcommands.iter().any(|s| s.name == "help"));
    }

    #[test]
    fn tree_serializes_to_valid_json() {
        let cmd = TestCli::command();
        let tree = build_tree(&cmd);
        let json = serde_json::to_string(&tree).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(parsed.is_object());
        assert_eq!(parsed["name"].as_str(), Some("testcli"));
        assert!(parsed["subcommands"].is_array());
    }

    #[derive(clap::Parser)]
    #[command(name = "aliascli")]
    struct AliasCli {
        /// Global flag with alias
        #[arg(long, global = true, visible_alias = "ni", visible_short_alias = 'n')]
        non_interactive: bool,

        #[command(subcommand)]
        command: AliasCommands,
    }

    #[derive(clap::Subcommand)]
    enum AliasCommands {
        Dummy,
    }

    #[test]
    fn introspect_json_schema_snapshot() {
        use crate::cli::Cli;
        let cmd = Cli::command();
        let tree = build_tree(&cmd);
        let output = IntrospectOutput {
            schema_version: INTROSPECT_SCHEMA_VERSION,
            root: tree,
        };
        insta::assert_json_snapshot!("introspect_schema", output);
    }

    #[test]
    fn build_arg_surfaces_long_and_short_aliases() {
        let cmd = AliasCli::command();
        let tree = build_tree(&cmd);
        let ni = tree
            .args
            .iter()
            .find(|a| a.name == "non_interactive")
            .expect("non_interactive arg should be present");
        assert!(
            ni.aliases.contains(&"ni".to_string()),
            "expected 'ni' in aliases, got: {:?}",
            ni.aliases
        );
        assert!(
            ni.aliases.contains(&"n".to_string()),
            "expected short alias 'n' in aliases, got: {:?}",
            ni.aliases
        );
    }
}