symforge 11.22.1

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
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
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
//! Single-file admission + publication seam (relocated from `watcher`,
//! task #24) — the ONE canonical path a single repository file takes into the
//! live index: hard-scope/source/gitignore exclusion checks, the same
//! metadata-first scout and admission classification bulk load runs (including
//! secret-content demotion), content-hash-gated parsing, and
//! generation-fenced publication.
//!
//! Compiled under BOTH the server and embed features: the watcher, freshen,
//! and reconciliation paths consume it via `crate::watcher`'s re-export, and
//! the embed facade exposes [`update_file_from_disk`] / [`remove_file`] so an
//! embedder's per-file reindex goes through the identical seam instead of a
//! hand-rolled parse-and-poke (which would bypass admission entirely).

use std::path::{Path, PathBuf};
use std::sync::Arc;

use tracing::{debug, trace, warn};

use crate::domain::{
    FileClassification, FileDisposition, LanguageId, MetadataOnlyReason, ScoutDecision,
};
use crate::hash;
use crate::live_index::store::{
    FencedRemoval, IndexedFile, PublicationFence, PublishedGeneration, SharedIndex,
    SnapshotVerifiedAdmission, SnapshotVerifiedFile,
};
use crate::parsing;

/// Result of a single re-index attempt for one file.
#[derive(Debug, PartialEq, Eq)]
pub enum ReindexResult {
    /// Content hash matched existing entry — tree-sitter parse was skipped.
    HashSkip,
    /// File was re-parsed and the index was updated.
    Reindexed,
    /// File classified as Tier 2/3 by the admission gate — NOT parsed/inserted.
    /// Any prior Tier-1 entry was removed and a skip record recorded. The index
    /// remains free of this path's symbols.
    ///
    /// [`update_file_from_disk`] also returns this when it refuses the path
    /// itself: it lies outside the root, or it is not the file's own on-disk
    /// spelling. Nothing is read, removed or recorded in that case.
    Skipped,
    /// ENOENT observed by `read_and_index`; caller decides whether to retry or treat as confirmed-absent.
    NotFound,
    /// File was not found (ENOENT) — it has been removed from the index.
    Removed,
    /// File could not be read for a reason other than ENOENT.
    ReadError(String),
}

/// Crate-internal result of a single-file publication attempt.
///
/// `ReindexResult` is part of the semver-public embed facade and downstream
/// callers can exhaustively match its six variants. Publication contention is
/// therefore carried on this private result instead of widening that public
/// enum in a patch release.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum ReindexOutcome {
    HashSkip,
    Reindexed,
    Skipped,
    NotFound,
    Removed,
    ReadError(String),
    /// The observed change did not reach a publication boundary. Callers must
    /// retry or refuse rather than claim the stale state was reconciled.
    PublicationRejected,
}

impl ReindexOutcome {
    fn into_public_compat(self) -> ReindexResult {
        match self {
            Self::HashSkip => ReindexResult::HashSkip,
            Self::Reindexed => ReindexResult::Reindexed,
            Self::Skipped => ReindexResult::Skipped,
            Self::NotFound => ReindexResult::NotFound,
            Self::Removed => ReindexResult::Removed,
            Self::ReadError(error) => ReindexResult::ReadError(error),
            // Before this patch the public update seam reported a lost
            // publication race as Skipped. Preserve that compatibility only at
            // the frozen embed boundary; in-crate callers retain the typed
            // rejection and must retry or refuse.
            Self::PublicationRejected => ReindexResult::Skipped,
        }
    }
}

pub(crate) struct ReindexReceipt {
    pub outcome: ReindexOutcome,
    /// Publication fence captured immediately before this attempt's
    /// filesystem observation.
    pub observed_at: PublicationFence,
    /// Exact immutable generation returned by the winning publication seam.
    pub published: Option<Arc<PublishedGeneration>>,
    pub snapshot_created: bool,
}

impl ReindexReceipt {
    fn observed(outcome: ReindexOutcome, observed_at: PublicationFence) -> Self {
        Self {
            outcome,
            observed_at,
            published: None,
            snapshot_created: false,
        }
    }

    fn published(
        outcome: ReindexOutcome,
        observed_at: PublicationFence,
        published: Arc<PublishedGeneration>,
    ) -> Self {
        Self {
            outcome,
            observed_at,
            published: Some(published),
            snapshot_created: false,
        }
    }
}

/// Content-hash-gated single-file re-index.
///
/// Reads the file, compares its hash against the existing index entry, and
/// skips the expensive tree-sitter parse when the hash matches.
///
/// # Lock discipline
/// The write lock is **never** held during the tree-sitter parse. The sequence is:
/// 1. Read file bytes (no lock)
/// 2. Acquire read lock → compare hash → drop read lock
/// 3. Parse (no lock)
/// 4. Acquire write lock → update_file → drop write lock
pub(crate) fn maybe_reindex<L>(
    relative_path: &str,
    abs_path: &Path,
    shared: &SharedIndex,
    language: L,
    expected_gen: u64,
) -> ReindexOutcome
where
    L: Into<Option<LanguageId>>,
{
    let language = language.into();
    let first =
        read_and_index_with_receipt(relative_path, abs_path, shared, language, expected_gen);
    if first.observed_at.project_generation != expected_gen {
        return ReindexOutcome::PublicationRejected;
    }
    let mut last_absence_fence = match first.outcome {
        ReindexOutcome::NotFound => first.observed_at,
        other => return other,
    };

    // Spec 036 FR-020: the vanish waits draw on the enclosing call's retry
    // budget, so one answer over many deleted files is not blocked for each.
    // Round 3 item 4: they keep a small minimum of their own, so a locked
    // file that spent the call's budget cannot turn an editor's
    // delete-then-rename save into an eviction.
    let budget = crate::discovery::os_response::current_budget();
    let own = crate::discovery::os_response::RetryBudget::new(VANISH_WAIT_MINIMUM);
    let delays_ms = [50u64, 200, 500];
    for delay_ms in delays_ms {
        let remaining = budget.remaining().max(own.remaining());
        if remaining.is_zero() {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(delay_ms).min(remaining));
        let retry =
            read_and_index_with_receipt(relative_path, abs_path, shared, language, expected_gen);
        if retry.observed_at.project_generation != expected_gen {
            return ReindexOutcome::PublicationRejected;
        }
        match retry.outcome {
            ReindexOutcome::NotFound => last_absence_fence = retry.observed_at,
            other => return other,
        }
    }

    finalize_missing_file(
        shared,
        relative_path,
        abs_path,
        expected_gen,
        last_absence_fence,
    )
}

/// The vanish waits every missing file gets whatever the call's retry budget
/// has left: enough for an atomic save's delete-then-rename (round 3 item 4).
const VANISH_WAIT_MINIMUM: std::time::Duration = std::time::Duration::from_millis(250);

fn finalize_missing_file(
    shared: &SharedIndex,
    relative_path: &str,
    abs_path: &Path,
    expected_gen: u64,
    absence_fence: PublicationFence,
) -> ReindexOutcome {
    if absence_fence.project_generation != expected_gen {
        return ReindexOutcome::PublicationRejected;
    }
    match shared.remove_file_if_absent_at_publication_fence_with_receipt(
        relative_path,
        abs_path,
        absence_fence,
    ) {
        FencedRemoval::Removed(_) => {
            warn!("watcher: file not found after retries, removed from index: {relative_path}");
            ReindexOutcome::Removed
        }
        // Nothing held this path anywhere: the absence is confirmed and there
        // is no removal to publish. Reporting `Removed` (or publishing) here
        // would claim an operation nothing observed (the D14 defect).
        FencedRemoval::NothingHeld => {
            trace!(
                "watcher: file not found and nothing held, no removal to publish: {relative_path}"
            );
            ReindexOutcome::NotFound
        }
        FencedRemoval::Rejected => {
            trace!(
                "watcher: file not found after retries, stale publication rejected remove: {relative_path}"
            );
            ReindexOutcome::PublicationRejected
        }
    }
}

/// Recover the project root by walking up from the absolute event path once per
/// component of the relative path. Both come from the same watcher event (or
/// freshen-on-read call), so the suffix relationship holds by construction;
/// `None` only if the relative path is deeper than the absolute one.
fn project_root_from_paths(abs_path: &Path, relative_path: &str) -> Option<PathBuf> {
    let depth = relative_depth(Path::new(relative_path));
    abs_path.ancestors().nth(depth).map(|p| p.to_path_buf())
}

/// Stable-content admission with the project's secret dismissals applied. The
/// root is recovered from the event paths; if that ever fails the plain
/// classifier runs, which can only withhold more, never admit more.
fn classify_for_project(
    abs_path: &Path,
    relative_path: &str,
    targets: crate::domain::IndexTargets,
    bytes: &[u8],
) -> crate::knowledge::StableContentAdmission {
    match project_root_from_paths(abs_path, relative_path) {
        Some(root) => {
            crate::knowledge::classify_stable_content_for_root(&root, relative_path, targets, bytes)
        }
        None => crate::knowledge::classify_stable_content(relative_path, targets, bytes),
    }
}

/// How many ancestors of the absolute path the relative path spans. `.`
/// components have no ancestor of their own; counting them would walk above
/// the root.
fn relative_depth(relative: &Path) -> usize {
    relative
        .components()
        .filter(|component| !matches!(component, std::path::Component::CurDir))
        .count()
}

/// The cold walk never follows a symlink: it skips a linked file and does not
/// descend a linked directory. A single path is held to the same rule, checked
/// on each in-repository component of `abs_path`, so a link committed to the
/// repository or created by a checkout never publishes its target's bytes
/// under the in-repository name.
fn path_crosses_symlink(abs_path: &Path, relative: &Path) -> bool {
    abs_path
        .ancestors()
        .take(relative_depth(relative))
        .any(|path| {
            std::fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_symlink())
        })
}

/// A watcher event or freshen request can carry a spelling other than the
/// file's own on-disk name, such as an 8.3 short name or a letter-case
/// variant. Indexing it would publish the file under a second key that the
/// gitignore, scope and credential rules judged by the alias, so the lane
/// refuses any spelling the shared resolver refuses.
fn path_spelling_is_refused(abs_path: &Path, relative_path: &str) -> bool {
    project_root_from_paths(abs_path, relative_path)
        .is_some_and(|root| crate::discovery::resolve_repo_path(&root, relative_path).is_err())
}

/// The metadata scout both halves of the seam run, with a test-only failure
/// injection standing in for a scout error on a file that exists.
fn scout_single_path(
    relative_path: &str,
    abs_path: &Path,
) -> anyhow::Result<crate::domain::ScoutedEntry> {
    #[cfg(test)]
    if test_scout_failure_path().lock().as_deref() == Some(relative_path) {
        anyhow::bail!("injected scout failure");
    }
    crate::discovery::scout_single_path(relative_path, abs_path)
}

/// Test-only fault injection for [`scout_single_path`].
#[cfg(test)]
pub(crate) fn test_scout_failure_path() -> &'static parking_lot::Mutex<Option<String>> {
    static PATH: parking_lot::Mutex<Option<String>> = parking_lot::Mutex::new(None);
    &PATH
}

pub(crate) fn catalog_terminal_disposition(decision: &ScoutDecision) -> Option<FileDisposition> {
    match decision {
        ScoutDecision::HardSkip { reason } => Some(FileDisposition::HardSkip { reason: *reason }),
        ScoutDecision::MetadataOnly { reason } => Some(FileDisposition::MetadataOnly {
            reason: reason.clone(),
        }),
        ScoutDecision::Ingest { .. } | ScoutDecision::Unavailable { .. } => None,
    }
}

pub(crate) fn read_and_index<L>(
    relative_path: &str,
    abs_path: &Path,
    shared: &SharedIndex,
    language: L,
    expected_gen: u64,
) -> ReindexOutcome
where
    L: Into<Option<LanguageId>>,
{
    read_and_index_with_receipt(relative_path, abs_path, shared, language, expected_gen).outcome
}

fn read_and_index_with_receipt<L>(
    relative_path: &str,
    abs_path: &Path,
    shared: &SharedIndex,
    language: L,
    expected_gen: u64,
) -> ReindexReceipt
where
    L: Into<Option<LanguageId>>,
{
    read_and_index_with_stable_read_receipt(
        relative_path,
        abs_path,
        shared,
        language,
        expected_gen,
        crate::live_index::store::stable_read_file,
    )
}

/// Run one canonical repository-relative path through the same metadata-first
/// admission and publication seam used by watcher events and reconciliation.
pub(crate) fn admit_and_index_single_path(
    relative_path: &str,
    abs_path: &Path,
    shared: &SharedIndex,
    expected_gen: u64,
) -> ReindexOutcome {
    admit_and_index_single_path_with_receipt(relative_path, abs_path, shared, expected_gen).outcome
}

pub(crate) fn admit_and_index_single_path_with_receipt(
    relative_path: &str,
    abs_path: &Path,
    shared: &SharedIndex,
    expected_gen: u64,
) -> ReindexReceipt {
    read_and_index_with_stable_read_receipt(
        relative_path,
        abs_path,
        shared,
        None,
        expected_gen,
        crate::live_index::store::stable_read_file,
    )
}

/// Off-lock half of the canonical seam, for snapshot-verify batches.
///
/// Runs the gates of [`read_and_index_with_stable_read_receipt`] in the same
/// order (exclusions, metadata scout, generated-output placement, stable read,
/// content policy) but publishes nothing: the caller commits many paths in one
/// publication. Returns `None` for every outcome this cannot settle without a
/// publication of its own (exclusion eviction, unreadable, unstable, missing),
/// and the caller sends that path through the canonical seam instead. `base`
/// is the row the stat pass saw; matching bytes reuse it without a parse.
pub(crate) fn prepare_snapshot_verify_admission(
    relative_path: &str,
    abs_path: &Path,
    shared: &SharedIndex,
    base: Option<&Arc<IndexedFile>>,
) -> Option<SnapshotVerifiedFile> {
    let relative = Path::new(relative_path);
    // The same refusals as the canonical seam, before any read: a link or a
    // spelling the resolver refuses goes to that seam, which evicts it.
    if crate::discovery::path_is_hard_scope_excluded(relative)
        || shared.is_source_excluded(relative)
        || shared.read().is_path_gitignored(relative_path)
        || path_crosses_symlink(abs_path, relative)
        || path_spelling_is_refused(abs_path, relative_path)
    {
        return None;
    }
    let mut scouted = scout_single_path(relative_path, abs_path).ok()?;
    let prepare = |scouted, bytes| {
        prepare_snapshot_verify_from_observation(
            relative_path,
            scouted,
            bytes,
            base,
            |targets, bytes| classify_for_project(abs_path, relative_path, targets, bytes),
        )
    };
    if catalog_terminal_disposition(&scouted.decision).is_some() {
        return prepare(scouted, None);
    }
    let ScoutDecision::Ingest { .. } = scouted.decision else {
        return None;
    };
    if let Some(root) = project_root_from_paths(abs_path, relative_path)
        && crate::discovery::is_untracked_generated_output_path(&root, relative_path)
    {
        scouted.decision = ScoutDecision::MetadataOnly {
            reason: MetadataOnlyReason::GeneratedOrVendor,
        };
        return prepare(scouted, None);
    }
    let bytes = match crate::live_index::store::stable_read_file(abs_path, &scouted.stamp) {
        crate::live_index::store::StableReadOutcome::Accepted { bytes, .. } => bytes,
        crate::live_index::store::StableReadOutcome::HardSkip { reason } => {
            scouted.decision = ScoutDecision::HardSkip { reason };
            return prepare(scouted, None);
        }
        _ => return None,
    };
    prepare(scouted, Some(bytes))
}

/// Parse one already admitted, stable observation without reopening its path.
/// The caller supplies the shared scout decision, enforces source exclusions
/// and path spelling, and binds the content classifier to its admitted source.
/// Missing bytes for an ingest decision are unsettled, never an empty file.
pub(crate) fn prepare_snapshot_verify_from_observation(
    relative_path: &str,
    scouted: crate::domain::ScoutedEntry,
    bytes: Option<Vec<u8>>,
    base: Option<&Arc<IndexedFile>>,
    classify: impl FnOnce(
        crate::domain::IndexTargets,
        &[u8],
    ) -> crate::knowledge::StableContentAdmission,
) -> Option<SnapshotVerifiedFile> {
    #[cfg(test)]
    if test_scout_failure_path().lock().as_deref() == Some(relative_path) {
        return None;
    }
    let base_hash = base.map(|row| row.content_hash.clone());
    let terminal = |scouted, disposition| SnapshotVerifiedFile {
        path: relative_path.to_string(),
        scouted,
        admission: SnapshotVerifiedAdmission::Terminal(disposition),
        base_hash: base_hash.clone(),
    };
    if let Some(disposition) = catalog_terminal_disposition(&scouted.decision) {
        return Some(terminal(scouted, disposition));
    }
    let ScoutDecision::Ingest { targets } = scouted.decision else {
        return None;
    };
    let bytes = bytes?;
    if let crate::knowledge::StableContentAdmission::MetadataOnly(reason) =
        classify(targets, &bytes)
    {
        return Some(terminal(scouted, FileDisposition::MetadataOnly { reason }));
    }
    let mtime_secs = scouted
        .stamp
        .modified_hint
        .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|duration| duration.as_secs())
        .unwrap_or(0);
    let file = match base {
        Some(row) if row.content_hash == hash::digest_hex(&bytes) => {
            let mut row = row.as_ref().clone();
            row.mtime_secs = mtime_secs;
            row
        }
        _ => {
            let language = scouted.language.unwrap_or(LanguageId::Text);
            let result = parsing::process_file_with_classification(
                relative_path,
                &bytes,
                language,
                FileClassification::for_indexed_path(relative_path, targets),
            );
            IndexedFile::from_parse_result(result, bytes).with_mtime(mtime_secs)
        }
    };
    Some(SnapshotVerifiedFile {
        path: relative_path.to_string(),
        scouted,
        admission: SnapshotVerifiedAdmission::Indexed {
            file: Box::new(file),
            targets,
        },
        base_hash,
    })
}

#[cfg(test)]
pub(crate) fn read_and_index_with_stable_read<L, R>(
    relative_path: &str,
    abs_path: &Path,
    shared: &SharedIndex,
    language: L,
    expected_gen: u64,
    stable_read: R,
) -> ReindexOutcome
where
    L: Into<Option<LanguageId>>,
    R: FnMut(&Path, &crate::domain::FileStamp) -> crate::live_index::store::StableReadOutcome,
{
    read_and_index_with_stable_read_receipt(
        relative_path,
        abs_path,
        shared,
        language,
        expected_gen,
        stable_read,
    )
    .outcome
}

fn read_and_index_with_stable_read_receipt<L, R>(
    relative_path: &str,
    abs_path: &Path,
    shared: &SharedIndex,
    language: L,
    expected_gen: u64,
    mut stable_read: R,
) -> ReindexReceipt
where
    L: Into<Option<LanguageId>>,
    R: FnMut(&Path, &crate::domain::FileStamp) -> crate::live_index::store::StableReadOutcome,
{
    let language = language.into();
    let mut base = shared.published_generation();
    let mut observed_at = PublicationFence::from_published(&base);
    // Keep single-file watcher/freshen paths symmetric with the bulk walk.
    // Both universal name exclusions and placement-derived subtree exclusions
    // run before any metadata/content read from VCS or runtime-state internals.
    let relative = Path::new(relative_path);
    if crate::discovery::path_is_hard_scope_excluded(relative)
        || shared.is_source_excluded(relative)
        || shared.read().is_path_gitignored(relative_path)
        || path_crosses_symlink(abs_path, relative)
        || path_spelling_is_refused(abs_path, relative_path)
    {
        if observed_at.project_generation != expected_gen {
            return ReindexReceipt::observed(ReindexOutcome::PublicationRejected, observed_at);
        }
        return match shared
            .remove_file_at_publication_fence_with_receipt(relative_path, observed_at)
        {
            FencedRemoval::Removed(published) => {
                debug!("watcher: source-scope eviction {relative_path}");
                ReindexReceipt::published(ReindexOutcome::Skipped, observed_at, published)
            }
            // The excluded path was never held: the exclusion is already the
            // published state, so there is no eviction to publish.
            FencedRemoval::NothingHeld => {
                trace!("watcher: source-scope exclusion already reconciled {relative_path}");
                ReindexReceipt::observed(ReindexOutcome::Skipped, observed_at)
            }
            FencedRemoval::Rejected => {
                trace!("watcher: source-scope eviction publication rejected {relative_path}");
                ReindexReceipt::observed(ReindexOutcome::PublicationRejected, observed_at)
            }
        };
    }

    const MAX_PUBLICATION_ATTEMPTS: usize = 4;
    for attempt in 1..=MAX_PUBLICATION_ATTEMPTS {
        base = shared.published_generation();
        observed_at = PublicationFence::from_published(&base);
        // The store mutation CAS protects the health/live index base, whose
        // generation is intentionally distinct from the full publication
        // bundle generation. Bridge- or authority-only publishes can advance
        // the latter while retaining this same live-index base.
        let expected_index_state_generation = base.health.generation;

        // Nested junction/symlink: leaf metadata looks regular; canonicalize
        // must still refuse ingest under the in-repo name.
        if !crate::paths::canonical_abs_stays_under_relative_root(abs_path, relative_path) {
            return ReindexReceipt::observed(ReindexOutcome::Skipped, observed_at);
        }

        // Run the same metadata-first scout as cold load before any whole-file read.
        let mut scouted = match scout_single_path(relative_path, abs_path) {
            Ok(scouted) => scouted,
            Err(error) => {
                if matches!(
                    std::fs::metadata(abs_path),
                    Err(error) if error.kind() == std::io::ErrorKind::NotFound
                ) {
                    return ReindexReceipt::observed(ReindexOutcome::NotFound, observed_at);
                }
                warn!("watcher: failed to scout {relative_path}: {error}");
                return ReindexReceipt::observed(
                    ReindexOutcome::ReadError(error.to_string()),
                    observed_at,
                );
            }
        };
        let mtime_secs = scouted
            .stamp
            .modified_hint
            .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|duration| duration.as_secs())
            .unwrap_or(0);

        if let Some(disposition) = catalog_terminal_disposition(&scouted.decision) {
            if let Some(published) = shared.publish_terminal_disposition_at_generation(
                relative_path,
                scouted,
                disposition,
                expected_gen,
                expected_index_state_generation,
            ) {
                debug!("watcher: metadata-terminal admission {relative_path}");
                return ReindexReceipt::published(ReindexOutcome::Skipped, observed_at, published);
            }
            if shared.current_project_generation() == expected_gen
                && shared.published_state().generation != expected_index_state_generation
            {
                trace!(attempt, "watcher: retrying metadata-terminal publication");
                continue;
            }
            trace!("watcher: stale metadata-terminal admission rejected: {relative_path}");
            return ReindexReceipt::observed(ReindexOutcome::PublicationRejected, observed_at);
        }
        if let ScoutDecision::Unavailable { stage, kind } = &scouted.decision {
            if *stage == crate::domain::AccessStage::Metadata
                && *kind == crate::domain::AccessErrorKind::NotFound
            {
                return ReindexReceipt::observed(ReindexOutcome::NotFound, observed_at);
            }
            let disposition = FileDisposition::Unreadable {
                stage: *stage,
                kind: *kind,
            };
            if let Some(published) = shared.publish_terminal_disposition_at_generation(
                relative_path,
                scouted,
                disposition,
                expected_gen,
                expected_index_state_generation,
            ) {
                return ReindexReceipt::published(
                    ReindexOutcome::ReadError("single-path scout unavailable".to_string()),
                    observed_at,
                    published,
                );
            }
            if shared.current_project_generation() == expected_gen
                && shared.published_state().generation != expected_index_state_generation
            {
                trace!(attempt, "watcher: retrying unavailable publication");
                continue;
            }
            return ReindexReceipt::observed(ReindexOutcome::PublicationRejected, observed_at);
        }

        // Generated-output placement is metadata policy too; evaluate it before
        // loading content, matching the cold-walk ordering.
        if let Some(root) = project_root_from_paths(abs_path, relative_path)
            && crate::discovery::is_untracked_generated_output_path(&root, relative_path)
        {
            let decision = ScoutDecision::MetadataOnly {
                reason: MetadataOnlyReason::GeneratedOrVendor,
            };
            let disposition = catalog_terminal_disposition(&decision)
                .expect("metadata-only decision must project to a terminal disposition");
            scouted.decision = decision;
            if let Some(published) = shared.publish_terminal_disposition_at_generation(
                relative_path,
                scouted,
                disposition,
                expected_gen,
                expected_index_state_generation,
            ) {
                return ReindexReceipt::published(ReindexOutcome::Skipped, observed_at, published);
            }
            if shared.current_project_generation() == expected_gen
                && shared.published_state().generation != expected_index_state_generation
            {
                trace!(attempt, "watcher: retrying generated-output publication");
                continue;
            }
            return ReindexReceipt::observed(ReindexOutcome::PublicationRejected, observed_at);
        }

        let targets = match &scouted.decision {
            ScoutDecision::Ingest { targets } => *targets,
            _ => unreachable!("terminal scout decisions return before content ingestion"),
        };

        let language = language.or(scouted.language).unwrap_or(LanguageId::Text);

        let bytes = match stable_read(abs_path, &scouted.stamp) {
            crate::live_index::store::StableReadOutcome::Accepted { bytes, .. } => bytes,
            crate::live_index::store::StableReadOutcome::HardSkip { reason } => {
                let decision = ScoutDecision::HardSkip { reason };
                let disposition = catalog_terminal_disposition(&decision)
                    .expect("hard-skip decision must project to a terminal disposition");
                scouted.decision = decision;
                if let Some(published) = shared.publish_terminal_disposition_at_generation(
                    relative_path,
                    scouted,
                    disposition,
                    expected_gen,
                    expected_index_state_generation,
                ) {
                    return ReindexReceipt::published(
                        ReindexOutcome::Skipped,
                        observed_at,
                        published,
                    );
                }
                if shared.current_project_generation() == expected_gen
                    && shared.published_state().generation != expected_index_state_generation
                {
                    trace!(
                        attempt,
                        "watcher: retrying stable-read hard-skip publication"
                    );
                    continue;
                }
                return ReindexReceipt::observed(ReindexOutcome::PublicationRejected, observed_at);
            }
            crate::live_index::store::StableReadOutcome::Unreadable { stage, kind, .. } => {
                let publication = shared.publish_terminal_disposition_at_generation(
                    relative_path,
                    scouted,
                    FileDisposition::Unreadable { stage, kind },
                    expected_gen,
                    expected_index_state_generation,
                );
                if let Some(published) = publication {
                    return ReindexReceipt::published(
                        ReindexOutcome::ReadError("stable read unavailable".to_string()),
                        observed_at,
                        published,
                    );
                }
                if shared.current_project_generation() == expected_gen
                    && shared.published_state().generation != expected_index_state_generation
                {
                    trace!(
                        attempt,
                        "watcher: retrying stable-read unavailable publication"
                    );
                    continue;
                }
                return ReindexReceipt::observed(ReindexOutcome::PublicationRejected, observed_at);
            }
            crate::live_index::store::StableReadOutcome::UnstableDuringRead => {
                let publication = shared.publish_terminal_disposition_at_generation(
                    relative_path,
                    scouted,
                    FileDisposition::UnstableDuringRead,
                    expected_gen,
                    expected_index_state_generation,
                );
                if let Some(published) = publication {
                    return ReindexReceipt::published(
                        ReindexOutcome::ReadError("file changed during stable read".to_string()),
                        observed_at,
                        published,
                    );
                }
                if shared.current_project_generation() == expected_gen
                    && shared.published_state().generation != expected_index_state_generation
                {
                    trace!(attempt, "watcher: retrying unstable-read publication");
                    continue;
                }
                return ReindexReceipt::observed(ReindexOutcome::PublicationRejected, observed_at);
            }
        };

        // The watcher shares the exact stable-content admission boundary used
        // by cold load. Terminal outcomes are published before hashing or parsing,
        // and the owned byte buffer is discarded on every non-admitted path.
        if let crate::knowledge::StableContentAdmission::MetadataOnly(reason) =
            classify_for_project(abs_path, relative_path, targets, &bytes)
        {
            if let Some(published) = shared.publish_terminal_disposition_at_generation(
                relative_path,
                scouted,
                FileDisposition::MetadataOnly { reason },
                expected_gen,
                expected_index_state_generation,
            ) {
                return ReindexReceipt::published(ReindexOutcome::Skipped, observed_at, published);
            }
            if shared.current_project_generation() == expected_gen
                && shared.published_state().generation != expected_index_state_generation
            {
                trace!(attempt, "watcher: retrying content-policy publication");
                continue;
            }
            return ReindexReceipt::observed(ReindexOutcome::PublicationRejected, observed_at);
        }

        // Compute the hash and compare without holding the publication writer lock.
        let new_hash = hash::digest_hex(&bytes);
        {
            // The resident row, not the query-gated `get_file`: a restored row
            // hidden while its snapshot is verified still proves these bytes
            // are already held, and missing it re-parses and republishes.
            let index = shared.read();
            if let Some(existing) = index.files.get(relative_path)
                && existing.content_hash == new_hash
            {
                drop(index);
                if let Some(published) = shared.publish_hash_skip_at_generation(
                    relative_path,
                    mtime_secs,
                    scouted,
                    targets,
                    expected_gen,
                    expected_index_state_generation,
                ) {
                    debug!("watcher: hash-skip {relative_path}");
                    return ReindexReceipt {
                        outcome: ReindexOutcome::HashSkip,
                        observed_at,
                        published: Some(published),
                        snapshot_created: false,
                    };
                }
                if shared.current_project_generation() == expected_gen
                    && shared.published_state().generation != expected_index_state_generation
                {
                    trace!(attempt, "watcher: retrying hash-skip publication");
                    continue;
                }
                return ReindexReceipt::observed(ReindexOutcome::PublicationRejected, observed_at);
            }
        }

        // Parse outside the lock (Tier-1 only).
        let result = parsing::process_file_with_classification(
            relative_path,
            &bytes,
            language,
            FileClassification::for_indexed_path(relative_path, targets),
        );
        let indexed = IndexedFile::from_parse_result(result, bytes).with_mtime(mtime_secs);

        // Commit every observable lane under one source-base fence and one
        // publication boundary. If another update won while this build was
        // off-lock, retry from disk instead of overwriting that newer bundle.
        if let Some(publication) = shared.publish_indexed_file_at_generation(
            relative_path,
            indexed,
            scouted,
            targets,
            expected_gen,
            expected_index_state_generation,
        ) {
            debug!("watcher: re-indexed {relative_path}");
            return ReindexReceipt {
                outcome: ReindexOutcome::Reindexed,
                observed_at,
                published: Some(publication.published),
                snapshot_created: publication.snapshot_created,
            };
        }
        if shared.current_project_generation() == expected_gen
            && shared.published_state().generation != expected_index_state_generation
        {
            trace!(attempt, "watcher: retrying indexed-file publication");
            continue;
        }
        trace!("watcher: stale indexed-file publication rejected: {relative_path}");
        return ReindexReceipt::observed(ReindexOutcome::PublicationRejected, observed_at);
    }

    warn!(
        "watcher: aborting {relative_path} after {MAX_PUBLICATION_ATTEMPTS} concurrent publications"
    );
    ReindexReceipt::observed(ReindexOutcome::PublicationRejected, observed_at)
}

/// Re-index one repository file FROM DISK through the canonical single-file
/// admission seam (embed facade; task #24 / AAP ask 3).
///
/// `relative_path` is the repo-relative, forward-slash path (backslashes are
/// normalized). The file's current bytes are read from
/// `repo_root/relative_path` with the same stable-read, admission, hash-skip,
/// and fenced-publication behavior the watcher applies — an embedder needs no
/// parsing or store internals, and a file the admission gate demotes is
/// recorded as skipped, never silently parsed.
///
/// No retries, no sleeps: a missing file returns [`ReindexResult::NotFound`]
/// immediately (deadline-friendly for in-VM embedders); callers tracking a
/// deletion should follow up with [`remove_file`].
pub fn update_file_from_disk(
    shared: &SharedIndex,
    repo_root: &Path,
    relative_path: &str,
) -> ReindexResult {
    let relative = relative_path.replace('\\', "/");
    // The embedder's path is caller-supplied: an escape, an absolute path or
    // another spelling of a file is refused before anything is read.
    match crate::discovery::resolve_repo_path(repo_root, &relative) {
        Ok(Some(_)) => {}
        Ok(None) => return ReindexResult::NotFound,
        Err(_) => return ReindexResult::Skipped,
    }
    let abs_path = repo_root.join(&relative);
    let expected_gen = shared.current_project_generation();
    let outcome = admit_and_index_single_path(&relative, &abs_path, shared, expected_gen)
        .into_public_compat();
    // V11 observation lane (Feature 020 Slice 4, T029): an admission that
    // MUTATED the index is observed through the isolated candidate pipeline,
    // permit-free, attributed to the current incarnation (this synchronous
    // facade holds no id across time). D1 applies: the LiveIndex mutation
    // above IS the data plane mid-cut; the lane runs the frozen lifecycle
    // semantics beside it. A hash-skip observed no change.
    if matches!(outcome, ReindexResult::Reindexed) {
        crate::live_index::index_lifecycle::activation::project_source_authority(repo_root)
            .observe_admission_active(&relative);
    }
    outcome
}

/// Bring the index in line with the secret-dismissal store at `repo_root`.
///
/// When the store differs from the one the live verdicts were classified
/// under, every path named by the old or the new records is re-admitted
/// through the canonical single-file seam, which classifies with the current
/// store, so the index lane and the read lane agree again. With no held state
/// recorded, every indexed path is re-admitted. The held state advances only
/// when every re-admission reached a publication boundary; otherwise it keeps
/// a digest no snapshot can match, so the next trigger retries.
pub(crate) fn reconcile_secret_dismissals(
    shared: &SharedIndex,
    repo_root: &Path,
) -> std::collections::BTreeMap<String, ReindexOutcome> {
    use crate::knowledge::secret_dismissals as dismissals;
    let current = dismissals::observe_dismissals(repo_root);
    let held = dismissals::held_dismissals(repo_root);
    let mut outcomes = std::collections::BTreeMap::new();
    if held
        .as_ref()
        .is_some_and(|held| held.digest == current.digest)
    {
        return outcomes;
    }
    let mut paths = current.paths.clone();
    match held {
        Some(held) => paths.extend(held.paths),
        None => paths.extend(shared.read().files.keys().cloned()),
    }
    let expected_gen = shared.current_project_generation();
    for relative in paths.iter().cloned() {
        // Record paths are store text: only a path that is its own canonical
        // spelling beneath the root is re-admitted.
        if !matches!(
            crate::discovery::resolve_repo_path(repo_root, &relative),
            Ok(Some(_))
        ) {
            continue;
        }
        let abs_path = repo_root.join(&relative);
        let outcome = admit_and_index_single_path(&relative, &abs_path, shared, expected_gen);
        if matches!(outcome, ReindexOutcome::Reindexed) {
            crate::live_index::index_lifecycle::activation::project_source_authority(repo_root)
                .observe_admission_active(&relative);
        }
        outcomes.insert(relative, outcome);
    }
    let settled = !outcomes
        .values()
        .any(|outcome| matches!(outcome, ReindexOutcome::PublicationRejected));
    let held = if settled {
        current
    } else {
        dismissals::HeldDismissals {
            digest: dismissals::UNKNOWN_DISMISSAL_DIGEST.to_string(),
            paths,
        }
    };
    dismissals::set_held_dismissals(repo_root, held);
    outcomes
}

/// Remove one file from the live index (embed facade; task #24 / AAP ask 3).
///
/// Generation-fenced like the watcher's removals: returns `true` when the
/// removal was APPLIED under the current project generation (including the
/// no-op case where the path was not tracked), `false` only when a concurrent
/// retarget invalidated the generation fence.
pub fn remove_file(shared: &SharedIndex, relative_path: &str) -> bool {
    let relative = relative_path.replace('\\', "/");
    let outcome =
        shared.remove_file_outcome_at_generation(&relative, shared.current_project_generation());
    // V11 observation lane (T029): an applied removal lands as an
    // accumulator invalidation (the dark candidate pipeline carries no
    // removal payload — recorded bridging simplification). Fixture indexes
    // with no bound root have no source authority to observe through.
    // `NothingHeld` observes nothing: no removal happened, and nothing
    // published (the D14 fence) — but the facade contract still reports the
    // fence-held no-op as applied.
    if matches!(outcome, FencedRemoval::Removed(_))
        && let Some(root) = shared.read().indexed_root.clone()
    {
        crate::live_index::index_lifecycle::activation::project_source_authority(&root)
            .observe_removal_active(&relative);
    }
    !matches!(outcome, FencedRemoval::Rejected)
}

pub(crate) fn refuses_observed_admission_into_cold_bootstrap(shared: &SharedIndex) -> bool {
    shared.read().refuses_watcher_observed_admission()
}

pub(crate) fn maybe_reindex_observed<L>(
    relative_path: &str,
    abs_path: &Path,
    shared: &SharedIndex,
    language: L,
    expected_gen: u64,
) -> ReindexOutcome
where
    L: Into<Option<LanguageId>>,
{
    if refuses_observed_admission_into_cold_bootstrap(shared) {
        trace!(
            "watcher: refusing observed reindex into cold bootstrap placeholder: {relative_path}"
        );
        return ReindexOutcome::Skipped;
    }
    maybe_reindex(relative_path, abs_path, shared, language, expected_gen)
}

#[must_use]
pub(crate) enum FreshenResult {
    Fresh,
    StaleReindexed,
    StaleRemoved,
    GenerationMismatch,
    PublicationRejected,
    /// The file could not be compared with the disk; the cause is classified
    /// from the operating system's own error (spec 036 FR-019).
    Unconfirmed(crate::discovery::os_response::OsCause),
    /// The row records no modification time and no file is on disk: left in
    /// place as the mtime-only guard did, and never counted as confirmed.
    UnstampedAbsent,
}

/// Return the authoritative `LanguageId` for a complete repository path.
/// Extensionless narrative files and configuration dotfiles are path-classified.
pub(crate) fn supported_language(path: &Path) -> Option<LanguageId> {
    path.to_str().and_then(LanguageId::from_path)
}

pub(crate) enum DiskComparison {
    Same,
    Differs,
    /// The project was retargeted during the comparison (round 3 item 3):
    /// nothing is confirmed and no stamp is saved.
    GenerationChanged,
    Unconfirmed(crate::discovery::os_response::OsCause),
    /// A row with no recorded modification time and no file on disk.
    UnstampedAbsent,
}

/// Compare one indexed file with the disk (spec 036 FR-015, FR-016): size and
/// modification time first; inside the racy window, or when this process never
/// confirmed the content (a restored or freshly loaded row), by content hash.
/// A confirmation by hash is remembered, so the next call trusts the stat
/// again once the window has passed: one hash per file per change.
pub(crate) fn compare_with_disk(
    relative_path: &str,
    abs_path: &Path,
    shared: &SharedIndex,
    expected_gen: u64,
) -> DiskComparison {
    use crate::discovery::os_response::{AccessFailure, OsClass, current_budget, retry_transient};

    let budget = current_budget();
    let stat = retry_transient(&budget, Some(abs_path), || {
        #[cfg(test)]
        if let Some(code) = compare_faults::STAT_ERROR.with(std::cell::Cell::get) {
            return Err(AccessFailure::capture(std::io::Error::from_raw_os_error(
                code,
            )));
        }
        crate::paths::path_must_be_regular_non_link(abs_path).map_err(AccessFailure::capture)
    });
    #[cfg(test)]
    if let Some(hook) = compare_faults::AFTER_STAT.with(|hook| hook.borrow_mut().take()) {
        hook();
    }
    let metadata = match stat {
        Ok(metadata) => Some(metadata),
        Err(cause) if cause.class == OsClass::NotFound => None,
        Err(cause) => return DiskComparison::Unconfirmed(cause),
    };
    // Read lock, released before any further I/O.
    let indexed = shared
        .read()
        .get_file(relative_path)
        .map(|file| (file.byte_len, file.mtime_secs, file.content_hash.clone()));
    // Round 3 item 3: a row read after a retarget belongs to another root.
    if shared.current_project_generation() != expected_gen {
        return DiskComparison::GenerationChanged;
    }
    let (metadata, (byte_len, mtime_secs, content_hash)) = match (metadata, indexed) {
        // Nothing on disk and no row: the reindex below confirms the
        // absence (and records it), exactly as the mtime-only guard did.
        (None, None) => return DiskComparison::Differs,
        // A row that never recorded a modification time and has no file
        // behind it (rows built in memory, not from a disk walk): left in
        // place as before, but named for what it is, never "confirmed".
        (None, Some((_, 0, _))) => return DiskComparison::UnstampedAbsent,
        (Some(metadata), Some(indexed)) => (metadata, indexed),
        _ => return DiskComparison::Differs,
    };
    let modified = metadata.modified().ok();
    let disk_mtime_secs = modified
        .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
        .map_or(0, |duration| duration.as_secs());
    // M11: the racy rule reads the filesystem's own clock, the newest
    // modification time it has shown this index, never the host clock.
    let filesystem_now = shared.observe_filesystem_time(modified);
    if metadata.len() != byte_len || disk_mtime_secs != mtime_secs {
        return DiskComparison::Differs;
    }
    if shared
        .verified_stamp(relative_path)
        .is_some_and(|stamp| stamp.trusts(byte_len, modified, &content_hash))
    {
        return DiskComparison::Same;
    }
    // Round 3 item 8: the same size limit as the admission gate's stable
    // read for indexing; a file over it is not confirmed, and is not read.
    #[cfg(test)]
    let limit = compare_faults::HASH_LIMIT
        .with(std::cell::Cell::get)
        .unwrap_or(crate::domain::index::HARD_SKIP_BYTES);
    #[cfg(not(test))]
    let limit = crate::domain::index::HARD_SKIP_BYTES;
    if byte_len > limit {
        return DiskComparison::Unconfirmed(crate::discovery::os_response::OsCause::refused(
            "larger than the indexing size limit",
        ));
    }
    // The read goes through the read gate's own reader: regular files only,
    // no link at the leaf, and a FIFO or device never blocks it (H2).
    let bytes = match retry_transient(&budget, Some(abs_path), || {
        crate::index_lifecycle::guidance::read_gate::read_regular_file(abs_path)
            .map_err(AccessFailure::capture)
    }) {
        Ok(bytes) => bytes,
        Err(cause) if cause.class == OsClass::NotFound => return DiskComparison::Differs,
        Err(cause) => return DiskComparison::Unconfirmed(cause),
    };
    if hash::digest_hex(&bytes) != content_hash {
        return DiskComparison::Differs;
    }
    if shared.current_project_generation() != expected_gen {
        return DiskComparison::GenerationChanged;
    }
    shared.record_verified_stamp(
        relative_path,
        crate::live_index::store::VerifiedStamp {
            size: byte_len,
            modified,
            content_hash,
            filesystem_now,
        },
    );
    DiskComparison::Same
}

/// Test-only fault injection for [`compare_with_disk`] (spec 036 FR-037): a
/// raw OS code the stat fails with, and a hook that runs between the stat and
/// the content read.
#[cfg(test)]
pub(crate) mod compare_faults {
    thread_local! {
        pub(crate) static STAT_ERROR: std::cell::Cell<Option<i32>> =
            const { std::cell::Cell::new(None) };
        pub(crate) static AFTER_STAT: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
            const { std::cell::RefCell::new(None) };
        /// A smaller content-read size limit than the admission gate's.
        pub(crate) static HASH_LIMIT: std::cell::Cell<Option<u64>> =
            const { std::cell::Cell::new(None) };
    }
}

/// Size, modification-time and racy-content freshness check for one file.
///
/// Compares the file on disk with the indexed row ([`compare_with_disk`]).
/// If they differ (or the file is not yet indexed), re-indexes it
/// immediately before the caller proceeds. A failed comparison is
/// [`FreshenResult::Unconfirmed`] with its classified cause, never `Fresh`.
///
/// Returns a structured freshness outcome so callers can distinguish a
/// confirmed deletion from a stale project-generation mismatch.
pub(crate) fn freshen_file_if_stale(
    relative_path: &str,
    abs_path: &Path,
    shared: &SharedIndex,
    expected_gen: u64,
    authority: &crate::live_index::index_lifecycle::activation::ProjectSourceAuthority,
    observer: crate::live_index::index_lifecycle::observer::ObserverId,
) -> FreshenResult {
    if shared.current_project_generation() != expected_gen {
        if shared.remove_file_at_generation(relative_path, expected_gen)
            && authority.observe_removal(observer, relative_path).is_err()
        {
            debug!("freshen: stale incarnation's removal observation refused");
        }
        return FreshenResult::GenerationMismatch;
    }

    // H2: confinement BEFORE any I/O. A spelling that resolves outside the
    // repository (a directory swapped for a junction or symlink) is never
    // read, and is reported as not confirmed, never as fresh.
    if let Some(root) = abs_path
        .ancestors()
        .nth(std::path::Path::new(relative_path).components().count())
        && crate::index_lifecycle::guidance::read_gate::resolve_repo_path(root, relative_path)
            .is_err_and(|message| message.contains("outside the repository"))
    {
        return FreshenResult::Unconfirmed(crate::discovery::os_response::OsCause::refused(
            "resolves outside the repository",
        ));
    }
    match compare_with_disk(relative_path, abs_path, shared, expected_gen) {
        DiskComparison::Same => return FreshenResult::Fresh,
        DiskComparison::GenerationChanged => return FreshenResult::GenerationMismatch,
        DiskComparison::Unconfirmed(cause) => return FreshenResult::Unconfirmed(cause),
        DiskComparison::UnstampedAbsent => return FreshenResult::UnstampedAbsent,
        DiskComparison::Differs => {}
    }

    // 3. Stale — re-index
    let language = supported_language(abs_path);

    debug!("freshness guard: stale file detected, re-indexing {relative_path}");
    let result = maybe_reindex_observed(relative_path, abs_path, shared, language, expected_gen);
    // V11 observation lane (C4c): observe on the mutation EVIDENCE (the
    // reindex outcome), before the generation re-check — a commit that landed
    // just ahead of a reload must still be observed; a spurious observation
    // only dirties the next cut, a missed one loses the change.
    if matches!(result, ReindexOutcome::Reindexed)
        && authority
            .observe_admission(observer, relative_path)
            .is_err()
    {
        debug!("freshen: stale incarnation's admission observation refused");
    }
    if matches!(result, ReindexOutcome::Removed)
        && authority.observe_removal(observer, relative_path).is_err()
    {
        debug!("freshen: stale incarnation's removal observation refused");
    }
    if shared.current_project_generation() != expected_gen {
        if shared.remove_file_at_generation(relative_path, expected_gen)
            && authority.observe_removal(observer, relative_path).is_err()
        {
            debug!("freshen: stale incarnation's removal observation refused");
        }
        return FreshenResult::GenerationMismatch;
    }

    match result {
        ReindexOutcome::HashSkip | ReindexOutcome::Reindexed => FreshenResult::StaleReindexed,
        // The re-read failed: the stale row was reconciled to a terminal
        // disposition, but the file itself was not confirmed.
        ReindexOutcome::ReadError(message) => FreshenResult::Unconfirmed(
            crate::discovery::os_response::recorded_failure(abs_path).unwrap_or_else(|| {
                crate::discovery::os_response::classify(&std::io::Error::other(message), None, None)
            }),
        ),
        // Admission demoted the file to Tier 2/3: the index WAS reconciled
        // (any prior Tier-1 entry removed, skip record recorded), so the file is
        // no longer parsed/indexed. Report it as a refresh — the caller's stale
        // state has been resolved — without claiming the file is still indexed.
        ReindexOutcome::Skipped => FreshenResult::StaleReindexed,
        ReindexOutcome::NotFound | ReindexOutcome::Removed => {
            shared.forget_verified_stamp(relative_path);
            FreshenResult::StaleRemoved
        }
        ReindexOutcome::PublicationRejected => FreshenResult::PublicationRejected,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::live_index::LiveIndex;

    /// `freshen_file_if_stale` of `path` under `root` at the current generation.
    fn freshen_at(shared: &SharedIndex, root: &Path, path: &str, generation: u64) -> FreshenResult {
        let authority =
            crate::live_index::index_lifecycle::activation::project_source_authority(root);
        let observer = authority.active_observer();
        freshen_file_if_stale(
            path,
            &root.join(path),
            shared,
            generation,
            &authority,
            observer,
        )
    }

    fn set_mtime(path: &Path, time: std::time::SystemTime) {
        std::fs::File::options()
            .write(true)
            .open(path)
            .unwrap()
            .set_modified(time)
            .unwrap();
    }

    /// Review round 3 item 2: a file stamped years ahead must not end the
    /// racy window for every other file: a same-size edit inside one mtime
    /// tick is still found by content.
    #[test]
    fn a_future_dated_file_does_not_end_the_racy_window() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("future.rs"), "fn f() {}\n").unwrap();
        std::fs::write(dir.path().join("b.rs"), "fn b() {}\n").unwrap();
        let future =
            std::time::SystemTime::now() + std::time::Duration::from_secs(5 * 365 * 86_400);
        set_mtime(&dir.path().join("future.rs"), future);
        let shared = LiveIndex::load(dir.path()).unwrap();
        let generation = shared.current_project_generation();
        // The future file is observed, then b.rs is confirmed by content.
        let _ = freshen_at(&shared, dir.path(), "future.rs", generation);
        assert!(matches!(
            freshen_at(&shared, dir.path(), "b.rs", generation),
            FreshenResult::Fresh
        ));
        let stamp = std::fs::metadata(dir.path().join("b.rs"))
            .unwrap()
            .modified()
            .unwrap();
        std::fs::write(dir.path().join("b.rs"), "fn c() {}\n").unwrap();
        set_mtime(&dir.path().join("b.rs"), stamp);
        assert!(
            matches!(
                freshen_at(&shared, dir.path(), "b.rs", generation),
                FreshenResult::StaleReindexed
            ),
            "a same-size edit in the same tick must be found by content"
        );
    }

    /// Review round 3 item 3: a retarget between the stat and the hash must
    /// not confirm one root's row against another root's file, nor stamp it.
    #[test]
    fn a_retarget_during_the_comparison_confirms_nothing() {
        let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
        for dir in [&a, &b] {
            std::fs::write(dir.path().join("lib.rs"), "pub fn same() {}\n").unwrap();
        }
        let shared = LiveIndex::load(a.path()).unwrap();
        let generation = shared.current_project_generation();
        let (retarget, root_b) = (shared.clone(), b.path().to_path_buf());
        compare_faults::AFTER_STAT.with(|hook| {
            *hook.borrow_mut() = Some(Box::new(move || retarget.reload(&root_b).unwrap()));
        });
        let result = freshen_at(&shared, a.path(), "lib.rs", generation);
        assert!(
            matches!(result, FreshenResult::GenerationMismatch),
            "the comparison must report the retarget"
        );
        assert!(
            shared.verified_stamp("lib.rs").is_none(),
            "no stamp is saved under the new generation"
        );
    }

    /// Review round 3 item 4: an editor's delete-then-rename save still gets
    /// its vanish waits after a locked file used up the call's retry budget.
    #[test]
    fn a_save_by_rename_survives_a_spent_call_budget() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "pub fn a() {}\n").unwrap();
        let shared = LiveIndex::load(dir.path()).unwrap();
        let generation = shared.current_project_generation();
        std::fs::remove_file(&path).unwrap();
        let writer = {
            let path = path.clone();
            std::thread::spawn(move || {
                std::thread::sleep(std::time::Duration::from_millis(30));
                std::fs::write(path, "pub fn renamed() {}\n").unwrap();
            })
        };
        let result = crate::discovery::os_response::with_spent_call_budget(|| {
            freshen_at(&shared, dir.path(), "a.rs", generation)
        });
        writer.join().unwrap();
        assert!(
            matches!(result, FreshenResult::StaleReindexed),
            "the re-saved file is re-indexed, not evicted"
        );
        assert!(shared.read().get_file("a.rs").is_some());
    }

    /// Review round 3 item 8: the content read obeys the admission gate's
    /// size limit; a file over it is not confirmed, and is never read.
    #[test]
    fn a_file_over_the_size_limit_is_not_read_for_its_hash() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("a.rs"), "pub fn a() {}\n").unwrap();
        let shared = LiveIndex::load(dir.path()).unwrap();
        let generation = shared.current_project_generation();
        compare_faults::HASH_LIMIT.with(|limit| limit.set(Some(4)));
        let result = freshen_at(&shared, dir.path(), "a.rs", generation);
        compare_faults::HASH_LIMIT.with(|limit| limit.set(None));
        match result {
            FreshenResult::Unconfirmed(cause) => assert!(
                cause.describe().contains("size limit"),
                "{}",
                cause.describe()
            ),
            _ => panic!("a file over the limit must not be confirmed"),
        }
    }

    /// Task #24: the facade per-file entry points drive the SAME admission
    /// seam — index a new file, see its symbols, update it, remove it — with
    /// no parsing/store imports below the facade.
    #[test]
    fn facade_update_and_remove_round_trip() {
        let dir = tempfile::TempDir::new().expect("root");
        std::fs::write(
            dir.path().join("lib.rs"),
            "pub fn first() {}
",
        )
        .expect("seed");
        let shared = LiveIndex::load(dir.path()).expect("cold load");
        assert_eq!(shared.read().file_count(), 1);

        // New file appears through the seam.
        std::fs::write(
            dir.path().join("extra.rs"),
            "pub fn second() {}
",
        )
        .expect("new file");
        let outcome = update_file_from_disk(&shared, dir.path(), "extra.rs");
        assert!(
            matches!(outcome, ReindexResult::Reindexed),
            "new file must be admitted and parsed, got {outcome:?}"
        );
        assert_eq!(shared.read().file_count(), 2);

        // Unchanged content is hash-skipped, not re-parsed.
        let outcome = update_file_from_disk(&shared, dir.path(), "extra.rs");
        assert!(
            matches!(outcome, ReindexResult::HashSkip),
            "unchanged file must hash-skip, got {outcome:?}"
        );

        // Edited content re-parses.
        std::fs::write(
            dir.path().join("extra.rs"),
            "pub fn renamed() {}
",
        )
        .expect("edit");
        let outcome = update_file_from_disk(&shared, dir.path(), "extra.rs");
        assert!(
            matches!(outcome, ReindexResult::Reindexed),
            "edited file must re-parse, got {outcome:?}"
        );

        // Removal is fenced: applied under the current generation (a second
        // removal is an applied no-op, still fence-true).
        assert!(remove_file(&shared, "extra.rs"), "tracked file removes");
        assert_eq!(shared.read().file_count(), 1);
        assert!(
            remove_file(&shared, "extra.rs"),
            "no-op removal still passes the generation fence"
        );
        assert_eq!(shared.read().file_count(), 1);

        // Missing file reports NotFound without retries.
        let outcome = update_file_from_disk(&shared, dir.path(), "ghost.rs");
        assert!(
            matches!(outcome, ReindexResult::NotFound),
            "missing file must be NotFound, got {outcome:?}"
        );
    }

    #[test]
    fn javascript_module_aliases_extract_symbols_on_cold_load_and_update() {
        let dir = tempfile::TempDir::new().unwrap();
        let modules = [
            (
                "module.cjs",
                "function common_before() { return 1; }\nmodule.exports = common_before;\n",
                "common_before",
            ),
            (
                "module.mjs",
                "export function module_before() { return 1; }\n",
                "module_before",
            ),
        ];
        for (path, source, _) in modules {
            std::fs::write(dir.path().join(path), source).unwrap();
        }
        let shared = LiveIndex::load(dir.path()).unwrap();
        for (path, source, before) in modules {
            {
                let index = shared.read();
                let file = index.get_file(path).expect("cold module must be indexed");
                assert_eq!(file.language, LanguageId::JavaScript);
                assert!(file.classification.is_code());
                assert!(file.symbols.iter().any(|symbol| symbol.name == before));
            }
            let after = before.replace("_before", "_after");
            std::fs::write(dir.path().join(path), source.replace("_before", "_after")).unwrap();
            assert!(matches!(
                update_file_from_disk(&shared, dir.path(), path),
                ReindexResult::Reindexed
            ));
            let index = shared.read();
            let file = index
                .get_file(path)
                .expect("updated module must be indexed");
            assert_eq!(file.language, LanguageId::JavaScript);
            assert!(file.symbols.iter().any(|symbol| symbol.name == after));
            assert!(!file.symbols.iter().any(|symbol| symbol.name == before));
        }
    }

    #[test]
    fn javascript_module_aliases_keep_credential_admission_on_cold_load_and_update() {
        for extension in ["cjs", "mjs"] {
            let dir = tempfile::TempDir::new().unwrap();
            let safe = format!("safe.{extension}");
            let guarded = format!("guarded.{extension}");
            let canary = ["runtime", "-", "canary", "-", "segment"].concat();
            let sensitive = format!("const password = \"{canary}\";\nfunction withheld() {{}}\n");
            std::fs::write(dir.path().join(&safe), "function safe_function() {}\n").unwrap();
            std::fs::write(dir.path().join(&guarded), &sensitive).unwrap();
            let shared = LiveIndex::load(dir.path()).unwrap();
            {
                let index = shared.read();
                assert!(
                    index.get_file(&guarded).is_none(),
                    "cold admission must withhold credentials"
                );
                assert_eq!(
                    index.get_file(&safe).unwrap().language,
                    LanguageId::JavaScript
                );
            }
            std::fs::write(dir.path().join(&safe), &sensitive).unwrap();
            assert!(matches!(
                update_file_from_disk(&shared, dir.path(), &safe),
                ReindexResult::Skipped
            ));
            assert!(
                shared.read().get_file(&safe).is_none(),
                "changed-file admission must evict credentials"
            );
        }
    }

    const OUTBOUND_LINK_SECRET: &str = "OUTBOUND_LINK_SECRET_7f3a9c2e";

    fn plant_outbound_secret(repo: &Path) -> (tempfile::TempDir, &'static str) {
        let outside = tempfile::TempDir::new().expect("outside");
        std::fs::write(
            outside.path().join("secret.txt"),
            format!("{OUTBOUND_LINK_SECRET}\n"),
        )
        .expect("secret");
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(outside.path(), repo.join("junc")).expect("dir symlink");
            (outside, "junc/secret.txt")
        }
        #[cfg(windows)]
        {
            let junction = repo.join("junc");
            let status = crate::process_util::hidden_command("cmd")
                .args(["/C", "mklink", "/J"])
                .arg(&junction)
                .arg(outside.path())
                .output()
                .expect("mklink");
            assert!(
                status.status.success(),
                "mklink /J failed: {}",
                String::from_utf8_lossy(&status.stderr)
            );
            (outside, "junc/secret.txt")
        }
    }

    #[test]
    fn outbound_link_single_path_ingest_skips_nested_secret() {
        let dir = tempfile::TempDir::new().expect("repo");
        std::fs::write(dir.path().join("plain.rs"), "pub fn plain() {}\n").expect("plain");
        let (_outside, link_path) = plant_outbound_secret(dir.path());
        let shared = LiveIndex::load(dir.path()).expect("load");
        let outcome = update_file_from_disk(&shared, dir.path(), link_path);
        assert!(
            matches!(outcome, ReindexResult::Skipped),
            "nested outbound ingest must skip, got {outcome:?}"
        );
        assert!(
            shared.read().get_file(link_path).is_none()
                || shared.read().get_file(link_path).is_some_and(|file| {
                    !String::from_utf8_lossy(&file.content).contains(OUTBOUND_LINK_SECRET)
                }),
            "ingest must not publish the outside secret"
        );
        let plain = update_file_from_disk(&shared, dir.path(), "plain.rs");
        assert!(
            matches!(plain, ReindexResult::HashSkip | ReindexResult::Reindexed),
            "ordinary file must still ingest, got {plain:?}"
        );
    }

    /// Feature 020 Slice 4, T029 (observation lane): every facade admission
    /// that MUTATED the index also drives the isolated candidate pipeline to
    /// its commit point, permit-free; a hash-skip observes no change and
    /// commits nothing.
    #[test]
    fn facade_admission_feeds_the_observation_lane() {
        let dir = tempfile::TempDir::new().expect("root");
        std::fs::write(dir.path().join("lib.rs"), "pub fn first() {}\n").expect("seed");
        let shared = LiveIndex::load(dir.path()).expect("cold load");
        let authority =
            crate::live_index::index_lifecycle::activation::project_source_authority(dir.path());
        assert_eq!(authority.committed_observations("extra.rs"), 0);

        std::fs::write(dir.path().join("extra.rs"), "pub fn second() {}\n").expect("new file");
        assert!(matches!(
            update_file_from_disk(&shared, dir.path(), "extra.rs"),
            ReindexResult::Reindexed
        ));
        assert_eq!(
            authority.committed_observations("extra.rs"),
            1,
            "an admitted mutation must reach the candidate commit point"
        );

        assert!(matches!(
            update_file_from_disk(&shared, dir.path(), "extra.rs"),
            ReindexResult::HashSkip
        ));
        assert_eq!(
            authority.committed_observations("extra.rs"),
            1,
            "a hash-skip observed no change and commits nothing"
        );

        std::fs::write(dir.path().join("extra.rs"), "pub fn renamed() {}\n").expect("edit");
        assert!(matches!(
            update_file_from_disk(&shared, dir.path(), "extra.rs"),
            ReindexResult::Reindexed
        ));
        assert_eq!(authority.committed_observations("extra.rs"), 2);

        assert!(remove_file(&shared, "extra.rs"));
        assert_eq!(
            authority.committed_observations("extra.rs"),
            2,
            "a removal rides the accumulator, not the candidate pipeline \
             (dark bridging: no removal payload exists yet)"
        );
    }

    /// The cold walk never follows a symlink, so the single-path lane shared by
    /// the watcher, freshen-on-read and the embed facade must not either. A link
    /// that arrives through a checkout would otherwise publish its target's bytes
    /// under the in-repo name.
    #[test]
    fn single_path_admission_does_not_follow_symlinks() {
        let root = tempfile::TempDir::new().expect("root");
        let outside = tempfile::TempDir::new().expect("outside");
        std::fs::write(
            outside.path().join("secret.txt"),
            "placeholder-fixture-value\n",
        )
        .expect("outside file");
        std::fs::create_dir_all(root.path().join("docs")).expect("docs");
        std::fs::write(root.path().join("lib.rs"), "pub fn first() {}\n").expect("seed");
        let shared = LiveIndex::load(root.path()).expect("cold load");

        #[cfg(unix)]
        let links = (
            std::os::unix::fs::symlink(
                outside.path().join("secret.txt"),
                root.path().join("docs/setup.txt"),
            ),
            std::os::unix::fs::symlink(outside.path(), root.path().join("linked")),
        );
        #[cfg(windows)]
        let links = (
            std::os::windows::fs::symlink_file(
                outside.path().join("secret.txt"),
                root.path().join("docs/setup.txt"),
            ),
            std::os::windows::fs::symlink_dir(outside.path(), root.path().join("linked")),
        );
        let mut exercised = Vec::new();
        match links.0 {
            Ok(()) => exercised.push("docs/setup.txt"),
            Err(error) => eprintln!("cannot create a file symlink here ({error}); skipped"),
        }
        match links.1 {
            Ok(()) => exercised.push("linked/secret.txt"),
            Err(error) => eprintln!("cannot create a directory symlink here ({error}); skipped"),
        }

        for relative in exercised {
            let outcome = admit_and_index_single_path(
                relative,
                &root.path().join(relative),
                &shared,
                shared.current_project_generation(),
            );
            assert!(
                matches!(outcome, ReindexOutcome::Skipped),
                "{relative} must be skipped like the cold walk skips it, got {outcome:?}"
            );
            assert!(
                shared.read().get_file(relative).is_none(),
                "{relative} was published through a symlink"
            );
        }
    }

    /// Detected at runtime rather than by `cfg`, so the case-alias checks run on
    /// every case-insensitive filesystem, including default macOS volumes.
    fn filesystem_is_case_insensitive(dir: &Path) -> bool {
        let probe = dir.join("case_probe.tmp");
        std::fs::write(&probe, b"").expect("case probe");
        let insensitive = dir.join("CASE_PROBE.TMP").exists();
        std::fs::remove_file(&probe).expect("remove case probe");
        insensitive
    }

    /// The embed facade takes a caller-supplied path, so it must refuse every
    /// spelling the server's entry points refuse: an escape, an absolute path,
    /// and another spelling of a file, which would index it under a second key.
    #[test]
    fn facade_refuses_paths_that_are_not_the_files_own_name_beneath_the_root() {
        let root = tempfile::TempDir::new().expect("root");
        let outside = tempfile::TempDir::new().expect("outside");
        std::fs::write(
            outside.path().join("secret.txt"),
            "placeholder-fixture-value\n",
        )
        .expect("outside file");
        std::fs::create_dir_all(root.path().join(".aws")).expect("aws dir");
        std::fs::write(
            root.path().join(".aws/credentials"),
            "placeholder-fixture-value\n",
        )
        .expect("credential fixture");
        std::fs::write(root.path().join("lib.rs"), "pub fn first() {}\n").expect("seed");
        std::fs::create_dir_all(root.path().join("src")).expect("src dir");
        std::fs::write(root.path().join("src/x.rs"), "pub fn x() {}\n").expect("src file");
        let shared = LiveIndex::load(root.path()).expect("cold load");

        let outside_name = outside
            .path()
            .file_name()
            .expect("tempdir name")
            .to_string_lossy()
            .into_owned();
        let mut refused = vec![
            format!("../{outside_name}/secret.txt"),
            outside
                .path()
                .join("secret.txt")
                .to_string_lossy()
                .into_owned(),
            ".aws/credentials.".to_string(),
            ".aws//credentials".to_string(),
            ".aws/./credentials".to_string(),
            "src/./x.rs".to_string(),
        ];
        if filesystem_is_case_insensitive(root.path()) {
            refused.push("LIB.RS".to_string());
        } else {
            eprintln!("case-sensitive filesystem; case alias skipped");
        }

        for spelling in refused {
            let result = update_file_from_disk(&shared, root.path(), &spelling);
            assert!(
                !matches!(result, ReindexResult::Reindexed | ReindexResult::HashSkip),
                "{spelling:?} was admitted: {result:?}"
            );
            let key = spelling.replace('\\', "/");
            assert!(
                shared.read().get_file(&key).is_none(),
                "{spelling:?} was published into the index"
            );
        }
    }

    /// A watcher event can carry a non-canonical spelling, such as an 8.3 short
    /// name. The single-path lane must not index the file under that key.
    #[test]
    fn single_path_admission_refuses_non_canonical_spellings() {
        let root = tempfile::TempDir::new().expect("root");
        std::fs::create_dir_all(root.path().join("src")).expect("src");
        std::fs::write(root.path().join("src/lib.rs"), "pub fn first() {}\n").expect("seed");
        std::fs::write(
            root.path().join("src/longer_module_name.rs"),
            "pub fn second() {}\n",
        )
        .expect("long name");
        let shared = LiveIndex::load(root.path()).expect("cold load");

        let mut aliases = Vec::new();
        if filesystem_is_case_insensitive(root.path()) {
            aliases.push("SRC/LIB.RS");
        } else {
            eprintln!("case-sensitive filesystem; case alias skipped");
        }
        if root.path().join("src/LONGER~1.RS").is_file() {
            aliases.push("src/LONGER~1.RS");
        } else {
            eprintln!("8.3 short names are not generated here; short-name alias skipped");
        }

        for alias in aliases {
            let outcome = admit_and_index_single_path(
                alias,
                &root.path().join(alias),
                &shared,
                shared.current_project_generation(),
            );
            assert!(
                matches!(outcome, ReindexOutcome::Skipped),
                "{alias} must be skipped, got {outcome:?}"
            );
            assert!(
                shared.read().get_file(alias).is_none(),
                "{alias} was published under a second key"
            );
        }
    }

    #[test]
    fn reindex_receipt_remains_exact_after_later_publication() {
        let dir = tempfile::TempDir::new().expect("root");
        let path = dir.path().join("lib.rs");
        std::fs::write(&path, "pub fn first() {}\n").expect("seed");
        let shared = LiveIndex::load(dir.path()).expect("cold load");
        let expected_gen = shared.current_project_generation();

        std::fs::write(&path, "pub fn second() {}\n").expect("first edit");
        let second =
            admit_and_index_single_path_with_receipt("lib.rs", &path, &shared, expected_gen);
        assert_eq!(second.outcome, ReindexOutcome::Reindexed);
        assert!(second.snapshot_created);
        let second_published = second.published.expect("second publication receipt");
        let second_fence = PublicationFence::from_published(&second_published);

        let unchanged =
            admit_and_index_single_path_with_receipt("lib.rs", &path, &shared, expected_gen);
        assert_eq!(unchanged.outcome, ReindexOutcome::HashSkip);
        assert!(!unchanged.snapshot_created);
        let unchanged_published = unchanged.published.expect("hash-skip publication receipt");
        assert!(
            unchanged_published
                .live
                .get_file("lib.rs")
                .expect("hash-skip file")
                .symbols
                .iter()
                .any(|symbol| symbol.name == "second")
        );

        std::fs::write(&path, "pub fn third() {}\n").expect("second edit");
        let third =
            admit_and_index_single_path_with_receipt("lib.rs", &path, &shared, expected_gen);
        assert_eq!(third.outcome, ReindexOutcome::Reindexed);
        let third_published = third.published.expect("third publication receipt");
        let third_fence = PublicationFence::from_published(&third_published);
        assert_ne!(second_fence, third_fence);

        let second_file = second_published
            .live
            .get_file("lib.rs")
            .expect("second file");
        assert!(
            second_file
                .symbols
                .iter()
                .any(|symbol| symbol.name == "second")
        );
        assert!(
            !second_file
                .symbols
                .iter()
                .any(|symbol| symbol.name == "third")
        );
        assert!(
            !unchanged_published
                .live
                .get_file("lib.rs")
                .expect("immutable hash-skip file")
                .symbols
                .iter()
                .any(|symbol| symbol.name == "third")
        );
        assert!(
            third_published
                .live
                .get_file("lib.rs")
                .expect("third file")
                .symbols
                .iter()
                .any(|symbol| symbol.name == "third")
        );

        assert!(
            shared
                .take_pre_update_snapshot_for_publication_at_generation(
                    "lib.rs",
                    expected_gen,
                    second_fence,
                )
                .is_none(),
            "the old receipt must not drain the later publication's snapshot"
        );
        let third_baseline = shared
            .take_pre_update_snapshot_for_publication_at_generation(
                "lib.rs",
                expected_gen,
                third_fence,
            )
            .expect("third publication owns the current snapshot");
        assert!(
            third_baseline
                .symbols
                .iter()
                .any(|symbol| symbol.name == "second")
        );
    }

    #[test]
    fn bridge_only_publication_does_not_invalidate_live_index_reindex_cas() {
        let dir = tempfile::TempDir::new().expect("root");
        let path = dir.path().join("lib.rs");
        std::fs::write(&path, "pub fn before() {}\n").expect("seed");
        let shared = LiveIndex::load(dir.path()).expect("cold load");
        let before = shared.published_generation();
        let health_generation = before.health.generation;

        let prepared = shared.prepare_bridge_rebuild();
        assert!(shared.publish_prepared_bridge(prepared));
        let bridge_only = shared.published_generation();
        assert!(
            bridge_only.publication_generation > before.publication_generation,
            "bridge publication must advance the full publication bundle"
        );
        assert_eq!(
            bridge_only.health.generation, health_generation,
            "bridge publication must retain the live-index health base"
        );

        std::fs::write(&path, "pub fn after() {}\n").expect("edit");
        let receipt = admit_and_index_single_path_with_receipt(
            "lib.rs",
            &path,
            &shared,
            shared.current_project_generation(),
        );
        assert_eq!(receipt.outcome, ReindexOutcome::Reindexed);
        assert!(
            receipt
                .published
                .expect("winning reindex publication")
                .live
                .get_file("lib.rs")
                .expect("reindexed file")
                .symbols
                .iter()
                .any(|symbol| symbol.name == "after")
        );
    }

    #[test]
    fn stale_not_found_fence_preserves_recreated_file_and_reports_rejection() {
        let dir = tempfile::TempDir::new().expect("root");
        let path = dir.path().join("lib.rs");
        std::fs::write(&path, "pub fn first() {}\n").expect("seed");
        let shared = LiveIndex::load(dir.path()).expect("cold load");

        std::fs::remove_file(&path).expect("simulate missing observation");
        let absence_fence = shared.publication_fence();

        std::fs::write(&path, "pub fn recreated() {}\n").expect("recreate");
        assert_eq!(
            finalize_missing_file(
                &shared,
                "lib.rs",
                &path,
                shared.current_project_generation(),
                absence_fence,
            ),
            ReindexOutcome::PublicationRejected,
            "a rejected stale removal must not claim the file was removed"
        );
        assert!(
            shared
                .read()
                .get_file("lib.rs")
                .expect("last-valid indexed file remains")
                .symbols
                .iter()
                .any(|symbol| symbol.name == "first")
        );
        assert!(
            std::fs::read_to_string(&path)
                .expect("recreated disk file")
                .contains("recreated")
        );
    }

    #[test]
    fn missing_file_finalization_ignores_unrelated_same_project_publication() {
        let dir = tempfile::TempDir::new().expect("root");
        let a_path = dir.path().join("a.rs");
        let b_path = dir.path().join("b.rs");
        std::fs::write(&a_path, "pub fn a_before() {}\n").expect("seed a");
        std::fs::write(&b_path, "pub fn b_before() {}\n").expect("seed b");
        let shared = LiveIndex::load(dir.path()).expect("cold load");
        let expected_gen = shared.current_project_generation();

        std::fs::remove_file(&a_path).expect("observe a missing");
        let absence_fence = shared.publication_fence();

        std::fs::write(&b_path, "pub fn b_after() {}\n").expect("edit b");
        let b_receipt =
            admit_and_index_single_path_with_receipt("b.rs", &b_path, &shared, expected_gen);
        assert_eq!(b_receipt.outcome, ReindexOutcome::Reindexed);
        let after_b = shared.publication_fence();
        assert_eq!(after_b.project_generation, absence_fence.project_generation);
        assert_ne!(
            after_b.publication_generation, absence_fence.publication_generation,
            "the regression requires an intervening unrelated publication"
        );

        assert_eq!(
            finalize_missing_file(&shared, "a.rs", &a_path, expected_gen, absence_fence,),
            ReindexOutcome::Removed,
            "an unrelated publication must not prevent convergence to disk absence"
        );
        let published = shared.published_generation();
        assert!(published.live.get_file("a.rs").is_none());
        assert!(
            published
                .live
                .get_file("b.rs")
                .expect("unrelated publication survives")
                .symbols
                .iter()
                .any(|symbol| symbol.name == "b_after")
        );
    }

    #[test]
    fn stale_project_generation_cannot_remove_from_rebound_project() {
        let project_a = tempfile::TempDir::new().expect("project A");
        let project_b = tempfile::TempDir::new().expect("project B");
        std::fs::write(project_a.path().join("lib.rs"), "pub fn a() {}\n").unwrap();
        std::fs::write(project_b.path().join("lib.rs"), "pub fn b() {}\n").unwrap();
        let shared = LiveIndex::load(project_a.path()).expect("load A");
        let stale_gen = shared.current_project_generation();
        shared.reload(project_b.path()).expect("rebind to B");
        let rebound_fence = shared.publication_fence();

        assert_eq!(
            finalize_missing_file(
                &shared,
                "lib.rs",
                &project_a.path().join("lib.rs"),
                stale_gen,
                rebound_fence,
            ),
            ReindexOutcome::PublicationRejected
        );
        assert!(
            shared
                .read()
                .get_file("lib.rs")
                .expect("B file survives stale absence finalization")
                .symbols
                .iter()
                .any(|symbol| symbol.name == "b")
        );

        let publication_before = shared.publication_fence();
        let excluded = read_and_index_with_receipt(
            ".git/config",
            &project_b.path().join(".git/config"),
            &shared,
            None::<LanguageId>,
            stale_gen,
        );
        assert_eq!(excluded.outcome, ReindexOutcome::PublicationRejected);
        assert_eq!(shared.publication_fence(), publication_before);
        assert!(shared.read().get_file("lib.rs").is_some());
    }

    #[test]
    fn outbound_link_freshen_skips_and_does_not_index_secret() {
        let dir = tempfile::TempDir::new().expect("repo");
        let plain_marker = "OUTBOUND_LINK_PLAIN_ok";
        std::fs::write(
            dir.path().join("plain.rs"),
            format!("fn plain() {{ let _ = \"{plain_marker}\"; }}\n"),
        )
        .expect("plain");
        let (_outside, link_path) = plant_outbound_secret(dir.path());
        let shared = LiveIndex::load(dir.path()).expect("load");
        let expected_gen = shared.current_project_generation();
        let authority =
            crate::live_index::index_lifecycle::activation::project_source_authority(dir.path());
        let outcome = freshen_file_if_stale(
            link_path,
            &dir.path().join(link_path),
            &shared,
            expected_gen,
            &authority,
            authority.active_observer(),
        );
        // Review H2: a path that resolves outside the repository is never
        // read and never reported fresh; it is not confirmed.
        assert!(
            matches!(outcome, FreshenResult::Unconfirmed(_)),
            "outbound path must skip reindex and stay unconfirmed"
        );
        assert!(
            shared.read().get_file(link_path).is_none()
                || shared.read().get_file(link_path).is_some_and(|file| {
                    !String::from_utf8_lossy(&file.content).contains(OUTBOUND_LINK_SECRET)
                }),
            "freshen must not index the outside secret"
        );

        let plain_abs = dir.path().join("plain.rs");
        let _ = freshen_file_if_stale(
            "plain.rs",
            &plain_abs,
            &shared,
            expected_gen,
            &authority,
            authority.active_observer(),
        );
        let guard = shared.read();
        let plain = guard.get_file("plain.rs").expect("plain indexed");
        assert!(
            String::from_utf8_lossy(&plain.content).contains(plain_marker),
            "ordinary file must remain readable"
        );
    }
}