symforge 8.16.2

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
2190
2191
2192
use std::collections::HashMap;
use std::fmt;

#[derive(
    Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
pub enum LanguageId {
    Rust,
    Python,
    JavaScript,
    TypeScript,
    Go,
    Java,
    C,
    Cpp,
    CSharp,
    Ruby,
    Php,
    Swift,
    Kotlin,
    Dart,
    Perl,
    Elixir,
    Json,
    Toml,
    Yaml,
    Markdown,
    Text,
    Env,
    Html,
    Css,
    Scss,
}

impl LanguageId {
    pub fn from_extension(ext: &str) -> Option<Self> {
        match ext.to_ascii_lowercase().as_str() {
            "rs" => Some(Self::Rust),
            "py" => Some(Self::Python),
            "js" | "jsx" => Some(Self::JavaScript),
            "ts" | "tsx" => Some(Self::TypeScript),
            "go" => Some(Self::Go),
            "java" => Some(Self::Java),
            "c" | "h" => Some(Self::C),
            "cpp" | "cxx" | "cc" | "hpp" | "hxx" | "hh" => Some(Self::Cpp),
            "cs" => Some(Self::CSharp),
            "rb" => Some(Self::Ruby),
            "php" => Some(Self::Php),
            "swift" => Some(Self::Swift),
            "dart" => Some(Self::Dart),
            "kt" | "kts" => Some(Self::Kotlin),
            "pl" | "pm" => Some(Self::Perl),
            "ex" | "exs" => Some(Self::Elixir),
            "json" => Some(Self::Json),
            "toml" => Some(Self::Toml),
            "yaml" | "yml" => Some(Self::Yaml),
            "md" | "mdx" => Some(Self::Markdown),
            "txt" | "text" | "rst" | "adoc" | "asciidoc" | "org" | "ini" | "conf"
            | "properties" | "xml" | "json5" => Some(Self::Text),
            "env" => Some(Self::Env),
            "html" => Some(Self::Html),
            "css" => Some(Self::Css),
            "scss" => Some(Self::Scss),
            _ => None,
        }
    }

    /// Detect an indexed language from the complete repository-relative path.
    ///
    /// Extensionless narrative entry points and dotfile configuration cannot be
    /// classified from [`Self::from_extension`] alone. Keeping that closed path
    /// matrix here gives cold discovery, watcher updates, reconciliation, and
    /// direct impact analysis one deterministic answer.
    pub fn from_path(relative_path: &str) -> Option<Self> {
        let basename = relative_path
            .rsplit(['/', '\\'])
            .next()
            .unwrap_or(relative_path)
            .to_ascii_lowercase();

        if basename == ".env" || basename.starts_with(".env.") {
            return Some(Self::Env);
        }
        if matches!(
            basename.as_str(),
            "readme"
                | "changelog"
                | "license"
                | "notice"
                | "agents"
                | "claude"
                | "contributing"
                | "security"
                | "governance"
                | ".gitignore"
                | ".gitattributes"
                | ".editorconfig"
        ) {
            return Some(Self::Text);
        }

        basename
            .rsplit_once('.')
            .and_then(|(_, extension)| Self::from_extension(extension))
    }

    /// True for programming languages (symbol-bearing code) as opposed to
    /// data/markup formats. Drives the higher metadata-only size threshold
    /// ([`METADATA_ONLY_CODE_BYTES`]): oversized machine-generated data files
    /// must stay Tier-2, but oversized first-party code is load-bearing.
    pub fn is_code_language(&self) -> bool {
        !matches!(
            self,
            Self::Json
                | Self::Toml
                | Self::Yaml
                | Self::Markdown
                | Self::Text
                | Self::Env
                | Self::Html
                | Self::Css
                | Self::Scss
        )
    }

    /// Returns `true` when `relative_path` is a TSX source file (`.tsx`).
    ///
    /// `.tsx` and `.ts` both map to [`LanguageId::TypeScript`], but they require
    /// different tree-sitter grammars: `.tsx` needs the TSX grammar (JSX-aware,
    /// rejects legacy `<T>expr` casts) while `.ts` needs the plain TypeScript
    /// grammar (no JSX, accepts angle-bracket casts). The grammar is therefore
    /// selected from the file extension, not the [`LanguageId`], so this helper
    /// threads the TSX flavor to the parse sites.
    pub fn is_tsx_path(relative_path: &str) -> bool {
        relative_path
            .rsplit(['/', '\\'])
            .next()
            .and_then(|name| name.rsplit_once('.'))
            .is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("tsx"))
    }

    /// Returns `true` when `relative_path` is a `.h` header file.
    ///
    /// `.h` maps to [`LanguageId::C`] by extension, but in cross-platform repos
    /// it routinely holds C++ (`class`/`namespace`/`::`) or Objective-C
    /// (`@interface`/`@property`) — none of which the C grammar can parse,
    /// causing total symbol loss (SF-STRESS-005). The grammar for a `.h` file is
    /// therefore disambiguated from CONTENT at parse time (see
    /// [`crate::parsing`]), not from the extension alone; this helper flags the
    /// `.h` extension so the parse site knows to apply that disambiguation.
    ///
    /// Unambiguous C++ header extensions (`.hpp`/`.hxx`/`.hh`) already map to
    /// [`LanguageId::Cpp`] and are NOT `.h`, so they are not flagged here.
    pub fn is_c_header_path(relative_path: &str) -> bool {
        relative_path
            .rsplit(['/', '\\'])
            .next()
            .and_then(|name| name.rsplit_once('.'))
            .is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("h"))
    }

    pub fn extensions(&self) -> &[&str] {
        match self {
            Self::Rust => &["rs"],
            Self::Python => &["py"],
            Self::JavaScript => &["js", "jsx"],
            Self::TypeScript => &["ts", "tsx"],
            Self::Go => &["go"],
            Self::Java => &["java"],
            Self::C => &["c", "h"],
            Self::Cpp => &["cpp", "cxx", "cc", "hpp", "hxx", "hh"],
            Self::CSharp => &["cs"],
            Self::Ruby => &["rb"],
            Self::Php => &["php"],
            Self::Swift => &["swift"],
            Self::Kotlin => &["kt", "kts"],
            Self::Dart => &["dart"],
            Self::Perl => &["pl", "pm"],
            Self::Elixir => &["ex", "exs"],
            Self::Json => &["json"],
            Self::Toml => &["toml"],
            Self::Yaml => &["yaml", "yml"],
            Self::Markdown => &["md", "mdx"],
            Self::Text => &[
                "txt",
                "text",
                "rst",
                "adoc",
                "asciidoc",
                "org",
                "ini",
                "conf",
                "properties",
                "xml",
                "json5",
            ],
            Self::Env => &["env"],
            Self::Html => &["html"],
            Self::Css => &["css"],
            Self::Scss => &["scss"],
        }
    }

    pub fn support_tier(&self) -> SupportTier {
        match self {
            Self::Rust | Self::Python | Self::JavaScript | Self::TypeScript | Self::Go => {
                SupportTier::QualityFocus
            }
            Self::Java
            | Self::C
            | Self::Cpp
            | Self::CSharp
            | Self::Ruby
            | Self::Php
            | Self::Swift
            | Self::Kotlin
            | Self::Dart
            | Self::Perl
            | Self::Elixir
            | Self::Json
            | Self::Toml
            | Self::Yaml
            | Self::Markdown
            | Self::Text
            | Self::Env
            | Self::Html
            | Self::Css
            | Self::Scss => SupportTier::Broader,
        }
    }
}

impl fmt::Display for LanguageId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            Self::Rust => "Rust",
            Self::Python => "Python",
            Self::JavaScript => "JavaScript",
            Self::TypeScript => "TypeScript",
            Self::Go => "Go",
            Self::Java => "Java",
            Self::C => "C",
            Self::Cpp => "C++",
            Self::CSharp => "C#",
            Self::Ruby => "Ruby",
            Self::Php => "PHP",
            Self::Swift => "Swift",
            Self::Kotlin => "Kotlin",
            Self::Dart => "Dart",
            Self::Perl => "Perl",
            Self::Elixir => "Elixir",
            Self::Json => "JSON",
            Self::Toml => "TOML",
            Self::Yaml => "YAML",
            Self::Markdown => "Markdown",
            Self::Text => "Text",
            Self::Env => "Env",
            Self::Html => "HTML",
            Self::Css => "CSS",
            Self::Scss => "SCSS",
        };
        write!(f, "{name}")
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SupportTier {
    QualityFocus,
    Broader,
    Unsupported,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum FileClass {
    Code,
    Text,
    Binary,
}

/// Canonical path-segment source of truth for noise classification, shared by
/// [`FileClassification::for_code_path`] (gates search_symbols/search_text) and
/// `NoiseClass::classify_path` (gates explore/repo_map/search_files) so the two
/// classifiers cannot diverge (SF-STRESS-011). A segment is a single
/// `/`-delimited path component, already lowercased.
///
/// Vendored / third-party dependency roots. `deps` and `extern`/`externals`
/// added per SF-STRESS-011 corpus evidence (redis `deps/`, node `deps/`).
pub const VENDOR_PATH_SEGMENTS: &[&str] = &[
    "vendor",
    "third_party",
    "third-party",
    "node_modules",
    ".venv",
    "venv",
    "site-packages",
    "pods",
    "bower_components",
    "deps",
    "extern",
    "externals",
];

/// Build-output / machine-generated directory roots. `dist` is shared here so
/// `FileClassification` agrees with `NoiseClass` (previously `dist` lived only
/// in `NoiseClass`, causing the laravel `dist/` divergence in SF-STRESS-011).
pub const GENERATED_PATH_SEGMENTS: &[&str] =
    &["dist", "generated", "__generated__", "generated-sources"];

/// Test-directory roots. `test_data`/`testdata`/`fixtures`/`__fixtures__`/
/// `__snapshots__` added per SF-STRESS-011 (rust-analyzer `test_data` fixtures,
/// snapshot trees) and SF-STRESS-009 (test-fixture bucket).
pub const TEST_PATH_SEGMENTS: &[&str] = &[
    "tests",
    "test",
    "__tests__",
    "spec",
    "test_data",
    "testdata",
    "fixtures",
    "__fixtures__",
    "__snapshots__",
];

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct FileClassification {
    pub class: FileClass,
    pub is_generated: bool,
    pub is_test: bool,
    pub is_vendor: bool,
    #[serde(default)]
    pub is_config: bool,
}

impl FileClassification {
    pub fn for_code_path(relative_path: &str) -> Self {
        let lower = relative_path.replace('\\', "/").to_ascii_lowercase();
        let segments: Vec<&str> = lower
            .split('/')
            .filter(|segment| !segment.is_empty())
            .collect();
        let basename = segments.last().copied().unwrap_or("");
        let stem = basename
            .rsplit_once('.')
            .map(|(name, _)| name)
            .unwrap_or(basename);

        let is_test = segments
            .iter()
            .any(|segment| TEST_PATH_SEGMENTS.contains(segment))
            || stem.starts_with("test_")
            || stem.ends_with("_test")
            || stem.ends_with(".test")
            || stem.ends_with("_spec")
            || stem.ends_with(".spec");

        let is_vendor = segments
            .iter()
            .any(|segment| VENDOR_PATH_SEGMENTS.contains(segment));

        let is_generated = segments
            .iter()
            .any(|segment| GENERATED_PATH_SEGMENTS.contains(segment))
            || basename.contains(".generated.")
            || basename.contains(".gen.")
            || basename.ends_with(".g.dart")
            || basename.ends_with(".pb.go")
            || basename.ends_with(".designer.cs")
            || basename.ends_with(".min.js")
            || basename.ends_with(".min.css")
            || basename.ends_with(".map");

        let ext = basename.rsplit_once('.').map(|(_, e)| e).unwrap_or("");
        let is_config = matches!(ext, "json" | "toml" | "yaml" | "yml" | "md" | "env");

        Self {
            class: FileClass::Code,
            is_generated,
            is_test,
            is_vendor,
            is_config,
        }
    }

    /// Classify one admitted path while keeping ingest routing in
    /// [`IndexTargets`]. Knowledge-only prose is descriptive text; overlapping
    /// configuration remains code-shaped and is marked as configuration.
    pub fn for_indexed_path(relative_path: &str, targets: IndexTargets) -> Self {
        let mut classification = Self::for_code_path(relative_path);
        classification.class = if matches!(targets, IndexTargets::Knowledge) {
            FileClass::Text
        } else {
            FileClass::Code
        };
        classification.is_config = matches!(targets, IndexTargets::CodeAndKnowledge);
        classification
    }

    pub const fn is_code(&self) -> bool {
        matches!(self.class, FileClass::Code)
    }

    pub const fn is_text(&self) -> bool {
        matches!(self.class, FileClass::Text)
    }

    pub const fn is_binary(&self) -> bool {
        matches!(self.class, FileClass::Binary)
    }
}

/// Stable identity for one canonical source root.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct ProjectId(pub String);

/// Stable identity shared by all sources from one logical repository.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct RepositoryId(String);

impl RepositoryId {
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Stable identity for one worktree or immutable repository source.
#[derive(
    Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
#[serde(transparent)]
pub struct SourceId(String);

impl SourceId {
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum SourceLocation {
    WorkingTree { worktree_id: String },
    GitRef { name: String },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum WorkingTreeState {
    Clean,
    Dirty,
    NotApplicable,
    Unknown,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct SourceVersion {
    pub branch: Option<String>,
    pub commit: Option<String>,
    pub working_tree: WorkingTreeState,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct SourceIdentity {
    pub repository_id: RepositoryId,
    pub source_id: SourceId,
    pub location: SourceLocation,
}

/// Captured repository state used to prove that persisted derived state still
/// belongs to the same source and source version.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum RepositoryFingerprint {
    Git {
        object_format: String,
        selected_ref_or_head: String,
        tip_object_id: String,
        reachable_history_fingerprint: String,
    },
    NonGit {
        catalog_identity_digest: String,
    },
}

/// Strong snapshot binding. `ProjectId` selects storage; the remaining fields
/// prove repository/source identity and the exact derived state captured there.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct SnapshotSourceIdentity {
    pub project_id: ProjectId,
    pub repository_id: RepositoryId,
    pub source_id: SourceId,
    pub source_version: SourceVersion,
    pub repository_fingerprint: RepositoryFingerprint,
    pub manifest_digest: String,
    pub indexed_content_digest: String,
}

/// Per-source provenance attached to every externally formatted repository
/// result. It is projected from one captured published generation.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct SourceResponseEnvelope {
    pub source: SourceIdentity,
    pub source_version: SourceVersion,
    pub publication_generation: u64,
    pub content_generation: u64,
    pub freshness: FreshnessStatus,
    pub manifest_digest: String,
    pub coverage: CoverageStatus,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum RootCandidateSource {
    WorkspaceEnvironment,
    McpClientRoot,
    GitAncestor,
    LaunchCwd,
    ExplicitIndexFolder,
    InitCwd,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum RootRequestMode {
    Automatic,
    Init,
    ExplicitIndexFolder { allow_protected_root: bool },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum RootClass {
    Normal,
    Protected,
    NeverIndexable,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum RootRefusalReason {
    FilesystemOrDriveRoot,
    HomeOrProfileRoot,
    OsOrSensitiveTree,
    BroadContainer,
    SymlinkAliasToForbiddenRoot,
    MissingOrNotDirectory,
    CanonicalizationFailed,
    DeviceOrSpecialNamespace,
    ProtectedRootRequiresExplicitOverride,
}

impl RootRefusalReason {
    pub const fn code(self) -> &'static str {
        match self {
            Self::FilesystemOrDriveRoot => "filesystem_or_drive_root",
            Self::HomeOrProfileRoot => "home_or_profile_root",
            Self::OsOrSensitiveTree => "os_or_sensitive_tree",
            Self::BroadContainer => "broad_container",
            Self::SymlinkAliasToForbiddenRoot => "symlink_alias_to_forbidden_root",
            Self::MissingOrNotDirectory => "missing_or_not_directory",
            Self::CanonicalizationFailed => "canonicalization_failed",
            Self::DeviceOrSpecialNamespace => "device_or_special_namespace",
            Self::ProtectedRootRequiresExplicitOverride => {
                "protected_root_requires_explicit_override"
            }
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum UnboundReason {
    NoCandidateDeclared,
    Refused(RootRefusalReason),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum SourceAccessMode {
    NormalProject,
    ExplicitProtected,
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct RootBinding {
    pub source: RootCandidateSource,
    pub canonical_root: std::path::PathBuf,
    pub root_id: ProjectId,
    pub access_mode: SourceAccessMode,
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum RootResolution {
    Bound(RootBinding),
    Unbound {
        rejected_source: Option<RootCandidateSource>,
        reason: UnboundReason,
        safe_path_id: Option<String>,
    },
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct ProjectStateDir(std::path::PathBuf);

impl ProjectStateDir {
    #[must_use]
    pub fn new(path: std::path::PathBuf) -> Self {
        assert!(
            path.is_absolute(),
            "project state directory must be absolute"
        );
        Self(path)
    }

    pub fn as_path(&self) -> &std::path::Path {
        &self.0
    }
}

/// Private process-global coordination state, resolved independently from any
/// repository binding.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct ControlStateDir(std::path::PathBuf);

impl ControlStateDir {
    #[must_use]
    pub fn new(path: std::path::PathBuf) -> Self {
        assert!(
            path.is_absolute(),
            "control state directory must be absolute"
        );
        Self(path)
    }

    pub fn as_path(&self) -> &std::path::Path {
        &self.0
    }
}

/// Placement for process-global transport, daemon, and replay coordination.
///
/// This lane is deliberately incapable of naming a repository or launch-CWD
/// directory when durable user-local state is unavailable.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ControlStatePlacement {
    UserLocal { directory: ControlStateDir },
    ProcessLocal { safe_reason: AccessErrorKind },
}

impl ControlStatePlacement {
    #[must_use]
    pub fn directory(&self) -> Option<&ControlStateDir> {
        match self {
            Self::UserLocal { directory } => Some(directory),
            Self::ProcessLocal { .. } => None,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum CapabilityUnavailableReason {
    ExplicitProtectedSource,
    SourceReadOnly,
    PersistentStateUnavailable,
    DurableMutationReplayUnavailable,
    NonProjectLocalPlacement,
    AtomicDurabilityUnavailable,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum CapabilityStatus {
    Available,
    Unavailable { reason: CapabilityUnavailableReason },
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ProjectCapabilities {
    pub persistent_snapshots: CapabilityStatus,
    pub checkpoint: CapabilityStatus,
    pub structural_edits: CapabilityStatus,
    pub repository_init: CapabilityStatus,
    pub repository_curation: CapabilityStatus,
    pub team_artifact_export: CapabilityStatus,
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum StatePlacement {
    ProjectLocal {
        directory: ProjectStateDir,
    },
    UserLocal {
        directory: ProjectStateDir,
        root_id: ProjectId,
        reason: UserLocalPlacementReason,
    },
    MemoryOnly {
        failures: Vec<StateFailure>,
    },
}

impl StatePlacement {
    #[must_use]
    pub fn directory(&self) -> Option<&ProjectStateDir> {
        match self {
            Self::ProjectLocal { directory } | Self::UserLocal { directory, .. } => Some(directory),
            Self::MemoryOnly { .. } => None,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum UserLocalPlacementReason {
    ExplicitProtected,
    ProjectLocalUnavailable { safe_reason: AccessErrorKind },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum StateLocationKind {
    ProjectLocal,
    UserLocal,
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct StateFailure {
    pub location: StateLocationKind,
    pub safe_reason: AccessErrorKind,
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum GitignoreHygiene {
    Effective,
    MissingRule,
    NoRootGitignore,
    Unverifiable { safe_reason: AccessErrorKind },
    NotApplicableExplicitProtected,
}

/// Lossless public identity for one repository-relative catalog path.
#[derive(
    Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
pub struct CatalogPath {
    pub public_id: String,
    pub normalized_utf8: Option<String>,
}

/// Non-empty indexing target selected by the metadata-first scout.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum IndexTargets {
    Code,
    Knowledge,
    CodeAndKnowledge,
}

impl IndexTargets {
    /// Determine the non-empty ingest lane set for one safe textual path.
    pub fn for_path(relative_path: &str, language: Option<&LanguageId>) -> Self {
        match language {
            Some(LanguageId::Markdown) => Self::Knowledge,
            Some(LanguageId::Json | LanguageId::Toml | LanguageId::Yaml | LanguageId::Env) => {
                Self::CodeAndKnowledge
            }
            Some(LanguageId::Text) if is_dual_target_text_path(relative_path) => {
                Self::CodeAndKnowledge
            }
            Some(LanguageId::Text) | None => Self::Knowledge,
            Some(_) => Self::Code,
        }
    }

    pub const fn includes_code(self) -> bool {
        matches!(self, Self::Code | Self::CodeAndKnowledge)
    }

    pub const fn includes_knowledge(self) -> bool {
        matches!(self, Self::Knowledge | Self::CodeAndKnowledge)
    }
}

fn is_dual_target_text_path(relative_path: &str) -> bool {
    let basename = relative_path
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or(relative_path)
        .to_ascii_lowercase();
    let extension = basename.rsplit_once('.').map(|(_, ext)| ext);
    matches!(
        extension,
        Some("ini" | "conf" | "properties" | "xml" | "json5")
    ) || matches!(
        basename.as_str(),
        ".gitignore" | ".gitattributes" | ".editorconfig" | "dockerfile"
    )
}

/// Private host file identity used only as a race/change hint.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PlatformFileId(Vec<u8>);

/// Metadata captured before any file payload is read.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileStamp {
    pub size: u64,
    pub created_hint: Option<std::time::SystemTime>,
    pub modified_hint: Option<std::time::SystemTime>,
    pub platform_id: Option<PlatformFileId>,
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum MetadataOnlyReason {
    Lockfile,
    Binary,
    OversizedData,
    GeneratedOrVendor,
    SensitivePath {
        rule_id: String,
    },
    SensitiveContent {
        rule_ids: Vec<String>,
        finding_count: u32,
    },
    LfsPointer {
        declared_oid: Option<String>,
        declared_size: Option<u64>,
    },
    PlatformPathCollision,
    UnsupportedPathEncoding,
    PathMetadataTooLarge,
    UnsupportedTextEncoding,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum HardSkipReason {
    ArtifactType,
    PerFileCeiling,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum AccessStage {
    Metadata,
    Probe,
    FullRead,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum AccessErrorKind {
    NotFound,
    PermissionDenied,
    InvalidData,
    ResourceExhausted,
    Other,
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ScoutDecision {
    Ingest {
        targets: IndexTargets,
    },
    MetadataOnly {
        reason: MetadataOnlyReason,
    },
    HardSkip {
        reason: HardSkipReason,
    },
    Unavailable {
        stage: AccessStage,
        kind: AccessErrorKind,
    },
}

/// One successfully metadata-observed path in the immutable scout plan.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ScoutedEntry {
    pub path: CatalogPath,
    pub absolute_path: Option<std::path::PathBuf>,
    pub stamp: FileStamp,
    pub language: Option<LanguageId>,
    pub classification: FileClassification,
    pub decision: ScoutDecision,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum CoverageStatus {
    Complete,
    Degraded,
}

/// Whether the published repository view reflects the latest accepted observation.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum FreshnessStatus {
    Current,
    Verifying,
    Degraded {
        last_valid_content_generation: u64,
        reason_codes: Vec<FreshnessReason>,
    },
}

/// Stable reason codes for a non-current repository view.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum FreshnessReason {
    ObservationFailed,
    WatcherUnavailable,
    ReconciliationPending,
    SnapshotVerificationFailed,
    DerivedPublicationPending,
    CatalogEntryCapacityExceeded,
    CatalogMetadataCapacityExceeded,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum HistoryLimit {
    Shallow,
    WindowLimited,
    RenameFollowLimited,
    DivergentHistory,
    WorkingTreeOnly,
    Unavailable,
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct HistoryCoverage {
    pub complete_to_root: bool,
    pub limitations: Vec<HistoryLimit>,
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ScoutIssueKind {
    DirectoryEntryUnreadable { kind: AccessErrorKind },
    ScopeEscape,
    UnsupportedSpecialFile,
    PathIdentityCollision,
    TraversalCircuitBreaker,
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ScoutIssue {
    pub path_id: Option<String>,
    pub safe_path: Option<String>,
    pub kind: ScoutIssueKind,
    pub safe_message: String,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ManifestResourceUsage {
    pub catalog_entries: u64,
    pub catalog_metadata_bytes: u64,
    pub admitted_content_bytes: u64,
}

/// Canonical, bounded aggregate status stored in a repository manifest.
///
/// Free-text parser and extractor diagnostics remain operational state and are
/// intentionally absent from this type.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ParseStatus {
    Parsed,
    PartialParse,
    Failed,
}

impl ParseStatus {
    /// Collapse the existing operational outcome while discarding diagnostic text.
    pub fn from_operational_outcome(outcome: &FileOutcome) -> Self {
        match outcome {
            FileOutcome::Processed => Self::Parsed,
            FileOutcome::PartialParse { .. } => Self::PartialParse,
            FileOutcome::Failed { .. } => Self::Failed,
        }
    }

    /// Aggregate only the processors selected by `targets`.
    ///
    /// A knowledge-only entry therefore derives its status solely from the
    /// knowledge extractor; an incidental or synthetic code status is ignored.
    pub fn aggregate_for_targets(
        targets: IndexTargets,
        code: Option<Self>,
        knowledge: Option<Self>,
    ) -> Self {
        let selected = match targets {
            IndexTargets::Code => return code.unwrap_or(Self::Failed),
            IndexTargets::Knowledge => return knowledge.unwrap_or(Self::Failed),
            IndexTargets::CodeAndKnowledge => [
                code.unwrap_or(Self::Failed),
                knowledge.unwrap_or(Self::Failed),
            ],
        };

        if selected.iter().all(|status| *status == Self::Parsed) {
            Self::Parsed
        } else if selected.iter().all(|status| *status == Self::Failed) {
            Self::Failed
        } else {
            Self::PartialParse
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum FileDisposition {
    Indexed {
        targets: IndexTargets,
        parse_status: ParseStatus,
    },
    MetadataOnly {
        reason: MetadataOnlyReason,
    },
    HardSkip {
        reason: HardSkipReason,
    },
    Unreadable {
        stage: AccessStage,
        kind: AccessErrorKind,
    },
    UnstableDuringRead,
    AbortedCircuitBreaker,
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct CatalogEntry {
    pub path: CatalogPath,
    pub size: u64,
    pub language: Option<LanguageId>,
    pub classification: FileClassification,
    pub disposition: FileDisposition,
    pub content_hash: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct RepositoryManifest {
    pub schema_version: u32,
    pub policy_version: u32,
    pub secret_policy_version: u32,
    pub source: SourceIdentity,
    pub source_version: SourceVersion,
    pub coverage: CoverageStatus,
    pub entries: Vec<CatalogEntry>,
    pub issues: Vec<ScoutIssue>,
    pub usage: ManifestResourceUsage,
    pub digest: String,
}

impl RepositoryManifest {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        schema_version: u32,
        policy_version: u32,
        secret_policy_version: u32,
        source: SourceIdentity,
        source_version: SourceVersion,
        coverage: CoverageStatus,
        mut entries: Vec<CatalogEntry>,
        mut issues: Vec<ScoutIssue>,
        usage: ManifestResourceUsage,
    ) -> Result<Self, serde_json::Error> {
        entries.sort_by_cached_key(|entry| match entry.path.normalized_utf8.as_deref() {
            Some(path) => (0_u8, path.to_lowercase(), path.to_string()),
            None => (1_u8, entry.path.public_id.clone(), String::new()),
        });
        issues.sort_by_cached_key(|issue| match issue.safe_path.as_deref() {
            Some(path) => (0_u8, path.to_lowercase(), path.to_string()),
            None => (
                1_u8,
                issue.path_id.clone().unwrap_or_default(),
                String::new(),
            ),
        });

        let digest = Self::compute_digest(
            schema_version,
            policy_version,
            secret_policy_version,
            &source,
            &entries,
        )?;

        Ok(Self {
            schema_version,
            policy_version,
            secret_policy_version,
            source,
            source_version,
            coverage,
            entries,
            issues,
            usage,
            digest,
        })
    }

    fn compute_digest(
        schema_version: u32,
        policy_version: u32,
        secret_policy_version: u32,
        source: &SourceIdentity,
        entries: &[CatalogEntry],
    ) -> Result<String, serde_json::Error> {
        #[derive(serde::Serialize)]
        struct CanonicalManifestDigest<'a> {
            schema_version: u32,
            policy_version: u32,
            secret_policy_version: u32,
            source: &'a SourceIdentity,
            entries: &'a [CatalogEntry],
        }

        let canonical = serde_json::to_vec(&CanonicalManifestDigest {
            schema_version,
            policy_version,
            secret_policy_version,
            source,
            entries,
        })?;
        Ok(crate::hash::digest_hex(&canonical))
    }
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ParseDiagnostic {
    pub parser: String,
    pub message: String,
    pub line: Option<u32>,
    pub column: Option<u32>,
    pub byte_span: Option<(u32, u32)>,
    pub fallback_used: bool,
}

impl ParseDiagnostic {
    pub fn location_display(&self) -> Option<String> {
        match (self.line, self.column) {
            (Some(line), Some(column)) => Some(format!("line {line}, column {column}")),
            (Some(line), None) => Some(format!("line {line}")),
            (None, Some(column)) => Some(format!("column {column}")),
            (None, None) => None,
        }
    }

    pub fn summary(&self) -> String {
        let mut summary = format!("{}: {}", self.parser, self.message);
        if let Some(location) = self.location_display() {
            summary.push_str(&format!(" ({location})"));
        }
        if self.fallback_used {
            summary.push_str(" [fallback symbol extraction used]");
        }
        summary
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileProcessingResult {
    pub relative_path: String,
    pub language: LanguageId,
    pub classification: FileClassification,
    pub outcome: FileOutcome,
    pub parse_diagnostic: Option<ParseDiagnostic>,
    pub symbols: Vec<SymbolRecord>,
    pub byte_len: u64,
    pub content_hash: String,
    /// Cross-references extracted by `parsing::xref::extract_references`.
    /// Empty until Task 2 wires xref extraction into the parse pipeline.
    pub references: Vec<ReferenceRecord>,
    /// Import alias map for this file: alias -> original name (e.g. "Map" -> "HashMap").
    pub alias_map: HashMap<String, String>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FileOutcome {
    Processed,
    PartialParse { warning: String },
    Failed { error: String },
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct SymbolRecord {
    pub name: String,
    pub kind: SymbolKind,
    pub depth: u32,
    pub sort_order: u32,
    pub byte_range: (u32, u32),
    pub line_range: (u32, u32),
    pub doc_byte_range: Option<(u32, u32)>,
    #[serde(default)]
    pub item_byte_range: Option<(u32, u32)>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum KnowledgeUnitKind {
    MarkdownSection,
    TextLine,
}

/// Ephemeral knowledge projection over canonical indexed bytes and symbol spans.
/// LiveIndex persists neither this value nor a second copy of source content.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct KnowledgeUnit {
    pub source: SourceIdentity,
    pub path: String,
    pub content_hash: String,
    pub kind: KnowledgeUnitKind,
    pub heading_path: Vec<String>,
    pub byte_range: std::ops::Range<u32>,
    pub line_range: std::ops::Range<u32>,
    pub parent: Option<u32>,
}

impl SymbolRecord {
    /// Returns the start byte of the full editable item when available.
    pub fn item_start(&self) -> u32 {
        self.item_byte_range.map_or_else(
            || {
                self.doc_byte_range
                    .map_or(self.byte_range.0, |(start, _)| start)
            },
            |(start, _)| start,
        )
    }

    /// Returns the end byte of the full editable item when available.
    pub fn item_end(&self) -> u32 {
        self.item_byte_range
            .map_or(self.byte_range.1, |(_, end)| end)
    }

    /// Returns the full editable item range when available.
    pub fn item_range(&self) -> (u32, u32) {
        (self.item_start(), self.item_end())
    }

    /// Returns the parser's core symbol node range.
    pub fn core_range(&self) -> (u32, u32) {
        self.byte_range
    }

    /// Returns the effective start byte, including doc comments if present.
    pub fn effective_start(&self) -> u32 {
        self.doc_byte_range
            .map_or(self.byte_range.0, |(start, _)| start)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum SymbolKind {
    Function,
    Method,
    Class,
    Struct,
    Enum,
    Interface,
    Module,
    Constant,
    Variable,
    Type,
    Trait,
    Impl,
    Other,
    Key,
    Section,
    /// A name declared by a module-level macro invocation (e.g.
    /// `define_id_type!(ProjectId)`). The definition is synthesized at compile
    /// time, so the index has the NAME but not the generated body — dogfood
    /// finding #3 (2026-07-06): these were invisible to search_symbols.
    MacroGenerated,
}

impl fmt::Display for SymbolKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let prefix = match self {
            Self::Function => "fn",
            Self::Method => "fn",
            Self::Class => "class",
            Self::Struct => "struct",
            Self::Enum => "enum",
            Self::Interface => "interface",
            Self::Module => "mod",
            Self::Constant => "const",
            Self::Variable => "let",
            Self::Type => "type",
            Self::Trait => "trait",
            Self::Impl => "impl",
            Self::Other => "other",
            Self::Key => "key",
            Self::Section => "section",
            Self::MacroGenerated => "macro-generated",
        };
        write!(f, "{prefix}")
    }
}

/// A single cross-reference (call site, import, type usage, or macro use) extracted
/// from a source file. Part of the Phase 4 cross-reference pipeline.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ReferenceRecord {
    /// Simple name at the reference site (e.g. "new", "process", "HashMap").
    pub name: String,
    /// Best-effort qualified name when available (e.g. "Vec::new", "fmt.Println").
    pub qualified_name: Option<String>,
    /// What kind of reference this is.
    pub kind: ReferenceKind,
    /// Byte range in the source file (start, end).
    pub byte_range: (u32, u32),
    /// Line range in the source file (start, end — zero-indexed).
    pub line_range: (u32, u32),
    /// Index into the file's symbol list for the innermost containing definition.
    /// `None` means the reference is at module/top level.
    pub enclosing_symbol_index: Option<u32>,
}

/// Discriminates the semantic role of a cross-reference.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ReferenceKind {
    /// A function or method call site.
    Call,
    /// An import/use/require statement.
    Import,
    /// A type annotation, generic parameter, or other type usage.
    TypeUsage,
    /// A macro invocation.
    MacroUse,
    /// A trait/interface implementation relationship.
    /// `name` holds the trait/interface name, `qualified_name` holds the implementing type.
    Implements,
    /// A read of a named `const`/`static` value at a value-expression site
    /// (e.g. iterated in a `for` loop, used as a receiver, or passed as a bare
    /// argument). Distinct from `Call` so callee/type analysis stays clean.
    ValueUse,
}

impl fmt::Display for ReferenceKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Self::Call => "call",
            Self::Import => "import",
            Self::TypeUsage => "type_usage",
            Self::MacroUse => "macro_use",
            Self::Implements => "implements",
            Self::ValueUse => "value_use",
        };
        write!(f, "{s}")
    }
}

/// Returns the index of the innermost `SymbolRecord` whose `line_range` contains
/// `ref_line`, or `None` if the reference is at module level.
///
/// "Innermost" is defined as the symbol with the latest `line_range.0` (start line)
/// that still contains `ref_line`. This handles nested function definitions correctly.
pub fn find_enclosing_symbol(symbols: &[SymbolRecord], ref_line: u32) -> Option<u32> {
    let mut best: Option<(u32, u32)> = None; // (start_line, index)
    for (idx, sym) in symbols.iter().enumerate() {
        let (start, end) = sym.line_range;
        if ref_line >= start && ref_line <= end {
            match best {
                None => best = Some((start, idx as u32)),
                Some((best_start, _)) if start > best_start => best = Some((start, idx as u32)),
                _ => {}
            }
        }
    }
    best.map(|(_, idx)| idx)
}

/// Admission tier — whether a file is eligible for indexing/parsing at all.
/// Separate from NoiseClass (which is about ranking/filtering signal).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AdmissionTier {
    /// Tier 1: Fully indexed — parsed, symbols extracted, text searchable.
    Normal,
    /// Tier 2: Metadata only — path, size, classification stored. No parsing.
    MetadataOnly,
    /// Tier 3: Hard-skipped — counted in health, minimal registration.
    HardSkip,
}

/// Reason a file was placed in Tier 2 or Tier 3.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SkipReason {
    SizeCeiling,
    DenylistedExtension,
    SizeThreshold,
    BinaryContent,
    /// File is a dependency lockfile (e.g. `package-lock.json`, `Cargo.lock`).
    /// Demoted to Tier-2 metadata-only so its machine-generated content does not
    /// flood the index with thousands of junk key/value symbols (a single
    /// `package-lock.json` can mint ~9k JSON-key symbols, dominating symbol counts
    /// and `conventions` complexity heuristics). The path stays searchable as
    /// metadata; only symbol extraction is skipped. See `LOCKFILE_BASENAMES`.
    DependencyLockfile,
    /// SF-009: file demoted to Tier-2 because it is not git-tracked, under the
    /// opt-in `SYMFORGE_EXCLUDE_UNTRACKED` policy (default OFF). Only minted when
    /// that env gate is explicitly enabled; the default admission path never
    /// produces this reason, so admission defaults are unchanged.
    Untracked,
    /// SF-004 / SF-012: file exists on disk and is small/non-binary, but its
    /// extension maps to no supported tree-sitter grammar (e.g. `.tcl`, `.sh`,
    /// `.m`, `.eex`, extensionless `LICENSE`/`Makefile`). It cannot be parsed, so
    /// it is admitted Tier-2 metadata-only instead of being stored with a
    /// contradictory Tier-1/Normal decision (which made it vanish from tier
    /// accounting and minted a false "File not found"). The path stays searchable
    /// as metadata; only symbol extraction is skipped.
    UnsupportedLanguage,
    /// F5: file demoted to Tier-2 because it lives under an untracked
    /// generated-output directory (`dist`, `build`, `out`, `cache`, `*-out`, …)
    /// with no git-tracked file anywhere beneath it. Such dirs are
    /// machine-generated corpora (JSON cache dumps, build artifacts) that can
    /// dominate the symbol index. Tracked files are never demoted by this
    /// policy, and `SYMFORGE_INDEX_GENERATED_OUTPUT=1` opts back into full
    /// indexing. Non-git trees are unaffected (fail open: admit).
    GeneratedOutput,
}

impl std::fmt::Display for SkipReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SkipReason::SizeCeiling => write!(f, ">100MB"),
            SkipReason::DenylistedExtension => write!(f, "artifact"),
            SkipReason::SizeThreshold => write!(f, "over size threshold (1MB data / 4MB code)"),
            SkipReason::BinaryContent => write!(f, "binary"),
            SkipReason::DependencyLockfile => write!(f, "lockfile"),
            SkipReason::Untracked => write!(f, "untracked"),
            SkipReason::UnsupportedLanguage => write!(f, "unsupported language"),
            SkipReason::GeneratedOutput => write!(
                f,
                "untracked generated output (SYMFORGE_INDEX_GENERATED_OUTPUT=1 to index)"
            ),
        }
    }
}

/// Structured result from the admission gate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AdmissionDecision {
    pub tier: AdmissionTier,
    pub reason: Option<SkipReason>,
}

impl AdmissionDecision {
    pub fn normal() -> Self {
        Self {
            tier: AdmissionTier::Normal,
            reason: None,
        }
    }
    pub fn skip(tier: AdmissionTier, reason: SkipReason) -> Self {
        Self {
            tier,
            reason: Some(reason),
        }
    }
}

/// Metadata record for a file that was not fully indexed (Tier 2 or Tier 3).
/// Stores the AdmissionDecision directly — no re-derivation downstream.
#[derive(Debug, Clone)]
pub struct SkippedFile {
    pub path: String,
    pub size: u64,
    pub extension: Option<String>,
    pub decision: AdmissionDecision,
}

impl SkippedFile {
    pub fn tier(&self) -> AdmissionTier {
        self.decision.tier
    }
    pub fn reason(&self) -> Option<SkipReason> {
        self.decision.reason
    }
}

pub const HARD_SKIP_BYTES: u64 = 100 * 1024 * 1024;
pub const METADATA_ONLY_BYTES: u64 = 1024 * 1024;
/// Higher metadata-only threshold for CODE languages (dogfood #1/#7,
/// 2026-07-06): >1MB machine-generated JSON/YAML must stay Tier-2 (symbol
/// pollution), but >1MB first-party code is load-bearing in real repos — a
/// 1.2MB Rust module held the only construction site of a queried type, and
/// symforge's own `src/protocol/tools.rs` crossed 1MB. Tree-sitter parses
/// multi-MB source in milliseconds, so code gets 4MB before demotion.
pub const METADATA_ONLY_CODE_BYTES: u64 = 4 * 1024 * 1024;
pub const BINARY_SNIFF_BYTES: usize = 8192;

const DENYLISTED_EXTENSIONS: &[&str] = &[
    // ML models
    "safetensors",
    "ckpt",
    "pt",
    "onnx",
    "gguf",
    "pth",
    // VM/disk images
    "vmdk",
    "iso",
    "img",
    "qcow2",
    // Archives
    "tar",
    "gz",
    "zip",
    "7z",
    "rar",
    "bz2",
    "xz",
    "zst",
    // Databases
    "db",
    "sqlite",
    "sqlite3",
    "mdb",
    // Media
    "mp3",
    "mp4",
    "wav",
    "avi",
    "mov",
    "mkv",
    "png",
    "jpg",
    "jpeg",
    "gif",
    "bmp",
    "ico",
    "woff",
    "woff2",
    "ttf",
    "eot",
    // Binary
    "bin",
    // Executables and libraries
    "exe",
    "dll",
    "so",
    "dylib",
    "class",
];

pub fn is_denylisted_extension(ext: &str) -> bool {
    DENYLISTED_EXTENSIONS.contains(&ext.to_lowercase().as_str())
}

/// Dependency lockfiles matched by exact basename (case-sensitive, as these
/// names are conventionally fixed). These are machine-generated manifests whose
/// content (resolved dependency trees) parses into thousands of structurally
/// meaningless symbols — e.g. a single `package-lock.json` can mint ~9k JSON-key
/// symbols, dwarfing real source and skewing `conventions` complexity stats.
/// Admission demotes them to Tier-2 (metadata only): the path stays searchable,
/// but no symbols are extracted.
///
/// Cross-reference: the search ranker keeps an OVERLAPPING but distinct list,
/// `CHORE_ANCHOR_FILENAMES` in `src/live_index/rank_signals.rs`, used to suppress
/// co-change promotion. That list is intentionally NOT shared: it also contains
/// non-lockfile chore anchors (`CHANGELOG.md`, `.release-please-manifest.json`)
/// and lives in the `live_index` layer, which `domain` must not depend on. The
/// two lists answer different questions (admission vs. ranking) and are kept
/// separate on purpose; update both when the lockfile ecosystem changes.
const LOCKFILE_BASENAMES: &[&str] = &[
    "package-lock.json",
    "npm-shrinkwrap.json",
    "yarn.lock",
    "pnpm-lock.yaml",
    "bun.lock",
    "Cargo.lock",
    "composer.lock",
    "Gemfile.lock",
    "poetry.lock",
    "uv.lock",
    "Pipfile.lock",
    "flake.lock",
    "packages.lock.json",
    "go.sum",
];

/// Returns `true` when `path`'s file name is an exact (case-sensitive) match for
/// a known dependency lockfile. See [`LOCKFILE_BASENAMES`].
pub fn is_dependency_lockfile(path: &std::path::Path) -> bool {
    path.file_name()
        .and_then(|n| n.to_str())
        .is_some_and(|name| LOCKFILE_BASENAMES.contains(&name))
}

/// Maximum number of NUL byte offsets [`scan_nul_bytes`] enumerates explicitly.
/// Beyond this we report only the count plus the first few offsets — the warning
/// exists to alert, not to exhaustively map every NUL.
pub const NUL_OFFSET_SAMPLE_LIMIT: usize = 5;

/// Result of scanning a byte slice for literal NUL (`0x00`) bytes.
///
/// A NUL is valid UTF-8, so it survives `String::from_utf8_lossy` intact and is
/// then rendered invisibly (most terminals show nothing or a space). Source code
/// that smuggles a NUL into a string/template literal (legal for Node, Python,
/// etc.) therefore reads back as text that does NOT byte-match the file — an
/// agent copying that rendered text for an edit produces a mismatch. This scan
/// powers an honest warning at the content-rendering boundary.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NulScan {
    /// Total count of NUL bytes in the scanned slice.
    pub count: usize,
    /// Byte offsets (relative to the scanned slice) of the first
    /// [`NUL_OFFSET_SAMPLE_LIMIT`] NUL bytes, in ascending order.
    pub first_offsets: Vec<usize>,
}

impl NulScan {
    /// `true` when the scanned slice contained at least one NUL byte.
    pub fn has_nul(&self) -> bool {
        self.count > 0
    }
}

/// Scan `content` for literal NUL (`0x00`) bytes, returning a count and the
/// first [`NUL_OFFSET_SAMPLE_LIMIT`] offsets. Pure; scans the WHOLE slice it is
/// given (callers pass the exact bytes whose rendering they are warning about).
pub fn scan_nul_bytes(content: &[u8]) -> NulScan {
    let mut count = 0usize;
    let mut first_offsets = Vec::new();
    for (offset, &byte) in content.iter().enumerate() {
        if byte == 0 {
            count += 1;
            if first_offsets.len() < NUL_OFFSET_SAMPLE_LIMIT {
                first_offsets.push(offset);
            }
        }
    }
    NulScan {
        count,
        first_offsets,
    }
}

/// Render a single-line warning describing NUL bytes found by [`scan_nul_bytes`],
/// or `None` when the slice is clean. The message is deliberately blunt: copied
/// rendered text will not byte-match the file, so edits must use byte-exact tools.
pub fn nul_byte_warning_line(scan: &NulScan) -> Option<String> {
    if !scan.has_nul() {
        return None;
    }
    let offsets = scan
        .first_offsets
        .iter()
        .map(|o| o.to_string())
        .collect::<Vec<_>>()
        .join(", ");
    let plural = if scan.count == 1 { "" } else { "s" };
    let offset_suffix = if scan.count > scan.first_offsets.len() {
        format!("{offsets}, ...")
    } else {
        offsets
    };
    Some(format!(
        "WARNING: this file contains {} NUL byte{plural} (0x00) at byte offset(s) {offset_suffix}. \
         They are rendered invisibly above; copied text will NOT byte-match the file. \
         Edit this file with byte-exact tools, not rendered text.",
        scan.count
    ))
}

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

    #[test]
    fn test_symbol_kind_display_function() {
        assert_eq!(SymbolKind::Function.to_string(), "fn");
    }

    #[test]
    fn test_is_c_header_path() {
        // `.h` headers (any case, any directory separator) are flagged.
        assert!(LanguageId::is_c_header_path("foo.h"));
        assert!(LanguageId::is_c_header_path("src/runner/flutter_window.h"));
        assert!(LanguageId::is_c_header_path("windows\\runner\\utils.h"));
        assert!(LanguageId::is_c_header_path("API.H"));
        // C++ header extensions map to Cpp directly and are NOT `.h`.
        assert!(!LanguageId::is_c_header_path("foo.hpp"));
        assert!(!LanguageId::is_c_header_path("foo.hxx"));
        assert!(!LanguageId::is_c_header_path("foo.hh"));
        // Non-headers.
        assert!(!LanguageId::is_c_header_path("foo.c"));
        assert!(!LanguageId::is_c_header_path("foo.cpp"));
        assert!(!LanguageId::is_c_header_path("README"));
        // A `.h` in the directory name, not the file, must not match.
        assert!(!LanguageId::is_c_header_path("foo.h/bar.c"));
    }

    #[test]
    fn test_symbol_kind_display_method() {
        assert_eq!(SymbolKind::Method.to_string(), "fn");
    }

    #[test]
    fn test_symbol_kind_display_class() {
        assert_eq!(SymbolKind::Class.to_string(), "class");
    }

    #[test]
    fn test_symbol_kind_display_struct() {
        assert_eq!(SymbolKind::Struct.to_string(), "struct");
    }

    #[test]
    fn test_symbol_kind_display_enum() {
        assert_eq!(SymbolKind::Enum.to_string(), "enum");
    }

    #[test]
    fn test_symbol_kind_display_interface() {
        assert_eq!(SymbolKind::Interface.to_string(), "interface");
    }

    #[test]
    fn test_symbol_kind_display_module() {
        assert_eq!(SymbolKind::Module.to_string(), "mod");
    }

    #[test]
    fn test_symbol_kind_display_constant() {
        assert_eq!(SymbolKind::Constant.to_string(), "const");
    }

    #[test]
    fn test_symbol_kind_display_variable() {
        assert_eq!(SymbolKind::Variable.to_string(), "let");
    }

    #[test]
    fn test_symbol_kind_display_type() {
        assert_eq!(SymbolKind::Type.to_string(), "type");
    }

    #[test]
    fn test_symbol_kind_display_trait() {
        assert_eq!(SymbolKind::Trait.to_string(), "trait");
    }

    #[test]
    fn test_symbol_kind_display_impl() {
        assert_eq!(SymbolKind::Impl.to_string(), "impl");
    }

    #[test]
    fn test_symbol_kind_display_other() {
        assert_eq!(SymbolKind::Other.to_string(), "other");
    }

    // --- ReferenceRecord and ReferenceKind ---

    #[test]
    fn test_reference_kind_all_variants_constructible() {
        let _call = ReferenceKind::Call;
        let _import = ReferenceKind::Import;
        let _type_usage = ReferenceKind::TypeUsage;
        let _macro_use = ReferenceKind::MacroUse;
    }

    #[test]
    fn test_reference_kind_display_call() {
        assert_eq!(ReferenceKind::Call.to_string(), "call");
    }

    #[test]
    fn test_reference_kind_display_import() {
        assert_eq!(ReferenceKind::Import.to_string(), "import");
    }

    #[test]
    fn test_reference_kind_display_type_usage() {
        assert_eq!(ReferenceKind::TypeUsage.to_string(), "type_usage");
    }

    #[test]
    fn test_reference_kind_display_macro_use() {
        assert_eq!(ReferenceKind::MacroUse.to_string(), "macro_use");
    }

    #[test]
    fn test_reference_record_construction_with_all_fields() {
        let r = ReferenceRecord {
            name: "foo".to_string(),
            qualified_name: Some("Bar::foo".to_string()),
            kind: ReferenceKind::Call,
            byte_range: (10, 20),
            line_range: (1, 1),
            enclosing_symbol_index: Some(0),
        };
        assert_eq!(r.name, "foo");
        assert_eq!(r.qualified_name.as_deref(), Some("Bar::foo"));
        assert_eq!(r.kind, ReferenceKind::Call);
        assert_eq!(r.byte_range, (10, 20));
        assert_eq!(r.line_range, (1, 1));
        assert_eq!(r.enclosing_symbol_index, Some(0));
    }

    #[test]
    fn test_reference_record_without_optional_fields() {
        let r = ReferenceRecord {
            name: "baz".to_string(),
            qualified_name: None,
            kind: ReferenceKind::Import,
            byte_range: (0, 5),
            line_range: (0, 0),
            enclosing_symbol_index: None,
        };
        assert!(r.qualified_name.is_none());
        assert!(r.enclosing_symbol_index.is_none());
    }

    #[test]
    fn test_file_processing_result_backward_compat_with_empty_refs() {
        use std::collections::HashMap;
        let result = FileProcessingResult {
            relative_path: "test.rs".to_string(),
            language: LanguageId::Rust,
            classification: FileClassification::for_code_path("test.rs"),
            outcome: FileOutcome::Processed,
            parse_diagnostic: None,
            symbols: vec![],
            byte_len: 0,
            content_hash: "abc".to_string(),
            references: vec![],
            alias_map: HashMap::new(),
        };
        assert!(result.references.is_empty());
        assert!(result.alias_map.is_empty());
    }

    #[test]
    fn test_file_classification_for_code_path_marks_code_only_by_default() {
        let classification = FileClassification::for_code_path("src/lib.rs");

        assert!(classification.is_code());
        assert!(!classification.is_text());
        assert!(!classification.is_binary());
        assert!(!classification.is_generated);
        assert!(!classification.is_test);
        assert!(!classification.is_vendor);
    }

    #[test]
    fn test_file_classification_for_code_path_marks_noise_tags_from_path() {
        let generated = FileClassification::for_code_path("src/generated/client.pb.go");
        assert!(generated.is_generated);

        let test_file = FileClassification::for_code_path("tests/parser_spec.rs");
        assert!(test_file.is_test);

        let vendor_file = FileClassification::for_code_path("node_modules/pkg/index.js");
        assert!(vendor_file.is_vendor);
    }

    #[test]
    fn text_format_matrix_routes_mdx_rst_asciidoc_org_extensionless_and_safe_configs() {
        let knowledge_only = [
            ("guide.mdx", LanguageId::Markdown),
            ("guide.rst", LanguageId::Text),
            ("guide.adoc", LanguageId::Text),
            ("guide.asciidoc", LanguageId::Text),
            ("guide.org", LanguageId::Text),
            ("README", LanguageId::Text),
            ("docs/NOTICE", LanguageId::Text),
        ];

        for (path, expected_language) in knowledge_only {
            let language = LanguageId::from_path(path).expect("text format must be recognized");
            assert_eq!(language, expected_language);
            assert_eq!(
                IndexTargets::for_path(path, Some(&language)),
                IndexTargets::Knowledge
            );
            assert!(FileClassification::for_indexed_path(path, IndexTargets::Knowledge).is_text());
        }

        for (path, expected_language) in [
            ("openapi.yaml", LanguageId::Yaml),
            ("schema.json", LanguageId::Json),
            ("config.toml", LanguageId::Toml),
            (".env.example", LanguageId::Env),
            ("config/settings.ini", LanguageId::Text),
            (".gitignore", LanguageId::Text),
        ] {
            let language = LanguageId::from_path(path).expect("safe config must be recognized");
            assert_eq!(language, expected_language);
            assert_eq!(
                IndexTargets::for_path(path, Some(&language)),
                IndexTargets::CodeAndKnowledge
            );
            let classification =
                FileClassification::for_indexed_path(path, IndexTargets::CodeAndKnowledge);
            assert!(classification.is_code());
            assert!(classification.is_config);
        }

        let rust = LanguageId::from_path("src/lib.rs").expect("Rust must stay recognized");
        assert_eq!(
            IndexTargets::for_path("src/lib.rs", Some(&rust)),
            IndexTargets::Code
        );
    }

    #[test]
    fn test_find_enclosing_symbol_innermost_for_nested() {
        // outer: line 0..10, inner: line 3..6
        let symbols = vec![
            SymbolRecord {
                name: "outer".to_string(),
                kind: SymbolKind::Function,
                depth: 0,
                sort_order: 0,
                byte_range: (0, 100),
                line_range: (0, 10),
                doc_byte_range: None,
                item_byte_range: None,
            },
            SymbolRecord {
                name: "inner".to_string(),
                kind: SymbolKind::Function,
                depth: 1,
                sort_order: 1,
                byte_range: (30, 60),
                line_range: (3, 6),
                doc_byte_range: None,
                item_byte_range: None,
            },
        ];
        // Reference at line 4 is inside both - should return inner (index 1)
        let idx = find_enclosing_symbol(&symbols, 4);
        assert_eq!(idx, Some(1), "should return innermost enclosing symbol");
    }

    #[test]
    fn test_find_enclosing_symbol_none_at_module_level() {
        let symbols = vec![SymbolRecord {
            name: "foo".to_string(),
            kind: SymbolKind::Function,
            depth: 0,
            sort_order: 0,
            byte_range: (50, 100),
            line_range: (5, 10),
            doc_byte_range: None,
            item_byte_range: None,
        }];
        // Reference at line 0 is not inside any symbol
        let idx = find_enclosing_symbol(&symbols, 0);
        assert_eq!(idx, None, "should return None when not inside any symbol");
    }

    #[test]
    fn test_symbol_record_item_helpers_fall_back_to_doc_range() {
        let symbol = SymbolRecord {
            name: "target".to_string(),
            kind: SymbolKind::Function,
            depth: 0,
            sort_order: 0,
            byte_range: (20, 40),
            line_range: (1, 3),
            doc_byte_range: Some((10, 20)),
            item_byte_range: None,
        };

        assert_eq!(symbol.item_start(), 10);
        assert_eq!(symbol.item_end(), 40);
        assert_eq!(symbol.item_range(), (10, 40));
        assert_eq!(symbol.core_range(), (20, 40));
    }

    #[test]
    fn test_symbol_record_item_helpers_prefer_item_range() {
        let symbol = SymbolRecord {
            name: "target".to_string(),
            kind: SymbolKind::Function,
            depth: 0,
            sort_order: 0,
            byte_range: (20, 40),
            line_range: (1, 3),
            doc_byte_range: Some((10, 20)),
            item_byte_range: Some((5, 44)),
        };

        assert_eq!(symbol.item_start(), 5);
        assert_eq!(symbol.item_end(), 44);
        assert_eq!(symbol.item_range(), (5, 44));
        assert_eq!(symbol.core_range(), (20, 40));
    }

    #[test]
    fn test_admission_tier_variants() {
        let t1 = AdmissionTier::Normal;
        let t2 = AdmissionTier::MetadataOnly;
        let t3 = AdmissionTier::HardSkip;
        assert_ne!(t1, t2);
        assert_ne!(t2, t3);
        assert_ne!(t1, t3);
    }

    #[test]
    fn test_extension_is_denylisted() {
        assert!(is_denylisted_extension("safetensors"));
        assert!(is_denylisted_extension("ckpt"));
        assert!(is_denylisted_extension("zip"));
        assert!(is_denylisted_extension("mp4"));
        assert!(is_denylisted_extension("woff2"));
        assert!(is_denylisted_extension("png"));
        assert!(is_denylisted_extension("bin"));
    }

    #[test]
    fn test_extension_not_denylisted() {
        assert!(!is_denylisted_extension("rs"));
        assert!(!is_denylisted_extension("ts"));
        assert!(!is_denylisted_extension("json"));
        assert!(!is_denylisted_extension("svg")); // SVG intentionally NOT denylisted
        assert!(!is_denylisted_extension("md"));
        assert!(!is_denylisted_extension("toml"));
    }

    #[test]
    fn test_new_executable_extensions_denylisted() {
        assert!(is_denylisted_extension("exe"));
        assert!(is_denylisted_extension("dll"));
        assert!(is_denylisted_extension("so"));
        assert!(is_denylisted_extension("dylib"));
        assert!(is_denylisted_extension("class"));
    }

    #[test]
    fn test_denylist_case_insensitive() {
        assert!(is_denylisted_extension("DLL"));
        assert!(is_denylisted_extension("So"));
        assert!(is_denylisted_extension("EXE"));
        assert!(is_denylisted_extension("Dylib"));
        assert!(is_denylisted_extension("CLASS"));
    }

    #[test]
    fn test_skipped_file_creation() {
        let decision =
            AdmissionDecision::skip(AdmissionTier::MetadataOnly, SkipReason::DenylistedExtension);
        let sf = SkippedFile {
            path: "model.safetensors".into(),
            size: 4_200_000_000,
            extension: Some("safetensors".into()),
            decision,
        };
        assert_eq!(sf.tier(), AdmissionTier::MetadataOnly);
        assert_eq!(sf.reason(), Some(SkipReason::DenylistedExtension));
    }

    #[test]
    fn test_scan_nul_bytes_clean_slice_reports_none() {
        let scan = scan_nul_bytes(b"fn main() {}\n");
        assert!(!scan.has_nul());
        assert_eq!(scan.count, 0);
        assert!(scan.first_offsets.is_empty());
        assert_eq!(nul_byte_warning_line(&scan), None);
    }

    #[test]
    fn test_scan_nul_bytes_empty_slice_reports_none() {
        let scan = scan_nul_bytes(b"");
        assert!(!scan.has_nul());
        assert_eq!(nul_byte_warning_line(&scan), None);
    }

    #[test]
    fn test_scan_nul_bytes_single_offset_and_singular_warning() {
        let scan = scan_nul_bytes(b"ab\0cd");
        assert_eq!(scan.count, 1);
        assert_eq!(scan.first_offsets, vec![2]);
        let warning = nul_byte_warning_line(&scan).expect("NUL present");
        assert!(warning.contains("1 NUL byte (0x00)"), "warning: {warning}");
        assert!(
            warning.contains("byte offset(s) 2."),
            "single offset, no ellipsis: {warning}"
        );
        assert!(warning.contains("byte-exact tools"));
    }

    #[test]
    fn test_scan_nul_bytes_plural_warning() {
        let scan = scan_nul_bytes(b"\0a\0b");
        assert_eq!(scan.count, 2);
        assert_eq!(scan.first_offsets, vec![0, 2]);
        let warning = nul_byte_warning_line(&scan).expect("NUL present");
        assert!(warning.contains("2 NUL bytes (0x00)"), "warning: {warning}");
        assert!(
            warning.contains("byte offset(s) 0, 2."),
            "warning: {warning}"
        );
    }

    #[test]
    fn test_scan_nul_bytes_caps_offsets_and_adds_ellipsis() {
        // 7 NUL bytes; only the first NUL_OFFSET_SAMPLE_LIMIT (5) are enumerated.
        let scan = scan_nul_bytes(b"\0\0\0\0\0\0\0");
        assert_eq!(scan.count, 7);
        assert_eq!(scan.first_offsets.len(), NUL_OFFSET_SAMPLE_LIMIT);
        assert_eq!(scan.first_offsets, vec![0, 1, 2, 3, 4]);
        let warning = nul_byte_warning_line(&scan).expect("NUL present");
        assert!(warning.contains("7 NUL bytes"), "warning: {warning}");
        assert!(
            warning.contains("0, 1, 2, 3, 4, ..."),
            "more NULs than sampled => ellipsis: {warning}"
        );
    }

    #[test]
    fn parse_status_is_bounded_and_digest_stable() {
        let old_diagnostic = FileOutcome::PartialParse {
            warning: "unexpected token near heading".to_string(),
        };
        let reworded_diagnostic = FileOutcome::PartialParse {
            warning: "heading contains recoverable syntax".to_string(),
        };

        let old_knowledge_status = ParseStatus::from_operational_outcome(&old_diagnostic);
        let reworded_knowledge_status = ParseStatus::from_operational_outcome(&reworded_diagnostic);
        assert_eq!(old_knowledge_status, ParseStatus::PartialParse);
        assert_eq!(old_knowledge_status, reworded_knowledge_status);

        let entry = |knowledge_status| CatalogEntry {
            path: CatalogPath {
                public_id: "path:README.md".to_string(),
                normalized_utf8: Some("README.md".to_string()),
            },
            size: 42,
            language: Some(LanguageId::Markdown),
            classification: FileClassification::for_code_path("README.md"),
            disposition: FileDisposition::Indexed {
                targets: IndexTargets::Knowledge,
                parse_status: ParseStatus::aggregate_for_targets(
                    IndexTargets::Knowledge,
                    Some(ParseStatus::Failed),
                    Some(knowledge_status),
                ),
            },
            content_hash: Some("stable-content-hash".to_string()),
        };

        let source = SourceIdentity {
            repository_id: RepositoryId::new("repository-fixture"),
            source_id: SourceId::new("source-fixture"),
            location: SourceLocation::WorkingTree {
                worktree_id: "worktree-fixture".to_string(),
            },
        };
        let source_version = SourceVersion {
            branch: Some("main".to_string()),
            commit: Some("0123456789abcdef".to_string()),
            working_tree: WorkingTreeState::Clean,
        };
        let usage = ManifestResourceUsage {
            catalog_entries: 1,
            catalog_metadata_bytes: 256,
            admitted_content_bytes: 42,
        };

        let old_manifest = RepositoryManifest::new(
            1,
            1,
            1,
            source.clone(),
            source_version.clone(),
            CoverageStatus::Complete,
            vec![entry(old_knowledge_status)],
            Vec::new(),
            usage,
        )
        .unwrap();
        let reworded_manifest = RepositoryManifest::new(
            1,
            1,
            1,
            source,
            source_version,
            CoverageStatus::Complete,
            vec![entry(reworded_knowledge_status)],
            Vec::new(),
            usage,
        )
        .unwrap();

        assert!(matches!(
            old_manifest.entries[0].disposition,
            FileDisposition::Indexed {
                targets: IndexTargets::Knowledge,
                parse_status: ParseStatus::PartialParse,
            }
        ));
        assert_eq!(old_manifest.digest, reworded_manifest.digest);
    }
}