apexe 0.3.0

Outside-In CLI-to-Agent Bridge
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
use std::sync::LazyLock;

use regex::Regex;

use crate::models::{ScannedArg, ScannedFlag, StructuredOutputInfo, ValueType};
use crate::scanner::protocol::{CliParser, ParsedHelp};

// Precompiled once (parsers run per subcommand on the recursive scan hot path).
// INVARIANT: every pattern is a compile-time constant valid regex.
static HAS_GNU_OPTS_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?m)^\s{1,}-\w,?\s+--\w").expect("valid static regex"));
static FLAG_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?m)^\s{1,}(-([a-zA-Z0-9]),?\s+)?(--([a-z][\w-]*))((?:[=\s])([A-Z_]+|<[^>]+>))?\s{2,}(.+)",
    )
    .expect("valid static regex")
});
static SHORT_ONLY_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?m)^\s{1,}-([a-zA-Z0-9])(?:,?\s+--[\w-]+)?(?:\s([A-Z_]+|<[^>]+>))?\s{2,}(.+)")
        .expect("valid static regex")
});
static DEFAULT_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\[default:\s*([^\]]+)\]").expect("valid static regex"));
static ENUM_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\{([^}]+)\}").expect("valid static regex"));
static ARG_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"<([a-zA-Z_][\w-]*)>(\.\.\.)?").expect("valid static regex"));
static SUBCMD_SECTION_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?mi)^(commands|subcommands|available commands):").expect("valid static regex")
});
static CMD_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?m)^\s{2,}([a-z][\w-]*)\s+\S").expect("valid static regex"));
static EXAMPLE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?mi)^(examples?|usage examples?):").expect("valid static regex")
});
static JSON_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"--json\b").expect("valid static regex"));

/// Parser for GNU-style --help output.
///
/// Handles tools like git, grep, curl, wget that follow GNU conventions:
/// - 'Usage: tool [OPTION]...' header
/// - Options formatted as '  -f, --flag=VALUE  Description'
/// - Sections separated by blank lines
pub struct GnuHelpParser;

impl CliParser for GnuHelpParser {
    fn name(&self) -> &str {
        "gnu"
    }

    fn priority(&self) -> u32 {
        100
    }

    fn can_parse(&self, help_text: &str, _tool_name: &str) -> bool {
        if help_text.trim().is_empty() {
            return false;
        }
        let has_usage = help_text.contains("Usage:") || help_text.contains("usage:");
        let has_gnu_opts = HAS_GNU_OPTS_RE.is_match(help_text);
        let not_cobra = !help_text.contains("Available Commands:");
        let not_clap = !help_text.contains("SUBCOMMANDS:");
        has_usage && (has_gnu_opts || !help_text.contains("Commands:")) && not_cobra && not_clap
    }

    fn parse(&self, help_text: &str, _tool_name: &str) -> anyhow::Result<ParsedHelp> {
        let description = extract_description(help_text);
        let flags = extract_flags(help_text);
        let positional_args = extract_positional_args(help_text);
        let subcommand_names = extract_subcommands(help_text);
        let examples = extract_examples(help_text);
        let structured_output = detect_structured_output(&flags, help_text);

        Ok(ParsedHelp {
            description,
            flags,
            positional_args,
            subcommand_names,
            examples,
            structured_output,
            help_format: crate::models::HelpFormat::Gnu,
        })
    }
}

/// Extract description from first paragraph before Usage/Options.
pub fn extract_description(help_text: &str) -> String {
    let mut desc_lines = Vec::new();
    for line in help_text.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("Usage:")
            || trimmed.starts_with("usage:")
            || trimmed.starts_with("Options:")
            || trimmed.starts_with("options:")
        {
            break;
        }
        if !trimmed.is_empty() {
            desc_lines.push(trimmed);
        }
    }
    let desc = desc_lines.join(" ");
    desc.chars().take(200).collect()
}

/// Extract flags from OPTIONS section using regex patterns.
pub fn extract_flags(help_text: &str) -> Vec<ScannedFlag> {
    // Match flags like:
    //   -m, --message=MSG   Use the given message
    //   -m, --message MSG   Use the given message
    //   --all               Stage all
    //   -v                  Verbose

    let mut flags = Vec::new();
    let mut seen_long: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut seen_short: std::collections::HashSet<String> = std::collections::HashSet::new();

    for cap in FLAG_RE.captures_iter(help_text) {
        let short_name = cap.get(2).map(|m| format!("-{}", m.as_str()));
        let long_name = cap.get(4).map(|m| format!("--{}", m.as_str()));
        let value_name = cap
            .get(6)
            .map(|m| m.as_str().trim_matches('<').trim_matches('>').to_string());
        let description = cap
            .get(7)
            .map(|m| m.as_str().trim().to_string())
            .unwrap_or_default();

        if let Some(ref ln) = long_name {
            if !seen_long.insert(ln.clone()) {
                continue;
            }
        }
        if let Some(ref sn) = short_name {
            seen_short.insert(sn.clone());
        }

        let flag = build_flag(long_name, short_name, description, value_name);
        flags.push(flag);
    }

    // Collect short-only flags not already captured
    for cap in SHORT_ONLY_RE.captures_iter(help_text) {
        let short_char = cap[1].to_string();
        let short_name = format!("-{short_char}");
        if seen_short.contains(&short_name) {
            continue;
        }
        // Check that this line doesn't also have a long flag (already captured above)
        let full_match = cap.get(0).unwrap().as_str();
        if full_match.contains("--") {
            continue;
        }

        let value_name = cap.get(2).map(|m| m.as_str().to_string());
        let description = cap
            .get(3)
            .map(|m| m.as_str().trim().to_string())
            .unwrap_or_default();

        seen_short.insert(short_name.clone());
        let flag = build_flag(None, Some(short_name), description, value_name);
        flags.push(flag);
    }

    flags
}

fn build_flag(
    long_name: Option<String>,
    short_name: Option<String>,
    description: String,
    value_name: Option<String>,
) -> ScannedFlag {
    let value_type = match value_name.as_deref() {
        None => ValueType::Boolean,
        Some("FILE" | "PATH" | "DIR" | "DIRECTORY" | "FILENAME") => ValueType::Path,
        Some("NUM" | "NUMBER" | "COUNT" | "N" | "PORT" | "INT") => ValueType::Integer,
        Some("FLOAT" | "DECIMAL") => ValueType::Float,
        Some("URL" | "URI") => ValueType::Url,
        _ => ValueType::String,
    };

    let default = DEFAULT_RE
        .captures(&description)
        .and_then(|c| c.get(1))
        .map(|m| m.as_str().trim().to_string());

    let enum_values = ENUM_RE
        .captures(&description)
        .and_then(|c| c.get(1))
        .map(|m| {
            m.as_str()
                .split(',')
                .map(|s| s.trim().to_string())
                .collect::<Vec<_>>()
        });

    let required = description.to_lowercase().contains("required");
    let repeatable = description.contains("can be repeated") || description.contains("...");

    let actual_type = if enum_values.is_some() {
        ValueType::Enum
    } else {
        value_type
    };

    ScannedFlag {
        long_name,
        short_name,
        description,
        value_type: actual_type,
        required,
        default,
        enum_values,
        repeatable,
        value_name,
    }
}

/// Extract positional arguments from Usage line.
pub fn extract_positional_args(help_text: &str) -> Vec<ScannedArg> {
    let mut args = Vec::new();

    for line in help_text.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("Usage:") || trimmed.starts_with("usage:") {
            for cap in ARG_RE.captures_iter(trimmed) {
                let name = cap[1].to_string();
                let variadic = cap.get(2).is_some();
                args.push(ScannedArg {
                    name,
                    description: String::new(),
                    value_type: ValueType::String,
                    required: true,
                    variadic,
                });
            }
        }
    }

    args
}

/// Extract subcommand names from commands section.
pub fn extract_subcommands(help_text: &str) -> Vec<String> {
    let mut names = Vec::new();

    if let Some(section_match) = SUBCMD_SECTION_RE.find(help_text) {
        let after_section = &help_text[section_match.end()..];
        for line in after_section.lines() {
            if line.trim().is_empty() || (!line.starts_with(' ') && !line.is_empty()) {
                if !names.is_empty() {
                    break;
                }
                continue;
            }
            if let Some(cap) = CMD_RE.captures(line) {
                names.push(cap[1].to_string());
            }
        }
    }

    names
}

/// Extract example invocations from help text.
pub fn extract_examples(help_text: &str) -> Vec<String> {
    let mut examples = Vec::new();

    if let Some(m) = EXAMPLE_RE.find(help_text) {
        for line in help_text[m.end()..].lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                if !examples.is_empty() {
                    break;
                }
                continue;
            }
            if trimmed.starts_with('$') || trimmed.starts_with('#') {
                examples.push(trimmed.to_string());
            }
        }
    }

    examples
}

/// Detect structured output flags from parsed flags and help text.
pub fn detect_structured_output(flags: &[ScannedFlag], help_text: &str) -> StructuredOutputInfo {
    // Check parsed flags first
    for flag in flags {
        let long = flag.long_name.as_deref().unwrap_or("");
        if matches!(long, "--format" | "--output-format" | "--output") {
            if let Some(ref enums) = flag.enum_values {
                if enums.iter().any(|v| v == "json") {
                    return StructuredOutputInfo {
                        supported: true,
                        flag: Some(format!("{long} json")),
                        format: Some("json".to_string()),
                    };
                }
            }
        }
        if long == "--json" {
            return StructuredOutputInfo {
                supported: true,
                flag: Some("--json".to_string()),
                format: Some("json".to_string()),
            };
        }
    }

    // Regex fallback on help text
    if JSON_RE.is_match(help_text) {
        return StructuredOutputInfo {
            supported: true,
            flag: Some("--json".to_string()),
            format: Some("json".to_string()),
        };
    }

    StructuredOutputInfo::default()
}

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

    // T13: GnuHelpParser can_parse
    #[test]
    fn test_can_parse_gnu_help() {
        let parser = GnuHelpParser;
        let gnu_help = "git commit - Record changes\n\nUsage: git commit [OPTIONS]\n\nOptions:\n  -m, --message MSG  Use the given message\n  -a, --all          Stage all\n";
        assert!(parser.can_parse(gnu_help, "git"));
    }

    #[test]
    fn test_can_parse_rejects_cobra() {
        let parser = GnuHelpParser;
        let cobra_help =
            "Usage:\n  kubectl [command]\n\nAvailable Commands:\n  apply  Apply config\n";
        assert!(!parser.can_parse(cobra_help, "kubectl"));
    }

    #[test]
    fn test_can_parse_rejects_clap() {
        let parser = GnuHelpParser;
        let clap_help = "rg 1.0\n\nSUBCOMMANDS:\n  search  Search files\n";
        assert!(!parser.can_parse(clap_help, "rg"));
    }

    #[test]
    fn test_can_parse_rejects_empty() {
        let parser = GnuHelpParser;
        assert!(!parser.can_parse("", "tool"));
    }

    // T14: extract_description
    #[test]
    fn test_extract_description_before_usage() {
        let help = "git commit - Record changes to the repository\n\nUsage: git commit [OPTIONS]\n";
        let desc = extract_description(help);
        assert_eq!(desc, "git commit - Record changes to the repository");
    }

    #[test]
    fn test_extract_description_starts_with_usage() {
        let help = "Usage: git commit [OPTIONS]\n\nOptions:\n  -m MSG  Message\n";
        let desc = extract_description(help);
        assert!(desc.is_empty());
    }

    #[test]
    fn test_extract_description_truncated() {
        let long_desc = "A".repeat(300);
        let help = format!("{long_desc}\nUsage: tool [OPTIONS]\n");
        let desc = extract_description(&help);
        assert_eq!(desc.len(), 200);
    }

    // T15: extract_flags basic
    #[test]
    fn test_extract_flags_short_and_long() {
        let help = "Options:\n  -m, --message MSG  Use the given message\n";
        let flags = extract_flags(help);
        assert_eq!(flags.len(), 1);
        assert_eq!(flags[0].short_name.as_deref(), Some("-m"));
        assert_eq!(flags[0].long_name.as_deref(), Some("--message"));
        assert_eq!(flags[0].value_type, ValueType::String);
    }

    #[test]
    fn test_extract_flags_boolean() {
        let help = "Options:\n  -a, --all          Stage all files\n";
        let flags = extract_flags(help);
        assert_eq!(flags.len(), 1);
        assert_eq!(flags[0].value_type, ValueType::Boolean);
    }

    #[test]
    fn test_extract_flags_path_type() {
        let help = "Options:\n      --config FILE  Config path\n";
        let flags = extract_flags(help);
        assert_eq!(flags.len(), 1);
        assert_eq!(flags[0].value_type, ValueType::Path);
    }

    #[test]
    fn test_extract_flags_integer_type() {
        let help = "Options:\n  -n, --count NUM    Number of items\n";
        let flags = extract_flags(help);
        assert_eq!(flags.len(), 1);
        assert_eq!(flags[0].value_type, ValueType::Integer);
    }

    // T16: enum, default, required, repeatable detection
    #[test]
    fn test_extract_flags_enum_values() {
        let help = "Options:\n  -f, --format FMT   Output format {json,text,csv}\n";
        let flags = extract_flags(help);
        assert_eq!(flags.len(), 1);
        assert_eq!(flags[0].value_type, ValueType::Enum);
        assert_eq!(
            flags[0].enum_values,
            Some(vec!["json".into(), "text".into(), "csv".into()])
        );
    }

    #[test]
    fn test_extract_flags_default_value() {
        let help = "Options:\n      --width NUM    Line width [default: 80]\n";
        let flags = extract_flags(help);
        assert_eq!(flags.len(), 1);
        assert_eq!(flags[0].default.as_deref(), Some("80"));
    }

    #[test]
    fn test_extract_flags_required() {
        let help = "Options:\n      --name MSG     Your name (required)\n";
        let flags = extract_flags(help);
        assert_eq!(flags.len(), 1);
        assert!(flags[0].required);
    }

    #[test]
    fn test_extract_flags_repeatable() {
        let help = "Options:\n      --include PATTERN  Include pattern (can be repeated)\n";
        let flags = extract_flags(help);
        assert_eq!(flags.len(), 1);
        assert!(flags[0].repeatable);
    }

    // T17: extract_positional_args
    #[test]
    fn test_extract_args_single() {
        let help = "Usage: tool <file>\n";
        let args = extract_positional_args(help);
        assert_eq!(args.len(), 1);
        assert_eq!(args[0].name, "file");
        assert!(args[0].required);
        assert!(!args[0].variadic);
    }

    #[test]
    fn test_extract_args_two() {
        let help = "Usage: tool <src> <dst>\n";
        let args = extract_positional_args(help);
        assert_eq!(args.len(), 2);
        assert_eq!(args[0].name, "src");
        assert_eq!(args[1].name, "dst");
    }

    #[test]
    fn test_extract_args_variadic() {
        let help = "Usage: tool <file>...\n";
        let args = extract_positional_args(help);
        assert_eq!(args.len(), 1);
        assert!(args[0].variadic);
    }

    #[test]
    fn test_extract_args_options_only() {
        let help = "Usage: tool [OPTIONS]\n";
        let args = extract_positional_args(help);
        assert!(args.is_empty());
    }

    // T18: extract_subcommands
    #[test]
    fn test_extract_subcommands() {
        let help =
            "Commands:\n  commit  Record changes\n  push    Upload changes\n\nSome other section\n";
        let subs = extract_subcommands(help);
        assert_eq!(subs, vec!["commit", "push"]);
    }

    #[test]
    fn test_extract_subcommands_none() {
        let help = "Usage: tool [OPTIONS]\n\nOptions:\n  -v  Verbose\n";
        let subs = extract_subcommands(help);
        assert!(subs.is_empty());
    }

    #[test]
    fn test_extract_subcommands_ends_at_blank() {
        let help = "Subcommands:\n  sub1  First\n  sub2  Second\n\nMore text\n";
        let subs = extract_subcommands(help);
        assert_eq!(subs, vec!["sub1", "sub2"]);
    }

    // T19: extract_examples
    #[test]
    fn test_extract_examples() {
        let help = "Examples:\n  $ git commit -m \"msg\"\n  $ git commit --amend\n\nSee also:\n";
        let examples = extract_examples(help);
        assert_eq!(examples.len(), 2);
        assert!(examples[0].starts_with('$'));
    }

    #[test]
    fn test_extract_examples_none() {
        let help = "Usage: tool [OPTIONS]\n\nOptions:\n  -v  Verbose\n";
        let examples = extract_examples(help);
        assert!(examples.is_empty());
    }

    #[test]
    fn test_extract_examples_hash_prefix() {
        let help = "Examples:\n  # Run the tool\n  $ tool run\n\n";
        let examples = extract_examples(help);
        assert_eq!(examples.len(), 2);
        assert!(examples[0].starts_with('#'));
    }

    // T20: full parse integration
    #[test]
    fn test_full_parse_gnu() {
        let help = r#"git commit - Record changes to the repository

Usage: git commit [OPTIONS] <file>...

Options:
  -m, --message MSG   Use the given message (required)
  -a, --all           Stage all modified files
      --amend         Amend the previous commit
      --format FMT    Output format {json,text}

Examples:
  $ git commit -m "fix bug"
  $ git commit --amend
"#;
        let parser = GnuHelpParser;
        assert!(parser.can_parse(help, "git"));
        let result = parser.parse(help, "git").unwrap();

        assert_eq!(
            result.description,
            "git commit - Record changes to the repository"
        );
        assert!(result.flags.len() >= 3);
        assert_eq!(result.positional_args.len(), 1);
        assert!(result.positional_args[0].variadic);
        assert_eq!(result.examples.len(), 2);

        // Check structured output detection
        assert!(result.structured_output.supported);
    }

    // Structured output detection tests
    #[test]
    fn test_detect_structured_output_format_enum() {
        let flags = vec![ScannedFlag {
            long_name: Some("--format".into()),
            short_name: None,
            description: "Output format".into(),
            value_type: ValueType::Enum,
            required: false,
            default: None,
            enum_values: Some(vec!["json".into(), "text".into()]),
            repeatable: false,
            value_name: None,
        }];
        let info = detect_structured_output(&flags, "");
        assert!(info.supported);
        assert_eq!(info.flag.as_deref(), Some("--format json"));
    }

    #[test]
    fn test_detect_structured_output_json_flag() {
        let flags = vec![ScannedFlag {
            long_name: Some("--json".into()),
            short_name: None,
            description: "JSON output".into(),
            value_type: ValueType::Boolean,
            required: false,
            default: None,
            enum_values: None,
            repeatable: false,
            value_name: None,
        }];
        let info = detect_structured_output(&flags, "");
        assert!(info.supported);
        assert_eq!(info.flag.as_deref(), Some("--json"));
    }

    #[test]
    fn test_detect_structured_output_none() {
        let flags = vec![ScannedFlag {
            long_name: Some("--verbose".into()),
            short_name: Some("-v".into()),
            description: "Be verbose".into(),
            value_type: ValueType::Boolean,
            required: false,
            default: None,
            enum_values: None,
            repeatable: false,
            value_name: None,
        }];
        let info = detect_structured_output(&flags, "some help text");
        assert!(!info.supported);
    }

    #[test]
    fn test_detect_structured_output_regex_fallback() {
        let flags: Vec<ScannedFlag> = vec![];
        let info = detect_structured_output(&flags, "Use --json for JSON output");
        assert!(info.supported);
    }

    #[test]
    fn test_extract_flags_curl_1space_indent() {
        let help = r#"Usage: curl [options...] <url>
 -d, --data <data>           HTTP POST data
 -f, --fail                  Fail fast with no output on HTTP errors
 -o, --output <file>         Write to file instead of stdout
 -v, --verbose               Make the operation more talkative
"#;
        let flags = extract_flags(help);
        assert!(
            flags.len() >= 4,
            "Expected >= 4 flags from curl-style help, got {}",
            flags.len()
        );
        let names: Vec<String> = flags.iter().filter_map(|f| f.long_name.clone()).collect();
        assert!(names.contains(&"--data".to_string()));
        assert!(names.contains(&"--fail".to_string()));
        assert!(names.contains(&"--output".to_string()));
        assert!(names.contains(&"--verbose".to_string()));
    }
}