mushroomdb-cli 0.6.12

CLI binary for mushroomdb: start, shell, and server commands
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
//! Structure ingest: the working tree read as symbols, imports, calls and
//! documentation mentions, on top of the history graph `ingest-git` builds.
//!
//! Every fixture here is a synthetic tree written into a throwaway git
//! repository by the test itself, so the assertions do not depend on the
//! contents of any real project.
use cli::ingest_git::{run_ingest_git, IngestGitOpts};
use core_api::{Direction, GraphDb, Value};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Unique per call: tests run concurrently and two of them can read the same
/// nanosecond, which would otherwise hand both the same repo.
static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

fn tmp(name: &str) -> PathBuf {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let d = std::env::temp_dir().join(format!(
        "mushroomdb-structure-{name}-{}-{nanos}-{seq}",
        std::process::id()
    ));
    std::fs::create_dir_all(&d).unwrap();
    d
}

fn git(repo: &Path, args: &[&str]) {
    let st = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(args)
        .env("GIT_AUTHOR_DATE", "2026-01-01T00:00:00Z")
        .env("GIT_COMMITTER_DATE", "2026-01-01T00:00:00Z")
        .status()
        .unwrap();
    assert!(st.success(), "git {args:?} failed");
}

fn write_files(repo: &Path, files: &[(&str, &str)]) {
    for (p, body) in files {
        let full = repo.join(p);
        std::fs::create_dir_all(full.parent().unwrap()).unwrap();
        std::fs::write(full, body).unwrap();
    }
}

fn commit_all(repo: &Path, msg: &str) {
    git(repo, &["add", "-A"]);
    git(
        repo,
        &[
            "-c",
            "user.name=alice",
            "-c",
            "user.email=alice@x.test",
            "commit",
            "-q",
            "-m",
            msg,
        ],
    );
}

fn commit(repo: &Path, msg: &str, files: &[(&str, &str)]) {
    write_files(repo, files);
    commit_all(repo, msg);
}

const LIB_RS: &str = "//! Demo crate root.

mod net;
mod util;

use crate::util::helper;

/// A record kept by the crate.
pub struct Record {
    pub id: u32,
}

/// Run the demo.
pub fn run() -> u32 {
    helper(1)
}
";

const UTIL_RS: &str = "//! Shared helpers.

/// Double a value.
pub fn helper(n: u32) -> u32 {
    n * 2
}
";

const NET_RS: &str = "//! Networking.

use crate::util::helper;

/// Open a connection.
pub fn connect(port: u32) -> u32 {
    helper(port)
}
";

/// `use crate::util::helper;` removed; `connect` still calls `helper`, so the
/// `IMPORTS` edge retracts while the `CALLS` edge stays.
const NET_RS_NO_IMPORT: &str = "//! Networking.

/// Open a connection.
pub fn connect(port: u32) -> u32 {
    helper(port)
}
";

const GUIDE_MD: &str = "# Demo guide

The networking layer lives in `src/net.rs` and is quicksilver by design.

## Wiring

See [the helpers](../src/util.rs) for the doubling routine.
";

/// A three-module Rust crate plus one Markdown guide, committed once.
fn seed_repo() -> PathBuf {
    let repo = tmp("repo");
    git(&repo, &["init", "-q", "-b", "main"]);
    commit(
        &repo,
        "demo crate",
        &[
            ("Cargo.toml", "[package]\nname = \"demo\"\n"),
            ("src/lib.rs", LIB_RS),
            ("src/util.rs", UTIL_RS),
            ("src/net.rs", NET_RS),
            ("docs/guide.md", GUIDE_MD),
        ],
    );
    repo
}

fn opts(repo: &Path) -> IngestGitOpts {
    IngestGitOpts {
        repo: repo.to_path_buf(),
        exclude: vec![],
        max_commits_per_file: 200,
        recurse_submodules: false,
        prs: false,
        structure: true,
        docs: true,
        ensure_gitignore: false,
    }
}

fn prop(db: &cli::structure::Db, key: &str, field: &str) -> Option<Value> {
    db.node_ref(key).and_then(|n| n.prop(field))
}

fn strings(v: Option<Value>) -> Vec<String> {
    match v {
        Some(Value::List(l)) => l
            .into_iter()
            .filter_map(|x| match x {
                Value::Str(s) => Some(s),
                _ => None,
            })
            .collect(),
        _ => Vec::new(),
    }
}

fn out(db: &cli::structure::Db, key: &str, edge: &str) -> Vec<String> {
    let mut v = db.neighbors(key, edge, Direction::Out).unwrap_or_default();
    v.sort();
    v
}

fn all_keys(db: &cli::structure::Db, label: &str) -> Vec<String> {
    let rs = db
        .query(
            &format!("MATCH (n:{label}) RETURN n.id AS id"),
            &BTreeMap::new(),
        )
        .unwrap();
    let mut v: Vec<String> = (0..rs.len())
        .filter_map(|i| match rs.get(i, "id") {
            Some(Value::Str(s)) => Some(s.clone()),
            _ => None,
        })
        .collect();
    v.sort();
    v
}

/// A callee whose name several crates define is ambiguous everywhere except in
/// a file that imports one of them. Before the importer tier every such call
/// was dropped, so a `context` on the callee named none of its cross-crate
/// callers — the one case where an incomplete blast radius is actively unsafe.
///
/// The fixture is a two-package workspace where both packages define
/// `sanitize`, plus a third that imports one of them and calls it — including
/// from inside a `format!`, whose arguments the grammar leaves unparsed.
#[test]
fn calls_resolve_across_crates_via_imports() {
    let repo = tmp("repo");
    git(&repo, &["init", "-q", "-b", "main"]);
    commit(
        &repo,
        "workspace",
        &[
            ("Cargo.toml", "[workspace]\nmembers = [\"crates/*\"]\n"),
            ("crates/alpha/Cargo.toml", "[package]\nname = \"alpha\"\n"),
            ("crates/alpha/src/lib.rs", "pub mod render;\n"),
            (
                "crates/alpha/src/render.rs",
                "/// Strip control characters.\npub fn sanitize(s: &str) -> String {\n    s.to_string()\n}\n",
            ),
            ("crates/beta/Cargo.toml", "[package]\nname = \"beta\"\n"),
            (
                "crates/beta/src/lib.rs",
                "/// A different escape entirely.\npub fn sanitize(s: &str) -> String {\n    s.to_string()\n}\n",
            ),
            ("crates/gamma/Cargo.toml", "[package]\nname = \"gamma\"\n"),
            (
                "crates/gamma/src/lib.rs",
                "use alpha::render::sanitize;\n\n\
                 pub fn show(t: &str) -> String {\n    \
                 let head = sanitize(t);\n    \
                 format!(\"{} {}\", head, sanitize(t))\n}\n",
            ),
        ],
    );

    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    let db = GraphDb::open(&db_dir).unwrap();

    // The `use` names the defining module, not the package root, which is what
    // makes the call resolvable.
    assert_eq!(
        out(&db, "crates/gamma/src/lib.rs", "IMPORTS"),
        vec!["crates/alpha/src/render.rs".to_string()]
    );
    assert_eq!(
        out(&db, "crates/gamma/src/lib.rs#show", "CALLS"),
        vec!["crates/alpha/src/render.rs#sanitize".to_string()],
        "the imported definition wins; beta's same-named function is not it"
    );
    // Both sites, the one inside `format!` included.
    assert_eq!(
        strings(prop(&db, "crates/gamma/src/lib.rs#show", "call_lines")),
        vec![
            "crates/alpha/src/render.rs#sanitize\t4".to_string(),
            "crates/alpha/src/render.rs#sanitize\t5".to_string(),
        ]
    );
    assert!(
        db.neighbors("crates/beta/src/lib.rs#sanitize", "CALLS", Direction::In)
            .unwrap()
            .is_empty(),
        "nothing calls beta's sanitize"
    );
}

/// A call written on a receiver names a method on a type, and the type is
/// usually outside the tree entirely. Resolving those on repository-wide
/// uniqueness bound `.collect()` to whatever single function happened to be
/// called `collect` — here a test helper in another crate. A method call now
/// resolves locally or through the caller's imports, or not at all; a call to a
/// function defined in the same file is unaffected.
#[test]
fn method_calls_do_not_reach_an_unrelated_function_of_the_same_name() {
    let repo = tmp("repo");
    git(&repo, &["init", "-q", "-b", "main"]);
    commit(
        &repo,
        "workspace",
        &[
            ("Cargo.toml", "[workspace]\nmembers = [\"crates/*\"]\n"),
            ("crates/helper/Cargo.toml", "[package]\nname = \"helper\"\n"),
            // The only `collect` in the tree, and nothing imports it.
            (
                "crates/helper/src/lib.rs",
                "/// Gather the fixtures.\npub fn collect(dir: &str) -> Vec<String> {\n    vec![dir.to_string()]\n}\n\n\
                 /// The only `take` in the tree.\npub fn take(n: usize) -> usize {\n    n\n}\n",
            ),
            ("crates/app/Cargo.toml", "[package]\nname = \"app\"\n"),
            (
                "crates/app/src/lib.rs",
                "/// A job the app runs.\npub struct Job;\n\n\
                 /// Do the work.\npub fn run(job: &Job) -> u32 {\n    let _ = job;\n    7\n}\n\n\
                 pub fn total(items: &[u32], job: &Job) -> u32 {\n    \
                 let picked: Vec<u32> = items.iter().copied().collect();\n    \
                 let moved = std::mem::take(&mut picked.clone());\n    \
                 picked.len() as u32 + moved.len() as u32 + job.run()\n}\n",
            ),
        ],
    );

    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    let db = GraphDb::open(&db_dir).unwrap();

    assert!(
        db.has_node("crates/helper/src/lib.rs#collect"),
        "the helper is in the graph; it is the edge to it that must not exist"
    );
    assert!(
        db.neighbors("crates/helper/src/lib.rs#collect", "CALLS", Direction::In)
            .unwrap()
            .is_empty(),
        "`.collect()` is a method on a type from outside the tree"
    );
    // `std::mem::take` is a call into the standard library, and the only `take`
    // in the tree is a helper in the other crate.
    assert!(
        db.neighbors("crates/helper/src/lib.rs#take", "CALLS", Direction::In)
            .unwrap()
            .is_empty(),
        "a path call leading with `std` names nothing here"
    );

    // The same-file tier still answers a method call, so the rules cost nothing
    // real: `job.run()` reaches the `run` defined beside it, and it is the only
    // edge `total` has.
    assert_eq!(
        out(&db, "crates/app/src/lib.rs#total", "CALLS"),
        vec!["crates/app/src/lib.rs#run".to_string()]
    );
}

#[test]
fn first_run_creates_symbols_imports_calls_and_mentions() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    let report = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert!(report.structure.files_scanned >= 5, "{report:?}");

    let db = GraphDb::open(&db_dir).unwrap();

    // IMPORTS: `mod` declarations from the crate root, `use crate::…` from a
    // module. Both resolve to working-tree files, so both become edges.
    assert_eq!(
        out(&db, "src/lib.rs", "IMPORTS"),
        vec!["src/net.rs".to_string(), "src/util.rs".to_string()]
    );
    assert_eq!(
        out(&db, "src/net.rs", "IMPORTS"),
        vec!["src/util.rs".to_string()]
    );

    // Symbols, keyed `<path>#<qualified name>`, with DEFINES back to the file.
    assert!(db.has_node("src/util.rs#helper"), "helper symbol missing");
    assert_eq!(
        prop(&db, "src/util.rs#helper", "kind"),
        Some(Value::Str("function".into()))
    );
    assert_eq!(
        prop(&db, "src/util.rs#helper", "file_id"),
        Some(Value::Str("src/util.rs".into()))
    );
    assert_eq!(
        prop(&db, "src/util.rs#helper", "doc"),
        Some(Value::Str("Double a value.".into()))
    );
    assert_eq!(
        out(&db, "src/util.rs#helper", "DEFINES"),
        vec!["src/util.rs".to_string()]
    );

    // CALLS: `connect` calls `helper`, which is defined in a sibling file.
    assert_eq!(
        out(&db, "src/net.rs#connect", "CALLS"),
        vec!["src/util.rs#helper".to_string()]
    );

    // MENTIONS: a backticked path and a relative link in the guide.
    assert_eq!(
        out(&db, "docs/guide.md", "MENTIONS"),
        vec!["src/net.rs".to_string(), "src/util.rs".to_string()]
    );

    // `symbols_n` and the content hash ride along on the file.
    assert_eq!(prop(&db, "src/util.rs", "symbols_n"), Some(Value::Int(1)));
    assert_eq!(
        prop(&db, "src/util.rs", "lang"),
        Some(Value::Str("rust".into()))
    );
    let Some(Value::Str(hash)) = prop(&db, "src/util.rs", "hash") else {
        panic!("no hash on src/util.rs");
    };
    assert_eq!(hash.len(), 32, "hash is 32 hex characters: {hash}");

    // `explain` names the rule behind the edge.
    let ex = db.explain("src/net.rs", "src/util.rs").unwrap();
    assert!(
        ex.iter()
            .any(|e| e.rule == "imports" && e.edge_type == "IMPORTS"),
        "explain must name the imports rule: {ex:?}"
    );
}

#[test]
fn editing_an_import_retracts_the_edge_on_refresh() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    {
        let db = GraphDb::open(&db_dir).unwrap();
        assert_eq!(
            out(&db, "src/net.rs", "IMPORTS"),
            vec!["src/util.rs".to_string()]
        );
    }

    commit(&repo, "drop the use", &[("src/net.rs", NET_RS_NO_IMPORT)]);
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();

    let db = GraphDb::open(&db_dir).unwrap();
    assert!(
        out(&db, "src/net.rs", "IMPORTS").is_empty(),
        "the import was deleted, so the edge must retract"
    );
    assert!(
        !strings(prop(&db, "src/net.rs", "imports")).contains(&"src/util.rs".to_string()),
        "the imports list must be rewritten, not just the edge"
    );

    // The call survives: `resolve_call` works off the symbol index, not the
    // import list, so dropping the `use` does not unlink the callee.
    assert_eq!(
        out(&db, "src/net.rs#connect", "CALLS"),
        vec!["src/util.rs#helper".to_string()]
    );

    let hist = db.edge_history("src/net.rs", "src/util.rs").unwrap();
    let imports: Vec<&core_api::EdgeHistoryEvent> = hist
        .items
        .iter()
        .filter(|e| e.edge_type == "IMPORTS")
        .collect();
    assert!(
        imports
            .iter()
            .any(|e| e.event == core_api::EdgeEvent::Added && e.rule.as_deref() == Some("imports")),
        "history must show the edge being added: {imports:?}"
    );
    assert!(
        imports
            .iter()
            .any(|e| e.event == core_api::EdgeEvent::Retracted),
        "history must show the edge being retracted: {imports:?}"
    );
}

#[test]
fn renamed_file_moves_its_symbols() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();

    git(&repo, &["mv", "src/util.rs", "src/helpers.rs"]);
    commit_all(&repo, "move util to helpers");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();

    let db = GraphDb::open(&db_dir).unwrap();
    assert!(!db.has_node("src/util.rs"), "the old path is gone");
    assert!(db.has_node("src/helpers.rs"), "the new path exists");

    // Symbols are keyed by path, so they are deleted and re-created.
    assert!(
        !db.has_node("src/util.rs#helper"),
        "the old symbol key must not survive the rename"
    );
    assert!(db.has_node("src/helpers.rs#helper"), "symbol must move");
    assert_eq!(
        prop(&db, "src/helpers.rs#helper", "file_id"),
        Some(Value::Str("src/helpers.rs".into()))
    );
    assert_eq!(
        out(&db, "src/helpers.rs#helper", "DEFINES"),
        vec!["src/helpers.rs".to_string()]
    );
    assert_eq!(
        all_keys(&db, "Symbol")
            .iter()
            .filter(|k| k.starts_with("src/util.rs#"))
            .count(),
        0,
        "no symbol may be left under the old path"
    );

    // The importer of the old path is re-extracted, so nothing dangles: the
    // `use crate::util::helper` in net.rs no longer names a file.
    assert!(
        out(&db, "src/net.rs", "IMPORTS").is_empty(),
        "an unresolvable import must leave no edge, stale or retargeted"
    );
    assert!(
        !strings(prop(&db, "src/net.rs", "imports")).contains(&"src/util.rs".to_string()),
        "the importer's list must no longer name the old key"
    );

    // The call follows the symbol to its new key.
    assert_eq!(
        out(&db, "src/net.rs#connect", "CALLS"),
        vec!["src/helpers.rs#helper".to_string()]
    );
}

#[test]
fn no_structure_skips_symbols_and_hashes() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    let mut o = opts(&repo);
    o.structure = false;
    o.docs = false;
    let report = run_ingest_git(&db_dir, &o).unwrap();
    assert_eq!(report.structure.files_scanned, 0);

    let db = GraphDb::open(&db_dir).unwrap();
    assert!(db.has_node("src/util.rs"), "history is still ingested");
    assert_eq!(prop(&db, "src/util.rs", "hash"), None, "no content hash");
    assert_eq!(prop(&db, "src/util.rs", "symbols_n"), None);
    assert!(all_keys(&db, "Symbol").is_empty(), "no symbols");
    assert!(
        out(&db, "src/net.rs", "IMPORTS").is_empty(),
        "no derived structure edges"
    );
}

#[test]
fn markdown_body_is_fulltext_searchable() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();

    let db = GraphDb::open(&db_dir).unwrap();
    assert_eq!(
        strings(prop(&db, "docs/guide.md", "headings")),
        vec!["Demo guide".to_string(), "Wiring".to_string()]
    );
    let hits = db.search("body", "quicksilver");
    assert_eq!(
        hits.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>(),
        vec!["docs/guide.md".to_string()],
        "the guide body must be searchable"
    );
    let by_heading = db.search("headings", "wiring");
    assert!(
        by_heading.iter().any(|(k, _)| k == "docs/guide.md"),
        "headings are indexed too: {by_heading:?}"
    );

    // Without --docs the prose is not stored at all.
    let db_dir2 = tmp("db-nodocs");
    let mut o = opts(&repo);
    o.docs = false;
    run_ingest_git(&db_dir2, &o).unwrap();
    let db2 = GraphDb::open(&db_dir2).unwrap();
    assert_eq!(prop(&db2, "docs/guide.md", "body"), None);
    assert_eq!(prop(&db2, "docs/guide.md", "headings"), None);
    assert!(
        out(&db2, "docs/guide.md", "MENTIONS").is_empty(),
        "no mentions without --docs"
    );
    assert!(
        prop(&db2, "docs/guide.md", "hash").is_some(),
        "the hash is structure, not docs"
    );
}

#[test]
fn large_and_binary_files_are_hash_only() {
    let repo = seed_repo();
    let big = format!("// {}\npub fn huge() {{}}\n", "x".repeat(1024 * 1024));
    write_files(&repo, &[("src/big.rs", &big)]);
    let mut binary = b"pub fn nope() {}\n".to_vec();
    binary.extend_from_slice(&[0u8, 1, 2, 3, 0]);
    std::fs::write(repo.join("src/blob.rs"), &binary).unwrap();
    commit_all(&repo, "add a huge file and a binary one");

    let db_dir = tmp("db");
    let report = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!(
        report.structure.skipped_large, 2,
        "both files are hash-only: {report:?}"
    );

    let db = GraphDb::open(&db_dir).unwrap();
    for path in ["src/big.rs", "src/blob.rs"] {
        assert!(
            prop(&db, path, "hash").is_some(),
            "{path} must still be hashed"
        );
        assert_eq!(
            prop(&db, path, "symbols_n"),
            Some(Value::Int(0)),
            "{path} must contribute no symbols"
        );
        assert_eq!(prop(&db, path, "imports"), None, "{path} has no imports");
    }
    assert!(
        !db.has_node("src/big.rs#huge"),
        "no symbol from a huge file"
    );
    assert!(
        !db.has_node("src/blob.rs#nope"),
        "no symbol from binary bytes"
    );
}

/// The hash is what makes a sync cheap: a file whose bytes did not change is
/// scanned, found identical, and left entirely alone.
#[test]
fn unchanged_files_are_not_rewritten() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    let before_file = {
        let db = GraphDb::open(&db_dir).unwrap();
        db.node_history("src/util.rs").unwrap().items.len()
    };
    let before_commits = core_api::wal_commit_count_at(&db_dir).unwrap();

    // A second full pass over the same working tree scans every file and
    // writes none of them.
    let report = {
        let shared = core_api::SharedDb::open(&db_dir).unwrap();
        let mut w = shared.write();
        cli::structure::refresh_all(&mut w, &repo, "", true).unwrap()
    };
    assert_eq!(report.files_scanned, 5, "every file is read again");

    assert_eq!(
        core_api::wal_commit_count_at(&db_dir).unwrap(),
        before_commits,
        "a re-scan of an unchanged tree must not add a single WAL commit"
    );
    let db = GraphDb::open(&db_dir).unwrap();
    assert_eq!(
        db.node_history("src/util.rs").unwrap().items.len(),
        before_file,
        "an unchanged file must produce no write on a re-scan"
    );
}

/// The last commit of a run is the sync marker. Anything written after it
/// would be work the marker already claims to cover, so a failure in that work
/// would be skipped forever: the next run would resume from a sha past it.
#[test]
fn the_sync_marker_is_written_after_the_structure_pass() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();

    let db = GraphDb::open(&db_dir).unwrap();
    let newest = |key: &str| {
        db.node_history(key)
            .unwrap()
            .items
            .iter()
            .map(|e| e.commit)
            .max()
            .unwrap_or_else(|| panic!("no history for {key}"))
    };
    let marker = newest("__mushroomdb_git_sync__");
    for key in [
        "src/util.rs",
        "src/net.rs",
        "docs/guide.md",
        "src/util.rs#helper",
    ] {
        assert!(
            newest(key) < marker,
            "{key} was written at commit {} but the marker landed at {marker}",
            newest(key)
        );
    }
}

/// The failure the marker ordering protects against is a structure batch that
/// will not commit. An unreadable file is *not* one of those: the pass skips
/// what it cannot read and the run still succeeds, so the marker advances and
/// the next run does not retry. This pins that deliberate degradation.
#[cfg(unix)]
#[test]
fn an_unreadable_file_is_skipped_rather_than_failing_the_run() {
    use std::os::unix::fs::PermissionsExt;

    let repo = seed_repo();
    let db_dir = tmp("db");
    let locked = repo.join("src/net.rs");
    std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
    let readable = std::fs::read(&locked).is_err();
    // Running as root, or on a filesystem that ignores the mode bits, makes
    // the file readable anyway; there is nothing to assert then.
    if !readable {
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o644)).unwrap();
        return;
    }

    let report = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o644)).unwrap();
    assert_eq!(
        report.structure.files_scanned, 4,
        "the unreadable file is skipped, the other four are read: {report:?}"
    );

    let db = GraphDb::open(&db_dir).unwrap();
    assert!(db.has_node("src/net.rs"), "its history is still ingested");
    assert_eq!(
        prop(&db, "src/net.rs", "hash"),
        None,
        "but nothing was read"
    );
    assert!(!db.has_node("src/net.rs#connect"));
    assert!(
        db.has_node("__mushroomdb_git_sync__"),
        "the run succeeded, so the marker advanced"
    );
}

/// `#` is legal in a path, so a file can be named exactly what another file's
/// symbol key would be. Whichever node holds the key keeps it: overwriting a
/// `File` node with symbol props would corrupt it.
#[test]
fn a_symbol_key_that_collides_with_a_file_leaves_the_file_alone() {
    let repo = seed_repo();
    write_files(&repo, &[("src/util.rs#helper", "not a symbol\n")]);
    commit_all(&repo, "a file named like a symbol key");

    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();

    let db = GraphDb::open(&db_dir).unwrap();
    assert_eq!(
        prop(&db, "src/util.rs#helper", "path"),
        Some(Value::Str("src/util.rs#helper".into())),
        "the File node keeps its own path"
    );
    assert_eq!(
        prop(&db, "src/util.rs#helper", "file_id"),
        None,
        "no symbol props were written onto it"
    );
    assert_eq!(prop(&db, "src/util.rs#helper", "kind"), None);
    // The rest of the file is unaffected: `helper` simply has no Symbol node.
    assert_eq!(prop(&db, "src/util.rs", "symbols_n"), Some(Value::Int(1)));
    assert_eq!(
        out(&db, "src/net.rs", "IMPORTS"),
        vec!["src/util.rs".to_string()]
    );
}

/// Turning a flag back on has to revisit files the previous run deliberately
/// skipped, even though not one byte of them changed since.
#[test]
fn turning_docs_back_on_fills_in_the_prose() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    let mut o = opts(&repo);
    o.docs = false;
    run_ingest_git(&db_dir, &o).unwrap();
    {
        let db = GraphDb::open(&db_dir).unwrap();
        assert_eq!(prop(&db, "docs/guide.md", "body"), None);
    }

    // Same commits, same bytes, different flag.
    let report = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!(
        report.structure.files_scanned, 5,
        "a full re-scan: {report:?}"
    );

    {
        // Scoped: an open handle holds the store's write lock, so the next
        // ingest would find the database busy.
        let db = GraphDb::open(&db_dir).unwrap();
        assert!(prop(&db, "docs/guide.md", "body").is_some(), "body arrives");
        assert_eq!(
            out(&db, "docs/guide.md", "MENTIONS"),
            vec!["src/net.rs".to_string(), "src/util.rs".to_string()]
        );
    }

    // And back off again retracts it, rather than leaving prose behind.
    run_ingest_git(&db_dir, &o).unwrap();
    let db = GraphDb::open(&db_dir).unwrap();
    assert_eq!(prop(&db, "docs/guide.md", "body"), None);
    assert!(out(&db, "docs/guide.md", "MENTIONS").is_empty());
}

#[test]
fn import_lines_are_recorded() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();

    let db = GraphDb::open(&db_dir).unwrap();
    assert_eq!(
        strings(prop(&db, "src/net.rs", "import_lines")),
        vec!["src/util.rs\t3".to_string()],
        "the evidence line is the line the `use` is written on"
    );
    assert_eq!(
        strings(prop(&db, "src/lib.rs", "import_lines")),
        vec![
            "src/net.rs\t3".to_string(),
            "src/util.rs\t4".to_string(),
            "src/util.rs\t6".to_string(),
        ],
        "one entry per import site, sorted"
    );
    assert_eq!(
        strings(prop(&db, "src/net.rs#connect", "call_lines")),
        vec!["src/util.rs#helper\t7".to_string()],
        "call evidence carries the call site line"
    );
}

/// An incremental refresh is handed the paths it is responsible for, and it
/// reads the graph for those and for the names its own calls look up — not for
/// every file and every symbol in the repository.
///
/// Both halves are asserted here, because narrowing the reads is only worth
/// anything if the writes come out the same. The first half is the saving: a
/// pass told about `src/util.rs` leaves an orphan under `src/net.rs` alone,
/// where the whole-tree pass sweeps it. The second is the constraint: the
/// edges the narrowed pass writes are exactly the ones a whole-tree pass
/// writes, including the repository-wide call tier that turns on a name being
/// unique across every file.
#[test]
fn touch_reads_only_the_touched_files() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();

    // Strand `src/net.rs#connect`: its file leaves the graph, so its key can
    // never be right again and a whole-tree pass would sweep it.
    {
        let shared = core_api::SharedDb::open(&db_dir).unwrap();
        let mut w = shared.write();
        w.delete_node("src/net.rs").unwrap();
    }
    assert!(GraphDb::open(&db_dir)
        .unwrap()
        .has_node("src/net.rs#connect"));

    // A pass responsible for one unrelated file does not go looking.
    let report = {
        let shared = core_api::SharedDb::open(&db_dir).unwrap();
        let mut w = shared.write();
        cli::structure::refresh_files(&mut w, &repo, "", &["src/util.rs".to_string()], true)
            .unwrap()
    };
    assert_eq!(
        report.files_scanned, 1,
        "one file was extracted: {report:?}"
    );
    assert!(
        GraphDb::open(&db_dir)
            .unwrap()
            .has_node("src/net.rs#connect"),
        "an orphan the pass was not told about is not its business"
    );

    // `src/util.rs` is intact, and the calls into it still resolve — the
    // narrowed index held every definition of every name it looked up.
    {
        let db = GraphDb::open(&db_dir).unwrap();
        assert_eq!(
            db.neighbors("src/lib.rs#run", "CALLS", Direction::Out)
                .unwrap_or_default(),
            vec!["src/util.rs#helper".to_string()],
            "a call out of an untouched file still points at the touched one"
        );
    }

    // The whole-tree pass, which is told about everything, does sweep it.
    {
        let shared = core_api::SharedDb::open(&db_dir).unwrap();
        let mut w = shared.write();
        cli::structure::refresh_all(&mut w, &repo, "", true).unwrap();
    }
    assert!(
        !GraphDb::open(&db_dir)
            .unwrap()
            .has_node("src/net.rs#connect"),
        "refresh_all still sweeps every orphan"
    );
}

/// The narrowed index must not change a single resolved call. Two files define
/// `helper`, so the repository-wide tier cannot fire; one file defines
/// `connect`, so it can. A refresh of one file has to see both facts.
#[test]
fn a_narrowed_refresh_resolves_calls_the_same_as_a_whole_tree_one() {
    let repo = seed_repo();
    commit(
        &repo,
        "a second helper, and a caller of both names",
        &[
            (
                "src/dup.rs",
                "//! A second definition of the same name.\n\n\
                 /// Also doubles.\npub fn helper(n: u32) -> u32 {\n    n + n\n}\n",
            ),
            (
                "src/caller.rs",
                "//! Calls one ambiguous name and one unique one.\n\n\
                 /// Do both.\npub fn both() -> u32 {\n    helper(1) + connect(2)\n}\n",
            ),
        ],
    );
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();

    let calls = |dir: &Path| {
        GraphDb::open(dir)
            .unwrap()
            .neighbors("src/caller.rs#both", "CALLS", Direction::Out)
            .unwrap_or_default()
    };
    let whole_tree = calls(&db_dir);
    assert_eq!(
        whole_tree,
        vec!["src/net.rs#connect".to_string()],
        "`connect` is unique so it resolves; `helper` is defined twice so it does not"
    );

    // Rewrite the caller and refresh only it. The answer must not move.
    write_files(
        &repo,
        &[(
            "src/caller.rs",
            "//! Calls one ambiguous name and one unique one.\n\n\
             /// Do both, twice.\npub fn both() -> u32 {\n    helper(1) + connect(2) + connect(3)\n}\n",
        )],
    );
    {
        let shared = core_api::SharedDb::open(&db_dir).unwrap();
        let mut w = shared.write();
        cli::structure::refresh_files(&mut w, &repo, "", &["src/caller.rs".to_string()], true)
            .unwrap();
    }
    assert_eq!(calls(&db_dir), whole_tree, "narrowing moved a call edge");
}

/// A Rust method is stored under its type — `Store.flush` — while every call
/// to it is written on a receiver, `store.flush()`. Before the index filed
/// methods under their bare name too, not one method in this repository had a
/// single incoming `CALLS` edge, so `context` on any of them named no callers
/// at all.
#[test]
fn rust_methods_get_incoming_calls_from_receiver_syntax() {
    let repo = tmp("repo");
    git(&repo, &["init", "-q", "-b", "main"]);
    commit(
        &repo,
        "a store and its callers",
        &[
            ("Cargo.toml", "[package]\nname = \"demo\"\n"),
            (
                "src/store.rs",
                "//! The store.\n\n\
                 /// A store.\npub struct Store {\n    pub n: u32,\n}\n\n\
                 impl Store {\n\
                 \x20   /// Flush it.\n\
                 \x20   pub fn flush(&self) -> u32 {\n        self.n\n    }\n\n\
                 \x20   /// Flush it twice.\n\
                 \x20   pub fn flush_twice(&self) -> u32 {\n        self.flush() + self.flush()\n    }\n\
                 }\n",
            ),
            (
                "src/caller.rs",
                "//! A sibling that holds a Store.\n\n\
                 /// Do the thing.\npub fn drive(store: &Store) -> u32 {\n    store.flush()\n}\n",
            ),
            (
                "src/lib.rs",
                "//! Crate root.\n\nmod caller;\nmod store;\n",
            ),
        ],
    );
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    let db = GraphDb::open(&db_dir).unwrap();

    let callers = |key: &str| {
        let mut v = db
            .neighbors(key, "CALLS", Direction::In)
            .unwrap_or_default();
        v.sort();
        v
    };
    assert_eq!(
        callers("src/store.rs#Store.flush"),
        vec![
            "src/caller.rs#drive".to_string(),
            "src/store.rs#Store.flush_twice".to_string(),
        ],
        "both the `self.flush()` inside the type and the `store.flush()` next door"
    );

    // And a receiver that names no type the graph knows still earns nothing.
    assert!(
        callers("src/store.rs#Store.flush_twice").is_empty(),
        "nothing calls it"
    );
}

/// The other half of the same rule: a bare method name is not a claim about
/// the whole tree. `bytes.len()` is a `Vec`'s length, and binding it to
/// whichever `Type.len` a repository happens to define is a wrong edge.
#[test]
fn a_method_call_on_an_unrelated_receiver_writes_no_edge() {
    let repo = tmp("repo");
    git(&repo, &["init", "-q", "-b", "main"]);
    commit(
        &repo,
        "a type with a len, and a caller with a vec",
        &[
            ("Cargo.toml", "[package]\nname = \"demo\"\n"),
            (
                "src/reg.rs",
                "//! A registry.\n\n\
                 /// A registry.\npub struct Registry {\n    pub items: Vec<u32>,\n}\n\n\
                 impl Registry {\n\
                 \x20   /// How many.\n\
                 \x20   pub fn len(&self) -> usize {\n        self.items.len()\n    }\n\
                 }\n",
            ),
            (
                "src/other.rs",
                "//! Counts some bytes.\n\n\
                 /// Count them.\npub fn count(bytes: &[u8]) -> usize {\n    bytes.len()\n}\n",
            ),
            ("src/lib.rs", "//! Crate root.\n\nmod other;\nmod reg;\n"),
        ],
    );
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    let db = GraphDb::open(&db_dir).unwrap();

    assert!(
        db.has_node("src/reg.rs#Registry.len"),
        "the method is in the graph"
    );
    assert!(
        db.neighbors("src/other.rs#count", "CALLS", Direction::Out)
            .unwrap_or_default()
            .is_empty(),
        "`bytes.len()` is a slice's length, not the registry's"
    );
    assert!(
        db.neighbors("src/reg.rs#Registry.len", "CALLS", Direction::Out)
            .unwrap_or_default()
            .is_empty(),
        "`self.items.len()` is a vector's length, not a recursive call"
    );
}