mirage-analyzer 1.5.1

Path-Aware Code Intelligence Engine for Rust
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
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
// CLI command definitions following Magellan's CLI patterns

use clap::{Parser, Subcommand, ValueEnum};

// Re-export for CLI use
pub use crate::analysis::DeadSymbolJson;

/// Mirage - Path-Aware Code Intelligence Engine
///
/// A control-flow and logic graph engine for Rust codebases.
/// Extracts MIR from rustc, builds CFGs, enumerates execution paths.
#[derive(Parser, Debug, Clone)]
#[command(name = "mirage")]
#[command(author, version, about)]
#[command(
    long_about = "Mirage is a path-aware code intelligence engine that operates on graphs, not text.

It materializes behavior explicitly: paths, proofs, counterexamples.

NOT:
  - A search tool (llmgrep already does this)
  - An embedding tool
  - Static analysis / linting

IS:
  - Path enumeration and verification
  - Graph-based reasoning about code behavior
  - Truth engine that materializes facts for LLM consumption

The Golden Rule: An agent may only speak if it can reference a graph artifact."
)]
pub struct Cli {
    /// Path to the Magellan/Mirage database
    #[arg(global = true, long, env = "MIRAGE_DB")]
    pub db: Option<String>,

    /// Output format
    #[arg(global = true, long, value_enum, default_value_t = OutputFormat::Human)]
    pub output: OutputFormat,

    /// Detect and report backend format (sqlite or geometric)
    #[arg(long, global = true, default_value = "false")]
    pub detect_backend: bool,

    /// Record command telemetry (opt-in, local only)
    #[arg(long, global = true, default_value = "false")]
    pub record: bool,

    #[command(subcommand)]
    pub command: Option<Commands>,
}

/// Output format options
#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
    /// Human-readable text output
    Human,
    /// Compact JSON for programmatic consumption
    Json,
    /// Formatted JSON with indentation
    Pretty,
}

#[derive(Subcommand, Debug, Clone)]
pub enum Commands {
    /// Show database statistics
    Status(StatusArgs),

    /// Show all execution paths through a function
    Paths(PathsArgs),

    /// Show control-flow graph for a function
    Cfg(CfgArgs),

    /// Show dominance relationships for a function
    Dominators(DominatorsArgs),

    /// Show natural loops in CFG
    Loops(LoopsArgs),

    /// Find unreachable code within functions
    Unreachable(UnreachableArgs),

    /// Show branching patterns (if/else, match) in CFG
    Patterns(PatternsArgs),

    /// Show dominance frontiers in CFG
    Frontiers(FrontiersArgs),

    /// Verify a path is still valid
    Verify(VerifyArgs),

    /// Show impact analysis using paths (blast zone)
    BlastZone(BlastZoneArgs),

    /// Show cycles in code (call graph SCCs and function loops)
    Cycles(CyclesArgs),

    /// Perform program slicing (backward/forward impact analysis)
    Slice(SliceArgs),

    /// Show high-risk functions (hotspots)
    Hotspots(HotspotsArgs),

    /// Show most-traversed execution paths (hot paths)
    Hotpaths(HotpathsArgs),

    /// Show CFG differences between two snapshots
    Diff(DiffArgs),

    /// Show inter-procedural CFG (combined function CFGs with call/return edges)
    Icfg(IcfgArgs),

    /// Show per-block coverage for a function
    Coverage(CoverageArgs),

    /// Migrate database between storage backends
    Migrate(MigrateArgs),

    /// List source documents from graph memory
    Docs(DocsArgs),

    /// Compute risk score for a function
    Risk(RiskArgs),

    /// Suggest refactoring actions for a symbol
    Suggest(SuggestArgs),

    /// Show code statistics from the database
    Stats(StatsArgs),
}

// ============================================================================
// Query Commands
// ============================================================================

#[derive(Parser, Debug, Clone, Copy)]
pub struct StatusArgs {}

#[derive(Parser, Debug, Clone)]
pub struct PathsArgs {
    /// Function symbol ID or name
    #[arg(long)]
    pub function: String,

    /// File path to disambiguate functions with same name (optional)
    #[arg(long)]
    pub file: Option<String>,

    /// Show only error paths
    #[arg(long)]
    pub show_errors: bool,

    /// Maximum path length (for pruning)
    #[arg(long)]
    pub max_length: Option<usize>,

    /// Show block details for each path
    #[arg(long)]
    pub with_blocks: bool,

    /// Incremental mode: analyze only changed functions since git revision
    #[arg(long)]
    pub incremental: bool,

    /// Git revision for incremental analysis (e.g., "HEAD~1")
    #[arg(long)]
    pub since: Option<String>,

    /// Sort paths by coverage hit count (highest first)
    #[arg(long)]
    pub by_coverage: bool,
}

#[derive(Parser, Debug, Clone)]
pub struct CfgArgs {
    /// Function symbol ID or name
    #[arg(long)]
    pub function: String,

    /// File path to disambiguate functions with same name (optional)
    #[arg(long)]
    pub file: Option<String>,

    /// Output format
    #[arg(long, value_enum)]
    pub format: Option<CfgFormat>,
}

#[derive(Parser, Debug, Clone)]
pub struct CoverageArgs {
    /// Function symbol ID or name
    #[arg(long)]
    pub function: String,

    /// File path to disambiguate functions with same name (optional)
    #[arg(long)]
    pub file: Option<String>,
}

#[derive(Parser, Debug, Clone)]
pub struct DominatorsArgs {
    /// Function symbol ID or name
    #[arg(long)]
    pub function: String,

    /// File path to disambiguate functions with same name (optional)
    #[arg(long)]
    pub file: Option<String>,

    /// Show blocks that must pass through this block
    #[arg(long)]
    pub must_pass_through: Option<String>,

    /// Show post-dominators instead of dominators
    #[arg(long)]
    pub post: bool,

    /// Use inter-procedural (call graph) dominance instead of intra-procedural (CFG)
    #[arg(long)]
    pub inter_procedural: bool,
}

#[derive(Parser, Debug, Clone)]
pub struct LoopsArgs {
    /// Function to analyze for loops
    #[arg(long)]
    pub function: String,

    /// File path to disambiguate functions with same name (optional)
    #[arg(long)]
    pub file: Option<String>,

    /// Show detailed loop body blocks
    #[arg(long)]
    pub verbose: bool,
}

#[derive(Parser, Debug, Clone)]
pub struct UnreachableArgs {
    /// Find unreachable code within functions
    #[arg(long)]
    pub within_functions: bool,

    /// Show branch details
    #[arg(long)]
    pub show_branches: bool,

    /// Include uncalled functions (requires Magellan call graph)
    #[arg(long)]
    pub include_uncalled: bool,
}

#[derive(Parser, Debug, Clone)]
pub struct PatternsArgs {
    /// Function to analyze for branching patterns
    #[arg(long)]
    pub function: String,

    /// File path to disambiguate functions with same name (optional)
    #[arg(long)]
    pub file: Option<String>,

    /// Show only if/else patterns
    #[arg(long)]
    pub if_else: bool,

    /// Show only match patterns
    #[arg(long)]
    pub r#match: bool,
}

#[derive(Parser, Debug, Clone)]
pub struct FrontiersArgs {
    /// Function to analyze for dominance frontiers
    #[arg(long)]
    pub function: String,

    /// File path to disambiguate functions with same name (optional)
    #[arg(long)]
    pub file: Option<String>,

    /// Show iterated dominance frontier (for phi placement)
    #[arg(long)]
    pub iterated: bool,

    /// Show frontiers for specific node only
    #[arg(long)]
    pub node: Option<usize>,
}

#[derive(Parser, Debug, Clone)]
pub struct VerifyArgs {
    /// Path ID to verify
    #[arg(long)]
    pub path_id: String,
}

#[derive(Parser, Debug, Clone)]
pub struct BlastZoneArgs {
    /// Function symbol ID or name (for block-based analysis)
    #[arg(long)]
    pub function: Option<String>,

    /// File path to disambiguate functions with same name (optional)
    #[arg(long)]
    pub file: Option<String>,

    /// Block ID to analyze impact from (default: entry block 0)
    #[arg(long)]
    pub block_id: Option<usize>,

    /// Path ID to analyze impact for
    #[arg(long)]
    pub path_id: Option<String>,

    /// Maximum depth to traverse
    #[arg(long, default_value_t = 100)]
    pub max_depth: usize,

    /// Include error paths in analysis
    #[arg(long)]
    pub include_errors: bool,

    /// Use call graph for inter-procedural impact analysis
    #[arg(long)]
    pub use_call_graph: bool,
}

/// Cycle type filter for the cycles command
#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
pub enum CycleTypeArg {
    /// Show all cycles (default)
    All,
    /// Show only inter-function cycles (mutual recursion, size > 1)
    InterFunction,
    /// Show only self-loops (single recursive function)
    SelfLoop,
}

#[derive(Parser, Debug, Clone)]
pub struct CyclesArgs {
    /// Show call graph cycles (mutual recursion between functions)
    #[arg(long)]
    pub call_graph: bool,

    /// Show function loops (within individual functions)
    #[arg(long)]
    pub function_loops: bool,

    /// Show both types of cycles (default)
    #[arg(long)]
    pub both: bool,

    /// Filter cycle type: all, inter-function, or self-loop
    #[arg(long, value_enum, default_value = "all")]
    pub cycle_type: CycleTypeArg,

    /// Verbose output (show cycle members/loop bodies)
    #[arg(long)]
    pub verbose: bool,
}

#[derive(Parser, Debug, Clone)]
pub struct SliceArgs {
    /// Symbol ID or FQN to slice
    #[arg(long)]
    pub symbol: String,

    /// Slice direction: backward (what affects) or forward (what affects)
    #[arg(long, value_enum)]
    pub direction: SliceDirectionArg,

    /// Show detailed symbol information
    #[arg(long)]
    pub verbose: bool,
}

#[derive(Parser, Debug, Clone)]
pub struct HotspotsArgs {
    /// Entry point symbol (default: main)
    #[arg(long, default_value = "main")]
    pub entry: String,

    /// Maximum number of hotspots to return
    #[arg(long, default_value = "20")]
    pub top: usize,

    /// Minimum path count threshold
    #[arg(long)]
    pub min_paths: Option<usize>,

    /// Show detailed metrics for each hotspot
    #[arg(long)]
    pub verbose: bool,

    /// Use inter-procedural analysis (requires Magellan DB)
    /// Enabled by default. Use --intra-procedural to force intra-procedural analysis.
    #[arg(long, default_value = "true")]
    pub inter_procedural: bool,

    /// Use intra-procedural analysis only (faster, but may show 0 functions if cfg_blocks not populated)
    #[arg(long, conflicts_with = "inter_procedural")]
    pub intra_procedural: bool,
}

/// Hot path detection arguments
#[derive(Parser, Debug, Clone)]
pub struct HotpathsArgs {
    /// Function symbol ID or name
    #[arg(long)]
    pub function: String,

    /// Number of hot paths to return (default: 10)
    #[arg(long, default_value = "10")]
    pub top: usize,

    /// Show rationale for hotness scores
    #[arg(long)]
    pub rationale: bool,

    /// Minimum hotness threshold (0.0 to 1.0)
    #[arg(long)]
    pub min_score: Option<f64>,
}

/// Migrate database between storage backends
#[derive(Parser, Debug, Clone)]
pub struct MigrateArgs {
    /// Source backend format
    #[arg(long, value_enum)]
    pub from: BackendFormat,

    /// Target backend format
    #[arg(long, value_enum)]
    pub to: BackendFormat,

    /// Database path to migrate
    #[arg(short, long)]
    pub db: String,

    /// Create backup before migration
    #[arg(long)]
    pub backup: bool,

    /// Dry run: detect format only without migrating
    #[arg(long)]
    pub dry_run: bool,
}

/// Source documents listing arguments
#[derive(Parser, Debug, Clone)]
pub struct DocsArgs {
    /// Filter by source kind (wiki, code, message, etc.)
    #[arg(long)]
    pub kind: Option<String>,

    /// Filter by tag
    #[arg(long)]
    pub tag: Option<String>,

    /// Maximum number of results
    #[arg(long, default_value = "50")]
    pub limit: usize,
}

/// Risk analysis arguments
#[derive(Parser, Debug, Clone)]
pub struct RiskArgs {
    /// Function symbol ID or name
    #[arg(long)]
    pub function: String,

    /// File path to disambiguate functions with same name (optional)
    #[arg(long)]
    pub file: Option<String>,
}

/// Suggest refactoring arguments
#[derive(Parser, Debug, Clone)]
pub struct SuggestArgs {
    /// Symbol ID or name to analyze
    #[arg(long)]
    pub symbol: String,

    /// File path to disambiguate (optional)
    #[arg(long)]
    pub file: Option<String>,
}

/// Code statistics arguments
#[derive(Parser, Debug, Clone, Copy)]
pub struct StatsArgs {}

/// Inter-procedural CFG arguments
#[derive(Parser, Debug, Clone)]
pub struct IcfgArgs {
    /// Entry function symbol ID or name
    #[arg(long)]
    pub entry: String,

    /// Maximum depth for call graph traversal (default: 3)
    #[arg(long, default_value = "3")]
    pub depth: usize,

    /// Include return edges (default: true)
    #[arg(long, default_value = "true")]
    pub return_edges: bool,

    /// Output format
    #[arg(long, value_enum)]
    pub format: Option<IcfgFormat>,
}

/// ICFG output format
#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
pub enum IcfgFormat {
    /// DOT graph format (for graphviz)
    Dot,
    /// JSON format
    Json,
    /// Human-readable summary
    Human,
}

/// Diff command arguments
#[derive(Parser, Debug, Clone)]
pub struct DiffArgs {
    /// Function symbol ID or name to compare
    #[arg(long)]
    pub function: String,

    /// Path to the "before" database (.db from a previous magellan scan)
    #[arg(long)]
    pub before_db: String,

    /// Path to the "after" database (.db from the current magellan scan)
    #[arg(long)]
    pub after_db: String,

    /// Show edge differences
    #[arg(long)]
    pub show_edges: bool,

    /// Show detailed block changes
    #[arg(long)]
    pub verbose: bool,
}

/// Backend format for migration
#[derive(clap::ValueEnum, Clone, Debug, Copy, PartialEq, Eq)]
pub enum BackendFormat {
    /// SQLite database (traditional backend)
    Sqlite,
}

impl std::fmt::Display for BackendFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Sqlite => write!(f, "sqlite"),
        }
    }
}

#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
pub enum SliceDirectionArg {
    /// Backward: what affects this symbol
    Backward,
    /// Forward: what this symbol affects
    Forward,
}

/// CFG output format
#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
pub enum CfgFormat {
    /// Human-readable text
    Human,
    /// Graphviz DOT format
    Dot,
    /// JSON export
    Json,
}

// ============================================================================
// Utility Functions
// ============================================================================

/// Resolve the database path from multiple sources
///
/// Priority: CLI arg > MIRAGE_DB env var > auto-discover in common locations
/// Auto-discovery searches: .magellan/*.db, .forge/*.db, *.db in current directory
pub fn resolve_db_path(cli_db: Option<String>) -> anyhow::Result<String> {
    if let Some(path) = cli_db {
        return Ok(path);
    }

    // Try environment variable
    if let Ok(path) = std::env::var("MIRAGE_DB") {
        return Ok(path);
    }

    // Auto-discover database in common locations
    if let Some(path) = auto_discover_db() {
        eprintln!("Info: Auto-discovered database at {}", path);
        return Ok(path);
    }

    Err(anyhow::anyhow!(
        "No database specified. Use --db, set MIRAGE_DB env var, \
         or run from a directory with a .db file"
    ))
}

/// Auto-discover database file in common locations
///
/// Searches in priority order:
/// 1. .magellan/*.db files (Magellan's conventional location)
/// 2. .forge/*.db files
/// 3. *.db in current directory
/// 4. mirage.db or magellan.db in current directory
fn auto_discover_db() -> Option<String> {
    use std::path::Path;

    // Search directories in priority order
    let search_dirs = [".magellan", ".forge", "."];

    for dir in &search_dirs {
        if let Ok(entries) = std::fs::read_dir(dir) {
            let mut db_files: Vec<_> = entries
                .filter_map(|e| e.ok())
                .filter(|e| {
                    let path = e.path();
                    path.extension().map(|ext| ext == "db").unwrap_or(false)
                })
                .map(|e| e.path())
                .collect();

            // Sort for deterministic results
            db_files.sort();

            // Return first match, preferring current Magellan/Mirage database names.
            if let Some(preferred) = db_files.iter().find(|p| {
                let name = p
                    .file_stem()
                    .map(|s| s.to_string_lossy())
                    .unwrap_or_default();
                name == "magellan" || name == "mirage"
            }) {
                return Some(preferred.to_string_lossy().to_string());
            }

            // Otherwise return first .db file
            if let Some(first) = db_files.first() {
                return Some(first.to_string_lossy().to_string());
            }
        }
    }

    // Check for specific filenames in current directory
    let candidates = [
        ".magellan/mirage.db",
        ".magellan/magellan.db",
        "mirage.db",
        "magellan.db",
        "graph.db",
    ];
    for name in &candidates {
        if Path::new(name).exists() {
            return Some(name.to_string());
        }
    }

    None
}

/// Detect the git repository path from the database path
///
/// Starts from the db path and searches upward for .git directory.
/// Falls back to current directory if not found.
fn detect_repo_path(db_path: &str) -> std::path::PathBuf {
    use std::path::Path;

    let db_path = Path::new(db_path);

    // Start from db path and search up for .git directory
    let mut path = if db_path.is_absolute() {
        db_path.to_path_buf()
    } else {
        std::env::current_dir()
            .map(|cwd| cwd.join(db_path))
            .unwrap_or_else(|_| db_path.to_path_buf())
    };

    // Search up the directory tree
    while path.pop() {
        let git_dir = path.join(".git");
        if git_dir.exists() {
            return path;
        }
    }

    // Fallback to current directory
    Path::new(".").to_path_buf()
}

pub mod cmds;
pub mod responses;
pub mod tests;