magellan 3.2.0

Deterministic codebase mapping tool for local development
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
use magellan::{FileSystemWatcher, WatcherConfig};
use std::fs::{self, File};
use std::io::Write;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::thread::sleep;
use std::time::Duration;
use tempfile::TempDir;

/// Helper: poll for event with timeout
fn poll_for_event(watcher: &FileSystemWatcher, timeout_ms: u64) -> Option<magellan::FileEvent> {
    let start = std::time::Instant::now();
    let timeout = Duration::from_millis(timeout_ms);

    loop {
        match watcher.try_recv_event() {
            Ok(Some(event)) => return Some(event),
            Ok(None) => {
                if start.elapsed() >= timeout {
                    return None;
                }
            }
            Err(_) => {
                // Error receiving event - treat as no event
                if start.elapsed() >= timeout {
                    return None;
                }
            }
        }

        sleep(Duration::from_millis(50));
    }
}

#[test]
fn test_file_create_event() {
    let temp_dir = TempDir::new().unwrap();
    let shutdown = Arc::new(AtomicBool::new(false));
    let watcher = FileSystemWatcher::new(
        temp_dir.path().to_path_buf(),
        WatcherConfig::default(),
        shutdown,
    )
    .unwrap();

    // Give watcher time to start
    sleep(Duration::from_millis(200));

    let file_path = temp_dir.path().join("test.rs");
    let mut file = File::create(&file_path).unwrap();
    writeln!(file, "fn test() {{}}").unwrap();

    // Poll for event with timeout
    let event = poll_for_event(&watcher, 2000);

    assert!(event.is_some(), "Should receive file event");
    let event = event.unwrap();

    assert_eq!(event.path, file_path);
    // Note: With notify 8.x debouncer, event type is always Modify
    // The reconcile operation handles Create vs Delete based on actual file state
    assert_eq!(event.event_type, magellan::EventType::Modify);
}

#[test]
fn test_file_modify_event() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.rs");

    // Create file first
    let mut file = File::create(&file_path).unwrap();
    writeln!(file, "fn old() {{}}").unwrap();
    drop(file);

    // Give OS time to settle
    sleep(Duration::from_millis(200));

    let shutdown = Arc::new(AtomicBool::new(false));
    let watcher = FileSystemWatcher::new(
        temp_dir.path().to_path_buf(),
        WatcherConfig::default(),
        shutdown,
    )
    .unwrap();

    // Give watcher time to start
    sleep(Duration::from_millis(200));

    // Modify file
    let mut file = File::create(&file_path).unwrap();
    writeln!(file, "fn new() {{}}").unwrap();

    // Poll for modify event
    let event = poll_for_event(&watcher, 2000);

    assert!(event.is_some(), "Should receive modify event");
    let event = event.unwrap();

    assert_eq!(event.path, file_path);
    assert_eq!(event.event_type, magellan::EventType::Modify);
}

#[test]
fn test_file_delete_event() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.rs");

    // Create file first
    let mut file = File::create(&file_path).unwrap();
    writeln!(file, "fn test() {{}}").unwrap();
    drop(file);

    // Give OS time to settle
    sleep(Duration::from_millis(200));

    let shutdown = Arc::new(AtomicBool::new(false));
    let watcher = FileSystemWatcher::new(
        temp_dir.path().to_path_buf(),
        WatcherConfig::default(),
        shutdown,
    )
    .unwrap();

    // Give watcher time to start
    sleep(Duration::from_millis(200));

    // Delete file
    std::fs::remove_file(&file_path).unwrap();

    // Poll for delete event
    let event = poll_for_event(&watcher, 2000);

    assert!(
        event.is_some(),
        "Should receive file event for deleted path"
    );
    let event = event.unwrap();

    assert_eq!(event.path, file_path);
    // Note: With notify 8.x debouncer, event type is always Modify
    // The reconcile operation handles Create vs Delete based on actual file state
    assert_eq!(event.event_type, magellan::EventType::Modify);
}

#[test]
fn test_debounce_rapid_changes() {
    let temp_dir = TempDir::new().unwrap();
    let shutdown = Arc::new(AtomicBool::new(false));
    let watcher = FileSystemWatcher::new(
        temp_dir.path().to_path_buf(),
        WatcherConfig::default(),
        shutdown,
    )
    .unwrap();

    // Give watcher time to start
    sleep(Duration::from_millis(200));

    let file_path = temp_dir.path().join("test.rs");

    // Rapidly modify file 3 times
    for i in 0..3 {
        let mut file = File::create(&file_path).unwrap();
        writeln!(file, "fn v{}() {{}}", i).unwrap();
        drop(file);
        sleep(Duration::from_millis(50));
    }

    // Wait for debounce period + buffer
    sleep(Duration::from_millis(600));

    // Count events - rapid changes should produce a single debounced event
    let mut event_count = 0;
    while let Ok(Some(_)) = watcher.try_recv_event() {
        event_count += 1;
        if event_count > 10 {
            break;
        }
    }

    // Should receive at least 1 event (OS-dependent debouncing)
    assert!(
        event_count >= 1,
        "Should receive at least 1 event, got {}",
        event_count
    );
}

#[test]
fn test_watch_temp_directory() {
    let temp_dir = TempDir::new().unwrap();
    let shutdown = Arc::new(AtomicBool::new(false));
    let watcher = FileSystemWatcher::new(
        temp_dir.path().to_path_buf(),
        WatcherConfig::default(),
        shutdown,
    )
    .unwrap();

    // Give watcher time to start
    sleep(Duration::from_millis(200));

    // Create nested directory and file
    let subdir = temp_dir.path().join("nested");
    std::fs::create_dir(&subdir).unwrap();

    // Give time for directory creation to settle
    sleep(Duration::from_millis(100));

    let file_path = subdir.join("test.rs");
    let mut file = File::create(&file_path).unwrap();
    writeln!(file, "fn test() {{}}").unwrap();

    // Poll for event - may get directory event first
    let mut found_file_event = false;
    let start = std::time::Instant::now();
    let timeout = Duration::from_millis(2000);

    while start.elapsed() < timeout {
        if let Ok(Some(event)) = watcher.try_recv_event() {
            if event.path == file_path {
                found_file_event = true;
                break;
            }
            // Directory events are filtered out in extract_dirty_paths
        }
        sleep(Duration::from_millis(50));
    }

    assert!(found_file_event, "Should receive event for nested file");
}

#[test]
fn test_concurrent_legacy_event_access() {
    use std::sync::Arc;
    use std::time::Duration;
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let shutdown = Arc::new(AtomicBool::new(false));
    let watcher = FileSystemWatcher::new(
        temp_dir.path().to_path_buf(),
        WatcherConfig::default(),
        shutdown,
    )
    .unwrap();

    // Give watcher time to start
    sleep(Duration::from_millis(200));

    // Verify that Arc<Mutex<T>> fields enable safe concurrent access
    //
    // With RefCell<T>:
    //   - Multiple borrow_mut() calls from different threads would panic
    //   - "already borrowed: BorrowMutError"
    //
    // With Arc<Mutex<T>>:
    //   - Multiple lock() calls serialize safely
    //   - Threads wait for lock acquisition instead of panicking
    //
    // Note: FileSystemWatcher itself is not Send (due to Receiver<WatcherBatch>),
    // but the Arc<Mutex<T>> migration prevents RefCell panics in real concurrent
    // scenarios where the watcher might be wrapped in Arc or accessed via channels.

    // This test verifies the lock() mechanism works correctly
    // by calling try_recv_event multiple times sequentially
    let _ = watcher.try_recv_event(); // Returns Result<Option<FileEvent>>
    let _ = watcher.try_recv_event();
    let _ = watcher.try_recv_event();

    // Test passes if no panic occurs
    // (RefCell would not panic in sequential calls, but would in concurrent calls)
}

/// Helper: poll for batch with timeout
fn poll_for_batch(watcher: &FileSystemWatcher, timeout_ms: u64) -> Option<magellan::WatcherBatch> {
    let start = std::time::Instant::now();
    let timeout = Duration::from_millis(timeout_ms);

    loop {
        if let Some(batch) = watcher.try_recv_batch() {
            return Some(batch);
        }

        if start.elapsed() >= timeout {
            return None;
        }

        sleep(Duration::from_millis(50));
    }
}

#[test]
fn test_gitignore_aware_watcher_skips_target_files() {
    let temp_dir = TempDir::new().unwrap();
    let root = temp_dir.path();

    // Create .gitignore with "target/" pattern
    fs::write(root.join(".gitignore"), "target/\nnode_modules/\n").unwrap();

    // Create target/ subdirectory with a .rs file
    fs::create_dir_all(root.join("target")).unwrap();
    let target_file = root.join("target/debug.rs");
    fs::write(&target_file, "fn target_fn() {}").unwrap();

    // Create src/ subdirectory with a .rs file
    fs::create_dir_all(root.join("src")).unwrap();
    let src_file = root.join("src/lib.rs");
    fs::write(&src_file, "fn src_fn() {}").unwrap();

    // Give OS time to settle
    sleep(Duration::from_millis(200));

    let shutdown = Arc::new(AtomicBool::new(false));
    let config = WatcherConfig {
        root_path: root.to_path_buf(),
        debounce_ms: 100,
        gitignore_aware: true, // Enable gitignore filtering
    };

    let watcher = FileSystemWatcher::new(root.to_path_buf(), config, shutdown).unwrap();

    // Give watcher time to start
    sleep(Duration::from_millis(200));

    // Modify both files
    fs::write(&target_file, "fn target_fn_updated() {}").unwrap();
    fs::write(&src_file, "fn src_fn_updated() {}").unwrap();

    // Wait for debounce and poll for batch
    sleep(Duration::from_millis(300));

    let mut found_src = false;
    let mut found_target = false;
    let start = std::time::Instant::now();
    let timeout = Duration::from_millis(2000);

    // Drain all batches within timeout
    while start.elapsed() < timeout {
        if let Some(batch) = watcher.try_recv_batch() {
            for path in &batch.paths {
                if path.ends_with("src/lib.rs") {
                    found_src = true;
                }
                if path.ends_with("target/debug.rs") {
                    found_target = true;
                }
            }
        }
        sleep(Duration::from_millis(50));
    }

    // Assert: src file generates event, target file does not
    assert!(found_src, "Should receive event for src/lib.rs");
    assert!(
        !found_target,
        "Should NOT receive event for target/debug.rs (ignored by .gitignore)"
    );
}

#[test]
fn test_gitignore_aware_false_indexes_all_files() {
    let temp_dir = TempDir::new().unwrap();
    let root = temp_dir.path();

    // Create .gitignore with "target/" pattern
    fs::write(root.join(".gitignore"), "target/\n").unwrap();

    // Create target/ subdirectory with a .rs file
    fs::create_dir_all(root.join("target")).unwrap();
    let target_file = root.join("target/debug.rs");
    fs::write(&target_file, "fn target_fn() {}").unwrap();

    // Create src/ subdirectory with a .rs file
    fs::create_dir_all(root.join("src")).unwrap();
    let src_file = root.join("src/lib.rs");
    fs::write(&src_file, "fn src_fn() {}").unwrap();

    // Give OS time to settle
    sleep(Duration::from_millis(200));

    let shutdown = Arc::new(AtomicBool::new(false));
    let config = WatcherConfig {
        root_path: root.to_path_buf(),
        debounce_ms: 100,
        gitignore_aware: false, // Disable gitignore filtering
    };

    let watcher = FileSystemWatcher::new(root.to_path_buf(), config, shutdown).unwrap();

    // Give watcher time to start
    sleep(Duration::from_millis(200));

    // Modify both files
    fs::write(&target_file, "fn target_fn_updated() {}").unwrap();
    fs::write(&src_file, "fn src_fn_updated() {}").unwrap();

    // Wait for debounce and poll for batch
    sleep(Duration::from_millis(300));

    let mut found_src = false;
    let mut found_target = false;
    let start = std::time::Instant::now();
    let timeout = Duration::from_millis(2000);

    // Drain all batches within timeout
    while start.elapsed() < timeout {
        if let Some(batch) = watcher.try_recv_batch() {
            for path in &batch.paths {
                if path.ends_with("src/lib.rs") {
                    found_src = true;
                }
                if path.ends_with("target/debug.rs") {
                    found_target = true;
                }
            }
        }
        sleep(Duration::from_millis(50));
    }

    // Assert: Both files generate events when gitignore_aware is false
    assert!(found_src, "Should receive event for src/lib.rs");
    assert!(
        found_target,
        "Should receive event for target/debug.rs when gitignore_aware=false"
    );
}

#[test]
fn test_gitignore_aware_internal_ignored_dirs() {
    let temp_dir = TempDir::new().unwrap();
    let root = temp_dir.path();

    // No .gitignore file - internal ignores only
    // Create node_modules/, target/, and .git directories with .rs files
    fs::create_dir_all(root.join("node_modules/pkg")).unwrap();
    fs::create_dir_all(root.join("target/debug")).unwrap();
    fs::create_dir_all(root.join(".git")).unwrap();
    fs::create_dir_all(root.join("src")).unwrap();

    let node_modules_file = root.join("node_modules/pkg/index.js");
    let target_file = root.join("target/debug/lib.rs");
    let git_file = root.join(".git/config");
    let src_file = root.join("src/lib.rs");

    // Use valid source code files
    fs::write(&target_file, "fn target_fn() {}").unwrap();
    fs::write(&src_file, "fn src_fn() {}").unwrap();
    // node_modules uses JS, .git uses text (not source code)
    fs::write(&node_modules_file, "module.exports = {};").unwrap();
    fs::write(&git_file, "[core]").unwrap();

    // Give OS time to settle
    sleep(Duration::from_millis(200));

    let shutdown = Arc::new(AtomicBool::new(false));
    let config = WatcherConfig {
        root_path: root.to_path_buf(),
        debounce_ms: 100,
        gitignore_aware: true,
    };

    let watcher = FileSystemWatcher::new(root.to_path_buf(), config, shutdown).unwrap();

    // Give watcher time to start
    sleep(Duration::from_millis(200));

    // Modify all files
    fs::write(&target_file, "fn updated() {}").unwrap();
    fs::write(&src_file, "fn updated() {}").unwrap();
    fs::write(&node_modules_file, "module.exports = {updated: true};").unwrap();
    fs::write(&git_file, "[core]\n  repositoryformatversion = 0").unwrap();

    // Wait for debounce
    sleep(Duration::from_millis(300));

    let mut found_src = false;
    let mut found_target = false;
    let mut found_node_modules = false;
    let mut found_git = false;
    let start = std::time::Instant::now();
    let timeout = Duration::from_millis(2000);

    // Drain all batches within timeout
    while start.elapsed() < timeout {
        if let Some(batch) = watcher.try_recv_batch() {
            for path in &batch.paths {
                if path.ends_with("src/lib.rs") {
                    found_src = true;
                }
                if path.ends_with("target/debug/lib.rs") {
                    found_target = true;
                }
                if path.ends_with("node_modules/pkg/index.js") {
                    found_node_modules = true;
                }
                if path.ends_with(".git/config") {
                    found_git = true;
                }
            }
        }
        sleep(Duration::from_millis(50));
    }

    // Assert: Only src file generates event (internal ignores apply)
    assert!(found_src, "Should receive event for src/lib.rs");
    assert!(
        !found_target,
        "Should NOT receive event for target/debug/lib.rs (internal ignore)"
    );
    assert!(
        !found_node_modules,
        "Should NOT receive event for node_modules/pkg/index.js (internal ignore)"
    );
    assert!(
        !found_git,
        "Should NOT receive event for .git/config (internal ignore)"
    );
}

#[test]
fn test_gitignore_complex_patterns() {
    let temp_dir = TempDir::new().unwrap();
    let root = temp_dir.path();

    // Create .gitignore with complex patterns FIRST (before watcher starts)
    fs::write(
        root.join(".gitignore"),
        "**/*.log\nbuild/\n*.tmp\ntest_*.rs\n",
    )
    .unwrap();

    // Create directories and initial files
    fs::create_dir_all(root.join("build")).unwrap();
    fs::create_dir_all(root.join("src")).unwrap();

    let log_file = root.join("debug.log");
    let build_file = root.join("build/output.rs");
    let tmp_file = root.join("temp.tmp");
    let test_file = root.join("test_foo.rs");
    let src_file = root.join("src/main.rs");

    fs::write(&log_file, "log content").unwrap();
    fs::write(&build_file, "fn build() {}").unwrap();
    fs::write(&tmp_file, "temp").unwrap();
    fs::write(&test_file, "fn test() {}").unwrap();
    fs::write(&src_file, "fn main() {}").unwrap();

    // Give OS time to settle AND ensure files are flushed
    sleep(Duration::from_millis(300));

    let shutdown = Arc::new(AtomicBool::new(false));
    let config = WatcherConfig {
        root_path: root.to_path_buf(),
        debounce_ms: 100,
        gitignore_aware: true,
    };

    let watcher = FileSystemWatcher::new(root.to_path_buf(), config, shutdown).unwrap();

    // Give watcher time to start
    sleep(Duration::from_millis(300));

    // Modify all files
    fs::write(&log_file, "updated log").unwrap();
    fs::write(&build_file, "fn updated() {}").unwrap();
    fs::write(&tmp_file, "updated temp").unwrap();
    fs::write(&test_file, "fn updated() {}").unwrap();
    fs::write(&src_file, "fn updated() {}").unwrap();

    // Wait for debounce
    sleep(Duration::from_millis(400));

    let mut found_src = false;
    let mut found_log = false;
    let mut found_build = false;
    let mut found_tmp = false;
    let mut found_test = false;
    let start = std::time::Instant::now();
    let timeout = Duration::from_millis(3000);

    // Drain all batches within timeout
    while start.elapsed() < timeout {
        if let Some(batch) = watcher.try_recv_batch() {
            for path in &batch.paths {
                if path.ends_with("src/main.rs") {
                    found_src = true;
                }
                if path.ends_with("debug.log") {
                    found_log = true;
                }
                if path.ends_with("build/output.rs") {
                    found_build = true;
                }
                if path.ends_with("temp.tmp") {
                    found_tmp = true;
                }
                if path.ends_with("test_foo.rs") {
                    found_test = true;
                }
            }
        }
        sleep(Duration::from_millis(50));
    }

    // Assert: Only src/main.rs generates events
    assert!(
        found_src,
        "Should receive event for src/main.rs (not ignored)"
    );
    // Note: .log, .tmp, and test_*.rs files may not generate events
    // because they're not recognized as supported source languages
    // But they definitely shouldn't if they were
    assert!(
        !found_log,
        "Should NOT receive event for debug.log (**/*.log pattern)"
    );
    // The build/ directory should be ignored by gitignore
    assert!(
        !found_build,
        "Should NOT receive event for build/output.rs (build/ pattern)"
    );
    assert!(
        !found_tmp,
        "Should NOT receive event for temp.tmp (*.tmp pattern)"
    );
    assert!(
        !found_test,
        "Should NOT receive event for test_foo.rs (test_*.rs pattern)"
    );
}

#[test]
fn test_gitignore_filter_matches_build_directory() {
    use magellan::graph::filter::FileFilter;
    use std::fs;

    let temp_dir = TempDir::new().unwrap();
    let root = temp_dir.path();

    // Create .gitignore with "build/" pattern
    fs::write(root.join(".gitignore"), "build/\n").unwrap();

    // Create build directory with file
    fs::create_dir_all(root.join("build")).unwrap();
    fs::write(root.join("build/output.rs"), "fn main() {}\n").unwrap();

    // Create src directory with file
    fs::create_dir_all(root.join("src")).unwrap();
    fs::write(root.join("src/lib.rs"), "fn lib() {}\n").unwrap();

    // Test FileFilter
    let filter = FileFilter::new(root, &[], &[]).unwrap();

    // build/output.rs should be skipped (IgnoredByGitignore)
    let result = filter.should_skip(&root.join("build/output.rs"));
    assert_eq!(
        result,
        Some(magellan::diagnostics::SkipReason::IgnoredByGitignore),
        "build/output.rs should be ignored by gitignore build/ pattern"
    );

    // src/lib.rs should NOT be skipped
    let result2 = filter.should_skip(&root.join("src/lib.rs"));
    assert_eq!(result2, None, "src/lib.rs should not be ignored");
}