apexe 0.1.0

Outside-In CLI-to-Agent Bridge
Documentation
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
use std::process::Command;
use std::time::Duration;

use tracing::{info, warn};

use super::cache::ScanCache;
use super::completion::CompletionParser;
use super::discovery::SubcommandDiscovery;
use super::man_page::ManPageParser;
use super::pipeline::ParserPipeline;
use super::resolver::ToolResolver;
use crate::config::ApexeConfig;
use crate::models::ScannedCLITool;

/// Top-level coordinator for the scanning process.
pub struct ScanOrchestrator {
    config: ApexeConfig,
    resolver: ToolResolver,
    pipeline: ParserPipeline,
    cache: ScanCache,
    man_parser: ManPageParser,
    completion_parser: CompletionParser,
}

impl ScanOrchestrator {
    pub fn new(config: ApexeConfig) -> Self {
        let cache = ScanCache::new(config.cache_dir.clone());
        Self {
            config,
            resolver: ToolResolver,
            pipeline: ParserPipeline::new(None),
            cache,
            man_parser: ManPageParser,
            completion_parser: CompletionParser,
        }
    }

    /// Construct with custom plugins for the parser pipeline.
    pub fn with_plugins(
        config: ApexeConfig,
        plugins: Vec<Box<dyn super::protocol::CliParser>>,
    ) -> Self {
        let cache = ScanCache::new(config.cache_dir.clone());
        Self {
            config,
            resolver: ToolResolver,
            pipeline: ParserPipeline::new(Some(plugins)),
            cache,
            man_parser: ManPageParser,
            completion_parser: CompletionParser,
        }
    }

    /// Scan one or more CLI tools.
    ///
    /// For each tool:
    /// 1. Resolve binary path and version
    /// 2. Check cache (unless no_cache)
    /// 3. Run --help and parse (Tier 1)
    /// 4. Discover subcommands recursively
    /// 5. Enrich with man pages (Tier 2) and completions (Tier 3)
    /// 6. Cache the result
    pub fn scan(
        &self,
        tool_names: &[String],
        no_cache: bool,
        depth: u32,
    ) -> anyhow::Result<Vec<ScannedCLITool>> {
        let mut results = Vec::new();

        for tool_name in tool_names {
            let tool = self.scan_single(tool_name, no_cache, depth)?;
            results.push(tool);
        }

        Ok(results)
    }

    fn scan_single(
        &self,
        tool_name: &str,
        no_cache: bool,
        depth: u32,
    ) -> anyhow::Result<ScannedCLITool> {
        // Resolve binary
        let resolved = self.resolver.resolve(tool_name)?;

        // Check cache
        if !no_cache {
            if let Some(cached) = self.cache.get(tool_name, resolved.version.as_deref()) {
                info!(tool = %tool_name, "Using cached scan result");
                return Ok(cached);
            }
        }

        // Run --help with timeout
        let help_text = self.run_help_with_timeout(tool_name)?;

        let mut warnings = Vec::new();

        if help_text.trim().is_empty() {
            warnings.push(format!("Empty help output from '{tool_name} --help'"));
        }

        // Parse help text (Tier 1)
        let mut parsed = self.pipeline.parse(&help_text, tool_name, None);

        // If few flags found, try expanded help variants (e.g., `curl --help all`)
        if parsed.flags.len() < 3 {
            if let Ok(expanded) = self.try_expanded_help(tool_name) {
                if !expanded.trim().is_empty() {
                    let expanded_parsed = self.pipeline.parse(&expanded, tool_name, None);
                    if expanded_parsed.flags.len() > parsed.flags.len() {
                        parsed = expanded_parsed;
                    }
                }
            }
        }

        // Discover subcommands
        let discovery = SubcommandDiscovery::new(&self.pipeline, depth);
        let subcommands = discovery.discover(
            tool_name,
            &[tool_name.to_string()],
            &parsed.subcommand_names,
            0,
        );

        // Build initial ScannedCLITool (Tier 1)
        let mut tool = ScannedCLITool {
            name: tool_name.to_string(),
            binary_path: resolved.binary_path,
            version: resolved.version,
            subcommands,
            global_flags: parsed.flags,
            structured_output: parsed.structured_output,
            scan_tier: 1,
            warnings,
        };

        // Tier 2 enrichment: man pages
        self.enrich_with_man_page(&mut tool, tool_name);

        // Tier 3 enrichment: shell completions
        self.enrich_with_completions(&mut tool, tool_name);

        // Cache result
        if let Err(e) = self.cache.put(&tool) {
            warn!(tool = %tool_name, "Failed to cache scan result: {e}");
        }

        Ok(tool)
    }

    fn run_help_with_timeout(&self, tool_name: &str) -> anyhow::Result<String> {
        let timeout = Duration::from_secs(self.config.default_timeout);

        let mut child = match Command::new(tool_name)
            .arg("--help")
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
        {
            Ok(c) => c,
            Err(e) => {
                if e.kind() == std::io::ErrorKind::PermissionDenied {
                    return Err(crate::errors::ApexeError::ScanPermission {
                        command: tool_name.to_string(),
                    }
                    .into());
                }
                return Err(e.into());
            }
        };

        // Enforce timeout: poll in a loop with a deadline
        let deadline = std::time::Instant::now() + timeout;
        loop {
            match child.try_wait() {
                Ok(Some(_)) => break,
                Ok(None) => {
                    if std::time::Instant::now() >= deadline {
                        let _ = child.kill();
                        let _ = child.wait();
                        return Err(crate::errors::ApexeError::ScanTimeout {
                            command: format!("{tool_name} --help"),
                            timeout: self.config.default_timeout,
                        }
                        .into());
                    }
                    std::thread::sleep(Duration::from_millis(50));
                }
                Err(e) => return Err(e.into()),
            }
        }

        let output = child.wait_with_output()?;

        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();

        // Some tools output help to stderr
        if stdout.trim().is_empty() && !stderr.trim().is_empty() {
            Ok(stderr)
        } else {
            Ok(stdout)
        }
    }

    /// Try expanded help variants: `--help all`, `-h`, `help`.
    fn try_expanded_help(&self, tool_name: &str) -> anyhow::Result<String> {
        let variants = [vec!["--help", "all"], vec!["-h"]];
        for args in &variants {
            let output = std::process::Command::new(tool_name)
                .args(args)
                .stdout(std::process::Stdio::piped())
                .stderr(std::process::Stdio::piped())
                .output();
            if let Ok(out) = output {
                let text = String::from_utf8_lossy(&out.stdout).to_string();
                let stderr = String::from_utf8_lossy(&out.stderr).to_string();
                let result = if text.len() > stderr.len() {
                    text
                } else {
                    stderr
                };
                if result.len() > 100 {
                    return Ok(result);
                }
            }
        }
        Ok(String::new())
    }

    fn enrich_with_man_page(&self, tool: &mut ScannedCLITool, tool_name: &str) {
        if let Some(man_help) = self.man_parser.parse_man_page(tool_name) {
            if !man_help.description.is_empty() {
                tool.scan_tier = tool.scan_tier.max(2);

                // Enrich subcommands with sparse descriptions
                for cmd in &mut tool.subcommands {
                    if cmd.description.len() < 20 && !cmd.description.is_empty() {
                        cmd.description = format!("{} — {}", cmd.description, man_help.description);
                    }
                }

                // Merge man page flag descriptions into flags with empty/sparse descriptions
                if !man_help.flags.is_empty() {
                    for cmd in &mut tool.subcommands {
                        for flag in &mut cmd.flags {
                            if flag.description.len() < 10 {
                                let canonical = flag.canonical_name();
                                for man_flag in &man_help.flags {
                                    let man_name = man_flag.canonical_name();
                                    if canonical == man_name && !man_flag.description.is_empty() {
                                        flag.description.clone_from(&man_flag.description);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    fn enrich_with_completions(&self, tool: &mut ScannedCLITool, tool_name: &str) {
        if let Some(comp_help) = self.completion_parser.parse_completions(tool_name) {
            tool.scan_tier = tool.scan_tier.max(3);

            // Merge completion-discovered subcommands that Tier 1 missed
            let existing_names: std::collections::HashSet<String> =
                tool.subcommands.iter().map(|c| c.name.clone()).collect();

            for sub_name in &comp_help.subcommand_names {
                if !existing_names.contains(sub_name) {
                    // Discovered a new subcommand via completions — add a stub
                    tool.subcommands.push(crate::models::ScannedCommand {
                        name: sub_name.clone(),
                        full_command: format!("{} {}", tool_name, sub_name),
                        description: format!("{tool_name} {sub_name}"),
                        flags: vec![],
                        positional_args: vec![],
                        subcommands: vec![],
                        examples: vec![],
                        help_format: crate::models::HelpFormat::Unknown,
                        structured_output: crate::models::StructuredOutputInfo::default(),
                        raw_help: String::new(),
                    });
                    tool.warnings.push(format!(
                        "Subcommand '{sub_name}' discovered via shell completion (stub only)"
                    ));
                }
            }
        }
    }
}

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

    fn test_config(tmp: &TempDir) -> ApexeConfig {
        ApexeConfig {
            modules_dir: tmp.path().join("modules"),
            cache_dir: tmp.path().join("cache"),
            config_dir: tmp.path().to_path_buf(),
            audit_log: tmp.path().join("audit.jsonl"),
            log_level: "warn".into(),
            default_timeout: 10,
            scan_depth: 2,
            json_output_preference: true,
            ..ApexeConfig::default()
        }
    }

    // T37: ScanOrchestrator construction
    #[test]
    fn test_orchestrator_new() {
        let tmp = TempDir::new().unwrap();
        let config = test_config(&tmp);
        let _orchestrator = ScanOrchestrator::new(config);
        // Should not panic
    }

    #[test]
    fn test_orchestrator_uses_config_cache_dir() {
        let tmp = TempDir::new().unwrap();
        let config = test_config(&tmp);
        let orchestrator = ScanOrchestrator::new(config);
        // Verify by attempting a cache operation
        let result = orchestrator.cache.get("nonexistent", None);
        assert!(result.is_none());
    }

    // T38: Single tool scan
    #[test]
    fn test_scan_echo() {
        let tmp = TempDir::new().unwrap();
        let config = test_config(&tmp);
        let orchestrator = ScanOrchestrator::new(config);

        let result = orchestrator.scan(&["echo".into()], true, 1);
        assert!(result.is_ok());
        let tools = result.unwrap();
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].name, "echo");
        assert!(!tools[0].binary_path.is_empty());
        // scan_tier >= 1; may be 2 if man page is available on this system
        assert!(tools[0].scan_tier >= 1);
    }

    // T39: Cache integration
    #[test]
    fn test_scan_uses_cache() {
        let tmp = TempDir::new().unwrap();
        let config = test_config(&tmp);
        let orchestrator = ScanOrchestrator::new(config);

        // First scan
        let result1 = orchestrator.scan(&["echo".into()], false, 1).unwrap();
        assert_eq!(result1.len(), 1);

        // Second scan should use cache
        let result2 = orchestrator.scan(&["echo".into()], false, 1).unwrap();
        assert_eq!(result2.len(), 1);
        assert_eq!(result2[0].name, "echo");
    }

    #[test]
    fn test_scan_no_cache_forces_rescan() {
        let tmp = TempDir::new().unwrap();
        let config = test_config(&tmp);
        let orchestrator = ScanOrchestrator::new(config);

        // First scan
        let result1 = orchestrator.scan(&["echo".into()], false, 1).unwrap();
        assert_eq!(result1.len(), 1);

        // no_cache=true forces rescan
        let result2 = orchestrator.scan(&["echo".into()], true, 1).unwrap();
        assert_eq!(result2.len(), 1);
    }

    // T41: Multi-tool scan
    #[test]
    fn test_scan_multiple_tools() {
        let tmp = TempDir::new().unwrap();
        let config = test_config(&tmp);
        let orchestrator = ScanOrchestrator::new(config);

        let result = orchestrator.scan(&["echo".into(), "ls".into()], true, 1);
        assert!(result.is_ok());
        let tools = result.unwrap();
        assert_eq!(tools.len(), 2);
    }

    #[test]
    fn test_scan_nonexistent_tool_errors() {
        let tmp = TempDir::new().unwrap();
        let config = test_config(&tmp);
        let orchestrator = ScanOrchestrator::new(config);

        let result = orchestrator.scan(&["zzz_no_such_tool_xyz".into()], true, 1);
        assert!(result.is_err());
    }

    // T42: Error handling
    #[test]
    fn test_scan_tool_with_empty_help_adds_warning() {
        let tmp = TempDir::new().unwrap();
        let config = test_config(&tmp);
        let orchestrator = ScanOrchestrator::new(config);

        // true (the tool) typically produces empty help with --help
        // We'll test with echo which will produce some output
        let result = orchestrator.scan(&["echo".into()], true, 1).unwrap();
        assert_eq!(result[0].name, "echo");
    }

    // T40: Tier 2/3 enrichment (tested implicitly via scan)
    #[test]
    fn test_scan_tier_is_at_least_1() {
        let tmp = TempDir::new().unwrap();
        let config = test_config(&tmp);
        let orchestrator = ScanOrchestrator::new(config);

        let result = orchestrator.scan(&["echo".into()], true, 1).unwrap();
        assert!(result[0].scan_tier >= 1);
    }
}