mati 0.1.4

An enforcement layer for codebase knowledge: confirmed gotchas gate what AI agents read and edit at the hook level. Not a passive memory store.
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
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
use super::*;
use crate::health::staleness::analyzer::MIN_TOMBSTONE_SAMPLE;
use crate::store::record::*;
use tempfile::TempDir;

/// A deadline no test will reach — for call sites not testing the budget.
fn far_deadline() -> Instant {
    Instant::now() + std::time::Duration::from_secs(3600)
}

fn make_file_record_with_staleness(value: f32) -> Record {
    Record {
        key: "file:src/main.rs".to_string(),
        value: String::new(),
        category: Category::File,
        priority: Priority::Normal,
        tags: vec![],
        created_at: 1_000_000,
        updated_at: 1_000_000,
        ref_url: None,
        staleness: StalenessScore {
            value,
            tier: StalenessScore::tier_from_value(value),
            signals: vec![],
            computed_at: 0,
            last_record_sha: String::new(),
        },
        lifecycle: RecordLifecycle::Active,
        version: RecordVersion {
            device_id: uuid::Uuid::new_v4(),
            logical_clock: 1,
            wall_clock: 1_000_000,
        },
        quality: QualityScore::layer0_default(),
        access_count: 0,
        last_accessed: 0,
        source: RecordSource::StaticAnalysis,
        confidence: ConfidenceScore::for_new_record(&RecordSource::StaticAnalysis),
        gap_analysis_score: 0.0,
        payload: None,
    }
}

fn make_gotcha_record(key: &str) -> Record {
    let gotcha = GotchaRecord {
        rule: "test rule".into(),
        reason: "test reason".into(),
        severity: Priority::High,
        affected_files: vec!["src/main.rs".into()],
        ref_url: None,
        discovered_session: 0,
        confirmed: true,
        confirmed_content: Default::default(),
    };
    Record {
        key: key.to_string(),
        value: gotcha.rule.clone(),
        payload: serde_json::to_value(&gotcha).ok(),
        category: Category::Gotcha,
        priority: Priority::High,
        tags: vec![],
        created_at: 1_000_000,
        updated_at: 1_000_000,
        ref_url: None,
        staleness: StalenessScore::fresh(),
        lifecycle: RecordLifecycle::Active,
        version: RecordVersion {
            device_id: uuid::Uuid::new_v4(),
            logical_clock: 1,
            wall_clock: 1_000_000,
        },
        quality: QualityScore::layer0_default(),
        access_count: 0,
        last_accessed: 0,
        source: RecordSource::DeveloperManual,
        confidence: ConfidenceScore::for_new_record(&RecordSource::DeveloperManual),
        gap_analysis_score: 0.0,
    }
}

fn make_linked_file_record() -> FileRecord {
    FileRecord {
        path: "src/main.rs".into(),
        purpose: String::new(),
        entry_points: vec![],
        imports: vec![],
        gotcha_keys: vec![],
        decision_keys: vec![],
        todos: vec![],
        unsafe_count: 0,
        unwrap_count: 0,
        change_frequency: 0,
        last_author: None,
        is_hotspot: false,
        token_cost_estimate: 0,
        last_modified_session: 0,
        content_hash: None,
        line_count: 0,
        blast_radius: None,
        propagated_staleness: None,
    }
}

fn empty_diff() -> ReparseDiff {
    ReparseDiff {
        entry_points_added: vec![],
        entry_points_removed: vec![],
        imports_added: vec![],
        imports_removed: vec![],
        todos_changed: false,
        unsafe_delta: 0,
        unwrap_delta: 0,
    }
}

#[test]
fn empty_diff_produces_no_signals() {
    let mut record = make_file_record_with_staleness(0.0);
    let signals = apply_reparse_staleness(&mut record, &empty_diff());
    assert!(signals.is_empty());
    assert!(record.staleness.value < 0.01);
}

#[test]
fn entry_point_changes_bump_staleness() {
    let mut record = make_file_record_with_staleness(0.0);
    let diff = ReparseDiff {
        entry_points_added: vec!["new_fn".into()],
        entry_points_removed: vec!["old_fn".into()],
        ..empty_diff()
    };
    let signals = apply_reparse_staleness(&mut record, &diff);
    assert_eq!(signals.len(), 1);
    assert!((record.staleness.value - 0.30).abs() < 0.01);
    assert_eq!(record.staleness.tier, StalenessTier::Aging);
}

#[test]
fn import_changes_bump_staleness() {
    let mut record = make_file_record_with_staleness(0.0);
    let diff = ReparseDiff {
        imports_added: vec!["new_dep".into()],
        ..empty_diff()
    };
    let signals = apply_reparse_staleness(&mut record, &diff);
    assert_eq!(signals.len(), 1);
    assert!((record.staleness.value - 0.10).abs() < 0.01);
}

#[test]
fn increment_capped_at_max() {
    let mut record = make_file_record_with_staleness(0.0);
    let diff = ReparseDiff {
        entry_points_added: vec!["a".into(), "b".into(), "c".into(), "d".into()],
        imports_added: vec!["x".into(), "y".into(), "z".into()],
        ..empty_diff()
    };
    let _signals = apply_reparse_staleness(&mut record, &diff);
    // 4*0.15 + 3*0.10 = 0.90, capped at 0.40
    assert!((record.staleness.value - 0.40).abs() < 0.01);
}

#[test]
fn staleness_does_not_exceed_one() {
    let mut record = make_file_record_with_staleness(0.85);
    let diff = ReparseDiff {
        entry_points_added: vec!["a".into(), "b".into()],
        ..empty_diff()
    };
    let _signals = apply_reparse_staleness(&mut record, &diff);
    assert!(record.staleness.value <= 1.0);
}

#[test]
fn tier_updates_correctly_after_increment() {
    let mut record = make_file_record_with_staleness(0.35);
    let diff = ReparseDiff {
        entry_points_removed: vec!["removed_fn".into()],
        ..empty_diff()
    };
    let _signals = apply_reparse_staleness(&mut record, &diff);
    // 0.35 + 0.15 = 0.50 → Stale
    assert_eq!(record.staleness.tier, StalenessTier::Stale);
}

#[tokio::test]
async fn cascade_staleness_bumps_linked_gotchas() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    let gotcha = make_gotcha_record("gotcha:test-rule");
    store.put("gotcha:test-rule", &gotcha).await.unwrap();

    let file_record = FileRecord {
        path: "src/main.rs".into(),
        purpose: String::new(),
        entry_points: vec![],
        imports: vec![],
        gotcha_keys: vec!["gotcha:test-rule".into()],
        decision_keys: vec![],
        todos: vec![],
        unsafe_count: 0,
        unwrap_count: 0,
        change_frequency: 0,
        last_author: None,
        is_hotspot: false,
        token_cost_estimate: 0,
        last_modified_session: 0,
        content_hash: None,
        line_count: 0,
        blast_radius: None,
        propagated_staleness: None,
    };

    let cascaded = cascade_staleness_to_gotchas(&store, &file_record)
        .await
        .unwrap();

    assert_eq!(cascaded, 1);

    let updated = store.get("gotcha:test-rule").await.unwrap().unwrap();
    assert!((updated.staleness.value - 0.10).abs() < 0.01);
    assert!(updated.staleness.signals.iter().any(|s| {
        matches!(s, StalenessSignal::LinkedFileChanged { path } if path == "src/main.rs")
    }));

    store.close().await.unwrap();
}

#[tokio::test]
async fn cascade_noop_when_no_gotcha_keys() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    let file_record = FileRecord {
        path: "src/main.rs".into(),
        purpose: String::new(),
        entry_points: vec![],
        imports: vec![],
        gotcha_keys: vec![],
        decision_keys: vec![],
        todos: vec![],
        unsafe_count: 0,
        unwrap_count: 0,
        change_frequency: 0,
        last_author: None,
        is_hotspot: false,
        token_cost_estimate: 0,
        last_modified_session: 0,
        content_hash: None,
        line_count: 0,
        blast_radius: None,
        propagated_staleness: None,
    };

    let cascaded = cascade_staleness_to_gotchas(&store, &file_record)
        .await
        .unwrap();
    assert_eq!(cascaded, 0);

    store.close().await.unwrap();
}

#[tokio::test]
async fn cascade_skips_missing_gotcha_records() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    let file_record = FileRecord {
        path: "src/main.rs".into(),
        purpose: String::new(),
        entry_points: vec![],
        imports: vec![],
        gotcha_keys: vec!["gotcha:nonexistent".into()],
        decision_keys: vec![],
        todos: vec![],
        unsafe_count: 0,
        unwrap_count: 0,
        change_frequency: 0,
        last_author: None,
        is_hotspot: false,
        token_cost_estimate: 0,
        last_modified_session: 0,
        content_hash: None,
        line_count: 0,
        blast_radius: None,
        propagated_staleness: None,
    };

    let cascaded = cascade_staleness_to_gotchas(&store, &file_record)
        .await
        .unwrap();
    assert_eq!(cascaded, 0);

    store.close().await.unwrap();
}

// ── M-13-A: StalenessAnalyzer tests ─────────────────────────────────────

/// Helper: create a record with specific timestamps for time_factor tests.
fn make_record_at(key: &str, updated_at: u64, last_accessed: u64) -> Record {
    Record {
        key: key.to_string(),
        value: String::new(),
        category: Category::File,
        priority: Priority::Normal,
        tags: vec![],
        created_at: updated_at,
        updated_at,
        ref_url: None,
        staleness: StalenessScore {
            value: 0.0,
            tier: StalenessTier::Fresh,
            signals: vec![],
            computed_at: 0,
            last_record_sha: String::new(),
        },
        lifecycle: RecordLifecycle::Active,
        version: RecordVersion {
            device_id: uuid::Uuid::new_v4(),
            logical_clock: 1,
            wall_clock: updated_at,
        },
        quality: QualityScore::layer0_default(),
        access_count: 0,
        last_accessed,
        source: RecordSource::StaticAnalysis,
        confidence: ConfidenceScore::for_new_record(&RecordSource::StaticAnalysis),
        gap_analysis_score: 0.0,
        payload: None,
    }
}

/// Helper: make a file record with FileRecord value JSON.
fn make_file_record_full(
    key: &str,
    imports: Vec<String>,
    gotcha_keys: Vec<String>,
    decision_keys: Vec<String>,
    last_modified_session: u64,
) -> Record {
    let fr = FileRecord {
        path: key.strip_prefix("file:").unwrap_or(key).to_string(),
        purpose: String::new(),
        entry_points: vec![],
        imports,
        gotcha_keys: gotcha_keys.clone(),
        decision_keys: decision_keys.clone(),
        todos: vec![],
        unsafe_count: 0,
        unwrap_count: 0,
        change_frequency: 0,
        last_author: None,
        is_hotspot: false,
        token_cost_estimate: 0,
        last_modified_session,
        content_hash: None,
        line_count: 0,
        blast_radius: None,
        propagated_staleness: None,
    };
    Record {
        key: key.to_string(),
        value: serde_json::to_string(&fr).unwrap(),
        category: Category::File,
        priority: Priority::Normal,
        tags: vec![],
        created_at: 1_000_000,
        updated_at: 1_000_000,
        ref_url: None,
        staleness: StalenessScore::fresh(),
        lifecycle: RecordLifecycle::Active,
        version: RecordVersion {
            device_id: uuid::Uuid::new_v4(),
            logical_clock: 1,
            wall_clock: 1_000_000,
        },
        quality: QualityScore::layer0_default(),
        access_count: 0,
        last_accessed: 0,
        source: RecordSource::StaticAnalysis,
        confidence: ConfidenceScore::for_new_record(&RecordSource::StaticAnalysis),
        gap_analysis_score: 0.0,
        payload: None,
    }
}

// ── time_factor tests ───────────────────────────────────────────────────

#[test]
fn time_factor_zero_when_just_updated() {
    let now = 10_000_000u64;
    let record = make_record_at("file:test.rs", now, 0);
    let factor = time_factor(&record, now);
    assert!(factor.abs() < 0.001, "expected ~0.0, got {factor}");
}

#[test]
fn time_factor_half_at_45_days() {
    let now = 10_000_000u64;
    let forty_five_days_ago = now - (45 * 86400);
    let record = make_record_at("file:test.rs", forty_five_days_ago, 0);
    let factor = time_factor(&record, now);
    assert!(
        (factor - 0.5).abs() < 0.02,
        "expected ~0.5 at 45 days, got {factor}"
    );
}

#[test]
fn time_factor_max_at_90_days() {
    let now = 10_000_000u64;
    let ninety_days_ago = now - (90 * 86400);
    let record = make_record_at("file:test.rs", ninety_days_ago, 0);
    let factor = time_factor(&record, now);
    assert!(
        (factor - 1.0).abs() < 0.02,
        "expected ~1.0 at 90 days, got {factor}"
    );
}

#[test]
fn time_factor_uses_last_accessed_when_newer() {
    let now = 10_000_000u64;
    // updated_at is old, but last_accessed is recent.
    let record = make_record_at("file:test.rs", now - (90 * 86400), now - 86400);
    let factor = time_factor(&record, now);
    // Should use last_accessed (1 day ago), not updated_at (90 days ago).
    assert!(
        factor < 0.05,
        "expected near-zero with recent access, got {factor}"
    );
}

// ── git_factor tests ────────────────────────────────────────────────────

#[test]
fn git_factor_zero_when_no_repo() {
    let analyzer = StalenessAnalyzer {
        repo: None,
        root: PathBuf::from("/nonexistent"),
        root_from_git: false,
        now: 2_000_000,
        head_commit: None,
    };
    assert_eq!(
        analyzer.git_factor_for("file:src/main.rs", "deadbeef", far_deadline()),
        (0.0, None)
    );
}

// ── dep_factor tests ────────────────────────────────────────────────────

#[test]
fn dep_factor_zero_when_no_imports() {
    let fr = FileRecord {
        path: "src/main.rs".into(),
        purpose: String::new(),
        entry_points: vec![],
        imports: vec![],
        gotcha_keys: vec![],
        decision_keys: vec![],
        todos: vec![],
        unsafe_count: 0,
        unwrap_count: 0,
        change_frequency: 0,
        last_author: None,
        is_hotspot: false,
        token_cost_estimate: 0,
        last_modified_session: 1_000_000,
        content_hash: None,
        line_count: 0,
        blast_radius: None,
        propagated_staleness: None,
    };
    let cache = HashMap::new();
    let factor = dep_factor(Some(&fr), &cache);
    assert!(factor.abs() < 0.001);
}

#[test]
fn dep_factor_detects_bumped_dep() {
    let fr = FileRecord {
        path: "src/main.rs".into(),
        purpose: String::new(),
        entry_points: vec![],
        imports: vec!["tokio::sync::Mutex".into()],
        gotcha_keys: vec![],
        decision_keys: vec![],
        todos: vec![],
        unsafe_count: 0,
        unwrap_count: 0,
        change_frequency: 0,
        last_author: None,
        is_hotspot: false,
        token_cost_estimate: 0,
        last_modified_session: 1_000_000,
        content_hash: None,
        line_count: 0,
        blast_radius: None,
        propagated_staleness: None,
    };

    // Create a dep record for tokio that was updated after the file.
    let mut dep_rec = Record {
        key: "dep:cargo:tokio".to_string(),
        value: String::new(),
        category: Category::Dependency,
        priority: Priority::Normal,
        tags: vec![],
        created_at: 500_000,
        updated_at: 2_000_000, // Updated after file's last_modified_session.
        ref_url: None,
        staleness: StalenessScore {
            value: 0.0,
            tier: StalenessTier::Fresh,
            signals: vec![StalenessSignal::DependencyBumped {
                dep: "tokio".into(),
                old_ver: "1.0".into(),
                new_ver: "1.1".into(),
            }],
            computed_at: 0,
            last_record_sha: String::new(),
        },
        lifecycle: RecordLifecycle::Active,
        version: RecordVersion {
            device_id: uuid::Uuid::new_v4(),
            logical_clock: 1,
            wall_clock: 2_000_000,
        },
        quality: QualityScore::layer0_default(),
        access_count: 0,
        last_accessed: 0,
        source: RecordSource::StaticAnalysis,
        confidence: ConfidenceScore::for_new_record(&RecordSource::StaticAnalysis),
        gap_analysis_score: 0.0,
        payload: None,
    };

    let mut cache = HashMap::new();
    cache.insert("dep:cargo:tokio".to_string(), dep_rec.clone());

    let factor = dep_factor(Some(&fr), &cache);
    assert!(
        factor > 0.5,
        "expected high dep factor for bumped dep, got {factor}"
    );

    // With no bump signal and same updated_at, factor should be zero.
    dep_rec.staleness.signals.clear();
    dep_rec.updated_at = 1_000_000; // Same as file.
    cache.insert("dep:cargo:tokio".to_string(), dep_rec);
    let factor2 = dep_factor(Some(&fr), &cache);
    assert!(
        factor2.abs() < 0.001,
        "expected zero when dep not bumped, got {factor2}"
    );
}

#[test]
fn dep_factor_detects_bumped_npm_dep_from_subpath_import() {
    let fr = FileRecord {
        path: "src/app.ts".into(),
        purpose: String::new(),
        entry_points: vec![],
        imports: vec!["@types/node/fs".into()],
        gotcha_keys: vec![],
        decision_keys: vec![],
        todos: vec![],
        unsafe_count: 0,
        unwrap_count: 0,
        change_frequency: 0,
        last_author: None,
        is_hotspot: false,
        token_cost_estimate: 0,
        line_count: 0,
        blast_radius: None,
        propagated_staleness: None,
        last_modified_session: 1_000_000,
        content_hash: None,
    };

    let dep_rec = Record {
        key: "dep:npm:@types/node".to_string(),
        value: String::new(),
        category: Category::Dependency,
        priority: Priority::Normal,
        tags: vec![],
        created_at: 500_000,
        updated_at: 2_000_000,
        ref_url: None,
        staleness: StalenessScore {
            value: 0.0,
            tier: StalenessTier::Fresh,
            signals: vec![StalenessSignal::DependencyBumped {
                dep: "@types/node".into(),
                old_ver: "20.0.0".into(),
                new_ver: "20.1.0".into(),
            }],
            computed_at: 0,
            last_record_sha: String::new(),
        },
        lifecycle: RecordLifecycle::Active,
        version: RecordVersion {
            device_id: uuid::Uuid::new_v4(),
            logical_clock: 1,
            wall_clock: 2_000_000,
        },
        quality: QualityScore::layer0_default(),
        access_count: 0,
        last_accessed: 0,
        source: RecordSource::StaticAnalysis,
        confidence: ConfidenceScore::for_new_record(&RecordSource::StaticAnalysis),
        gap_analysis_score: 0.0,
        payload: None,
    };

    let mut cache = HashMap::new();
    cache.insert(dep_rec.key.clone(), dep_rec);

    let factor = dep_factor(Some(&fr), &cache);
    assert!(
        factor > 0.5,
        "expected high dep factor for bumped npm dep, got {factor}"
    );
}

#[test]
fn dep_factor_detects_bumped_go_dep_from_subpackage_import() {
    let fr = FileRecord {
        path: "internal/server.go".into(),
        purpose: String::new(),
        entry_points: vec![],
        imports: vec!["github.com/gin-gonic/gin/render".into()],
        gotcha_keys: vec![],
        decision_keys: vec![],
        todos: vec![],
        unsafe_count: 0,
        unwrap_count: 0,
        change_frequency: 0,
        last_author: None,
        is_hotspot: false,
        token_cost_estimate: 0,
        line_count: 0,
        blast_radius: None,
        propagated_staleness: None,
        last_modified_session: 1_000_000,
        content_hash: None,
    };

    let dep_rec = Record {
        key: "dep:go:github.com/gin-gonic/gin".to_string(),
        value: String::new(),
        category: Category::Dependency,
        priority: Priority::Normal,
        tags: vec![],
        created_at: 500_000,
        updated_at: 2_000_000,
        ref_url: None,
        staleness: StalenessScore {
            value: 0.0,
            tier: StalenessTier::Fresh,
            signals: vec![StalenessSignal::DependencyBumped {
                dep: "github.com/gin-gonic/gin".into(),
                old_ver: "1.9.0".into(),
                new_ver: "1.9.1".into(),
            }],
            computed_at: 0,
            last_record_sha: String::new(),
        },
        lifecycle: RecordLifecycle::Active,
        version: RecordVersion {
            device_id: uuid::Uuid::new_v4(),
            logical_clock: 1,
            wall_clock: 2_000_000,
        },
        quality: QualityScore::layer0_default(),
        access_count: 0,
        last_accessed: 0,
        source: RecordSource::StaticAnalysis,
        confidence: ConfidenceScore::for_new_record(&RecordSource::StaticAnalysis),
        gap_analysis_score: 0.0,
        payload: None,
    };

    let mut cache = HashMap::new();
    cache.insert(dep_rec.key.clone(), dep_rec);

    let factor = dep_factor(Some(&fr), &cache);
    assert!(
        factor > 0.5,
        "expected high dep factor for bumped go dep, got {factor}"
    );
}

// ── cascade_factor tests ────────────────────────────────────────────────

#[tokio::test]
async fn cascade_factor_zero_when_no_linked() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    let fr = FileRecord {
        path: "src/main.rs".into(),
        purpose: String::new(),
        entry_points: vec![],
        imports: vec![],
        gotcha_keys: vec![],
        decision_keys: vec![],
        todos: vec![],
        unsafe_count: 0,
        unwrap_count: 0,
        change_frequency: 0,
        last_author: None,
        is_hotspot: false,
        token_cost_estimate: 0,
        last_modified_session: 0,
        content_hash: None,
        line_count: 0,
        blast_radius: None,
        propagated_staleness: None,
    };

    let record = make_file_record_full("file:src/main.rs", vec![], vec![], vec![], 0);

    let factor = cascade_factor(&record, Some(&fr), &store).await;
    assert!(factor.abs() < 0.001);

    store.close().await.unwrap();
}

#[tokio::test]
async fn cascade_factor_detects_stale_linked_gotcha() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    // Create a stale gotcha.
    let mut gotcha = make_gotcha_record("gotcha:stale-rule");
    gotcha.staleness.value = 0.6;
    gotcha.staleness.tier = StalenessTier::Stale;
    store.put("gotcha:stale-rule", &gotcha).await.unwrap();

    let fr = FileRecord {
        path: "src/main.rs".into(),
        purpose: String::new(),
        entry_points: vec![],
        imports: vec![],
        gotcha_keys: vec!["gotcha:stale-rule".into()],
        decision_keys: vec![],
        todos: vec![],
        unsafe_count: 0,
        unwrap_count: 0,
        change_frequency: 0,
        last_author: None,
        is_hotspot: false,
        token_cost_estimate: 0,
        last_modified_session: 0,
        content_hash: None,
        line_count: 0,
        blast_radius: None,
        propagated_staleness: None,
    };

    let record = make_file_record_full(
        "file:src/main.rs",
        vec![],
        vec!["gotcha:stale-rule".into()],
        vec![],
        0,
    );

    let factor = cascade_factor(&record, Some(&fr), &store).await;
    assert!(
        factor > 0.5,
        "expected positive cascade factor for stale linked gotcha, got {factor}"
    );

    store.close().await.unwrap();
}

#[tokio::test]
async fn cascade_factor_gotcha_detects_stale_affected_file() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    // Create a stale file record.
    let mut file_rec = make_file_record_with_staleness(0.6);
    file_rec.key = "file:src/main.rs".to_string();
    store.put("file:src/main.rs", &file_rec).await.unwrap();

    // Create a gotcha that references this file.
    let gotcha_record = make_gotcha_record("gotcha:test-cascade");
    let factor = cascade_factor(&gotcha_record, None, &store).await;
    assert!(
        factor > 0.5,
        "expected positive cascade factor for stale affected file, got {factor}"
    );

    store.close().await.unwrap();
}

// ── Hard override tests ─────────────────────────────────────────────────

#[tokio::test]
async fn hard_override_file_deleted_sets_tombstone() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();
    // Deletion is only asserted from a git-proven root — establish one.
    git2::Repository::init(dir.path()).unwrap();

    // Use a path that definitely doesn't exist on disk.
    let mut record = make_file_record_with_staleness(0.0);
    record.key = "file:/tmp/definitely_nonexistent_mati_test_file_xyz.rs".to_string();
    store.put(&record.key, &record).await.unwrap();

    let analyzer = StalenessAnalyzer::new_with_now(dir.path(), 2_000_000);
    let dep_cache = HashMap::new();
    analyzer
        .compute_staleness(&mut record, &store, &dep_cache, far_deadline())
        .await
        .unwrap();

    assert_eq!(record.staleness.tier, StalenessTier::Tombstone);
    assert!((record.staleness.value - 1.0).abs() < 0.01);

    store.close().await.unwrap();
}

/// The tombstone override is the only path that reaches `Tombstone`, and a
/// tombstoned file record makes `hooks::decide::evaluate` pass every read
/// through before it reaches the gotcha loop. Without a git-proven root the
/// analyzer cannot tell "deleted" from "wrong working directory", so it must
/// assert nothing — otherwise a daemon started outside the repo would switch
/// enforcement off for the whole project.
#[tokio::test]
async fn missing_file_is_not_tombstoned_without_a_git_root() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    let mut record = make_file_record_with_staleness(0.0);
    record.key = "file:src/definitely_nonexistent_mati_xyz.rs".to_string();

    // No `Repository::init` — `root_from_git` is false.
    let analyzer = StalenessAnalyzer::new_with_now(dir.path(), 2_000_000);
    assert!(!analyzer.root_from_git);

    analyzer
        .compute_staleness(&mut record, &store, &HashMap::new(), far_deadline())
        .await
        .unwrap();

    assert_ne!(record.staleness.tier, StalenessTier::Tombstone);
    assert!(!record
        .staleness
        .signals
        .iter()
        .any(|s| matches!(s, StalenessSignal::FileDeleted)));

    store.close().await.unwrap();
}

/// Build a repo at `parent` with a child directory whose `.git` is a gitlink
/// *file* rather than a directory — the on-disk shape of a submodule and of a
/// linked worktree. `git2` resolves the link to the child's own root.
fn make_gitlink_child(parent: &Path) -> PathBuf {
    git2::Repository::init(parent).unwrap();
    let child = parent.join("sub");
    std::fs::create_dir_all(&child).unwrap();

    let child_git = git2::Repository::init(&child).unwrap().path().to_path_buf();
    let moved = parent.join(".git").join("modules").join("sub");
    std::fs::create_dir_all(moved.parent().unwrap()).unwrap();
    std::fs::rename(&child_git, &moved).unwrap();
    std::fs::write(child.join(".git"), format!("gitdir: {}\n", moved.display())).unwrap();

    let mut cfg = git2::Config::open(&moved.join("config")).unwrap();
    cfg.set_str("core.worktree", child.to_str().unwrap())
        .unwrap();
    child
}

/// The store's slug and the analyzer's root now derive from the same
/// [`crate::store::RepoIdent`] discovery, so a gitlink child (submodule or
/// linked worktree) is grounded to ITSELF, not the parent — the fix for the
/// 43-of-43 tombstone storm, where a daemon whose CWD sat inside a submodule
/// opened the parent's store while resolving paths against the child's tree.
#[tokio::test]
async fn a_gitlink_child_is_grounded_to_itself() {
    let dir = TempDir::new().unwrap();
    let child = make_gitlink_child(dir.path());

    let analyzer = StalenessAnalyzer::new_with_now(&child, 2_000_000);

    assert!(
        analyzer.root_from_git,
        "the child has its own working tree — git2 must ground it"
    );
    assert_eq!(
        analyzer.root,
        std::fs::canonicalize(&child).unwrap(),
        "root must be the child's own workdir, not the parent's"
    );
}

/// The control for the test above: a plain repo agrees with itself, so the
/// guard must not fire. Without this, the assertion above would pass on an
/// analyzer that is never grounded.
#[tokio::test]
async fn a_plain_repo_is_grounded() {
    let dir = TempDir::new().unwrap();
    git2::Repository::init(dir.path()).unwrap();

    let analyzer = StalenessAnalyzer::new_with_now(dir.path(), 2_000_000);

    assert!(analyzer.root_from_git);
    assert_eq!(analyzer.root, std::fs::canonicalize(dir.path()).unwrap());
}

/// Grounded to itself (see the test above), the child can now correctly
/// detect a path missing from ITS OWN tree — before the fix this analysis
/// was permanently disabled for any submodule or linked worktree, because
/// the analyzer could never ground to a child in the first place.
#[tokio::test]
async fn a_gitlink_child_asserts_deletions_in_its_own_tree() {
    let dir = TempDir::new().unwrap();
    let child = make_gitlink_child(dir.path());
    let store = Store::open(dir.path()).await.unwrap();

    let mut record = make_file_record_with_staleness(0.0);
    record.key = "file:src/definitely_nonexistent_mati_xyz.rs".to_string();

    let analyzer = StalenessAnalyzer::new_with_now(&child, 2_000_000);
    analyzer
        .compute_staleness(&mut record, &store, &HashMap::new(), far_deadline())
        .await
        .unwrap();

    assert_eq!(record.staleness.tier, StalenessTier::Tombstone);
    assert!(record
        .staleness
        .signals
        .iter()
        .any(|s| matches!(s, StalenessSignal::FileDeleted)));

    store.close().await.unwrap();
}

/// The gitlink child is grounded to itself now, but `src/gone.rs` genuinely
/// does not exist in its own tree either, so a standing `FileDeleted` is
/// correctly left in place — same outcome as the pre-fix "ungrounded, so
/// leave it alone" case, for a different and now more precise reason.
#[tokio::test]
async fn an_ungrounded_root_leaves_a_standing_deletion_alone() {
    let dir = TempDir::new().unwrap();
    let child = make_gitlink_child(dir.path());
    let store = Store::open(dir.path()).await.unwrap();

    let mut record = make_file_record_with_staleness(1.0);
    record.key = "file:src/gone.rs".to_string();
    record.staleness.signals.push(StalenessSignal::FileDeleted);
    record.staleness.tier = StalenessTier::Tombstone;

    let analyzer = StalenessAnalyzer::new_with_now(&child, 2_000_000);
    analyzer
        .compute_staleness(&mut record, &store, &HashMap::new(), far_deadline())
        .await
        .unwrap();

    assert_eq!(record.staleness.tier, StalenessTier::Tombstone);
    assert!(record
        .staleness
        .signals
        .iter()
        .any(|s| matches!(s, StalenessSignal::FileDeleted)));

    store.close().await.unwrap();
}

/// Relative record paths resolve against the analyzer's root, not the
/// process CWD. The daemon inherits its CWD from whichever hook spawned it.
#[tokio::test]
async fn relative_paths_resolve_against_the_repo_root_not_the_cwd() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();
    git2::Repository::init(dir.path()).unwrap();
    std::fs::create_dir_all(dir.path().join("src")).unwrap();
    std::fs::write(dir.path().join("src/present.rs"), "fn main() {}").unwrap();

    let analyzer = StalenessAnalyzer::new_with_now(dir.path(), 2_000_000);

    // `src/present.rs` does not exist relative to the test process CWD.
    assert!(!Path::new("src/present.rs").exists());

    let mut record = make_file_record_with_staleness(0.0);
    record.key = "file:src/present.rs".to_string();
    analyzer
        .compute_staleness(&mut record, &store, &HashMap::new(), far_deadline())
        .await
        .unwrap();

    assert_ne!(record.staleness.tier, StalenessTier::Tombstone);

    store.close().await.unwrap();
}

#[tokio::test]
async fn hard_override_file_renamed_sets_liability() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    // Create both old and new files on disk.
    let old_path = dir.path().join("old_file.rs");
    let new_path = dir.path().join("renamed.rs");
    std::fs::write(&old_path, "fn main() {}").unwrap();
    std::fs::write(&new_path, "fn main() {}").unwrap();

    let mut record = make_file_record_with_staleness(0.0);
    record.key = format!("file:{}", old_path.to_string_lossy());
    record.staleness.signals.push(StalenessSignal::FileRenamed {
        new_path: new_path.to_string_lossy().to_string(),
    });

    let analyzer = StalenessAnalyzer::new_with_now(dir.path(), 2_000_000);
    let dep_cache = HashMap::new();
    analyzer
        .compute_staleness(&mut record, &store, &dep_cache, far_deadline())
        .await
        .unwrap();

    assert_eq!(record.staleness.tier, StalenessTier::Liability);
    assert!((record.staleness.value - 0.85).abs() < 0.01);

    store.close().await.unwrap();
}

#[tokio::test]
async fn file_restored_clears_deleted_override() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    // Create a file on disk.
    let file_path = dir.path().join("restored.rs");
    std::fs::write(&file_path, "fn main() {}").unwrap();

    // Record has a FileDeleted signal, but the file now exists on disk.
    let mut record = make_file_record_with_staleness(0.5);
    record.key = format!("file:{}", file_path.to_string_lossy());
    record.staleness.signals.push(StalenessSignal::FileDeleted);

    let analyzer = StalenessAnalyzer::new_with_now(dir.path(), 2_000_000);
    let dep_cache = HashMap::new();
    analyzer
        .compute_staleness(&mut record, &store, &dep_cache, far_deadline())
        .await
        .unwrap();

    // Should NOT be tombstoned since file exists.
    assert_ne!(record.staleness.tier, StalenessTier::Tombstone);
    // FileDeleted signal should be cleared.
    assert!(
        !record
            .staleness
            .signals
            .iter()
            .any(|s| matches!(s, StalenessSignal::FileDeleted)),
        "FileDeleted signal should be cleared when file is restored"
    );

    store.close().await.unwrap();
}

// ── staleness_changed tests ─────────────────────────────────────────────

#[test]
fn staleness_changed_detects_tier_change() {
    let mut old = make_file_record_with_staleness(0.19);
    let mut new = old.clone();
    new.staleness.value = 0.21;
    new.staleness.tier = StalenessTier::Aging;
    old.staleness.tier = StalenessTier::Fresh;
    assert!(staleness_changed(&old, &new));
}

#[test]
fn staleness_changed_ignores_small_delta() {
    let old = make_file_record_with_staleness(0.10);
    let mut new = old.clone();
    new.staleness.value = 0.105; // Delta 0.005 < 0.01 threshold.
    assert!(!staleness_changed(&old, &new));
}

#[test]
fn staleness_changed_detects_sha_change() {
    let old = make_file_record_with_staleness(0.10);
    let mut new = old.clone();
    new.staleness.last_record_sha = "abc123".to_string();
    assert!(staleness_changed(&old, &new));
}

#[test]
fn staleness_changed_detects_signal_count_change() {
    let old = make_file_record_with_staleness(0.10);
    let mut new = old.clone();
    new.staleness
        .signals
        .push(StalenessSignal::LinesChangedPct(0.5));
    assert!(staleness_changed(&old, &new));
}

// ── analyze_all tests ───────────────────────────────────────────────────

/// The scan checks the deadline before every prefix and every record, so an
/// already-expired budget must stop it before it touches anything.
#[tokio::test]
async fn expired_time_budget_stops_the_scan_before_any_write() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();
    let file_path = dir.path().join("old_file.rs");
    std::fs::write(&file_path, "fn main() {}").unwrap();

    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let mut record = make_record_at(
        &format!("file:{}", file_path.to_string_lossy()),
        now - (60 * 86400),
        0,
    );
    record.lifecycle = RecordLifecycle::Active;
    store.put(&record.key, &record).await.unwrap();
    let before = store.get(&record.key).await.unwrap().unwrap();

    let analyzer = StalenessAnalyzer::new(dir.path());
    let expired = Instant::now() - std::time::Duration::from_millis(1);
    let report = analyzer.analyze_until(&store, expired).await.unwrap();

    assert_eq!(report.scanned, 0);
    assert_eq!(report.updated, 0);
    let after = store.get(&record.key).await.unwrap().unwrap();
    assert_eq!(after.version.logical_clock, before.version.logical_clock);

    // Same store, same analyzer, real budget — proves the assertion above is
    // the deadline talking and not an empty scan.
    let report = analyzer.analyze_all(&store).await.unwrap();
    assert!(report.scanned >= 1);
    assert!(report.updated >= 1);

    store.close().await.unwrap();
}

#[tokio::test]
async fn analyze_all_updates_stale_records() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    // Create a record that should become stale (old timestamp).
    // Use a file path that exists on disk so it doesn't get tombstoned.
    let file_path = dir.path().join("old_file.rs");
    std::fs::write(&file_path, "fn main() {}").unwrap();

    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let sixty_days_ago = now - (60 * 86400);

    let mut record = make_record_at(
        &format!("file:{}", file_path.to_string_lossy()),
        sixty_days_ago,
        0,
    );
    record.lifecycle = RecordLifecycle::Active;
    store.put(&record.key, &record).await.unwrap();

    let analyzer = StalenessAnalyzer::new(dir.path());
    let report = analyzer.analyze_all(&store).await.unwrap();

    assert!(report.scanned >= 1, "should scan at least 1 record");
    // The time factor at 60 days = 60/90 = ~0.67 * 0.20 = ~0.13
    // That's enough to register a change from 0.0.
    assert!(report.updated >= 1, "should update stale record");

    store.close().await.unwrap();
}

#[tokio::test]
async fn analyze_all_skips_non_active() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let old = now - (60 * 86400);

    let mut record = make_record_at("file:tombstoned.rs", old, 0);
    record.lifecycle = RecordLifecycle::Tombstoned {
        reason: TombstoneReason::ManualDeletion,
        at: now,
    };
    store.put(&record.key, &record).await.unwrap();

    let analyzer = StalenessAnalyzer::new_with_now(dir.path(), now);
    let report = analyzer.analyze_all(&store).await.unwrap();

    // Record was scanned but not updated because it's tombstoned.
    assert_eq!(report.updated, 0);

    store.close().await.unwrap();
}

// ── tombstone circuit breaker tests ─────────────────────────────────────

/// Seed `missing` records naming files that do not exist plus `present`
/// records whose files do, under a git-proven root. Returns the store dir.
async fn seed_deletion_mix(store: &Store, dir: &Path, now: u64, missing: u32, present: u32) {
    git2::Repository::init(dir).unwrap();
    let old = now - (60 * 86_400);
    for i in 0..missing {
        let mut record = make_record_at(&format!("file:src/gone_{i}.rs"), old, 0);
        record.lifecycle = RecordLifecycle::Active;
        store.put(&record.key, &record).await.unwrap();
    }
    for i in 0..present {
        let name = format!("here_{i}.rs");
        std::fs::write(dir.join(&name), "fn main() {}").unwrap();
        let mut record = make_record_at(&format!("file:{name}"), old, 0);
        record.lifecycle = RecordLifecycle::Active;
        store.put(&record.key, &record).await.unwrap();
    }
}

/// A pass that tombstones past the ratio writes nothing at all — not the
/// deletions, and not the other records it computed alongside them. This is
/// the 2026-08-04 shape: 368 of 387 records tombstoned in one pass, which
/// switched enforcement off repo-wide.
#[tokio::test]
async fn a_pass_over_the_tombstone_ratio_writes_nothing() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

    seed_deletion_mix(&store, dir.path(), now, 30, 2).await;
    let before = store.get("file:src/gone_0.rs").await.unwrap().unwrap();

    let analyzer = StalenessAnalyzer::new_with_now(dir.path(), now);
    assert!(analyzer.root_from_git, "the deletion path needs a git root");
    let report = analyzer.analyze_all(&store).await.unwrap();

    assert_eq!(report.updated, 0, "discarded pass persisted nothing");
    assert_eq!(report.tombstoned, 0, "report must match persisted reality");
    assert!(report.scanned >= 32, "the scan itself still ran");

    let after = store.get("file:src/gone_0.rs").await.unwrap().unwrap();
    assert_eq!(after.staleness.tier, before.staleness.tier);
    assert_eq!(after.version.logical_clock, before.version.logical_clock);

    store.close().await.unwrap();
}

/// Below the ratio the breaker stays out of the way — deletions persist.
/// Without this, the test above would pass on an analyzer that never writes.
#[tokio::test]
async fn deletions_under_the_ratio_still_persist() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

    seed_deletion_mix(&store, dir.path(), now, 10, 25).await;

    let analyzer = StalenessAnalyzer::new_with_now(dir.path(), now);
    let report = analyzer.analyze_all(&store).await.unwrap();

    assert_eq!(report.tombstoned, 10);
    assert!(report.updated >= 10);
    let after = store.get("file:src/gone_0.rs").await.unwrap().unwrap();
    assert_eq!(after.staleness.tier, StalenessTier::Tombstone);

    store.close().await.unwrap();
}

/// A pass smaller than the sample floor is not evidence of anything, so the
/// ratio does not apply to it — a store whose every file record is a deletion
/// is a normal cleanup at that size.
#[tokio::test]
async fn a_pass_below_the_sample_floor_skips_the_ratio() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

    let below_floor = MIN_TOMBSTONE_SAMPLE - 1;
    seed_deletion_mix(&store, dir.path(), now, below_floor, 0).await;

    let analyzer = StalenessAnalyzer::new_with_now(dir.path(), now);
    let report = analyzer.analyze_all(&store).await.unwrap();

    assert_eq!(report.tombstoned, below_floor);
    let after = store.get("file:src/gone_0.rs").await.unwrap().unwrap();
    assert_eq!(after.staleness.tier, StalenessTier::Tombstone);

    store.close().await.unwrap();
}

// ── dead Layer 0 stub tests ─────────────────────────────────────────────

/// An unconfirmed auto-derived stub at `key`, naming `files`. Quality matches
/// what `mati init` mints, so these clear the 0.4 injection gate as real ones do.
fn make_stub(key: &str, files: &[&str]) -> Record {
    let mut record = make_gotcha_record(key);
    let mut gotcha = record.payload_as::<GotchaRecord>().unwrap();
    gotcha.confirmed = false;
    gotcha.affected_files = files.iter().map(|f| (*f).to_string()).collect();
    record.payload = serde_json::to_value(&gotcha).ok();
    record.quality = QualityScore::cochange_default();
    record
}

async fn compute_in(dir: &Path, record: &mut Record, store: &Store) {
    StalenessAnalyzer::new_with_now(dir, 2_000_000)
        .compute_staleness(record, store, &HashMap::new(), far_deadline())
        .await
        .unwrap();
}

/// The gap: `--purge-orphans` and the `FileDeleted` signal both tombstone the
/// `file:*` record, and the stub that only ever named that path stayed Active
/// and Fresh — still injecting through `is_injectable_gotcha`'s allowlist.
#[tokio::test]
async fn a_stub_whose_only_file_is_gone_is_tombstoned() {
    let dir = TempDir::new().unwrap();
    git2::Repository::init(dir.path()).unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    let mut record = make_stub("gotcha:ownership:src/gone.rs", &["src/gone.rs"]);
    compute_in(dir.path(), &mut record, &store).await;

    assert_eq!(record.staleness.tier, StalenessTier::Tombstone);
    assert!(!crate::mcp::tools::is_injectable_gotcha(&record));

    store.close().await.unwrap();
}

/// The read gate is untouched: a stub on a file that still exists scores
/// normally and keeps injecting.
#[tokio::test]
async fn a_stub_on_a_live_file_still_injects() {
    let dir = TempDir::new().unwrap();
    git2::Repository::init(dir.path()).unwrap();
    std::fs::write(dir.path().join("here.rs"), "fn main() {}").unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    let mut record = make_stub("gotcha:ownership:here.rs", &["here.rs"]);
    compute_in(dir.path(), &mut record, &store).await;

    assert_ne!(record.staleness.tier, StalenessTier::Tombstone);
    assert!(crate::mcp::tools::is_injectable_gotcha(&record));

    store.close().await.unwrap();
}

/// A cochange stub names a pair. One surviving path is still a live claim.
#[tokio::test]
async fn a_stub_with_one_surviving_file_is_not_dead() {
    let dir = TempDir::new().unwrap();
    git2::Repository::init(dir.path()).unwrap();
    std::fs::write(dir.path().join("here.rs"), "fn main() {}").unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    let mut record = make_stub(
        "gotcha:cochange:here.rs|src/gone.rs",
        &["here.rs", "src/gone.rs"],
    );
    compute_in(dir.path(), &mut record, &store).await;

    assert_ne!(record.staleness.tier, StalenessTier::Tombstone);

    store.close().await.unwrap();
}

/// A confirmed gotcha with a dead address is knowledge to re-point, not
/// garbage — the triage that preserved `gotcha:arm-the-dirty-marker-once-…`
/// rather than dropping it. Confirming a stub makes it the developer's rule,
/// so the key prefix alone must not be enough to discard it.
#[tokio::test]
async fn a_confirmed_gotcha_with_a_dead_path_survives() {
    let dir = TempDir::new().unwrap();
    git2::Repository::init(dir.path()).unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    // Same dead path, same auto key prefix — only `confirmed` differs.
    let mut confirmed_stub = make_gotcha_record("gotcha:ownership:src/gone.rs");
    let mut hand_written = make_gotcha_record("gotcha:arm-the-dirty-marker-once");
    for record in [&mut confirmed_stub, &mut hand_written] {
        let mut gotcha = record.payload_as::<GotchaRecord>().unwrap();
        gotcha.affected_files = vec!["src/gone.rs".into()];
        record.payload = serde_json::to_value(&gotcha).ok();
        compute_in(dir.path(), record, &store).await;
        assert_ne!(record.staleness.tier, StalenessTier::Tombstone);
    }

    // And unconfirmed but hand-written: not an auto key, so still out of reach.
    let mut unconfirmed = make_stub("gotcha:arm-the-dirty-marker-once", &["src/gone.rs"]);
    compute_in(dir.path(), &mut unconfirmed, &store).await;
    assert_ne!(unconfirmed.staleness.tier, StalenessTier::Tombstone);

    store.close().await.unwrap();
}

/// A stub naming nothing is not vacuously dead.
#[tokio::test]
async fn a_stub_with_no_affected_files_is_not_dead() {
    let dir = TempDir::new().unwrap();
    git2::Repository::init(dir.path()).unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    let mut record = make_stub("gotcha:ownership:src/gone.rs", &[]);
    compute_in(dir.path(), &mut record, &store).await;

    assert_ne!(record.staleness.tier, StalenessTier::Tombstone);

    store.close().await.unwrap();
}

/// Without a git-proven root the analyzer cannot tell "deleted" from "wrong
/// tree", so it asserts nothing here either — the same gate `FileDeleted` sits
/// behind, and the reason the 2026-08-05 mass tombstone must not recur.
#[tokio::test]
async fn a_dead_stub_is_not_tombstoned_without_a_git_root() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    let analyzer = StalenessAnalyzer::new_with_now(dir.path(), 2_000_000);
    assert!(!analyzer.root_from_git);

    let mut record = make_stub("gotcha:ownership:src/gone.rs", &["src/gone.rs"]);
    analyzer
        .compute_staleness(&mut record, &store, &HashMap::new(), far_deadline())
        .await
        .unwrap();

    assert_ne!(record.staleness.tier, StalenessTier::Tombstone);

    store.close().await.unwrap();
}

/// Self-reversing, like the `FileDeleted` override: restore the path and the
/// stub scores normally again.
#[tokio::test]
async fn a_restored_file_revives_its_stub() {
    let dir = TempDir::new().unwrap();
    git2::Repository::init(dir.path()).unwrap();
    std::fs::write(dir.path().join("back.rs"), "fn main() {}").unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    let mut record = make_stub("gotcha:ownership:back.rs", &["back.rs"]);
    record.staleness.value = 1.0;
    record.staleness.tier = StalenessTier::Tombstone;
    compute_in(dir.path(), &mut record, &store).await;

    assert_ne!(record.staleness.tier, StalenessTier::Tombstone);
    assert!(record.staleness.value < 1.0);

    store.close().await.unwrap();
}

/// Seed `dead` unconfirmed stubs naming paths that do not exist, plus `present`
/// file records whose files do, under a git-proven root.
async fn seed_stub_mix(store: &Store, dir: &Path, now: u64, dead: u32, present: u32) {
    git2::Repository::init(dir).unwrap();
    for i in 0..dead {
        let path = format!("src/gone_{i}.rs");
        let record = make_stub(&format!("gotcha:ownership:{path}"), &[&path]);
        store.put(&record.key, &record).await.unwrap();
    }
    let old = now - (60 * 86_400);
    for i in 0..present {
        let name = format!("here_{i}.rs");
        std::fs::write(dir.join(&name), "fn main() {}").unwrap();
        let mut record = make_record_at(&format!("file:{name}"), old, 0);
        record.lifecycle = RecordLifecycle::Active;
        store.put(&record.key, &record).await.unwrap();
    }
}

/// The propagation rule cascades, so it answers to the same breaker the file
/// deletions do: a pass that tombstones past the ratio writes nothing. A root
/// naming the wrong tree fails every stub path at once, which is exactly the
/// shape this refuses.
#[tokio::test]
async fn dead_stubs_over_the_tombstone_ratio_write_nothing() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

    seed_stub_mix(&store, dir.path(), now, 25, 5).await;
    let before = store
        .get("gotcha:ownership:src/gone_0.rs")
        .await
        .unwrap()
        .unwrap();

    let report = StalenessAnalyzer::new_with_now(dir.path(), now)
        .analyze_all(&store)
        .await
        .unwrap();

    assert_eq!(report.updated, 0, "discarded pass persisted nothing");
    assert_eq!(report.tombstoned, 0);
    assert!(report.scanned >= MIN_TOMBSTONE_SAMPLE);

    let after = store
        .get("gotcha:ownership:src/gone_0.rs")
        .await
        .unwrap()
        .unwrap();
    assert_eq!(after.staleness.tier, before.staleness.tier);
    assert_eq!(after.version.logical_clock, before.version.logical_clock);

    store.close().await.unwrap();
}

/// Below the ratio the breaker stays out of the way. Without this, the test
/// above would pass on a rule that never fires.
#[tokio::test]
async fn dead_stubs_under_the_ratio_persist() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

    seed_stub_mix(&store, dir.path(), now, 5, 25).await;

    let report = StalenessAnalyzer::new_with_now(dir.path(), now)
        .analyze_all(&store)
        .await
        .unwrap();

    assert_eq!(report.tombstoned, 5);
    let after = store
        .get("gotcha:ownership:src/gone_0.rs")
        .await
        .unwrap()
        .unwrap();
    assert_eq!(after.staleness.tier, StalenessTier::Tombstone);

    store.close().await.unwrap();
}

// ── resume cursor tests ─────────────────────────────────────────────────

/// Every prefix, seeded old enough that the first computation changes the
/// score and therefore persists `computed_at`.
async fn seed_one_record_per_prefix(store: &Store, now: u64) -> Vec<String> {
    let old = now - (60 * 86_400);
    let keys = [
        "file:zzz_last.rs",
        "gotcha:g1",
        "decision:d1",
        "dep:cargo:serde",
        "dev_note:n1",
    ];
    for key in keys {
        let mut record = make_record_at(key, old, 0);
        record.category = match key.split(':').next().unwrap() {
            "gotcha" => Category::Gotcha,
            "decision" => Category::Decision,
            "dep" => Category::Dependency,
            "dev_note" => Category::DevNote,
            _ => Category::File,
        };
        store.put(key, &record).await.unwrap();
    }
    keys.iter().map(|k| k.to_string()).collect()
}

/// A `file:` record that costs a whole budget to score: `cascade_factor`
/// issues one store read per linked key, and none of these exist.
fn make_budget_eating_record(key: &str, now: u64, links: usize) -> Record {
    let mut record = make_record_at(key, now - (60 * 86_400), 0);
    let gotcha_keys: Vec<String> = (0..links).map(|i| format!("gotcha:absent-{i}")).collect();
    let fr = make_file_record_full(key, vec![], gotcha_keys, vec![], 0);
    record.payload = serde_json::from_str(&fr.value).ok();
    record
}

/// The scan order is fixed, so a budget that expires always expires inside
/// `file:`, and the four prefixes behind it would never recompute. The
/// cursor is what bounds coverage: pass 2 must start where pass 1 stopped
/// and finish the store, not restart at `file:` and starve the tail again.
#[tokio::test]
async fn a_truncated_pass_parks_a_cursor_and_the_next_pass_finishes_the_store() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();
    let now = 20_000_000u64;

    let mut keys = seed_one_record_per_prefix(&store, now).await;
    // Sorts first inside `file:`, so it is what a truncated pass spends
    // its whole budget on.
    let hog = "file:aaa_expensive.rs";
    let record = make_budget_eating_record(hog, now, 20_000);
    store.put(hog, &record).await.unwrap();
    keys.push(hog.to_string());

    let analyzer = StalenessAnalyzer::new_with_now(dir.path(), now);

    let deadline = Instant::now() + std::time::Duration::from_millis(5);
    let first = analyzer.analyze_until(&store, deadline).await.unwrap();
    assert!(first.scanned >= 1, "a pass must make progress");
    assert!(
        first.scanned < keys.len() as u32,
        "the budget did not truncate: scanned {} of {}",
        first.scanned,
        keys.len()
    );
    assert_eq!(
        read_cursor(&store).await.as_deref(),
        Some(hog),
        "a truncated pass parks the cursor on the last record it finished"
    );

    let second = analyzer.analyze_all(&store).await.unwrap();
    assert_eq!(
        second.scanned,
        keys.len() as u32 - first.scanned,
        "the resumed pass must not re-scan what the cursor already covered"
    );
    assert!(
        read_cursor(&store).await.is_none(),
        "a pass that reaches the end clears the cursor"
    );

    for key in &keys {
        let record = store.get(key).await.unwrap().unwrap();
        assert_eq!(
            record.staleness.computed_at, now,
            "{key} was never recomputed across the sweep"
        );
    }

    store.close().await.unwrap();
}

/// The cursor is scheduling state on the Eventual path, so it can be lost,
/// stale, or left behind by a prefix list that has since changed. Anything
/// the sweep cannot place must restart it, never skip.
#[tokio::test]
async fn an_unplaceable_cursor_restarts_the_sweep() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();
    let now = 20_000_000u64;

    let keys = seed_one_record_per_prefix(&store, now).await;
    write_cursor(&store, "retired_namespace:zzz", now).await;

    let analyzer = StalenessAnalyzer::new_with_now(dir.path(), now);
    let report = analyzer.analyze_all(&store).await.unwrap();

    assert_eq!(
        report.scanned,
        keys.len() as u32,
        "an unplaceable cursor must not skip any record"
    );
    assert!(read_cursor(&store).await.is_none());

    store.close().await.unwrap();
}

/// An empty position is absence, not position zero.
#[tokio::test]
async fn an_empty_cursor_position_reads_as_no_cursor() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    write_cursor(&store, "", 20_000_000).await;
    assert!(read_cursor(&store).await.is_none());

    store.close().await.unwrap();
}

/// The position must not reach the search index: it is a record key, and a
/// `mem_query` for that path would otherwise match the cursor.
#[tokio::test]
async fn the_cursor_position_is_not_searchable() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    write_cursor(&store, "file:src/distinctive_marker.rs", 20_000_000).await;
    let hits = store.search("distinctive_marker", 10).await.unwrap();

    assert!(
        !hits.iter().any(|r| r.key == STALENESS_CURSOR_KEY),
        "cursor leaked into the search index: {hits:?}"
    );

    store.close().await.unwrap();
}

/// The budget still stops the scan. An expired one writes no cursor either:
/// a pass that visited nothing has no position to record, and rewinding to
/// one it did not reach would re-run work the previous pass already did.
#[tokio::test]
async fn an_expired_budget_leaves_the_cursor_untouched() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();
    let now = 20_000_000u64;

    seed_one_record_per_prefix(&store, now).await;
    write_cursor(&store, "file:zzz_last.rs", now).await;

    let analyzer = StalenessAnalyzer::new_with_now(dir.path(), now);
    let expired = Instant::now() - std::time::Duration::from_millis(1);
    let report = analyzer.analyze_until(&store, expired).await.unwrap();

    assert_eq!(report.scanned, 0);
    assert_eq!(
        read_cursor(&store).await.as_deref(),
        Some("file:zzz_last.rs")
    );

    store.close().await.unwrap();
}

// ── commits_to_factor tests ─────────────────────────────────────────────

#[test]
fn commits_to_factor_mapping() {
    assert!((commits_to_factor(0) - 0.0).abs() < 0.001);
    assert!((commits_to_factor(1) - 0.15).abs() < 0.001);
    assert!((commits_to_factor(2) - 0.30).abs() < 0.001);
    assert!((commits_to_factor(3) - 0.50).abs() < 0.001);
    assert!((commits_to_factor(4) - 0.70).abs() < 0.001);
    assert!((commits_to_factor(5) - 1.0).abs() < 0.001);
    assert!((commits_to_factor(100) - 1.0).abs() < 0.001);
}

// ── reparse signal preservation tests ───────────────────────────────────

#[tokio::test]
async fn reparse_signals_preserved_within_24h() {
    let dir = TempDir::new().unwrap();
    let store = Store::open(dir.path()).await.unwrap();

    let file_path = dir.path().join("recent_reparse.rs");
    std::fs::write(&file_path, "fn main() {}").unwrap();

    let now = 2_000_000u64;
    let recent = now - 3600; // 1 hour ago

    let mut record = make_record_at(
        &format!("file:{}", file_path.to_string_lossy()),
        now - 100,
        0,
    );
    // Simulate recent reparse: computed_at within 24h, with reparse signals.
    record.staleness.computed_at = recent;
    record.staleness.value = 0.3;
    record.staleness.tier = StalenessTier::Aging;
    record.staleness.signals = vec![
        StalenessSignal::EntryPointsChanged(2),
        StalenessSignal::ImportsChanged(1),
    ];

    let analyzer = StalenessAnalyzer::new_with_now(dir.path(), now);
    let dep_cache = HashMap::new();
    analyzer
        .compute_staleness(&mut record, &store, &dep_cache, far_deadline())
        .await
        .unwrap();

    // The 5-factor formula would compute a low value (record is ~100s old),
    // but reparse signal preservation should keep the higher value.
    assert!(
        record.staleness.value >= 0.3,
        "reparse signal preservation should keep value >= 0.3, got {}",
        record.staleness.value
    );

    // Reparse signals should be preserved.
    let has_ep = record
        .staleness
        .signals
        .iter()
        .any(|s| matches!(s, StalenessSignal::EntryPointsChanged(_)));
    assert!(has_ep, "EntryPointsChanged signal should be preserved");

    store.close().await.unwrap();
}

#[test]
fn signal_cap_at_20_for_reparse_signals() {
    let mut record = make_file_record_with_staleness(0.0);

    // Add 25 signals via repeated reparse applications.
    for i in 0..25 {
        let diff = ReparseDiff {
            entry_points_added: vec![format!("fn_{i}")],
            ..empty_diff()
        };
        apply_reparse_staleness(&mut record, &diff);
    }

    // Signal list should be capped at 20.
    assert!(
        record.staleness.signals.len() <= 20,
        "signals should be capped at 20, got {}",
        record.staleness.signals.len()
    );
}

// ── is_reparse_signal tests ─────────────────────────────────────────────

#[test]
fn is_reparse_signal_identifies_reparse_signals() {
    assert!(is_reparse_signal(&StalenessSignal::EntryPointsChanged(1)));
    assert!(is_reparse_signal(&StalenessSignal::ImportsChanged(2)));
    assert!(is_reparse_signal(&StalenessSignal::TodosChanged));
    assert!(is_reparse_signal(&StalenessSignal::UnsafeCountChanged(1)));
    assert!(is_reparse_signal(&StalenessSignal::UnwrapCountChanged(-1)));

    // Non-reparse signals.
    assert!(!is_reparse_signal(&StalenessSignal::FileDeleted));
    assert!(!is_reparse_signal(&StalenessSignal::LinesChangedPct(0.5)));
    assert!(!is_reparse_signal(&StalenessSignal::NotAccessedDays(7)));
}

// ── Reparse accumulation cannot disable enforcement ─────────────────────

/// `hooks::decide::evaluate` runs the gotcha loop before it looks at the
/// file's staleness tier — pinned by `decide::tests::gate_never_silently_
/// disables`. So `Liability`/`Tombstone` no longer disable enforcement of
/// a confirmed gotcha. They still gate *injection*: `Liability` degrades
/// the file's cached purpose blurb to a bare warning, and `Tombstone`
/// (absent a `FileDeleted` signal) suppresses it entirely. Reparse
/// staleness is applied per edit, so without a ceiling across passes,
/// editing one file a handful of times in a session would cross that
/// boundary and mark its cached blurb untrustworthy — a false signal,
/// since the file wasn't abandoned, just actively edited.
///
/// These tests bound the reparse contribution. They do not touch the tier
/// thresholds or what the tiers mean.
mod reparse_cannot_disable_enforcement {
    use super::*;
    use crate::hooks::decide::{evaluate, Decision, EnforcementInput};

    /// A diff big enough to saturate a single pass at
    /// [`MAX_REPARSE_INCREMENT`].
    fn saturating_diff() -> ReparseDiff {
        ReparseDiff {
            entry_points_added: vec!["a".into(), "b".into(), "c".into(), "d".into()],
            imports_added: vec!["x".into(), "y".into(), "z".into()],
            ..empty_diff()
        }
    }

    /// A file record carrying one maximally-valid confirmed gotcha, plus
    /// that gotcha, in the JSON shape `evaluate` reads.
    fn enforcement_input_for(record: &Record) -> EnforcementInput {
        let mut gotcha = make_gotcha_record("gotcha:test");
        gotcha.confidence.value = 1.0;
        gotcha.quality.value = 1.0;

        let mut file = record.clone();
        file.confidence.value = 0.7;
        file.quality.value = 0.5;
        file.payload = serde_json::json!({ "gotcha_keys": ["gotcha:test"] }).into();

        let mut gotchas = HashMap::new();
        gotchas.insert(
            "gotcha:test".to_string(),
            serde_json::to_value(&gotcha).unwrap(),
        );
        EnforcementInput {
            rel_path: "src/main.rs".into(),
            file_record: Some(serde_json::to_value(&file).unwrap()),
            gotcha_records: gotchas,
            already_consulted: false,
            file_exists: None,
        }
    }

    /// The anchor: no number of reparse passes reaches a tier that
    /// degrades injection, and a confirmed gotcha keeps denying
    /// regardless — the second assertion holds even without the ceiling
    /// now, but stays here as a regression guard.
    #[test]
    fn repeated_reparse_never_reaches_a_tier_that_degrades_injection() {
        let mut record = make_file_record_with_staleness(0.0);

        for pass in 1..=50 {
            apply_reparse_staleness(&mut record, &saturating_diff());
            assert!(
                !matches!(
                    record.staleness.tier,
                    StalenessTier::Liability | StalenessTier::Tombstone
                ),
                "INJECTION DEGRADED: {} reparse passes reached tier {:?} \
                     (value {}). Liability and Tombstone still gate what gets \
                     injected for this file, even though they no longer gate \
                     gotcha enforcement",
                pass,
                record.staleness.tier,
                record.staleness.value
            );

            let decision = evaluate(&enforcement_input_for(&record)).decision;
            assert!(
                matches!(decision, Decision::Deny { .. }),
                "ENFORCEMENT DISABLED: after {pass} reparse passes a confirmed \
                     gotcha produced {decision:?} instead of Deny"
            );
        }

        assert!(record.staleness.value <= MAX_REPARSE_STALENESS + f32::EPSILON);
    }

    /// The ceiling is only meaningful while it stays inside `Stale`.
    #[test]
    fn ceiling_sits_below_the_liability_floor() {
        assert_eq!(
            StalenessScore::tier_from_value(MAX_REPARSE_STALENESS),
            StalenessTier::Stale,
            "MAX_REPARSE_STALENESS must stay below the 0.7 Liability floor"
        );
    }

    /// The signal is not neutered: one pass still moves the score, and the
    /// score keeps climbing until it saturates.
    #[test]
    fn a_single_reparse_still_raises_staleness() {
        let mut record = make_file_record_with_staleness(0.0);
        let signals = apply_reparse_staleness(&mut record, &saturating_diff());

        assert!(!signals.is_empty(), "a non-empty diff must emit signals");
        assert!(
            (record.staleness.value - MAX_REPARSE_INCREMENT).abs() < 0.01,
            "one saturating pass must still add the full increment, got {}",
            record.staleness.value
        );
        assert_eq!(record.staleness.tier, StalenessTier::Stale);

        let after_first = record.staleness.value;
        apply_reparse_staleness(&mut record, &saturating_diff());
        assert!(
            record.staleness.value > after_first,
            "a second pass must still raise the score below the ceiling"
        );
    }

    /// Another factor may legitimately hold a record above the ceiling.
    /// Reparse must not drag it back down.
    #[test]
    fn reparse_never_lowers_a_score_set_by_another_factor() {
        let mut record = make_file_record_with_staleness(0.95);
        apply_reparse_staleness(&mut record, &saturating_diff());
        assert!((record.staleness.value - 0.95).abs() < f32::EPSILON);
        assert_eq!(record.staleness.tier, StalenessTier::Tombstone);
    }

    /// The cascade to linked gotchas accumulates the same way. A tombstoned
    /// gotcha is dropped by `mcp::tools::is_injectable_gotcha`.
    #[tokio::test]
    async fn cascade_to_gotchas_saturates_below_liability() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        store
            .put("gotcha:test-rule", &make_gotcha_record("gotcha:test-rule"))
            .await
            .unwrap();

        let mut file_record = make_linked_file_record();
        file_record.gotcha_keys = vec!["gotcha:test-rule".into()];

        for _ in 0..30 {
            cascade_staleness_to_gotchas(&store, &file_record)
                .await
                .unwrap();
        }

        let updated = store.get("gotcha:test-rule").await.unwrap().unwrap();
        assert!(
            updated.staleness.value <= MAX_REPARSE_STALENESS + f32::EPSILON,
            "cascade accumulated to {}",
            updated.staleness.value
        );
        assert_eq!(updated.staleness.tier, StalenessTier::Stale);

        store.close().await.unwrap();
    }

    /// `compute_staleness` preserves a recent reparse score against a lower
    /// recompute. A record already over the ceiling — accumulated before it
    /// existed — must recompute down instead of staying pinned.
    #[tokio::test]
    async fn analyze_recomputes_an_over_accumulated_record_down() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        let file_path = dir.path().join("hot.rs");
        std::fs::write(&file_path, "fn main() {}").unwrap();

        let now = 2_000_000u64;
        let key = format!("file:{}", file_path.to_string_lossy());
        let mut record = make_record_at(&key, now - 100, 0);
        record.staleness.value = 0.95;
        record.staleness.tier = StalenessTier::Tombstone;
        record.staleness.computed_at = now - 3600;
        record.staleness.signals = vec![
            StalenessSignal::ImportsChanged(2),
            StalenessSignal::UnwrapCountChanged(12),
        ];

        let analyzer = StalenessAnalyzer::new_with_now(dir.path(), now);
        analyzer
            .compute_staleness(&mut record, &store, &HashMap::new(), far_deadline())
            .await
            .unwrap();

        assert!(
            record.staleness.value <= MAX_REPARSE_STALENESS + f32::EPSILON,
            "the 24h preservation window pinned the record at {}",
            record.staleness.value
        );
        assert!(!matches!(
            record.staleness.tier,
            StalenessTier::Liability | StalenessTier::Tombstone
        ));
        assert!(
            record
                .staleness
                .signals
                .iter()
                .any(|s| matches!(s, StalenessSignal::ImportsChanged(_))),
            "recomputing down must not erase the reparse signals"
        );

        store.close().await.unwrap();
    }
}

// ── revwalk deadline ────────────────────────────────────────────────────

/// Commit `content` to `name` and return the commit SHA.
fn commit_file(repo: &git2::Repository, name: &str, content: &str) -> String {
    let workdir = repo.workdir().expect("bare repo").to_path_buf();
    std::fs::write(workdir.join(name), content).unwrap();
    let mut index = repo.index().unwrap();
    index.add_path(Path::new(name)).unwrap();
    index.write().unwrap();
    let tree = repo.find_tree(index.write_tree().unwrap()).unwrap();
    let sig = git2::Signature::now("t", "t@example.com").unwrap();
    let parent = repo.head().ok().and_then(|h| h.peel_to_commit().ok());
    let parents: Vec<&git2::Commit> = parent.iter().collect();
    repo.commit(Some("HEAD"), &sig, &sig, "c", &tree, &parents)
        .unwrap()
        .to_string()
}

/// The revwalk stops at the pass deadline instead of running to
/// `GIT_REVWALK_LIMIT`.
///
/// `analyze_until` gates only when a record *starts*, so before the
/// deadline reached here one record could walk 2000 commits — seconds —
/// after the pass had already spent its budget, and the SessionEnd hook
/// overshot by that much.
#[test]
fn count_commits_since_stops_at_the_deadline() {
    let dir = TempDir::new().unwrap();
    let repo = git2::Repository::init(dir.path()).unwrap();
    let mut shas = Vec::new();
    for i in 0..12 {
        shas.push(commit_file(&repo, "a.txt", &format!("v{i}\n")));
    }
    let analyzer = StalenessAnalyzer::new(dir.path());
    let root_sha = &shas[0];

    assert_eq!(
        analyzer.count_commits_since(&repo, "a.txt", root_sha, far_deadline()),
        11,
        "an unbounded walk reaches the root commit and counts the rest"
    );

    assert_eq!(
        analyzer.count_commits_since(&repo, "a.txt", root_sha, Instant::now()),
        GIT_CAP_HIT_COMMITS,
        "an expired deadline stops the walk and reports the conservative floor"
    );
}

/// A record whose walk cannot finish inside the budget still gets a
/// staleness signal — undercounting keeps enforcement on, silence would
/// read as "unchanged".
#[test]
fn deadline_truncated_walk_reports_a_nonzero_git_factor() {
    let dir = TempDir::new().unwrap();
    let repo = git2::Repository::init(dir.path()).unwrap();
    let root_sha = commit_file(&repo, "a.txt", "v0\n");
    commit_file(&repo, "a.txt", "v1\n");
    let analyzer = StalenessAnalyzer::new(dir.path());

    let (factor, sha) = analyzer.git_factor(&repo, "a.txt", &root_sha, Instant::now());
    assert!(factor > 0.0, "truncated walk must not report 'unchanged'");
    assert!(sha.is_some(), "baseline still advances to HEAD");
}