mirage-analyzer 1.4.2

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
//! Integration tests for all mirage commands
//!
//! Tests verify commands work correctly on SQLite backend.
//! These are "smoke tests" that verify:
//! - CLI parsing works correctly
//! - Commands can be invoked without panicking
//! - Output format is correct (human/json/pretty)
//! - Error handling works appropriately
//!
//! For deeper functional testing, see the unit tests in src/cli/mod.rs.

use std::path::PathBuf;
use std::process::Command;
use tempfile::TempDir;

/// Test context for integration tests
///
/// Provides a test database and mirage binary path.
struct TestContext {
    mirage_bin: PathBuf,
    db_path: PathBuf,
    _temp_dir: TempDir,
}

impl TestContext {
    /// Create a new test context with a minimal test database
    fn new() -> Self {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test.db");

        // Create a minimal Magellan v7 database
        Self::create_test_database(&db_path);

        // Use CARGO_BIN_EXE_mirage if available (for cargo test), otherwise fallback
        let mirage_bin = std::env::var("CARGO_BIN_EXE_mirage")
            .ok()
            .map(PathBuf::from)
            .unwrap_or_else(|| {
                // Check for debug binary first (cargo test builds debug by default)
                let debug_path = PathBuf::from("./target/debug/mirage");
                if debug_path.exists() {
                    debug_path
                } else {
                    PathBuf::from("./target/release/mirage")
                }
            });

        Self {
            mirage_bin,
            db_path,
            _temp_dir: temp_dir,
        }
    }

    /// Run mirage with the given arguments
    fn run_command(&self, args: &[&str]) -> TestOutput {
        let output = Command::new(&self.mirage_bin)
            .args(args)
            .arg("--db")
            .arg(&self.db_path)
            .output()
            .expect("Failed to run mirage");

        TestOutput {
            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
            status: output.status,
        }
    }

    /// Create a minimal test database with Magellan v11 schema
    fn create_test_database(db_path: &PathBuf) {
        use rusqlite::Connection;
        use std::fs;

        let conn = Connection::open(db_path).unwrap();

        // Enable foreign keys
        conn.execute("PRAGMA foreign_keys = ON", []).unwrap();

        // Create magellan_meta table
        conn.execute(
            "CREATE TABLE magellan_meta (
                id INTEGER PRIMARY KEY CHECK (id = 1),
                magellan_schema_version INTEGER NOT NULL,
                sqlitegraph_schema_version INTEGER NOT NULL,
                created_at INTEGER NOT NULL
            )",
            [],
        )
        .unwrap();

        conn.execute(
            "INSERT INTO magellan_meta (id, magellan_schema_version, sqlitegraph_schema_version, created_at)
             VALUES (1, 11, 4, 0)",
            [],
        ).unwrap();

        // Create graph_entities table
        conn.execute(
            "CREATE TABLE graph_entities (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                kind TEXT NOT NULL,
                name TEXT NOT NULL,
                file_path TEXT,
                data TEXT NOT NULL
            )",
            [],
        )
        .unwrap();

        // Create cfg_blocks table (Magellan v11 schema)
        conn.execute(
            "CREATE TABLE cfg_blocks (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                function_id INTEGER NOT NULL,
                kind TEXT NOT NULL,
                terminator TEXT NOT NULL,
                byte_start INTEGER NOT NULL,
                byte_end INTEGER NOT NULL,
                start_line INTEGER NOT NULL,
                start_col INTEGER NOT NULL,
                end_line INTEGER NOT NULL,
                end_col INTEGER NOT NULL,
                cfg_hash TEXT,
                statements TEXT,
                coord_x INTEGER DEFAULT 0,
                coord_y INTEGER DEFAULT 0,
                coord_z INTEGER DEFAULT 0,
                cfg_condition TEXT,
                coord_t TEXT DEFAULT NULL,
                FOREIGN KEY (function_id) REFERENCES graph_entities(id) ON DELETE CASCADE
            )",
            [],
        )
        .unwrap();

        // Insert a test function
        conn.execute(
            "INSERT INTO graph_entities (kind, name, file_path, data)
             VALUES ('Symbol', 'test_function', 'src/test.rs', '{\"kind\": \"Function\"}')",
            [],
        )
        .unwrap();

        // Insert test CFG blocks
        conn.execute(
            "INSERT INTO cfg_blocks (function_id, kind, terminator, byte_start, byte_end,
                                     start_line, start_col, end_line, end_col, coord_x, coord_y, coord_z)
             VALUES (1, 'entry', 'fallthrough', 0, 10, 1, 0, 1, 10, 0, 0, 0),
                    (1, 'normal', 'conditional', 10, 50, 2, 4, 5, 8, 1, 0, 1),
                    (1, 'return', 'return', 50, 60, 5, 0, 5, 10, 2, 0, 2)",
            [],
        )
        .unwrap();

        // Create mirage_meta table for Mirage schema
        conn.execute(
            "CREATE TABLE mirage_meta (
                id INTEGER PRIMARY KEY CHECK (id = 1),
                mirage_schema_version INTEGER NOT NULL,
                magellan_schema_version INTEGER NOT NULL
            )",
            [],
        )
        .unwrap();

        conn.execute(
            "INSERT INTO mirage_meta (id, mirage_schema_version, magellan_schema_version)
             VALUES (1, 1, 11)",
            [],
        )
        .unwrap();

        // Create graph_meta table for sqlitegraph compatibility
        conn.execute(
            "CREATE TABLE graph_meta (
                id INTEGER PRIMARY KEY CHECK (id = 1),
                schema_version INTEGER NOT NULL,
                created_at INTEGER NOT NULL
            )",
            [],
        )
        .unwrap();

        conn.execute(
            "INSERT INTO graph_meta (id, schema_version, created_at)
             VALUES (1, 4, 0)",
            [],
        )
        .unwrap();

        // Create cfg_edges table (Magellan v11 schema)
        conn.execute(
            "CREATE TABLE cfg_edges (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                function_id INTEGER NOT NULL,
                source_idx INTEGER NOT NULL,
                target_idx INTEGER NOT NULL,
                edge_type TEXT NOT NULL,
                FOREIGN KEY (function_id) REFERENCES graph_entities(id) ON DELETE CASCADE
            )",
            [],
        )
        .unwrap();

        // Create cfg_paths table
        conn.execute(
            "CREATE TABLE cfg_paths (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                function_id INTEGER NOT NULL,
                path_hash TEXT NOT NULL,
                path_length INTEGER NOT NULL,
                FOREIGN KEY (function_id) REFERENCES graph_entities(id)
            )",
            [],
        )
        .unwrap();

        // Create cfg_path_elements table
        conn.execute(
            "CREATE TABLE cfg_path_elements (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                path_id INTEGER NOT NULL,
                block_id INTEGER NOT NULL,
                sequence_order INTEGER NOT NULL,
                FOREIGN KEY (path_id) REFERENCES cfg_paths(id),
                FOREIGN KEY (block_id) REFERENCES cfg_blocks(id)
            )",
            [],
        )
        .unwrap();

        // Explicitly close the connection to ensure all writes are flushed
        drop(conn);

        // Verify the database file exists and is readable
        assert!(
            db_path.exists(),
            "Database file should exist after creation"
        );
        assert!(
            fs::metadata(db_path).unwrap().len() > 0,
            "Database file should not be empty"
        );
    }
}

/// Output from running a mirage command
struct TestOutput {
    stdout: String,
    stderr: String,
    status: std::process::ExitStatus,
}

impl TestOutput {
    /// Returns true if the command succeeded
    fn success(&self) -> bool {
        self.status.success()
    }

    /// Returns true if stdout contains the given substring
    fn stdout_contains(&self, s: &str) -> bool {
        self.stdout.contains(s)
    }

    /// Returns true if stderr contains the given substring
    fn stderr_contains(&self, s: &str) -> bool {
        self.stderr.contains(s)
    }
}

// ============================================================================
// Integration tests for each command
// ============================================================================

#[test]
fn test_status_command() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["status"]);

    assert!(output.success(), "status command should succeed");
    assert!(
        output.stdout_contains("Mirage") || output.stdout_contains("Database"),
        "status output should contain database info"
    );
}

#[test]
fn test_status_command_json() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["status", "--output", "json"]);

    assert!(output.success(), "status --output json should succeed");
    assert!(
        output.stdout_contains("{"),
        "JSON output should contain opening brace"
    );
    assert!(
        output.stdout_contains("}"),
        "JSON output should contain closing brace"
    );
}

#[test]
fn test_cfg_command() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["cfg", "--function", "test_function"]);

    // cfg command should work (may have no output if function not found)
    // We just verify it doesn't panic
    assert!(
        output.success()
            || output.stderr_contains("not found")
            || output.stderr_contains("No function"),
        "cfg command should succeed or show not found error"
    );
}

#[test]
fn test_paths_command() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["paths", "--function", "test_function"]);

    // paths command should work (may have no paths if none computed)
    assert!(
        output.success()
            || output.stderr_contains("not found")
            || output.stderr_contains("No function"),
        "paths command should succeed or show not found error"
    );
}

#[test]
fn test_dominators_command() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["dominators", "--function", "test_function"]);

    assert!(
        output.success()
            || output.stderr_contains("not found")
            || output.stderr_contains("No function"),
        "dominators command should succeed or show not found error"
    );
}

#[test]
fn test_loops_command() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["loops", "--function", "test_function"]);

    assert!(
        output.success()
            || output.stderr_contains("not found")
            || output.stderr_contains("No function"),
        "loops command should succeed or show not found error"
    );
}

#[test]
fn test_unreachable_command() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["unreachable", "--within-functions"]);

    // unreachable command may have no output for small test databases
    assert!(
        output.success()
            || output.stdout_contains("No unreachable")
            || output.stdout_contains("Unreachable"),
        "unreachable command should succeed or show message"
    );
}

#[test]
fn test_patterns_command() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["patterns", "--function", "test_function"]);

    assert!(
        output.success()
            || output.stderr_contains("not found")
            || output.stderr_contains("No function"),
        "patterns command should succeed or show not found error"
    );
}

#[test]
fn test_frontiers_command() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["frontiers", "--function", "test_function"]);

    assert!(
        output.success()
            || output.stderr_contains("not found")
            || output.stderr_contains("No function"),
        "frontiers command should succeed or show not found error"
    );
}

#[test]
fn test_cycles_command() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["cycles"]);

    // cycles command analyzes the entire codebase
    assert!(
        output.success() || output.stdout_contains("No cycles") || output.stdout_contains("Cycles"),
        "cycles command should succeed"
    );
}

#[test]
fn test_hotspots_command() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["hotspots"]);

    // hotspots command may have no output for small test databases
    assert!(
        output.success()
            || output.stdout_contains("No hotspots")
            || output.stdout.contains("Hotspots"),
        "hotspots command should succeed"
    );
}

#[test]
fn test_slice_command() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&[
        "slice",
        "--symbol",
        "test_function",
        "--direction",
        "backward",
    ]);

    // slice command runs but may not find the symbol
    // We just verify it doesn't panic
    let stderr_lower = output.stderr.to_lowercase();
    let stdout_lower = output.stdout.to_lowercase();
    assert!(
        output.success()
            || stderr_lower.contains("not found")
            || stderr_lower.contains("no symbol")
            || stderr_lower.contains("could not")
            || stdout_lower.contains("slice"),
        "slice command should succeed or show appropriate message: stderr={}, stdout={}",
        output.stderr,
        output.stdout
    );
}

#[test]
fn test_blast_zone_command() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["blast-zone", "--function", "test_function"]);

    // blast-zone may not find the function, but should handle error gracefully
    assert!(
        output.success()
            || output.stderr.contains("not found")
            || output.stderr.contains("No function")
            || output.stdout.contains("Blast"),
        "blast-zone command should succeed or show not found error"
    );
}

#[test]
fn test_verify_command() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["verify", "--path-id", "1"]);

    // verify requires a valid path ID, so it will likely fail
    // We just verify it handles errors gracefully
    assert!(
        output.success()
            || output.stderr.contains("not found")
            || output.stderr.contains("No path")
            || output.stdout.contains("Path"),
        "verify command should succeed or show not found error"
    );
}

#[test]
fn test_migrate_command_help() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["migrate", "--help"]);

    // migrate --help should show usage
    assert!(output.success(), "migrate --help should succeed");
    assert!(
        output.stdout_contains("migrate") || output.stdout_contains("MIGRATE"),
        "migrate help should mention migrate"
    );
}

#[test]
fn test_detect_backend_flag() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["--detect-backend"]);

    assert!(output.success(), "--detect-backend should succeed");
    assert!(
        output.stdout_contains("sqlite")
            || output.stdout_contains("geometric")
            || output.stdout.contains("{"),
        "--detect-backend should output backend type"
    );
}

#[test]
fn test_detect_backend_json() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["--detect-backend", "--output", "json"]);

    assert!(
        output.success(),
        "--detect-backend --output json should succeed"
    );
    assert!(
        output.stdout_contains("\"backend\""),
        "JSON output should contain backend field"
    );
    assert!(
        output.stdout_contains("\"database\""),
        "JSON output should contain database field"
    );
}

#[test]
fn test_no_command_error() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&[]);

    // Running without a command should show an error
    assert!(
        !output.success() || output.stdout_contains("help") || output.stderr_contains("required"),
        "Running without command should show error or help"
    );
}

#[test]
fn test_help_flag() {
    let ctx = TestContext::new();
    let output = ctx.run_command(&["--help"]);

    assert!(output.success(), "--help should succeed");
    assert!(
        output.stdout_contains("Mirage") || output.stdout_contains("mirage"),
        "help should mention mirage"
    );
    assert!(
        output.stdout_contains("USAGE") || output.stdout_contains("Usage"),
        "help should show usage"
    );
}

#[test]
fn test_invalid_database() {
    let temp_dir = TempDir::new().unwrap();
    let nonexistent_db = temp_dir.path().join("nonexistent.db");

    let mirage_bin = std::env::var("CARGO_BIN_EXE_mirage")
        .ok()
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("./target/release/mirage"));

    let output = Command::new(&mirage_bin)
        .args(["status", "--db", nonexistent_db.to_str().unwrap()])
        .output()
        .expect("Failed to run mirage");

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

    // Should fail gracefully
    assert!(
        !output.status.success() || stderr.contains("not found") || stdout.contains("not found"),
        "Invalid database path should show error"
    );
}