mushroomdb-cli 0.6.2

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
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
//! ingest-git builds a codebase graph from git history and keeps it current
//! across re-runs (adds, modifies, deletes, renames) so derived edges retract.
use cli::ingest_git::{run_ingest_git, IngestGitOpts};
use core_api::{Direction, GraphDb};
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-ingest-git-{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");
}

/// Stage whatever is in the worktree (including `git rm` / `git mv` results)
/// and commit it.
fn commit_all(repo: &Path, author: &str, msg: &str) {
    git(repo, &["add", "-A"]);
    git(
        repo,
        &[
            "-c",
            &format!("user.name={author}"),
            "-c",
            &format!("user.email={author}@x.test"),
            "commit",
            "-q",
            "-m",
            msg,
        ],
    );
}

/// Like [`commit_all`] but with the author's email given explicitly, so a test
/// can commit as the same person under two addresses.
fn commit_all_as(repo: &Path, name: &str, email: &str, msg: &str) {
    git(repo, &["add", "-A"]);
    git(
        repo,
        &[
            "-c",
            &format!("user.name={name}"),
            "-c",
            &format!("user.email={email}"),
            "commit",
            "-q",
            "-m",
            msg,
        ],
    );
}

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

fn commit_as(repo: &Path, name: &str, email: &str, msg: &str, files: &[(&str, &str)]) {
    write_files(repo, files);
    commit_all_as(repo, name, email, msg);
}

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();
    }
}

/// Absolute path of a program on the ambient PATH, for the shims below.
fn which(program: &str) -> String {
    let out = Command::new("sh")
        .args(["-c", &format!("command -v {program}")])
        .output()
        .unwrap();
    assert!(out.status.success(), "{program} is not on PATH");
    String::from_utf8(out.stdout).unwrap().trim().to_string()
}

/// Write `body` to `dir/name` and make it executable.
fn write_script(dir: &Path, name: &str, body: &str) -> PathBuf {
    let p = dir.join(name);
    std::fs::write(&p, body).unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
    p
}

/// `git mv`, creating the destination directory first — git will not.
fn mv(repo: &Path, from: &str, to: &str) {
    if let Some(parent) = Path::new(to).parent() {
        std::fs::create_dir_all(repo.join(parent)).unwrap();
    }
    git(repo, &["mv", from, to]);
}

fn seed_repo() -> PathBuf {
    let repo = tmp("repo");
    git(&repo, &["init", "-q", "-b", "main"]);
    commit(
        &repo,
        "alice",
        "init api and model",
        &[("src/api.rs", "a1"), ("src/model.rs", "m1")],
    );
    commit(
        &repo,
        "alice",
        "api+model again",
        &[("src/api.rs", "a2"), ("src/model.rs", "m2")],
    );
    commit(&repo, "bob", "docs only", &[("docs/readme.md", "r1")]);
    commit(
        &repo,
        "alice",
        "api+model third",
        &[("src/api.rs", "a3"), ("src/model.rs", "m3")],
    );
    repo
}

fn rev_parse_head(repo: &Path) -> String {
    let out = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(["rev-parse", "HEAD"])
        .output()
        .unwrap();
    assert!(out.status.success());
    String::from_utf8(out.stdout).unwrap().trim().to_string()
}

fn sync_marker(db_dir: &Path) -> String {
    let db = GraphDb::open(db_dir).unwrap();
    let sha = db
        .node_ref("__mushroomdb_git_sync__")
        .and_then(|n| n.prop("sha"));
    match sha {
        Some(core_api::Value::Str(s)) => s,
        other => panic!("no sync marker sha: {other:?}"),
    }
}

/// The marker must equal the head the walk was bounded by, and every commit it
/// can reach must already be a `Commit` node. A marker that ran ahead of the
/// walk would silently skip those commits on every later run.
fn assert_marker_covers_everything_ingested(db_dir: &Path, repo: &Path) {
    let marker = sync_marker(db_dir);
    let db = GraphDb::open(db_dir).unwrap();
    assert_eq!(
        marker,
        rev_parse_head(repo),
        "marker must be the head the walk ended on"
    );
    let out = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(["rev-list", &marker])
        .output()
        .unwrap();
    assert!(out.status.success());
    let listed = String::from_utf8(out.stdout).unwrap();
    let mut n = 0;
    for sha in listed.lines() {
        assert!(
            db.has_node(sha),
            "{sha} is reachable from the marker but was never ingested"
        );
        n += 1;
    }
    assert!(n > 0, "rev-list returned nothing");
}

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,
    }
}

/// `std::fs::canonicalize`, which is what `ingest-git` records as `GitSync.repo`
/// — on macOS the temp dir is a symlink, so the raw path never compares equal.
fn canonical(p: &Path) -> PathBuf {
    std::fs::canonicalize(p).unwrap()
}

#[test]
fn initial_ingest_builds_files_authors_and_co_change_edges() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    let r = run_ingest_git(&db_dir, &opts(&repo)).expect("ingest");
    assert_eq!((r.commits, r.files, r.authors), (4, 3, 2));
    assert!(!r.incremental);
    let db = GraphDb::open(&db_dir).unwrap();
    assert!(db.has_node("src/api.rs") && db.has_node("docs/readme.md"));
    // co-changed both ways, docs excluded (jaccard 0 with the src files)
    let n = db
        .neighbors("src/api.rs", "CO_CHANGED", Direction::Out)
        .unwrap();
    assert_eq!(n, vec!["src/model.rs".to_string()]);
    assert!(db
        .neighbors("docs/readme.md", "CO_CHANGED", Direction::Out)
        .unwrap()
        .is_empty());
    // ownership: alice authored 3 of 3 commits on api.rs
    assert_eq!(
        db.neighbors("src/api.rs", "TOP_AUTHOR", Direction::Out)
            .unwrap(),
        vec!["alice@x.test".to_string()]
    );
    // via-hop: alice KNOWS model.rs through api.rs (co-change overlap)
    assert!(db
        .neighbors("alice@x.test", "KNOWS", Direction::Out)
        .unwrap()
        .contains(&"src/model.rs".to_string()));
    // explain gives the rule and a score
    let ex = db.explain("src/api.rs", "src/model.rs").unwrap();
    assert_eq!(ex[0].rule, "co_changed");
    assert!(ex[0].weight.unwrap() > 0.7);
    assert!(db
        .fulltext_pairs()
        .contains(&("File".to_string(), "path".to_string())));
}

#[test]
fn rerun_is_incremental_and_delete_retracts_edges() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    // delete model.rs in a new commit
    std::fs::remove_file(repo.join("src/model.rs")).unwrap();
    commit_all(&repo, "alice", "drop model");
    let r = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert!(r.incremental);
    assert_eq!((r.commits, r.deleted), (1, 1));
    let db = GraphDb::open(&db_dir).unwrap();
    assert!(
        !db.has_node("src/model.rs"),
        "deleted file node must be removed"
    );
    assert!(
        db.neighbors("src/api.rs", "CO_CHANGED", Direction::Out)
            .unwrap()
            .is_empty(),
        "co-change edge must retract"
    );
    assert!(!db
        .neighbors("alice@x.test", "KNOWS", Direction::Out)
        .unwrap()
        .contains(&"src/model.rs".to_string()));
    assert_eq!(
        db.query("MATCH (c:Commit) RETURN count(*) AS n", &Default::default())
            .unwrap()
            .get(0, "n"),
        Some(&core_api::Value::Int(5))
    );
    drop(db);
    assert_marker_covers_everything_ingested(&db_dir, &repo);
}

#[test]
fn rename_keeps_history_and_moves_edges() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    mv(&repo, "src/model.rs", "src/domain/model.rs");
    commit_all(&repo, "alice", "move model");
    let r = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!(r.renamed, 1);
    let db = GraphDb::open(&db_dir).unwrap();
    assert!(!db.has_node("src/model.rs"));
    assert!(db.has_node("src/domain/model.rs"));
    assert_eq!(
        db.neighbors("src/api.rs", "CO_CHANGED", Direction::Out)
            .unwrap(),
        vec!["src/domain/model.rs".to_string()]
    );
    let n = db.node_ref("src/domain/model.rs").unwrap();
    assert_eq!(
        n.prop("n_commits"),
        Some(core_api::Value::Int(4)),
        "history follows the rename"
    );
    assert_eq!(
        n.prop("id"),
        Some(core_api::Value::Str("src/domain/model.rs".to_string())),
        "the id property follows the key"
    );
}

#[test]
fn exclude_patterns_skip_vendored_paths() {
    let repo = seed_repo();
    commit(
        &repo,
        "bob",
        "vendor blob",
        &[("lib/vendor/big.rs", "v"), ("lib/vendor/other.rs", "w")],
    );
    let db_dir = tmp("db");
    let mut o = opts(&repo);
    o.exclude = vec!["lib/vendor/".into(), "*.md".into()];
    let r = run_ingest_git(&db_dir, &o).unwrap();
    assert_eq!(r.files, 2, "only src/api.rs and src/model.rs remain");
}

#[test]
fn rerun_without_new_commits_is_a_noop() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    let before = GraphDb::open(&db_dir).unwrap().commit_seq();
    let r = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!(r.commits, 0);
    assert_eq!(
        GraphDb::open(&db_dir).unwrap().commit_seq(),
        before,
        "no writes on a no-op rerun"
    );
}

/// A file renamed and then deleted inside one window must leave nothing behind.
/// Renaming into a path that does not survive the window would strand a node
/// under the new key with stale props, which the next run would then duplicate
/// (its `id` prop still names the old path).
#[test]
fn rename_then_delete_in_one_window_leaves_no_phantom_node() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    mv(&repo, "src/api.rs", "src/renamed.rs");
    commit_all(&repo, "alice", "move api");
    std::fs::remove_file(repo.join("src/renamed.rs")).unwrap();
    commit_all(&repo, "alice", "drop the moved api");

    let r = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!((r.commits, r.renamed, r.deleted), (2, 0, 1));

    let db = GraphDb::open(&db_dir).unwrap();
    assert!(!db.has_node("src/api.rs"), "the original path is gone");
    assert!(
        !db.has_node("src/renamed.rs"),
        "the rename destination must not survive its own deletion"
    );
    // Nothing still points at either path.
    assert!(db
        .neighbors("src/model.rs", "CO_CHANGED", Direction::Out)
        .unwrap()
        .is_empty());
    let touched = db
        .query(
            "MATCH (c:Commit)-[:TOUCHED]->(f:File) RETURN f.id AS id",
            &Default::default(),
        )
        .unwrap();
    for i in 0..touched.len() {
        let id = touched.get(i, "id").cloned();
        assert_ne!(id, Some(core_api::Value::Str("src/api.rs".into())));
        assert_ne!(id, Some(core_api::Value::Str("src/renamed.rs".into())));
    }
    // Exactly one File node per live path, and no id/key disagreement.
    let files = db
        .query("MATCH (f:File) RETURN f.id AS id", &Default::default())
        .unwrap();
    assert_eq!(files.len(), 2, "only model.rs and readme.md remain");

    // A further run must find nothing to do — no resurrected duplicate.
    let before = db.commit_seq();
    drop(db);
    let again = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!(again.commits, 0);
    assert_eq!(
        GraphDb::open(&db_dir).unwrap().commit_seq(),
        before,
        "the follow-up run writes nothing"
    );
}

/// Two renames of the same file in one window collapse to a single move, so the
/// node lands on the final path with its whole history rather than being
/// dropped and recreated at the intermediate name.
#[test]
fn chained_rename_in_one_window_collapses_to_one_move() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    mv(&repo, "src/model.rs", "src/model2.rs");
    commit_all(&repo, "alice", "first move");
    mv(&repo, "src/model2.rs", "src/domain/model.rs");
    commit_all(&repo, "alice", "second move");

    let r = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!((r.commits, r.renamed, r.deleted), (2, 1, 0));

    let db = GraphDb::open(&db_dir).unwrap();
    assert!(!db.has_node("src/model.rs"));
    assert!(
        !db.has_node("src/model2.rs"),
        "the intermediate path must not exist"
    );
    assert!(db.has_node("src/domain/model.rs"));
    let n = db.node_ref("src/domain/model.rs").unwrap();
    assert_eq!(
        n.prop("n_commits"),
        Some(core_api::Value::Int(5)),
        "3 original commits plus both moves"
    );
    assert_eq!(
        n.prop("id"),
        Some(core_api::Value::Str("src/domain/model.rs".to_string()))
    );
    assert_eq!(
        db.neighbors("src/api.rs", "CO_CHANGED", Direction::Out)
            .unwrap(),
        vec!["src/domain/model.rs".to_string()]
    );
    // The commit that touched the intermediate name points at the final node.
    let touched = db
        .neighbors("src/domain/model.rs", "TOUCHED", Direction::In)
        .unwrap();
    assert_eq!(touched.len(), 5, "every touching commit retargeted");
}

/// A file moved away and moved back inside one window collapses to no move at
/// all, rather than a rename of the node onto its own key.
#[test]
fn rename_that_swaps_back_in_one_window_is_not_a_move() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    mv(&repo, "src/model.rs", "src/model2.rs");
    commit_all(&repo, "alice", "move away");
    mv(&repo, "src/model2.rs", "src/model.rs");
    commit_all(&repo, "alice", "move back");

    let r = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!((r.commits, r.renamed, r.deleted), (2, 0, 0));

    let db = GraphDb::open(&db_dir).unwrap();
    assert!(db.has_node("src/model.rs"));
    assert!(!db.has_node("src/model2.rs"));
    let n = db.node_ref("src/model.rs").unwrap();
    assert_eq!(
        n.prop("n_commits"),
        Some(core_api::Value::Int(5)),
        "both moves still count as commits touching the file"
    );
    assert_eq!(
        n.prop("id"),
        Some(core_api::Value::Str("src/model.rs".to_string()))
    );
}

/// A rename whose destination is excluded is a delete: the old node goes and no
/// node appears under the vendored path.
#[test]
fn rename_into_excluded_path_deletes_the_node() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    let mut o = opts(&repo);
    o.exclude = vec!["vendor/".into()];
    run_ingest_git(&db_dir, &o).unwrap();
    mv(&repo, "src/model.rs", "vendor/model.rs");
    commit_all(&repo, "alice", "vendor the model");

    let r = run_ingest_git(&db_dir, &o).unwrap();
    assert_eq!((r.renamed, r.deleted), (0, 1));

    let db = GraphDb::open(&db_dir).unwrap();
    assert!(!db.has_node("src/model.rs"));
    assert!(
        !db.has_node("vendor/model.rs"),
        "excluded destination gets no node"
    );
    assert!(db
        .neighbors("src/api.rs", "CO_CHANGED", Direction::Out)
        .unwrap()
        .is_empty());
}

/// A path freed by a delete and immediately claimed by a rename: the stale node
/// under that path is removed so `rename_node` has somewhere to land.
#[test]
fn rename_onto_a_just_deleted_path_replaces_the_old_node() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    std::fs::remove_file(repo.join("src/api.rs")).unwrap();
    commit_all(&repo, "alice", "drop api");
    mv(&repo, "docs/readme.md", "src/api.rs");
    commit_all(&repo, "bob", "readme takes the api path");

    let r = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!((r.commits, r.renamed, r.deleted), (2, 1, 1));

    let db = GraphDb::open(&db_dir).unwrap();
    assert!(!db.has_node("docs/readme.md"));
    assert!(db.has_node("src/api.rs"), "the moved node holds the path");
    let n = db.node_ref("src/api.rs").unwrap();
    assert_eq!(
        n.prop("n_commits"),
        Some(core_api::Value::Int(2)),
        "readme's own commit plus the move, not the old api.rs history"
    );
    assert_eq!(
        n.prop("id"),
        Some(core_api::Value::Str("src/api.rs".to_string()))
    );
    assert_eq!(
        n.prop("top_author_id"),
        Some(core_api::Value::Str("bob@x.test".to_string())),
        "ownership came across with the node, it is not the old api.rs owner"
    );
    let files = db
        .query("MATCH (f:File) RETURN f.id AS id", &Default::default())
        .unwrap();
    assert_eq!(files.len(), 2, "no duplicate under the reclaimed path");
}

/// Node keys are one namespace, so a repository file named `HEAD` must not
/// collide with the `GitSync` marker. If it did, the sha would land on the File
/// node, no marker would exist, and every run would re-ingest the whole history.
#[test]
fn a_repo_file_named_head_does_not_collide_with_the_sync_marker() {
    let repo = seed_repo();
    commit(&repo, "bob", "add a HEAD file", &[("HEAD", "not a ref")]);
    let db_dir = tmp("db");
    let r = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!(r.files, 4);

    let db = GraphDb::open(&db_dir).unwrap();
    let head_file = db.node_ref("HEAD").expect("the repo file keeps its path");
    assert_eq!(head_file.label(), "File");
    assert_eq!(
        head_file.prop("path"),
        Some(core_api::Value::Str("HEAD".to_string()))
    );
    assert!(
        head_file.prop("sha").is_none(),
        "the sync sha must not be written onto the File node"
    );
    let marker = db
        .node_ref("__mushroomdb_git_sync__")
        .expect("sync marker exists under its own key");
    assert_eq!(marker.label(), "GitSync");
    assert_eq!(
        marker.prop("id"),
        Some(core_api::Value::Str("__mushroomdb_git_sync__".to_string()))
    );
    assert!(matches!(marker.prop("sha"), Some(core_api::Value::Str(s)) if s.len() == 40));
    drop(db);

    // The marker is found again, so the rerun is incremental and writes nothing.
    let before = GraphDb::open(&db_dir).unwrap().commit_seq();
    let again = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert!(again.incremental);
    assert_eq!(again.commits, 0);
    assert_eq!(GraphDb::open(&db_dir).unwrap().commit_seq(), before);
}

/// The sync marker is exactly `git rev-parse HEAD`, and a merge whose side
/// branch is dated years in the future does not disturb that or the incremental
/// resume. Merge commits themselves carry no `TOUCHED` edges.
#[test]
fn sync_marker_is_head_across_a_merge_with_skewed_dates() {
    let repo = seed_repo();
    // A side branch off the first commit, dated far in the future, merged back.
    git(&repo, &["checkout", "-q", "-b", "feat", "HEAD~3"]);
    let full = repo.join("src/side.rs");
    std::fs::write(&full, "s1").unwrap();
    git(&repo, &["add", "-A"]);
    let st = Command::new("git")
        .arg("-C")
        .arg(&repo)
        .args([
            "-c",
            "user.name=bob",
            "-c",
            "user.email=bob@x.test",
            "commit",
            "-q",
            "-m",
            "future side work",
        ])
        .env("GIT_AUTHOR_DATE", "2030-01-01T00:00:00Z")
        .env("GIT_COMMITTER_DATE", "2030-01-01T00:00:00Z")
        .status()
        .unwrap();
    assert!(st.success());
    git(&repo, &["checkout", "-q", "main"]);
    git(
        &repo,
        &[
            "-c",
            "user.name=alice",
            "-c",
            "user.email=alice@x.test",
            "merge",
            "-q",
            "--no-ff",
            "feat",
            "-m",
            "merge the side branch",
        ],
    );

    let db_dir = tmp("db");
    let r = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!(r.commits, 6, "4 seed + side commit + merge");

    let real_head = String::from_utf8(
        Command::new("git")
            .arg("-C")
            .arg(&repo)
            .args(["rev-parse", "HEAD"])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap()
    .trim()
    .to_string();

    assert_eq!(
        sync_marker(&db_dir),
        real_head,
        "the marker is exactly rev-parse HEAD"
    );
    let db = GraphDb::open(&db_dir).unwrap();
    assert!(db.has_node("src/side.rs"));
    assert!(
        db.neighbors(&real_head, "TOUCHED", Direction::Out)
            .unwrap()
            .is_empty(),
        "a merge commit reports no file changes"
    );
    drop(db);

    // The marker resumes correctly: nothing new, nothing written.
    let before = GraphDb::open(&db_dir).unwrap().commit_seq();
    let again = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!(again.commits, 0);
    assert_eq!(GraphDb::open(&db_dir).unwrap().commit_seq(), before);
}

/// Non-ASCII paths are stored as written. Without `core.quotePath=false` git
/// renders them octal-escaped and quoted, so the node key would be mangled and
/// no later run would match it.
#[test]
fn non_ascii_paths_are_stored_unescaped() {
    let repo = seed_repo();
    commit(
        &repo,
        "bob",
        "add an accented file",
        &[("src/café.rs", "c1")],
    );
    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/café.rs"),
        "the real path is the key; keys present: {:?}",
        db.query("MATCH (f:File) RETURN f.id AS id", &Default::default())
            .unwrap()
            .len()
    );
    let n = db.node_ref("src/café.rs").unwrap();
    assert_eq!(
        n.prop("path"),
        Some(core_api::Value::Str("src/café.rs".to_string()))
    );
    assert_eq!(n.prop("ext"), Some(core_api::Value::Str("rs".to_string())));
}

/// An initialised repository with no commits reports zeros and writes nothing.
#[test]
fn empty_repository_reports_zeros_and_writes_nothing() {
    let repo = tmp("repo");
    git(&repo, &["init", "-q", "-b", "main"]);
    let db_dir = tmp("db");

    let r = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!((r.commits, r.files, r.authors), (0, 0, 0));
    assert!(!r.incremental);
    assert!(r.rules_created.is_empty(), "no rules on an empty repo");

    let db = GraphDb::open(&db_dir).unwrap();
    assert_eq!(db.commit_seq(), 0, "nothing was written");
    assert_eq!(db.stats().nodes_live, 0);
    drop(db);

    // The first real commit still gets a full, non-incremental ingest.
    commit(&repo, "alice", "first", &[("src/api.rs", "a1")]);
    let r = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!((r.commits, r.files, r.authors), (1, 1, 1));
    assert!(!r.incremental, "the empty run left no sync marker");
    assert!(r.rules_created.contains(&"co_changed".to_string()));
}

/// If the recorded sync head is not in the repository the run fails loudly
/// instead of replaying the whole history on top of what is already stored.
#[test]
fn missing_sync_head_errors_without_writing() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    let before = GraphDb::open(&db_dir).unwrap().commit_seq();

    // A different repository, whose history does not contain the recorded sha.
    let other = tmp("other");
    git(&other, &["init", "-q", "-b", "main"]);
    commit(&other, "carol", "unrelated work", &[("other.rs", "z")]);

    let err = run_ingest_git(&db_dir, &opts(&other)).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("sync head") && msg.contains("fresh database"),
        "error should name the problem and the way out, got: {msg}"
    );
    assert_eq!(
        GraphDb::open(&db_dir).unwrap().commit_seq(),
        before,
        "a failed run writes nothing"
    );
}

/// Ownership must be able to change across incremental runs. Per-author counts
/// are persisted on the `File` node, so a challenger's commits accumulate over
/// separate syncs instead of being credited to the incumbent on every reload.
///
/// alice opens the file with 3 commits, then bob adds 4 — one per incremental
/// run. Bob leads 4-3 and must own the file, and a full ingest of the same
/// repository into a fresh store must agree.
#[test]
fn ownership_flips_across_incremental_runs() {
    let repo = tmp("repo");
    git(&repo, &["init", "-q", "-b", "main"]);
    for i in 0..3 {
        commit(
            &repo,
            "alice",
            &format!("alice {i}"),
            &[("src/api.rs", &format!("a{i}"))],
        );
    }
    let db_dir = tmp("db");
    let first = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert!(!first.incremental);
    assert_eq!(
        GraphDb::open(&db_dir)
            .unwrap()
            .node_ref("src/api.rs")
            .unwrap()
            .prop("top_author_id"),
        Some(core_api::Value::Str("alice@x.test".to_string())),
        "alice owns the file after her three commits"
    );

    // Four separate incremental syncs, one bob commit each.
    for i in 0..4 {
        commit(
            &repo,
            "bob",
            &format!("bob {i}"),
            &[("src/api.rs", &format!("b{i}"))],
        );
        let r = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
        assert!(r.incremental, "run {i} should be incremental");
    }

    let incremental_top = GraphDb::open(&db_dir)
        .unwrap()
        .node_ref("src/api.rs")
        .unwrap()
        .prop("top_author_id");
    assert_eq!(
        incremental_top,
        Some(core_api::Value::Str("bob@x.test".to_string())),
        "bob has 4 commits to alice's 3, so ownership must move to bob"
    );

    // A fresh full ingest of the same repository is the oracle.
    let full_dir = tmp("db-full");
    run_ingest_git(&full_dir, &opts(&repo)).unwrap();
    let full_db = GraphDb::open(&full_dir).unwrap();
    let full_node = full_db.node_ref("src/api.rs").unwrap();
    assert_eq!(
        incremental_top,
        full_node.prop("top_author_id"),
        "incremental sync must agree with a full ingest of the same repo"
    );
    assert_eq!(full_node.prop("n_commits"), Some(core_api::Value::Int(7)));

    // TOP_AUTHOR is an auto-FK on top_author_id, so the edge must follow.
    let db = GraphDb::open(&db_dir).unwrap();
    assert_eq!(
        db.neighbors("src/api.rs", "TOP_AUTHOR", Direction::Out)
            .unwrap(),
        vec!["bob@x.test".to_string()],
    );
}

/// One person commits under two spellings of their name from the same address.
/// The `Author` node must be labelled with the spelling on the most commits,
/// not the one that happened to come first — and an incremental run that flips
/// the majority must move the label with it.
#[test]
fn author_name_is_the_majority_variant() {
    let repo = tmp("repo");
    git(&repo, &["init", "-q", "-b", "main"]);
    // The long spelling goes first, so "first seen" and "most commits" differ.
    commit_as(
        &repo,
        "Ada M. Lovelace",
        "ada@x.test",
        "long name",
        &[("src/api.rs", "a0")],
    );
    for i in 0..3 {
        commit_as(
            &repo,
            "Ada Lovelace",
            "ada@x.test",
            &format!("short name {i}"),
            &[("src/api.rs", &format!("a{}", i + 1))],
        );
    }

    let db_dir = tmp("db");
    let r = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!(r.authors, 1, "one address is one author");
    let name = |dir: &Path| {
        GraphDb::open(dir)
            .unwrap()
            .node_ref("ada@x.test")
            .unwrap()
            .prop("name")
    };
    assert_eq!(
        name(&db_dir),
        Some(core_api::Value::Str("Ada Lovelace".to_string())),
        "3 commits to 1, so the short spelling is the display name"
    );

    // Three more commits under the long spelling, one incremental run each:
    // 2-3 (no change), 3-3 (a tie, which the first-seen spelling wins), 4-3.
    let expected = [
        ("Ada Lovelace", "at 2-3 the short spelling still leads"),
        (
            "Ada M. Lovelace",
            "at 3-3 the tie goes to the one seen first",
        ),
        (
            "Ada M. Lovelace",
            "the majority flipped 4-3; the label follows",
        ),
    ];
    for (i, (want, why)) in expected.iter().enumerate() {
        commit_as(
            &repo,
            "Ada M. Lovelace",
            "ada@x.test",
            &format!("long name again {i}"),
            &[("src/api.rs", &format!("a{}", i + 4))],
        );
        assert!(run_ingest_git(&db_dir, &opts(&repo)).unwrap().incremental);
        assert_eq!(
            name(&db_dir),
            Some(core_api::Value::Str((*want).to_string())),
            "{why}"
        );
    }

    // A fresh full ingest of the same repository is the oracle for both the
    // label and the distribution behind it.
    let full_dir = tmp("db-full");
    run_ingest_git(&full_dir, &opts(&repo)).unwrap();
    assert_eq!(name(&db_dir), name(&full_dir));
    let counts = |dir: &Path| {
        GraphDb::open(dir)
            .unwrap()
            .node_ref("ada@x.test")
            .unwrap()
            .prop("name_counts")
    };
    assert_eq!(
        counts(&db_dir),
        Some(core_api::Value::List(vec![
            core_api::Value::Str("Ada M. Lovelace\t4".to_string()),
            core_api::Value::Str("Ada Lovelace\t3".to_string()),
        ])),
        "the distribution accumulates across syncs, in first-seen order"
    );
    assert_eq!(
        counts(&db_dir),
        counts(&full_dir),
        "incremental syncs must agree with a full ingest"
    );
}

/// A store built by released 0.6.0 carries `Author` nodes with a `name` and no
/// `name_counts`, and the name it holds is the *first* spelling that version
/// saw — which is exactly the wrong one this fix exists to correct. Nothing in
/// the graph records which spelling each commit used, so the first 0.6.1 sync
/// walks the log in full and recovers the real distribution. One new commit
/// must be enough to fix the label, not 500.
#[test]
fn legacy_store_recovers_the_majority_name_on_first_sync() {
    let repo = tmp("repo");
    git(&repo, &["init", "-q", "-b", "main"]);
    commit_as(
        &repo,
        "Ada M. Lovelace",
        "ada@x.test",
        "long name first",
        &[("src/api.rs", "a0")],
    );
    for i in 0..5 {
        commit_as(
            &repo,
            "Ada Lovelace",
            "ada@x.test",
            &format!("short name {i}"),
            &[("src/api.rs", &format!("a{}", i + 1))],
        );
    }

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

    // Age the store into what 0.6.0 wrote: the first-seen spelling, and no
    // distribution behind it.
    {
        let mut db = GraphDb::open(&db_dir).unwrap();
        db.set_prop(
            "ada@x.test",
            "name",
            core_api::Value::Str("Ada M. Lovelace".to_string()),
        )
        .unwrap();
        assert!(db.remove_prop("ada@x.test", "name_counts").unwrap());
    }

    // One new commit, one incremental sync.
    commit_as(
        &repo,
        "Ada Lovelace",
        "ada@x.test",
        "one more",
        &[("src/api.rs", "a6")],
    );
    assert!(run_ingest_git(&db_dir, &opts(&repo)).unwrap().incremental);

    let db = GraphDb::open(&db_dir).unwrap();
    let author = db.node_ref("ada@x.test").unwrap();
    assert_eq!(
        author.prop("name"),
        Some(core_api::Value::Str("Ada Lovelace".to_string())),
        "6 commits to 1: the recovered majority wins on the first sync"
    );
    assert_eq!(
        author.prop("name_counts"),
        Some(core_api::Value::List(vec![
            core_api::Value::Str("Ada M. Lovelace\t1".to_string()),
            core_api::Value::Str("Ada Lovelace\t6".to_string()),
        ])),
        "the whole history, counted once — the window is not added on top"
    );

    // And it agrees with a full ingest of the same repository.
    let full_dir = tmp("db-full");
    run_ingest_git(&full_dir, &opts(&repo)).unwrap();
    assert_eq!(
        GraphDb::open(&full_dir)
            .unwrap()
            .node_ref("ada@x.test")
            .unwrap()
            .prop("name_counts"),
        author.prop("name_counts")
    );
}

/// The `co_changed` rule scores on jaccard similarity, which is a ratio, so a
/// file that changes with this one often and *also* changes a lot on its own
/// falls under the floor and gets no edge. `impact` must still name it, by how
/// many commits the two share, and label it as a count rather than a score.
#[test]
fn impact_includes_partners_by_shared_commit_count() {
    let repo = tmp("repo");
    git(&repo, &["init", "-q", "-b", "main"]);

    // `api.rs` and `busy.rs` change together four times; `api.rs` and `pair.rs`
    // change together three times and almost never apart.
    for i in 0..4 {
        commit(
            &repo,
            "alice",
            &format!("api and busy {i}"),
            &[
                ("src/api.rs", &format!("a{i}")),
                ("src/busy.rs", &format!("b{i}")),
            ],
        );
    }
    for i in 0..3 {
        commit(
            &repo,
            "alice",
            &format!("api and pair {i}"),
            &[
                ("src/api.rs", &format!("a1{i}")),
                ("src/pair.rs", &format!("p{i}")),
            ],
        );
    }
    // Twenty commits to `busy.rs` alone drag its similarity to `api.rs` down to
    // 4/27 without touching how often the two actually change together.
    for i in 0..20 {
        commit(
            &repo,
            "alice",
            &format!("busy alone {i}"),
            &[("src/busy.rs", &format!("solo{i}"))],
        );
    }

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

    let mut edges = db
        .neighbors("src/api.rs", "CO_CHANGED", Direction::Out)
        .unwrap();
    edges.extend(
        db.neighbors("src/api.rs", "CO_CHANGED", Direction::In)
            .unwrap(),
    );
    assert!(
        !edges.contains(&"src/busy.rs".to_string()),
        "the rule writes no edge for the busy file: {edges:?}"
    );

    let r = core_api::repograph::impact(
        &db,
        &["src/api.rs".to_string()],
        &std::collections::BTreeSet::new(),
        &core_api::repograph::ImpactOptions::default(),
    );
    let named: Vec<(&str, Option<usize>)> = r.files[0]
        .partners
        .iter()
        .map(|p| (p.path.as_str(), p.shared_commits))
        .collect();
    assert_eq!(
        named,
        vec![("src/pair.rs", None), ("src/busy.rs", Some(4))],
        "the scored partner first, then the one only the commit counts see"
    );

    let text = core_api::repograph::render_impact(&r);
    assert!(
        text.contains("src/busy.rs (4 shared commits)"),
        "the digest labels it a count, not a score:\n{text}"
    );

    // `why` says the same thing when asked about the pair the rule skipped.
    let w = core_api::repograph::why(&db, "src/api.rs", "src/busy.rs");
    assert!(w.links.is_empty(), "no rule edge to report");
    assert_eq!(w.shared.as_ref().map(|s| s.count), Some(4));
    assert!(
        core_api::repograph::render_why(&w).contains("4 shared commits"),
        "{}",
        core_api::repograph::render_why(&w)
    );
}

/// A parent repository with an initialised submodule checked out at
/// `vendor/lib`, plus the repository the submodule was cloned from.
fn seed_repo_with_submodule() -> PathBuf {
    let lib = tmp("lib");
    git(&lib, &["init", "-q", "-b", "main"]);
    commit(&lib, "carol", "lib init", &[("src/lib.rs", "l1")]);

    let app = tmp("app");
    git(&app, &["init", "-q", "-b", "main"]);
    commit(&app, "alice", "app init", &[("src/app.rs", "a1")]);
    git(
        &app,
        &[
            // A file:// submodule source is refused by default since git 2.38.
            "-c",
            "protocol.file.allow=always",
            "submodule",
            "add",
            "-q",
            lib.to_str().unwrap(),
            "vendor/lib",
        ],
    );
    commit_all(&app, "alice", "add the vendored library");
    app
}

/// The `sha` on one unit's sync marker, or `None` when it has none. Opens its
/// own handle, so no other handle may be live when it is called.
fn marker(db_dir: &Path, key: &str) -> Option<String> {
    let db = GraphDb::open(db_dir).unwrap();
    match db.node_ref(key).and_then(|n| n.prop("sha")) {
        Some(core_api::Value::Str(s)) => Some(s),
        _ => None,
    }
}

fn run_cli(db_dir: &Path, repo: &Path, extra: &[&str], path: &str) -> std::process::Output {
    Command::new(env!("CARGO_BIN_EXE_mushroomdb"))
        .arg("ingest-git")
        .arg(db_dir)
        .arg(repo)
        .args(extra)
        .env("PATH", path)
        .output()
        .unwrap()
}

/// One person, two addresses, one `.mailmap`: the graph must hold a single
/// `Author`, keyed by the canonical address, with the canonical name.
#[test]
fn mailmap_merges_two_emails_into_one_author() {
    let repo = tmp("repo");
    git(&repo, &["init", "-q", "-b", "main"]);
    commit_as(
        &repo,
        "Alice Example",
        "alice@x.test",
        "init api",
        &[
            ("src/api.rs", "a1"),
            (
                ".mailmap",
                "Alice Example <alice@x.test> <alice.old@x.test>\n",
            ),
        ],
    );
    commit_as(
        &repo,
        "alice",
        "alice.old@x.test",
        "api again, old address",
        &[("src/api.rs", "a2")],
    );

    let db_dir = tmp("db");
    let r = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!(r.authors, 1, "the two addresses are one author");

    let db = GraphDb::open(&db_dir).unwrap();
    assert!(
        !db.has_node("alice.old@x.test"),
        "the mapped-away address must not become an Author"
    );
    let a = db.node_ref("alice@x.test").expect("canonical author");
    assert_eq!(a.label(), "Author");
    assert_eq!(
        a.prop("name"),
        Some(core_api::Value::Str("Alice Example".to_string())),
        "the mailmap name wins over the raw commit name"
    );
    assert_eq!(
        db.node_ref("src/api.rs").unwrap().prop("top_author_id"),
        Some(core_api::Value::Str("alice@x.test".to_string())),
        "both commits count towards the canonical identity"
    );
}

/// With `--recurse-submodules` a submodule is its own unit: its file keys carry
/// the submodule path, and it resumes from its own `GitSync` marker.
#[test]
fn recurse_submodules_prefixes_keys_and_keeps_separate_sync_markers() {
    let app = seed_repo_with_submodule();
    let sub = app.join("vendor/lib");
    let db_dir = tmp("db");
    let mut o = opts(&app);
    o.recurse_submodules = true;

    let r = run_ingest_git(&db_dir, &o).unwrap();
    assert_eq!(r.submodules, 1);
    assert_eq!(
        (r.commits, r.files, r.authors),
        (3, 3, 2),
        "2 parent commits + 1 submodule commit; src/app.rs, .gitmodules, vendor/lib/src/lib.rs"
    );

    let db = GraphDb::open(&db_dir).unwrap();
    assert!(db.has_node("src/app.rs"));
    assert!(
        db.has_node("vendor/lib/src/lib.rs"),
        "submodule files are keyed by their path in the parent"
    );
    assert!(
        !db.has_node("src/lib.rs"),
        "the unprefixed submodule path must not appear"
    );
    assert!(
        !db.has_node("vendor/lib"),
        "the gitlink itself is not a file"
    );
    drop(db);
    assert_eq!(
        marker(&db_dir, "__mushroomdb_git_sync__"),
        Some(rev_parse_head(&app))
    );
    assert_eq!(
        marker(&db_dir, "__mushroomdb_git_sync__:vendor/lib"),
        Some(rev_parse_head(&sub)),
        "the submodule resumes from its own marker"
    );

    // A commit inside the submodule only advances the submodule's marker.
    commit(&sub, "carol", "lib update", &[("src/lib.rs", "l2")]);
    let again = run_ingest_git(&db_dir, &o).unwrap();
    assert!(again.incremental);
    assert_eq!(again.commits, 1, "only the submodule moved");

    let db = GraphDb::open(&db_dir).unwrap();
    assert_eq!(
        db.node_ref("vendor/lib/src/lib.rs")
            .unwrap()
            .prop("n_commits"),
        Some(core_api::Value::Int(2)),
        "the submodule file keeps its cumulative history"
    );
    drop(db);
    assert_eq!(
        marker(&db_dir, "__mushroomdb_git_sync__"),
        Some(rev_parse_head(&app))
    );
    assert_eq!(
        marker(&db_dir, "__mushroomdb_git_sync__:vendor/lib"),
        Some(rev_parse_head(&sub))
    );
}

/// Without the flag the submodule is not walked at all, and the gitlink entry
/// the parent records for it does not become a `File`.
#[test]
fn without_recurse_the_gitlink_is_ignored() {
    let app = seed_repo_with_submodule();
    let db_dir = tmp("db");
    let r = run_ingest_git(&db_dir, &opts(&app)).unwrap();
    assert_eq!(r.submodules, 0);
    assert_eq!(
        (r.commits, r.files),
        (2, 2),
        "only the parent's commits, and only src/app.rs and .gitmodules"
    );

    let db = GraphDb::open(&db_dir).unwrap();
    assert!(db.has_node("src/app.rs") && db.has_node(".gitmodules"));
    assert!(
        !db.has_node("vendor/lib"),
        "the gitlink is a submodule pointer, not a file"
    );
    assert!(!db.has_node("vendor/lib/src/lib.rs"));
    assert!(
        db.node_ref("__mushroomdb_git_sync__:vendor/lib").is_none(),
        "no marker for a submodule that was never walked"
    );
}

/// `--prs` without `gh` on PATH prints one warning and ingests everything else.
#[test]
fn prs_without_gh_is_a_clean_skip() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    // A PATH holding git and nothing else, so `gh` cannot be found.
    let shim = tmp("shim");
    write_script(
        &shim,
        "git",
        &format!("#!/bin/sh\nexec {} \"$@\"\n", which("git")),
    );

    let out = run_cli(&db_dir, &repo, &["--prs"], shim.to_str().unwrap());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        out.status.success(),
        "a missing gh is not an error: {stderr}"
    );
    assert_eq!(
        stderr.lines().filter(|l| !l.trim().is_empty()).count(),
        1,
        "exactly one warning line, got: {stderr}"
    );
    assert!(stderr.contains("gh"), "the warning names gh: {stderr}");

    let db = GraphDb::open(&db_dir).unwrap();
    assert!(db.has_node("src/api.rs"), "the git ingest still ran");
    assert_eq!(
        db.query("MATCH (p:PR) RETURN p.id AS id", &Default::default())
            .unwrap()
            .len(),
        0,
        "no PR nodes without gh"
    );
    assert!(!db
        .fulltext_pairs()
        .contains(&("PR".to_string(), "title".to_string())));
}

/// Merged pull requests become `PR` nodes linked to the commit that carried
/// them: the merge commit by sha, and a squash merge by its `(#N)` subject.
#[test]
fn prs_from_fake_gh_link_merge_and_squash_commits() {
    let repo = tmp("repo");
    git(&repo, &["init", "-q", "-b", "main"]);
    commit(&repo, "alice", "init api", &[("src/api.rs", "a1")]);
    git(&repo, &["checkout", "-q", "-b", "feat"]);
    commit(&repo, "bob", "feature work", &[("src/feat.rs", "f1")]);
    git(&repo, &["checkout", "-q", "main"]);
    git(
        &repo,
        &[
            "-c",
            "user.name=alice",
            "-c",
            "user.email=alice@x.test",
            "merge",
            "-q",
            "--no-ff",
            "feat",
            "-m",
            "Merge pull request #7 from example/feat",
        ],
    );
    let merge_sha = rev_parse_head(&repo);
    commit(&repo, "bob", "add widget (#42)", &[("src/widget.rs", "w1")]);
    let squash_sha = rev_parse_head(&repo);

    // A fake `gh` first on PATH, printing a fixed listing.
    let fake = tmp("gh");
    let json = fake.join("prs.json");
    std::fs::write(
        &json,
        format!(
            r#"[{{"number":7,"title":"Add the feature","url":"https://example.test/pr/7",
  "mergedAt":"2026-01-02T00:00:00Z","mergeCommit":{{"oid":"{merge_sha}"}},
  "author":{{"login":"bobby"}}}},
 {{"number":42,"title":"Add a widget","url":"https://example.test/pr/42",
  "mergedAt":"2026-01-03T00:00:00Z","mergeCommit":null,"author":{{"login":"alicia"}}}}]"#
        ),
    )
    .unwrap();
    write_script(
        &fake,
        "gh",
        &format!("#!/bin/sh\ncat {}\n", json.to_str().unwrap()),
    );
    let path = format!(
        "{}:{}",
        fake.to_str().unwrap(),
        std::env::var("PATH").unwrap_or_default()
    );

    let db_dir = tmp("db");
    let out = run_cli(&db_dir, &repo, &["--prs"], &path);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );

    let db = GraphDb::open(&db_dir).unwrap();
    let pr = db.node_ref("pr:7").expect("pr:7 exists");
    assert_eq!(pr.label(), "PR");
    assert_eq!(pr.prop("number"), Some(core_api::Value::Int(7)));
    assert_eq!(
        pr.prop("title"),
        Some(core_api::Value::Str("Add the feature".to_string()))
    );
    assert_eq!(
        pr.prop("url"),
        Some(core_api::Value::Str(
            "https://example.test/pr/7".to_string()
        ))
    );
    assert_eq!(
        pr.prop("merged_at"),
        Some(core_api::Value::Str("2026-01-02T00:00:00Z".to_string()))
    );
    assert_eq!(
        pr.prop("author_login"),
        Some(core_api::Value::Str("bobby".to_string()))
    );

    // Merge commit: linked by sha.
    assert_eq!(
        db.neighbors("pr:7", "MERGED_AS", Direction::Out).unwrap(),
        vec![merge_sha.clone()]
    );
    assert_eq!(
        db.node_ref(&merge_sha).unwrap().prop("pr_id"),
        Some(core_api::Value::Str("pr:7".to_string()))
    );
    assert_eq!(
        db.neighbors(&merge_sha, "PR", Direction::Out).unwrap(),
        vec!["pr:7".to_string()],
        "the auto-FK on pr_id derives the Commit -> PR edge"
    );

    // Squash merge: linked by the `(#42)` subject.
    assert_eq!(
        db.neighbors("pr:42", "MERGED_AS", Direction::Out).unwrap(),
        vec![squash_sha.clone()]
    );
    assert_eq!(
        db.node_ref(&squash_sha).unwrap().prop("pr_id"),
        Some(core_api::Value::Str("pr:42".to_string()))
    );

    // A commit belonging to no pull request stays unlinked.
    let unrelated = db
        .query(
            "MATCH (c:Commit) WHERE c.message = 'init api' RETURN c.pr_id AS pr",
            &Default::default(),
        )
        .unwrap();
    assert_eq!(unrelated.get(0, "pr"), None);

    assert!(db
        .fulltext_pairs()
        .contains(&("PR".to_string(), "title".to_string())));
}

/// The sync marker records where the repository is and how it was ingested, so
/// a later run can repeat the same ingest without being told again.
#[test]
fn gitsync_records_repo_and_flags() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    let mut o = opts(&repo);
    o.recurse_submodules = true;
    o.prs = false;
    o.structure = false;
    o.docs = true;
    run_ingest_git(&db_dir, &o).unwrap();

    let db = GraphDb::open(&db_dir).unwrap();
    let m = db.node_ref("__mushroomdb_git_sync__").unwrap();
    assert_eq!(m.label(), "GitSync");
    assert_eq!(
        m.prop("repo"),
        Some(core_api::Value::Str(
            canonical(&repo).to_string_lossy().to_string()
        )),
        "the repository path is absolute"
    );
    assert_eq!(m.prop("recurse"), Some(core_api::Value::Bool(true)));
    assert_eq!(m.prop("prs"), Some(core_api::Value::Bool(false)));
    assert_eq!(m.prop("structure"), Some(core_api::Value::Bool(false)));
    assert_eq!(m.prop("docs"), Some(core_api::Value::Bool(true)));
    drop(db);

    // Re-running with the same flags and no new commits still writes nothing.
    let before = GraphDb::open(&db_dir).unwrap().commit_seq();
    run_ingest_git(&db_dir, &o).unwrap();
    assert_eq!(GraphDb::open(&db_dir).unwrap().commit_seq(), before);

    // Changing a flag updates the marker even with no new commits.
    o.structure = true;
    run_ingest_git(&db_dir, &o).unwrap();
    assert_eq!(
        GraphDb::open(&db_dir)
            .unwrap()
            .node_ref("__mushroomdb_git_sync__")
            .unwrap()
            .prop("structure"),
        Some(core_api::Value::Bool(true))
    );
}

/// The marker stamps when the store last took data, which is the only thing
/// that can tell a reader how stale the graph is: `Commit.ts` says when the
/// work was written, and on a store synced to head that is indistinguishable
/// from now.
#[test]
fn gitsync_stamps_when_the_store_last_took_data() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    let before = now_unix();
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();

    let stamp = |dir: &Path| match GraphDb::open(dir)
        .unwrap()
        .node_ref("__mushroomdb_git_sync__")
        .unwrap()
        .prop("synced_at")
    {
        Some(core_api::Value::Int(at)) => at,
        other => panic!("synced_at must be an integer, got {other:?}"),
    };

    let first = stamp(&db_dir);
    assert!(
        (before..=now_unix()).contains(&first),
        "the stamp is this run's wall clock, got {first}"
    );

    // A run that finds nothing new writes nothing at all — the stamp included.
    // It means "when this store last took something", so leaving it is right.
    let seq = GraphDb::open(&db_dir).unwrap().commit_seq();
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!(GraphDb::open(&db_dir).unwrap().commit_seq(), seq);
    assert_eq!(stamp(&db_dir), first);

    // A new commit moves it forward.
    std::thread::sleep(std::time::Duration::from_millis(1_100));
    commit(&repo, "alice", "one more", &[("src/api.rs", "a9")]);
    run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert!(
        stamp(&db_dir) > first,
        "ingesting new commits re-stamps the marker"
    );
}

/// Wall-clock seconds, for asserting the stamp lands in this run's window.
fn now_unix() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64
}

/// `--ensure-gitignore` adds the database directory to the repository's
/// `.gitignore` once, and leaves it alone on every later run.
#[test]
fn ensure_gitignore_is_idempotent() {
    let repo = seed_repo();
    std::fs::write(repo.join(".gitignore"), "target").unwrap(); // no trailing newline
    let db_dir = repo.join("mushroom-memory");
    let mut o = opts(&repo);
    o.ensure_gitignore = true;

    let first = run_ingest_git(&db_dir, &o).unwrap();
    assert!(first.gitignore_added);
    assert_eq!(
        std::fs::read_to_string(repo.join(".gitignore")).unwrap(),
        "target\nmushroom-memory/\n"
    );

    let again = run_ingest_git(&db_dir, &o).unwrap();
    assert!(!again.gitignore_added, "the line is already there");
    assert_eq!(
        std::fs::read_to_string(repo.join(".gitignore")).unwrap(),
        "target\nmushroom-memory/\n",
        "a second run must not append a duplicate"
    );

    // A database outside the repository is not the repository's business.
    let other = seed_repo();
    let outside = tmp("db-outside");
    let mut oo = opts(&other);
    oo.ensure_gitignore = true;
    let r = run_ingest_git(&outside, &oo).unwrap();
    assert!(!r.gitignore_added);
    assert!(
        !other.join(".gitignore").exists(),
        "no .gitignore is created for a database stored elsewhere"
    );
}

/// The store takes a cross-process write lock, so a second writer has to be
/// told to retry rather than failing obscurely or corrupting the WAL.
#[test]
fn a_busy_store_exits_three_with_a_retry_message() {
    let repo = seed_repo();
    let db_dir = tmp("db");
    // A plain read-write handle holds the lock for as long as it lives.
    let holder = GraphDb::open(&db_dir).unwrap();

    let out = run_cli(
        &db_dir,
        &repo,
        &[],
        &std::env::var("PATH").unwrap_or_default(),
    );
    assert_eq!(out.status.code(), Some(3), "Busy is exit code 3");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("another mushroomdb process is writing; retry"),
        "got: {stderr}"
    );
    assert_eq!(holder.commit_seq(), 0, "the busy run wrote nothing");
    drop(holder);

    // Once the lock is free the same ingest succeeds.
    let r = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert_eq!(r.commits, 4);
}

/// An incremental run reports what it wrote, and appends a number of WAL
/// commits set by the commit it picked up rather than by the property count.
///
/// Two separate things were wrong, and the two assertions pin one each.
///
/// The reported count came from the whole known file set, which an incremental
/// run loads in order to fold new commits into it — so a run over eight files
/// announced `397 file(s)`. The write scope was already correct; only the
/// number printed was wrong.
///
/// The properties of each written file went out as one WAL commit apiece. Every
/// frame is replayed on every later open and re-fires the rules watching the
/// property it carries, so the shape of the write is a cost the store keeps
/// paying. Batching them leaves this fixture appending six commits for a
/// one-file commit; one frame per property makes the same run append thirteen.
#[test]
fn an_incremental_run_writes_only_what_the_commit_touched() {
    let repo = tmp("repo");
    git(&repo, &["init", "-q", "-b", "main"]);
    // Twenty files, so "proportional to the repo" and "proportional to the
    // commit" are far enough apart to tell apart.
    let bodies: Vec<(String, String)> = (0..20)
        .map(|i| (format!("src/f{i}.rs"), format!("pub fn f{i}() {{}}\n")))
        .collect();
    write_files(
        &repo,
        &bodies
            .iter()
            .map(|(p, b)| (p.as_str(), b.as_str()))
            .collect::<Vec<_>>(),
    );
    commit_all(&repo, "alice", "twenty files");

    let db_dir = tmp("db");
    let full = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert!(!full.incremental);
    assert_eq!(full.files, 20, "the full run does write every file");

    let before = core_api::wal_commit_count_at(&db_dir).unwrap();

    // One commit, one file.
    commit(
        &repo,
        "alice",
        "touch one",
        &[("src/f3.rs", "pub fn f3() { let x = 1; }\n")],
    );
    let inc = run_ingest_git(&db_dir, &opts(&repo)).unwrap();
    assert!(inc.incremental);
    assert_eq!(
        inc.files, 1,
        "an incremental run reports the files it wrote, not every file it knows"
    );

    let delta = core_api::wal_commit_count_at(&db_dir).unwrap() - before;
    assert!(
        delta <= 8,
        "a one-file commit appended {delta} WAL commits; batched it is six, and \
         one commit per property makes it thirteen"
    );
}

/// `brief` is the `SessionStart` hook body, so it is measured by what a host
/// prepends to a session: the same bytes every time, inside the budget, and
/// nothing at all when the store cannot be read.
#[test]
fn brief_is_byte_stable_within_budget_and_silent_without_a_store() {
    let repo = tmp("brief-repo");
    git(&repo, &["init", "-q", "-b", "main"]);
    commit(
        &repo,
        "alice",
        "core and its callers",
        &[
            ("src/core.rs", "pub fn core() {}\n"),
            (
                "src/a.rs",
                "use crate::core;\npub fn a() { core::core(); }\n",
            ),
            (
                "src/b.rs",
                "use crate::core;\npub fn b() { core::core(); }\n",
            ),
        ],
    );

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

    let text = cli::run_brief(&db_dir).expect("brief");
    assert_eq!(text, cli::run_brief(&db_dir).expect("brief"));
    assert!(
        text.len() <= core_api::repograph::MAX_BRIEF_BYTES,
        "{} bytes",
        text.len()
    );
    // The brief reaches a session's context before its first turn, so it opens
    // with the marker every digest rendered out of a store opens with — inside
    // the budget asserted above, not on top of it.
    assert!(
        text.starts_with(core_api::repograph::UNTRUSTED_FRAMING),
        "{text}"
    );
    // The header names the repository, its size and the sha it is at — and no
    // age, which is what would move between two prompts of one session.
    let header = text.lines().nth(1).unwrap();
    let name = repo.file_name().unwrap().to_str().unwrap();
    let sha = marker(&db_dir, "__mushroomdb_git_sync__").expect("a sync marker");
    assert!(
        header.starts_with(&format!(
            "mushroomdb brief — {name} · 3 files · 3 symbols · "
        )),
        "{header}"
    );
    assert!(
        header.ends_with(&format!("· synced {}", &sha[..7])),
        "{header}"
    );
    assert!(!header.contains("ago"), "{header}");
    assert!(text.contains("src/core.rs"), "{text}");
    // The last line names both doors, and the CLI one is runnable: `explore`
    // takes a store, so the line has to carry one. This store was built by
    // `ingest-git`, so the door it names is the code graph's one tool.
    let reach = text.lines().next_back().unwrap();
    assert!(
        reach.starts_with("reach the graph: explore <target> (MCP tool)"),
        "{reach}"
    );
    assert!(
        reach.ends_with(&format!(" explore '{}' <target>", db_dir.display())),
        "{reach}"
    );

    // The hook's own contract: a store that cannot be opened at all says
    // nothing rather than opening a session with an error on stderr and a
    // non-zero exit.
    let not_a_store = repo.join("not-a-store");
    std::fs::write(&not_a_store, "a file where a store would be\n").unwrap();
    let out = Command::new(env!("CARGO_BIN_EXE_mushroomdb"))
        .arg("brief")
        .arg(&not_a_store)
        .output()
        .unwrap();
    assert!(out.status.success(), "the hook must never fail a session");
    assert!(out.stdout.is_empty(), "{:?}", String::from_utf8(out.stdout));
    assert!(out.stderr.is_empty(), "{:?}", String::from_utf8(out.stderr));

    // And a store that is simply not there is not created on the way to
    // finding that out: `RealFs::new` runs `create_dir_all`, so a `brief` hook
    // left behind by an uninstall would otherwise plant an empty
    // `mushroom-memory/` in the repository at the start of every session.
    let absent = repo.join("no-such-store");
    let out = Command::new(env!("CARGO_BIN_EXE_mushroomdb"))
        .arg("brief")
        .arg(&absent)
        .output()
        .unwrap();
    assert!(out.status.success(), "{out:?}");
    assert!(out.stdout.is_empty() && out.stderr.is_empty(), "{out:?}");
    assert!(!absent.exists(), "the hook created {}", absent.display());
}

/// Binding: on a store no repository was ingested into, the brief's last line
/// names `context`, not `explore`.
///
/// The two lines track the two MCP surfaces: a store with no `GitSync` marker
/// lists `context` among its eleven and does not list `explore` at all, so
/// naming `explore` there would send a session at a tool it cannot see.
#[test]
fn the_reach_line_names_context_on_a_store_with_no_git_sync_marker() {
    let db_dir = tmp("brief-memory-db");
    let out = Command::new(env!("CARGO_BIN_EXE_mushroomdb"))
        .arg("query")
        .arg(&db_dir)
        .arg("CREATE (n:File {id: 'a.rs', path: 'a.rs', lines: 1})")
        .output()
        .unwrap();
    assert!(out.status.success(), "{out:?}");

    let text = cli::run_brief(&db_dir).expect("brief");
    let reach = text.lines().next_back().unwrap();
    assert!(
        reach.starts_with("reach the graph: context <target> (MCP tool)"),
        "{reach}"
    );
    assert!(
        !reach.contains("explore"),
        "a memory store must not be sent at the code-graph tool: {reach}"
    );
    assert!(
        reach.ends_with(&format!(" context '{}' <target>", db_dir.display())),
        "{reach}"
    );
}

/// Binding: on a `--delivery cli` install the brief's last line names the
/// shell form and nothing else.
///
/// The reach line is the one place a session is told how to get at the graph.
/// A `cli` install registers no MCP server, so naming the tool would send it
/// at a door that is not there — the same failure as naming `explore` on a
/// memory store, one layer out.
#[test]
fn the_reach_line_on_a_cli_delivery_install_names_only_the_binary() {
    let root = tmp("brief-cli-delivery");
    let home = tmp("brief-cli-delivery-home");
    let db_dir = root.join("mushroom-memory");
    std::fs::create_dir_all(root.join(".git").join("hooks")).unwrap();

    cli::install::run_install_with(
        &root,
        &home,
        &cli::install::InstallOpts {
            platform: Some(cli::install::Platform::ClaudeCode),
            scope: Some(cli::install::Scope::Project),
            db: Some(db_dir.clone()),
            command: None,
            git_hooks: true,
            prewarm: false,
            delivery: cli::install::Delivery::Cli,
            intercept_grep: false,
        },
        &cli::install::McpCommand::OnPath,
        &cli::install::Externals::with_path(None),
    )
    .expect("install");

    let out = Command::new(env!("CARGO_BIN_EXE_mushroomdb"))
        .arg("query")
        .arg(&db_dir)
        .arg("CREATE (n:File {id: 'a.rs', path: 'a.rs', lines: 1})")
        .output()
        .unwrap();
    assert!(out.status.success(), "{out:?}");

    let text = cli::run_brief(&db_dir).expect("brief");
    let reach = text.lines().next_back().unwrap();
    assert!(
        !reach.contains("MCP tool"),
        "a cli install has no server to name: {reach}"
    );
    assert!(
        reach.ends_with(&format!(" context '{}' <target>", db_dir.display())),
        "{reach}"
    );
}