ucm-cli 0.1.2

CLI tool for UCM impact analysis on codebases
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
//! UCM CLI — Unified Context Model command-line tool.
//!
//! Provides terminal-based impact analysis, test intent generation,
//! and dependency graph exploration.

use clap::{Parser, Subcommand};
use std::path::PathBuf;

use ucm_graph_core::entity::EntityId;
use ucm_graph_core::graph::UcmGraph;
use ucm_ingest::code_parser;
use ucm_reason::ambiguity::enrich_with_ambiguities;
use ucm_reason::impact::analyze_impact;
use ucm_reason::intent::generate_test_intent;

/// UCM community edition entity limit.
/// Full analysis requires UCM Pro for repos exceeding this limit.
const COMMUNITY_ENTITY_LIMIT: usize = 500;

#[derive(Parser)]
#[command(
    name = "ucm",
    version,
    about = "Unified Context Model — probabilistic impact analysis"
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Scan source files and build a dependency graph
    Scan {
        /// Directory to scan (defaults to current directory)
        #[arg(default_value = ".")]
        path: PathBuf,

        /// Programming language to parse
        #[arg(short, long, default_value = "typescript")]
        language: String,
    },

    /// Show graph statistics
    Graph {
        /// Directory to scan
        #[arg(default_value = ".")]
        path: PathBuf,

        /// Export format
        #[arg(long)]
        export: Option<String>,

        /// Programming language
        #[arg(short, long, default_value = "typescript")]
        language: String,
    },

    /// Analyze the impact of changes to a file or entity
    Impact {
        /// The file path containing the changed entity
        file: String,

        /// The symbol name that changed
        symbol: String,

        /// Minimum confidence threshold (0.0-1.0)
        #[arg(long, default_value = "0.1")]
        min_confidence: f64,

        /// Maximum traversal depth
        #[arg(long, default_value = "10")]
        max_depth: usize,

        /// Output as JSON instead of formatted text
        #[arg(long)]
        json: bool,

        /// Directory to scan
        #[arg(short, long, default_value = ".")]
        path: PathBuf,

        /// Programming language
        #[arg(short, long, default_value = "typescript")]
        language: String,
    },

    /// Generate test intent recommendations from impact analysis
    Intent {
        /// The file path containing the changed entity
        file: String,

        /// The symbol name that changed
        symbol: String,

        /// Minimum confidence threshold
        #[arg(long, default_value = "0.1")]
        min_confidence: f64,

        /// Maximum traversal depth
        #[arg(long, default_value = "10")]
        max_depth: usize,

        /// Output as JSON
        #[arg(long)]
        json: bool,

        /// Directory to scan
        #[arg(short, long, default_value = ".")]
        path: PathBuf,

        /// Programming language
        #[arg(short, long, default_value = "typescript")]
        language: String,
    },
}

fn main() {
    let cli = Cli::parse();

    match cli.command {
        Commands::Scan { path, language } => cmd_scan(&path, &language),
        Commands::Graph {
            path,
            export,
            language,
        } => cmd_graph(&path, export.as_deref(), &language),
        Commands::Impact {
            file,
            symbol,
            min_confidence,
            max_depth,
            json,
            path,
            language,
        } => cmd_impact(
            &path,
            &language,
            &file,
            &symbol,
            min_confidence,
            max_depth,
            json,
        ),
        Commands::Intent {
            file,
            symbol,
            min_confidence,
            max_depth,
            json,
            path,
            language,
        } => cmd_intent(
            &path,
            &language,
            &file,
            &symbol,
            min_confidence,
            max_depth,
            json,
        ),
    }
}

/// Build a graph by scanning source files in the given directory.
fn build_graph(dir: &PathBuf, language: &str) -> UcmGraph {
    let mut graph = UcmGraph::new();

    // Walk the directory for source files
    let extensions: Vec<&str> = match language {
        "typescript" | "ts" => vec!["ts", "tsx"],
        "javascript" | "js" => vec!["js", "jsx"],
        "rust" | "rs" => vec!["rs"],
        "python" | "py" => vec!["py"],
        _ => vec!["ts", "js", "rs", "py"],
    };

    // Build crate map for Rust cross-crate import resolution.
    // Scans for Cargo.toml files and maps crate name → src/ directory path.
    let crate_map = if matches!(language, "rust" | "rs") {
        build_rust_crate_map(dir)
    } else {
        code_parser::RustCrateMap::new()
    };

    let walker = walk_source_files(dir, &extensions);
    for file_path in &walker {
        let source = match std::fs::read_to_string(file_path) {
            Ok(s) => s,
            Err(_) => continue,
        };

        let relative = file_path
            .strip_prefix(dir)
            .unwrap_or(file_path)
            .to_string_lossy()
            .to_string();

        let events =
            code_parser::parse_source_code_with_context(&relative, &source, language, &crate_map);
        for event in &events {
            ucm_events::projection::GraphProjection::apply_event(&mut graph, event);
        }
    }

    graph
}

/// Scan for Cargo.toml files and build a mapping: crate_name → src/ directory path.
/// e.g. "ucm_graph_core" → "ucm-core/src"
fn build_rust_crate_map(dir: &PathBuf) -> code_parser::RustCrateMap {
    let mut map = code_parser::RustCrateMap::new();

    fn scan_for_cargo_tomls(dir: &PathBuf, base: &PathBuf, map: &mut code_parser::RustCrateMap) {
        if let Ok(entries) = std::fs::read_dir(dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    let name = path.file_name().unwrap_or_default().to_string_lossy();
                    if name.starts_with('.') || name == "target" || name == "node_modules" {
                        continue;
                    }
                    scan_for_cargo_tomls(&path, base, map);
                } else if path.file_name().is_some_and(|n| n == "Cargo.toml") {
                    // Read crate name from Cargo.toml
                    if let Ok(content) = std::fs::read_to_string(&path) {
                        if let Some(name_line) = content.lines().find(|l| l.starts_with("name")) {
                            let crate_name = name_line
                                .split('=')
                                .nth(1)
                                .map(|s| s.trim().trim_matches('"').to_string())
                                .unwrap_or_default();
                            if !crate_name.is_empty() {
                                // Map underscored crate name to src/ path
                                let crate_dir = path.parent().unwrap_or(&path);
                                let src_dir = crate_dir.join("src");
                                if src_dir.exists() {
                                    let relative = src_dir
                                        .strip_prefix(base)
                                        .unwrap_or(&src_dir)
                                        .to_string_lossy()
                                        .to_string();
                                    // Rust uses underscores in import paths
                                    let rust_name = crate_name.replace('-', "_");
                                    map.insert(rust_name, relative);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    scan_for_cargo_tomls(dir, dir, &mut map);
    map
}

fn walk_source_files(dir: &PathBuf, extensions: &[&str]) -> Vec<PathBuf> {
    let mut files = Vec::new();
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                // Skip common non-source directories
                let name = path.file_name().unwrap_or_default().to_string_lossy();
                if name.starts_with('.')
                    || name == "node_modules"
                    || name == "target"
                    || name == "dist"
                    || name == "build"
                    || name == "__pycache__"
                {
                    continue;
                }
                files.extend(walk_source_files(&path, extensions));
            } else if let Some(ext) = path.extension() {
                if extensions.iter().any(|e| ext == *e) {
                    files.push(path);
                }
            }
        }
    }
    files
}

fn check_community_limit(graph: &UcmGraph) -> bool {
    let stats = graph.stats();
    if stats.entity_count > COMMUNITY_ENTITY_LIMIT {
        eprintln!();
        eprintln!(
            "  This repo has {} entities, exceeding the community edition limit of {}.",
            stats.entity_count, COMMUNITY_ENTITY_LIMIT
        );
        eprintln!("  Visit https://ucm.dev/pro for unlimited analysis.");
        eprintln!();
        return false;
    }
    true
}

fn cmd_scan(path: &PathBuf, language: &str) {
    println!("Scanning {} for {} files...", path.display(), language);
    let graph = build_graph(path, language);
    let stats = graph.stats();

    println!();
    println!("  Entities discovered: {}", stats.entity_count);
    println!("  Edges detected:     {}", stats.edge_count);
    println!("  Files tracked:       {}", stats.files_tracked);
    if stats.edge_count > 0 {
        println!(
            "  Avg confidence:      {:.1}%",
            stats.avg_confidence * 100.0
        );
    }
    println!();
    println!("  Graph built successfully. Use `ucm impact` to analyze changes.");
}

fn cmd_graph(path: &PathBuf, export: Option<&str>, language: &str) {
    let graph = build_graph(path, language);
    let stats = graph.stats();

    if let Some("json") = export {
        match graph.to_json() {
            Ok(json) => println!("{json}"),
            Err(e) => eprintln!("Error serializing graph: {e}"),
        }
        return;
    }

    println!("UCM Graph Statistics");
    println!("====================");
    println!("  Entities: {}", stats.entity_count);
    println!("  Edges:    {}", stats.edge_count);
    println!("  Files:    {}", stats.files_tracked);
    if stats.edge_count > 0 {
        println!("  Avg conf: {:.1}%", stats.avg_confidence * 100.0);
    }

    // List entities
    println!();
    println!("Entities:");
    for entity in graph.all_entities() {
        println!("  - {} ({})", entity.name, entity.file_path);
    }
}

fn cmd_impact(
    path: &PathBuf,
    language: &str,
    file: &str,
    symbol: &str,
    min_confidence: f64,
    max_depth: usize,
    json: bool,
) {
    let graph = build_graph(path, language);

    if !check_community_limit(&graph) {
        return;
    }

    let changed = vec![EntityId::local(file, symbol)];
    let mut report = analyze_impact(&graph, &changed, min_confidence, max_depth);
    enrich_with_ambiguities(&mut report, &graph, 0.60);

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&report).unwrap_or_default()
        );
        return;
    }

    // Formatted output
    println!("UCM Impact Analysis");
    println!("====================");
    println!("  Changed: {file}#{symbol}");
    println!();

    if !report.direct_impacts.is_empty() {
        println!("  DIRECT IMPACTS:");
        for impact in &report.direct_impacts {
            println!(
                "    {}{:.0}% confidence",
                impact.name,
                impact.confidence * 100.0
            );
            for step in &impact.explanation_chain.steps {
                println!("      {}. {}", step.step, step.inference);
            }
        }
        println!();
    }

    if !report.indirect_impacts.is_empty() {
        println!("  INDIRECT IMPACTS:");
        for impact in &report.indirect_impacts {
            println!(
                "    {}{:.0}% confidence ({} hops)",
                impact.name,
                impact.confidence * 100.0,
                impact.depth
            );
            for step in &impact.explanation_chain.steps {
                println!("      {}. {}", step.step, step.inference);
            }
        }
        println!();
    }

    if !report.not_impacted.is_empty() {
        println!("  NOT IMPACTED:");
        for ni in &report.not_impacted {
            println!(
                "    {}{:.0}% safe ({})",
                ni.name,
                ni.confidence * 100.0,
                ni.reason
            );
        }
        println!();
    }

    if !report.ambiguities.is_empty() {
        println!("  AMBIGUITIES:");
        for amb in &report.ambiguities {
            println!("    [{}] {}", amb.ambiguity_type, amb.description);
            println!("      Recommendation: {}", amb.recommendation);
        }
    }
}

fn cmd_intent(
    path: &PathBuf,
    language: &str,
    file: &str,
    symbol: &str,
    min_confidence: f64,
    max_depth: usize,
    json: bool,
) {
    let graph = build_graph(path, language);

    if !check_community_limit(&graph) {
        return;
    }

    let changed = vec![EntityId::local(file, symbol)];
    let mut report = analyze_impact(&graph, &changed, min_confidence, max_depth);
    enrich_with_ambiguities(&mut report, &graph, 0.60);
    let intent = generate_test_intent(&report);

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&intent).unwrap_or_default()
        );
        return;
    }

    println!("UCM Test Intent");
    println!("================");
    println!(
        "  {} scenarios total ({} high, {} medium, {} low)",
        intent.summary.total_scenarios,
        intent.summary.high_count,
        intent.summary.medium_count,
        intent.summary.low_count,
    );
    println!();

    if !intent.high_confidence.is_empty() {
        println!("  MUST TEST:");
        for s in &intent.high_confidence {
            println!("    [{}%] {}", (s.confidence * 100.0) as u32, s.description);
        }
        println!();
    }

    if !intent.medium_confidence.is_empty() {
        println!("  SHOULD TEST:");
        for s in &intent.medium_confidence {
            println!("    [{}%] {}", (s.confidence * 100.0) as u32, s.description);
        }
        println!();
    }

    if !intent.risks.is_empty() {
        println!("  RISKS:");
        for r in &intent.risks {
            println!(
                "    [{:?}] {}{}",
                r.severity, r.description, r.mitigation
            );
        }
        println!();
    }

    if !intent.coverage_gaps.is_empty() {
        println!("  COVERAGE GAPS:");
        for g in &intent.coverage_gaps {
            println!("    {}: {}", g.entity, g.description);
        }
    }
}