agent-file-tools 0.56.0

Agent File Tools — tree-sitter powered code analysis for AI agents
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
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
//! Manifest-only callgraph assembly.
//!
//! This module deliberately accepts a manifest plus immutable blob payloads rather
//! than a checkout root.  Extraction is content-addressed and path-free; binding a
//! blob to a manifest path and resolving its cross-file references happens here.
//! The existing resolver uses String file identities. Non-UTF-8 source members
//! remain in byte-addressed facts but are reported as unbound rather than being
//! converted lossily; supporting them requires a separate resolver identity change.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use serde::{Deserialize, Serialize};
use tree_sitter::Parser;

use super::facts::{BlobKey, FactPaths, ManifestFacts, ProjectFacts};
use crate::callgraph::{self, FileCallData, SymbolMeta};
use crate::imports::{ImportBlock, ImportForm, ImportGroup, ImportKind, ImportStatement};
use crate::parser::{grammar_for, LangId};
use crate::symbols::SymbolKind;
use crate::views::{Manifest, ManifestEntry, RelPath};
use std::collections::HashMap;
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;

const TOP_LEVEL_SYMBOL: &str = "<top-level>";

/// An error raised while decoding or assembling manifest-addressed callgraph data.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ManifestJoinError {
    UnsupportedLanguage(String),
    Parse(String),
    InvalidBlob(String),
    MissingBlob(String),
    InvalidConfig { path: Vec<u8>, reason: String },
}

impl fmt::Display for ManifestJoinError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnsupportedLanguage(language) => {
                write!(formatter, "unsupported callgraph blob language {language}")
            }
            Self::Parse(reason) => write!(formatter, "callgraph blob parse failed: {reason}"),
            Self::InvalidBlob(reason) => write!(formatter, "invalid callgraph blob: {reason}"),
            Self::MissingBlob(key) => write!(
                formatter,
                "manifest references missing callgraph blob {key}"
            ),
            Self::InvalidConfig { path, reason } => write!(
                formatter,
                "invalid manifest config {}: {reason}",
                String::from_utf8_lossy(path)
            ),
        }
    }
}

impl std::error::Error for ManifestJoinError {}

/// Reads immutable payloads by the full key recorded in a manifest entry.
///
/// Implementations may be backed by the family blob store, but this interface
/// intentionally exposes no checkout path or directory operation to the join.
pub trait ManifestBlobReader {
    fn read_callgraph_blob(&self, full_key: &str) -> Result<Option<Vec<u8>>, ManifestJoinError>;
}

/// Tree-sitter node position in canonical pre-order traversal order.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct AstPreorderNode {
    pub ordinal: u32,
    pub kind: String,
    pub byte_start: usize,
    pub byte_end: usize,
}

/// A symbol captured by extraction.  Its ordinal is the source AST node's
/// pre-order position, not a per-path or database-generated identifier.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct BlobSymbol {
    pub ordinal: u32,
    pub name: String,
    pub scoped_name: String,
    pub kind: String,
    pub exported: bool,
    pub is_default_export: bool,
    pub start_line: u32,
    pub start_col: u32,
    pub end_line: u32,
    pub end_col: u32,
    pub signature: Option<String>,
}

/// The parse-level class of a reference.  No target path is present in a blob.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BlobRefKind {
    Call,
    ValueRef,
    Import,
    Module,
    Reexport,
    ExportAlias,
}

/// An unresolved reference extracted from one source blob.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct BlobRef {
    /// Canonical tree-sitter AST pre-order position of this reference.
    pub ordinal: u32,
    pub kind: BlobRefKind,
    pub caller_symbol: Option<String>,
    pub short_name: Option<String>,
    pub full_ref: Option<String>,
    pub module_path: Option<String>,
    pub line: u32,
    pub byte_start: usize,
    pub byte_end: usize,
    pub path_override: Option<String>,
    pub local_name: Option<String>,
    pub requested_name: Option<String>,
    pub namespace_alias: Option<String>,
    pub wildcard: bool,
    pub import_kind: Option<String>,
}

/// A parsed import retained in the blob so binding can resolve aliases without
/// re-reading source text.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct BlobImport {
    pub ordinal: u32,
    pub module_path: String,
    pub names: Vec<String>,
    pub default_import: Option<String>,
    pub namespace_import: Option<String>,
    pub byte_start: usize,
    pub byte_end: usize,
    pub raw_text: String,
    pub type_only: bool,
    pub side_effect: bool,
}

/// Path-free parse output stored for a regular source file.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ParseBlob {
    pub extractor_version: String,
    pub language: String,
    pub ast_nodes: Vec<AstPreorderNode>,
    pub symbols: Vec<BlobSymbol>,
    pub default_export_symbol: Option<String>,
    pub exported_symbols: Vec<String>,
    pub callable_symbols: Vec<String>,
    pub imports: Vec<BlobImport>,
    pub refs: Vec<BlobRef>,
}

/// Raw source is retained only for configuration files and ignore-list members.
/// These blobs are parsed during joining because their interpretation depends on
/// the manifest view they configure.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ConfigBlob {
    pub extractor_version: String,
    pub language: String,
    pub source: Vec<u8>,
}

/// The immutable callgraph blob payload.  A regular source blob has parse output
/// only; a configuration blob is intentionally raw so its manifest-scoped
/// resolver settings can be interpreted during assembly.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CallgraphBlob {
    Parse(ParseBlob),
    Config(ConfigBlob),
}

impl CallgraphBlob {
    /// Extracts path-free callgraph parse output from source bytes and the
    /// extractor version that names the corresponding content key.
    pub fn extract(
        source: &str,
        language: &str,
        extractor_version: impl Into<String>,
    ) -> Result<Self, ManifestJoinError> {
        let lang = language_id(language)
            .ok_or_else(|| ManifestJoinError::UnsupportedLanguage(language.to_string()))?;
        let extractor_version = extractor_version.into();
        let ast_nodes = ast_preorder_nodes(source, lang)?;
        let mut data = callgraph::build_file_data_from_source_with_lang(
            std::path::Path::new("__callgraph_blob__"),
            source,
            lang,
        )
        .map_err(|error| ManifestJoinError::Parse(error.to_string()))?;
        if lang == LangId::Rust {
            super::extend_rust_imports_with_nested_uses(source, &mut data);
        }
        let symbols = blob_symbols(source, &data, &ast_nodes);
        let imports = blob_imports(&data, &ast_nodes);
        let mut refs = blob_refs(source, &data, &ast_nodes);
        refs.extend(rust_module_refs(source, lang, &ast_nodes));
        let empty =
            Manifest::new([]).map_err(|error| ManifestJoinError::Parse(error.to_string()))?;
        let reader = |_: &BlobKey| None;
        let empty_facts = ManifestFacts {
            manifest: &empty,
            blobs: &reader,
        };
        let paths = FactPaths {
            root: Path::new("/"),
            facts: &empty_facts,
        };
        let file = Path::new("/__callgraph_blob__");
        let mut structural =
            super::collect_reexport_refs(paths.root, file, "__callgraph_blob__", source, &paths)
                .raw_refs;
        structural.extend(
            super::collect_source_less_export_alias_refs("__callgraph_blob__", source).raw_refs,
        );
        if lang == LangId::Rust {
            structural.extend(
                super::collect_rust_pub_use_reexport_refs(
                    paths.root,
                    file,
                    "__callgraph_blob__",
                    &data.import_block.imports,
                    &super::LineIndex::new(source),
                    &paths,
                )
                .raw_refs,
            );
        }
        refs.extend(
            structural
                .into_iter()
                .map(|raw| structural_ref(raw, &ast_nodes)),
        );
        let mut exported_symbols = data.exported_symbols.clone();
        exported_symbols.sort();
        let mut callable_symbols = data.calls_by_symbol.keys().cloned().collect::<Vec<_>>();
        callable_symbols.sort();
        refs.sort_by(|left, right| {
            (
                left.ordinal,
                left.kind,
                left.byte_start,
                left.byte_end,
                left.full_ref.as_deref(),
            )
                .cmp(&(
                    right.ordinal,
                    right.kind,
                    right.byte_start,
                    right.byte_end,
                    right.full_ref.as_deref(),
                ))
        });
        refs.dedup_by(|left, right| {
            left.ordinal == right.ordinal
                && left.kind == right.kind
                && left.byte_start == right.byte_start
                && left.byte_end == right.byte_end
                && left.full_ref == right.full_ref
        });

        Ok(Self::Parse(ParseBlob {
            extractor_version,
            language: language.to_string(),
            ast_nodes,
            symbols,
            default_export_symbol: data.default_export_symbol,
            exported_symbols,
            callable_symbols,
            imports,
            refs,
        }))
    }

    /// Builds a manifest configuration input.  The caller must key it with
    /// `language = "config"` and the same extractor version stored here.
    pub fn config(source: impl Into<Vec<u8>>, extractor_version: impl Into<String>) -> Self {
        Self::Config(ConfigBlob {
            extractor_version: extractor_version.into(),
            language: "config".to_string(),
            source: source.into(),
        })
    }

    /// Uses one canonical JSON encoding for the immutable payload bytes.
    pub fn to_bytes(&self) -> Result<Vec<u8>, ManifestJoinError> {
        serde_json::to_vec(self).map_err(|error| ManifestJoinError::InvalidBlob(error.to_string()))
    }

    /// Decodes a payload after the blob store has verified its digest and schema.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, ManifestJoinError> {
        serde_json::from_slice(bytes)
            .map_err(|error| ManifestJoinError::InvalidBlob(error.to_string()))
    }

    pub fn parse(&self) -> Option<&ParseBlob> {
        match self {
            Self::Parse(blob) => Some(blob),
            Self::Config(_) => None,
        }
    }

    pub fn config_source(&self) -> Option<&ConfigBlob> {
        match self {
            Self::Parse(_) => None,
            Self::Config(blob) => Some(blob),
        }
    }
}

/// The stable identity of one bound blob reference.  The path breaks ties when
/// identical content is bound at more than one manifest path.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct CallerRefKey {
    pub caller_blob_key: String,
    pub ref_ordinal: u32,
    pub caller_path: Vec<u8>,
}

/// The manifest-derived resolution state for one reference.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum ResolutionStatus {
    Resolved,
    Unresolved,
}

/// A logical derived row.  It is intentionally independent of SQLite rowids and
/// other physical database details.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct DerivedRow {
    pub caller_blob_key: String,
    pub ref_ordinal: u32,
    pub caller_path: Vec<u8>,
    pub kind: BlobRefKind,
    pub status: ResolutionStatus,
    pub target_path: Option<Vec<u8>>,
    pub target_symbol: Option<String>,
}

impl DerivedRow {
    pub fn ref_key(&self) -> CallerRefKey {
        CallerRefKey {
            caller_blob_key: self.caller_blob_key.clone(),
            ref_ordinal: self.ref_ordinal,
            caller_path: self.caller_path.clone(),
        }
    }
}

/// The result of resolving one manifest.  `resolution_order` exposes the exact
/// canonical order consumed by the resolver for deterministic test coverage.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct JoinResult {
    pub rows: BTreeSet<DerivedRow>,
    pub resolution_order: Vec<CallerRefKey>,
    pub unbound_non_utf8_paths: Vec<Vec<u8>>,
}

impl JoinResult {
    /// Serializes logical rows in canonical order.  This is the comparison form
    /// for equal manifests; callers must not compare SQLite file bytes.
    pub fn canonical_serialization(&self) -> Vec<u8> {
        let mut output = Vec::new();
        for row in &self.rows {
            append_field(&mut output, row.caller_blob_key.as_bytes());
            append_field(&mut output, &row.ref_ordinal.to_be_bytes());
            append_field(&mut output, &row.caller_path);
            append_field(&mut output, &[row.kind as u8]);
            append_field(
                &mut output,
                &[match row.status {
                    ResolutionStatus::Resolved => 1,
                    ResolutionStatus::Unresolved => 0,
                }],
            );
            append_optional_field(&mut output, row.target_path.as_deref());
            append_optional_field(&mut output, row.target_symbol.as_deref().map(str::as_bytes));
        }
        output
    }
}

/// Incremental assembly details used to verify precise invalidation behavior.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IncrementalJoinResult {
    pub result: JoinResult,
    pub re_resolved: BTreeSet<CallerRefKey>,
    pub full_re_resolve: bool,
}

fn changed_manifest_paths(previous: &Manifest, current: &Manifest) -> BTreeSet<Vec<u8>> {
    let previous_entries = previous
        .entries()
        .map(|(path, entry)| (path.as_bytes().to_vec(), entry))
        .collect::<BTreeMap<_, _>>();
    let current_entries = current
        .entries()
        .map(|(path, entry)| (path.as_bytes().to_vec(), entry))
        .collect::<BTreeMap<_, _>>();
    previous_entries
        .keys()
        .chain(current_entries.keys())
        .collect::<BTreeSet<_>>()
        .into_iter()
        .filter(|path| previous_entries.get(*path) != current_entries.get(*path))
        .cloned()
        .collect()
}

fn manifest_resolution_input(manifest: &Manifest, path: &[u8]) -> bool {
    let lookup = if path.first() == Some(&0) {
        return manifest
            .entries()
            .find(|(candidate, _)| candidate.as_bytes() == path)
            .is_some_and(|(_, entry)| matches!(entry, ManifestEntry::Synthetic { .. }));
    } else {
        RelPath::new(path.to_vec()).ok()
    };
    lookup
        .as_ref()
        .and_then(|path| manifest.get(path))
        .is_some_and(|entry| {
            matches!(
                entry,
                ManifestEntry::Regular {
                    resolution_input: true,
                    ..
                }
            )
        })
}

fn append_field(output: &mut Vec<u8>, value: &[u8]) {
    output.extend_from_slice(&(value.len() as u64).to_be_bytes());
    output.extend_from_slice(value);
}

fn append_optional_field(output: &mut Vec<u8>, value: Option<&[u8]>) {
    match value {
        Some(value) => {
            output.push(1);
            append_field(output, value);
        }
        None => output.push(0),
    }
}

fn language_id(language: &str) -> Option<LangId> {
    Some(match language {
        "typescript" => LangId::TypeScript,
        "tsx" => LangId::Tsx,
        "javascript" => LangId::JavaScript,
        "python" => LangId::Python,
        "rust" => LangId::Rust,
        "go" => LangId::Go,
        "c" => LangId::C,
        "cpp" => LangId::Cpp,
        "cuda" => LangId::Cuda,
        "metal" => LangId::Metal,
        "zig" => LangId::Zig,
        "csharp" => LangId::CSharp,
        "bash" => LangId::Bash,
        "html" => LangId::Html,
        "markdown" => LangId::Markdown,
        "solidity" => LangId::Solidity,
        "scss" => LangId::Scss,
        "vue" => LangId::Vue,
        "json" => LangId::Json,
        "scala" => LangId::Scala,
        "java" => LangId::Java,
        "ruby" => LangId::Ruby,
        "kotlin" => LangId::Kotlin,
        "swift" => LangId::Swift,
        "php" => LangId::Php,
        "lua" => LangId::Lua,
        "perl" => LangId::Perl,
        "yaml" => LangId::Yaml,
        "pascal" => LangId::Pascal,
        "r" => LangId::R,
        "groovy" => LangId::Groovy,
        "objc" => LangId::ObjC,
        "toml" => LangId::Toml,
        _ => return None,
    })
}

fn ast_preorder_nodes(
    source: &str,
    lang: LangId,
) -> Result<Vec<AstPreorderNode>, ManifestJoinError> {
    let mut parser = Parser::new();
    parser
        .set_language(&grammar_for(lang))
        .map_err(|error| ManifestJoinError::Parse(error.to_string()))?;
    let tree = parser
        .parse(source, None)
        .ok_or_else(|| ManifestJoinError::Parse("tree-sitter returned no tree".to_string()))?;
    let mut nodes = Vec::new();
    let mut stack = vec![tree.root_node()];
    while let Some(node) = stack.pop() {
        nodes.push(AstPreorderNode {
            ordinal: nodes.len() as u32,
            kind: node.kind().to_string(),
            byte_start: node.start_byte(),
            byte_end: node.end_byte(),
        });
        let children = node.children(&mut node.walk()).collect::<Vec<_>>();
        stack.extend(children.into_iter().rev());
    }
    Ok(nodes)
}

fn blob_symbols(
    source: &str,
    data: &FileCallData,
    ast_nodes: &[AstPreorderNode],
) -> Vec<BlobSymbol> {
    let mut symbols = data
        .symbol_metadata
        .iter()
        .map(|(scoped_name, meta)| {
            blob_symbol(
                source,
                scoped_name,
                meta,
                &data.default_export_symbol,
                ast_nodes,
            )
        })
        .collect::<Vec<_>>();
    symbols.sort_by(|left, right| {
        (
            left.ordinal,
            left.start_line,
            left.start_col,
            left.scoped_name.as_str(),
        )
            .cmp(&(
                right.ordinal,
                right.start_line,
                right.start_col,
                right.scoped_name.as_str(),
            ))
    });
    symbols
}

fn blob_symbol(
    source: &str,
    scoped_name: &str,
    meta: &SymbolMeta,
    default_export: &Option<String>,
    ast_nodes: &[AstPreorderNode],
) -> BlobSymbol {
    let byte_start = byte_offset(source, meta.range.start_line, meta.range.start_col);
    let byte_end = byte_offset(source, meta.range.end_line, meta.range.end_col).max(byte_start);
    BlobSymbol {
        ordinal: ordinal_for_range(ast_nodes, byte_start, byte_end),
        name: unqualified_symbol_name(scoped_name).to_string(),
        scoped_name: scoped_name.to_string(),
        kind: symbol_kind_name(&meta.kind).to_string(),
        exported: meta.exported,
        is_default_export: default_export.as_deref() == Some(scoped_name),
        start_line: meta.range.start_line,
        start_col: meta.range.start_col,
        end_line: meta.range.end_line,
        end_col: meta.range.end_col,
        signature: meta.signature.clone(),
    }
}

fn blob_imports(data: &FileCallData, ast_nodes: &[AstPreorderNode]) -> Vec<BlobImport> {
    let mut imports = data
        .import_block
        .imports
        .iter()
        .map(|import| BlobImport {
            ordinal: ordinal_for_range(ast_nodes, import.byte_range.start, import.byte_range.end),
            module_path: import.module_path.clone(),
            names: import.names.clone(),
            default_import: import.default_import.clone(),
            namespace_import: import.namespace_import.clone(),
            byte_start: import.byte_range.start,
            byte_end: import.byte_range.end,
            raw_text: import.raw_text.clone(),
            type_only: import.kind == ImportKind::Type,
            side_effect: import.kind == ImportKind::SideEffect,
        })
        .collect::<Vec<_>>();
    imports.sort_by(|left, right| {
        (left.ordinal, left.module_path.as_str()).cmp(&(right.ordinal, right.module_path.as_str()))
    });
    imports
}

fn blob_refs(source: &str, data: &FileCallData, ast_nodes: &[AstPreorderNode]) -> Vec<BlobRef> {
    let mut refs = Vec::new();
    for (caller_symbol, calls) in &data.calls_by_symbol {
        for call in calls {
            refs.push(call_ref(caller_symbol, call, BlobRefKind::Call, ast_nodes));
        }
    }
    for (caller_symbol, calls) in &data.value_refs_by_symbol {
        for call in calls {
            refs.push(call_ref(
                caller_symbol,
                call,
                BlobRefKind::ValueRef,
                ast_nodes,
            ));
        }
    }
    for import in &data.import_block.imports {
        refs.push(BlobRef {
            ordinal: ordinal_for_range(ast_nodes, import.byte_range.start, import.byte_range.end),
            kind: BlobRefKind::Import,
            caller_symbol: None,
            short_name: None,
            full_ref: Some(import.module_path.clone()),
            module_path: Some(import.module_path.clone()),
            line: line_for_byte(source, import.byte_range.start),
            byte_start: import.byte_range.start,
            byte_end: import.byte_range.end,
            path_override: None,
            local_name: None,
            requested_name: None,
            namespace_alias: import.namespace_import.clone(),
            wildcard: super::import_is_wildcard(import),
            import_kind: None,
        });
    }
    refs
}

fn call_ref(
    caller_symbol: &str,
    call: &callgraph::CallSite,
    kind: BlobRefKind,
    ast_nodes: &[AstPreorderNode],
) -> BlobRef {
    BlobRef {
        ordinal: ordinal_for_range(ast_nodes, call.byte_start, call.byte_end),
        kind,
        caller_symbol: Some(caller_symbol.to_string()),
        short_name: Some(call.callee_name.clone()),
        full_ref: Some(call.full_callee.clone()),
        module_path: None,
        line: call.line,
        byte_start: call.byte_start,
        byte_end: call.byte_end,
        path_override: None,
        local_name: None,
        requested_name: None,
        namespace_alias: None,
        wildcard: false,
        import_kind: None,
    }
}

fn rust_module_refs(source: &str, lang: LangId, ast_nodes: &[AstPreorderNode]) -> Vec<BlobRef> {
    if lang != LangId::Rust {
        return Vec::new();
    }
    let mut parser = Parser::new();
    if parser.set_language(&grammar_for(lang)).is_err() {
        return Vec::new();
    }
    let Some(tree) = parser.parse(source, None) else {
        return Vec::new();
    };
    let mut refs = Vec::new();
    let mut stack = vec![tree.root_node()];
    while let Some(node) = stack.pop() {
        if node.kind() == "mod_item"
            && node
                .named_children(&mut node.walk())
                .all(|child| child.kind() != "declaration_list")
        {
            if let Some(name) = node.child_by_field_name("name") {
                let module_name = source[name.byte_range()].to_string();
                refs.push(BlobRef {
                    ordinal: ordinal_for_range(ast_nodes, node.start_byte(), node.end_byte()),
                    kind: BlobRefKind::Module,
                    caller_symbol: None,
                    short_name: Some(module_name.clone()),
                    full_ref: Some(module_name.clone()),
                    module_path: Some(module_name),
                    line: node.start_position().row as u32 + 1,
                    byte_start: node.start_byte(),
                    byte_end: node.end_byte(),
                    path_override: super::rust_module_path_override(source, node)
                        .map(str::to_string),
                    local_name: None,
                    requested_name: None,
                    namespace_alias: None,
                    wildcard: false,
                    import_kind: None,
                });
            }
        }
        let children = node.children(&mut node.walk()).collect::<Vec<_>>();
        stack.extend(children.into_iter().rev());
    }
    refs
}

fn ordinal_for_range(ast_nodes: &[AstPreorderNode], byte_start: usize, byte_end: usize) -> u32 {
    ast_nodes
        .iter()
        .filter(|node| node.byte_start <= byte_start && node.byte_end >= byte_end)
        .min_by_key(|node| (node.byte_end.saturating_sub(node.byte_start), node.ordinal))
        .map(|node| node.ordinal)
        .unwrap_or(0)
}

fn byte_offset(source: &str, line: u32, column: u32) -> usize {
    let mut offset = 0usize;
    for (index, segment) in source.split_inclusive('\n').enumerate() {
        if index as u32 == line {
            return offset + (column as usize).min(segment.len());
        }
        offset += segment.len();
    }
    source.len()
}

fn line_for_byte(source: &str, byte_start: usize) -> u32 {
    source[..byte_start.min(source.len())]
        .bytes()
        .filter(|byte| *byte == b'\n')
        .count() as u32
        + 1
}

fn symbol_kind_name(kind: &SymbolKind) -> &'static str {
    match kind {
        SymbolKind::Function => "function",
        SymbolKind::Kernel => "kernel",
        SymbolKind::Class => "class",
        SymbolKind::Method => "method",
        SymbolKind::Struct => "struct",
        SymbolKind::Interface => "interface",
        SymbolKind::Enum => "enum",
        SymbolKind::TypeAlias => "type_alias",
        SymbolKind::Variable => "variable",
        SymbolKind::Heading => "heading",
        SymbolKind::FileSummary => "file_summary",
    }
}

fn unqualified_symbol_name(scoped_name: &str) -> &str {
    if scoped_name == TOP_LEVEL_SYMBOL {
        return scoped_name;
    }
    scoped_name.rsplit("::").next().unwrap_or(scoped_name)
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn blob_ordinals_are_tree_sitter_preorder_positions() {
        let source = "export function run() { return helper(); }\nfunction helper() {}\n";
        let blob = CallgraphBlob::extract(source, "typescript", "join-test-v1").unwrap();
        let repeated = CallgraphBlob::extract(source, "typescript", "join-test-v1").unwrap();
        let different_version =
            CallgraphBlob::extract(source, "typescript", "join-test-v2").unwrap();
        assert_eq!(blob.to_bytes().unwrap(), repeated.to_bytes().unwrap());
        assert_ne!(
            blob.to_bytes().unwrap(),
            different_version.to_bytes().unwrap()
        );
        let parse = blob.parse().unwrap();
        assert_eq!(parse.ast_nodes[0].ordinal, 0);
        assert!(parse.refs.iter().all(|reference| parse
            .ast_nodes
            .iter()
            .any(|node| node.ordinal == reference.ordinal)));
        let helper = parse
            .refs
            .iter()
            .find(|reference| reference.short_name.as_deref() == Some("helper"))
            .unwrap();
        let node = parse
            .ast_nodes
            .iter()
            .find(|node| node.ordinal == helper.ordinal)
            .unwrap();
        assert!(node.byte_start <= helper.byte_start && node.byte_end >= helper.byte_end);
        assert_eq!(node.kind, "call_expression");
        let mut parser = Parser::new();
        parser
            .set_language(&grammar_for(LangId::TypeScript))
            .unwrap();
        let tree = parser.parse(source, None).unwrap();
        let mut cursor = tree.walk();
        let mut expected = Vec::new();
        'preorder: loop {
            let node = cursor.node();
            expected.push(AstPreorderNode {
                ordinal: expected.len() as u32,
                kind: node.kind().to_string(),
                byte_start: node.start_byte(),
                byte_end: node.end_byte(),
            });
            if cursor.goto_first_child() {
                continue;
            }
            while !cursor.goto_next_sibling() {
                if !cursor.goto_parent() {
                    break 'preorder;
                }
            }
        }
        assert_eq!(parse.ast_nodes, expected);
    }
}

fn structural_ref(raw: super::RawRef, nodes: &[AstPreorderNode]) -> BlobRef {
    BlobRef {
        ordinal: ordinal_for_range(nodes, raw.byte_start, raw.byte_end),
        kind: if raw.kind == "export_alias" {
            BlobRefKind::ExportAlias
        } else {
            BlobRefKind::Reexport
        },
        caller_symbol: raw.caller_symbol,
        short_name: raw.short_name,
        full_ref: raw.full_ref,
        module_path: raw.module_path,
        line: raw.line,
        byte_start: raw.byte_start,
        byte_end: raw.byte_end,
        path_override: None,
        local_name: raw.local_name,
        requested_name: raw.requested_name,
        namespace_alias: raw.namespace_alias,
        wildcard: raw.wildcard,
        import_kind: raw.import_kind,
    }
}

fn bound_name(name: &str, path: &str) -> String {
    name.replace(
        "<default:__callgraph_blob__>",
        &format!(
            "<default:{}>",
            Path::new(path)
                .file_name()
                .unwrap_or_default()
                .to_string_lossy()
        ),
    )
}

impl ParseBlob {
    fn file_data(&self, path: &str) -> Result<FileCallData, ManifestJoinError> {
        let lang = language_id(&self.language)
            .ok_or_else(|| ManifestJoinError::UnsupportedLanguage(self.language.clone()))?;
        let mut calls_by_symbol: HashMap<String, Vec<callgraph::CallSite>> = HashMap::new();
        let mut value_refs_by_symbol: HashMap<String, Vec<callgraph::CallSite>> = HashMap::new();
        for raw in &self.refs {
            let map = match raw.kind {
                BlobRefKind::Call => &mut calls_by_symbol,
                BlobRefKind::ValueRef => &mut value_refs_by_symbol,
                _ => continue,
            };
            let Some(caller) = &raw.caller_symbol else {
                continue;
            };
            map.entry(bound_name(caller, path))
                .or_default()
                .push(callgraph::CallSite {
                    callee_name: raw.short_name.clone().unwrap_or_default(),
                    full_callee: raw.full_ref.clone().unwrap_or_default(),
                    line: raw.line,
                    byte_start: raw.byte_start,
                    byte_end: raw.byte_end,
                });
        }
        for symbol in &self.callable_symbols {
            calls_by_symbol.entry(bound_name(symbol, path)).or_default();
        }
        let mut symbol_metadata = HashMap::new();
        for symbol in &self.symbols {
            let kind = match symbol.kind.as_str() {
                "function" => SymbolKind::Function,
                "method" => SymbolKind::Method,
                "class" => SymbolKind::Class,
                "struct" => SymbolKind::Struct,
                "interface" => SymbolKind::Interface,
                "enum" => SymbolKind::Enum,
                "type_alias" => SymbolKind::TypeAlias,
                "heading" => SymbolKind::Heading,
                "file_summary" => SymbolKind::FileSummary,
                _ => SymbolKind::Variable,
            };
            symbol_metadata.insert(
                bound_name(&symbol.scoped_name, path),
                SymbolMeta {
                    kind,
                    exported: symbol.exported,
                    signature: symbol.signature.clone(),
                    line: symbol.start_line + 1,
                    range: crate::symbols::Range {
                        start_line: symbol.start_line,
                        start_col: symbol.start_col,
                        end_line: symbol.end_line,
                        end_col: symbol.end_col,
                    },
                    entry_point_attribute: None,
                },
            );
        }
        let imports = self
            .imports
            .iter()
            .map(|import| ImportStatement {
                module_path: import.module_path.clone(),
                names: import.names.clone(),
                default_import: import.default_import.clone(),
                namespace_import: import.namespace_import.clone(),
                kind: if import.type_only {
                    ImportKind::Type
                } else if import.side_effect {
                    ImportKind::SideEffect
                } else {
                    ImportKind::Value
                },
                group: ImportGroup::Internal,
                byte_range: import.byte_start..import.byte_end,
                raw_text: import.raw_text.clone(),
                form: if lang == LangId::Rust {
                    ImportForm::RustUse {
                        visibility: import.default_import.clone(),
                        named: import.names.clone(),
                    }
                } else {
                    ImportForm::Es {
                        default_import: import.default_import.clone(),
                        namespace_import: import.namespace_import.clone(),
                        named: import.names.clone(),
                        type_only: import.type_only,
                        side_effect: import.side_effect,
                        attribute_clause: None,
                        attribute_type: None,
                    }
                },
            })
            .collect::<Vec<_>>();
        Ok(FileCallData {
            calls_by_symbol,
            value_refs_by_symbol,
            symbol_metadata,
            exported_symbols: self
                .exported_symbols
                .iter()
                .map(|s| bound_name(s, path))
                .collect(),
            default_export_symbol: self
                .default_export_symbol
                .as_ref()
                .map(|s| bound_name(s, path)),
            import_block: ImportBlock {
                imports,
                byte_range: None,
            },
            lang,
        })
    }

    fn bind(
        &self,
        path: &str,
        facts: &FactPaths<'_>,
    ) -> Result<super::FileExtract, ManifestJoinError> {
        self.bind_with_dependencies(path, facts, None)
    }

    fn bind_with_dependencies(
        &self,
        path: &str,
        facts: &FactPaths<'_>,
        cached: Option<&BTreeMap<u32, BTreeSet<String>>>,
    ) -> Result<super::FileExtract, ManifestJoinError> {
        let data = self.file_data(path)?;
        let nodes = self
            .symbols
            .iter()
            .map(|symbol| {
                let scoped_name = bound_name(&symbol.scoped_name, path);
                super::NodeRecord {
                    id: format!("{path}:{}:{scoped_name}", symbol.ordinal),
                    file_path: path.to_string(),
                    name: bound_name(&symbol.name, path),
                    scoped_name,
                    kind: symbol.kind.clone(),
                    range: crate::symbols::Range {
                        start_line: symbol.start_line,
                        start_col: symbol.start_col,
                        end_line: symbol.end_line,
                        end_col: symbol.end_col,
                    },
                    range_ordinal: symbol.ordinal,
                    signature: symbol.signature.clone(),
                    exported: symbol.exported,
                    is_default_export: symbol.is_default_export,
                    is_type_like: false,
                    is_callgraph_entry_point: false,
                }
            })
            .collect::<Vec<_>>();
        let abs = facts.root.join(path);
        let mut raw_refs = Vec::new();
        for (position, raw) in self.refs.iter().enumerate() {
            let position = u32::try_from(position).expect("reference vector fits u32");
            let dependencies =
                if let Some(dependencies) = cached.and_then(|cache| cache.get(&position)) {
                    dependencies.clone()
                } else if raw.kind == BlobRefKind::Module {
                    super::rust_external_module_target(
                        &abs,
                        raw.path_override.as_deref(),
                        raw.module_path.as_deref().unwrap_or_default(),
                        facts,
                    )
                    .and_then(|p| facts.canonical(&p))
                    .map(|p| super::relative_path(facts.root, &p))
                    .into_iter()
                    .collect()
                } else if let Some(module) = &raw.module_path {
                    super::module_dependencies(facts.root, &abs, module, facts)
                } else {
                    BTreeSet::new()
                };
            let caller_symbol = raw
                .caller_symbol
                .as_ref()
                .map(|name| bound_name(name, path));
            let caller_node = caller_symbol.as_ref().and_then(|name| {
                nodes
                    .iter()
                    .find(|n| &n.scoped_name == name)
                    .map(|n| n.id.clone())
            });
            raw_refs.push(super::RawRef {
                ref_id: format!("{path}:{}:{:?}", raw.ordinal, raw.kind),
                caller_node,
                caller_symbol,
                caller_file: path.to_string(),
                kind: match raw.kind {
                    BlobRefKind::Call => "call",
                    BlobRefKind::ValueRef => "value_ref",
                    BlobRefKind::Import => "import",
                    BlobRefKind::Module => "module",
                    BlobRefKind::Reexport => "reexport",
                    BlobRefKind::ExportAlias => "export_alias",
                }
                .to_string(),
                short_name: raw.short_name.clone(),
                full_ref: raw.full_ref.clone(),
                module_path: raw.module_path.clone(),
                import_kind: raw.import_kind.clone(),
                local_name: raw.local_name.clone(),
                requested_name: raw.requested_name.clone(),
                namespace_alias: raw.namespace_alias.clone(),
                wildcard: raw.wildcard,
                line: raw.line,
                byte_start: raw.byte_start,
                byte_end: raw.byte_end,
                dependencies,
            });
        }
        Ok(super::FileExtract {
            rel_path: path.to_string(),
            freshness: crate::cache_freshness::FileFreshness {
                mtime: std::time::UNIX_EPOCH,
                size: 0,
                content_hash: crate::cache_freshness::zero_hash(),
            },
            lang: data.lang,
            data,
            nodes,
            raw_refs,
            dispatch_hints: Vec::new(),
            surface_fingerprint: String::new(),
        })
    }
}

/// A manifest-backed index is the ordinary resolver index with different facts.
type ManifestProjectIndex<'a> = super::ProjectIndex<'a>;

impl JoinResult {
    pub fn from_manifest(
        manifest: &Manifest,
        blobs: &impl ManifestBlobReader,
    ) -> Result<Self, ManifestJoinError> {
        let loaded = manifest_payloads(manifest, blobs)?;
        let reader = |key: &BlobKey| loaded.get(key).cloned();
        let facts = Rc::new(ManifestFacts {
            manifest,
            blobs: &reader,
        });
        Self::from_facts(manifest, &loaded, Path::new("/"), facts, None)
    }

    fn from_facts<'a>(
        manifest: &'a Manifest,
        loaded: &BTreeMap<String, Arc<[u8]>>,
        root: &Path,
        facts: Rc<dyn ProjectFacts + 'a>,
        selected: Option<&BTreeSet<CallerRefKey>>,
    ) -> Result<Self, ManifestJoinError> {
        let paths = FactPaths {
            root,
            facts: facts.as_ref(),
        };
        let mut extracts = HashMap::new();
        let mut work = Vec::new();
        let mut unbound_non_utf8_paths = Vec::new();
        for (path, entry) in manifest.entries() {
            let ManifestEntry::Regular { planes, .. } = entry else {
                continue;
            };
            let Some(key) = &planes.callgraph else {
                continue;
            };
            let bytes = loaded
                .get(key)
                .ok_or_else(|| ManifestJoinError::MissingBlob(key.clone()))?;
            let CallgraphBlob::Parse(blob) = CallgraphBlob::from_bytes(bytes)? else {
                continue;
            };
            let Ok(rel) = std::str::from_utf8(path.as_bytes()) else {
                unbound_non_utf8_paths.push(path.as_bytes().to_vec());
                continue;
            };
            let extract = blob.bind(rel, &paths)?;
            for (raw, bound) in blob.refs.iter().zip(&extract.raw_refs) {
                let ref_key = CallerRefKey {
                    caller_blob_key: key.clone(),
                    ref_ordinal: raw.ordinal,
                    caller_path: path.as_bytes().to_vec(),
                };
                if selected.is_none_or(|set| set.contains(&ref_key)) {
                    work.push((ref_key, (raw.kind, bound.clone())));
                }
            }
            extracts.insert(rel.to_string(), extract);
        }
        let files = extracts
            .iter()
            .map(|(path, extract)| {
                (
                    path.clone(),
                    super::DbFileIndex::from_extract(root, extract, &paths),
                )
            })
            .collect();
        let caller_data = extracts
            .iter()
            .map(|(path, extract)| (path.clone(), &extract.data))
            .collect();
        let mut index = ManifestProjectIndex::from_parts(
            root,
            files,
            caller_data,
            super::WorkspaceCratePrefixCache::default(),
            facts,
        );
        index.unbound_non_utf8_paths = unbound_non_utf8_paths;
        if !index.unbound_non_utf8_paths.is_empty() {
            log::warn!(
                "callgraph index left {} non-UTF-8 source paths unbound",
                index.unbound_non_utf8_paths.len()
            );
        }
        let mut result = Self {
            rows: BTreeSet::new(),
            resolution_order: Vec::new(),
            unbound_non_utf8_paths: index.unbound_non_utf8_paths.clone(),
        };
        work.sort_by(|a, b| (&a.0, a.1 .0).cmp(&(&b.0, b.1 .0)));
        for (key, (kind, raw)) in work {
            let resolved = super::resolve_ref(raw, &index)
                .map_err(|error| ManifestJoinError::Parse(error.to_string()))?;
            result.rows.insert(DerivedRow {
                caller_blob_key: key.caller_blob_key.clone(),
                ref_ordinal: key.ref_ordinal,
                caller_path: key.caller_path.clone(),
                kind,
                status: if resolved.target_file.is_some() {
                    ResolutionStatus::Resolved
                } else {
                    ResolutionStatus::Unresolved
                },
                target_path: resolved.target_file.map(String::into_bytes),
                target_symbol: resolved.target_symbol,
            });
            result.resolution_order.push(key);
        }
        Ok(result)
    }

    pub fn update(
        &self,
        previous_manifest: &Manifest,
        manifest: &Manifest,
        blobs: &impl ManifestBlobReader,
    ) -> Result<IncrementalJoinResult, ManifestJoinError> {
        let changed = changed_manifest_paths(previous_manifest, manifest);
        let full_re_resolve = changed.iter().any(|path| {
            manifest_resolution_input(previous_manifest, path)
                || manifest_resolution_input(manifest, path)
        });
        let loaded = manifest_payloads(manifest, blobs)?;
        let reader = |key: &BlobKey| loaded.get(key).cloned();
        let mut current_keys = BTreeSet::new();
        for (path, entry) in manifest.entries() {
            if std::str::from_utf8(path.as_bytes()).is_err() {
                continue;
            }
            let ManifestEntry::Regular { planes, .. } = entry else {
                continue;
            };
            let Some(key) = &planes.callgraph else {
                continue;
            };
            if let CallgraphBlob::Parse(blob) = CallgraphBlob::from_bytes(&loaded[key])? {
                current_keys.extend(blob.refs.iter().map(|raw| CallerRefKey {
                    caller_blob_key: key.clone(),
                    ref_ordinal: raw.ordinal,
                    caller_path: path.as_bytes().to_vec(),
                }));
            }
        }
        let previous_rows = self
            .rows
            .iter()
            .map(|row| (row.ref_key(), row))
            .collect::<BTreeMap<_, _>>();
        let selected = current_keys
            .iter()
            .filter(|key| {
                full_re_resolve
                    || changed.contains(&key.caller_path)
                    || previous_rows.get(*key).is_none_or(|row| {
                        row.target_path
                            .as_ref()
                            .is_some_and(|path| changed.contains(path))
                    })
            })
            .cloned()
            .collect::<BTreeSet<_>>();
        let facts = Rc::new(ManifestFacts {
            manifest,
            blobs: &reader,
        });
        let mut result =
            Self::from_facts(manifest, &loaded, Path::new("/"), facts, Some(&selected))?;
        result.rows.extend(
            self.rows
                .iter()
                .filter(|row| {
                    current_keys.contains(&row.ref_key()) && !selected.contains(&row.ref_key())
                })
                .cloned(),
        );
        result.resolution_order = result.rows.iter().map(DerivedRow::ref_key).collect();
        result.resolution_order.sort();
        Ok(IncrementalJoinResult {
            result,
            re_resolved: selected,
            full_re_resolve,
        })
    }
}

fn manifest_payloads(
    manifest: &Manifest,
    blobs: &impl ManifestBlobReader,
) -> Result<BTreeMap<String, Arc<[u8]>>, ManifestJoinError> {
    let mut loaded = BTreeMap::new();
    for (_, entry) in manifest.entries() {
        let ManifestEntry::Regular { planes, .. } = entry else {
            continue;
        };
        let Some(key) = &planes.callgraph else {
            continue;
        };
        if !loaded.contains_key(key) {
            let bytes = blobs
                .read_callgraph_blob(key)?
                .ok_or_else(|| ManifestJoinError::MissingBlob(key.clone()))?;
            loaded.insert(key.clone(), Arc::from(bytes));
        }
    }
    Ok(loaded)
}

#[cfg(test)]
#[path = "../../tests/integration/join_manifest_test.rs"]
mod manifest_integration_tests;

/// Bound reference dependencies and resolver probes are generation-specific, unlike
/// parse blobs. The owner must invalidate these whenever a probed path changes.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub(crate) struct ViewBindingDependencies {
    // AST ordinals can collide for structural references. Vector positions are
    // unique and stable within the immutable caller blob used to validate reuse.
    pub references: BTreeMap<u32, BTreeSet<String>>,
    pub dependencies: BTreeSet<String>,
    #[serde(default)]
    pub consulted_facts: BTreeSet<(String, String)>,
    #[serde(default)]
    pub unattributed: bool,
    #[serde(default)]
    binding_facts: ConfigConsultations,
    #[serde(default)]
    resolution_facts: ConfigConsultations,
    binding_probes: BTreeSet<String>,
    resolved_dependencies: BTreeSet<String>,
    surface_queries: Vec<(ViewSurfaceQuery, String)>,
    #[serde(default)]
    surface: Option<ViewFileSurface>,
}

/// Inputs that determine a reference's target, excluding call-site identity.
/// Rust qualified imports are visible only after their declaration; the count
/// of visible imports identifies that monotone prefix even across nested uses.
#[derive(Hash, PartialEq, Eq)]
struct ViewResolutionBinding {
    caller: String,
    kind: String,
    full_ref: Option<String>,
    short_name: Option<String>,
    visible_rust_imports: usize,
}

impl ViewResolutionBinding {
    fn new(raw: &super::RawRef, caller: &FileCallData) -> Self {
        Self {
            caller: raw.caller_file.clone(),
            kind: raw.kind.clone(),
            full_ref: raw.full_ref.clone(),
            short_name: raw.short_name.clone(),
            visible_rust_imports: if caller.lang == LangId::Rust {
                caller
                    .import_block
                    .imports
                    .iter()
                    .filter(|import| import.byte_range.start <= raw.byte_start)
                    .count()
            } else {
                0
            },
        }
    }
}

pub(crate) struct SelectedManifestJoin {
    pub result: JoinResult,
    pub bindings: BTreeMap<String, ViewBindingDependencies>,
    pub resolved_callers: BTreeSet<String>,
    pub rebuilt_surface_entries: usize,
    pub decoded_caller_blobs: usize,
    pub resolved_bindings: usize,
}

/// Compact, deterministic snapshot of one file's resolver index. It deliberately
/// excludes source, AST nodes, and call sites: only callers actually resolved need
/// those payloads. Membership probes invalidate module/reexport targets along with
/// bindings; source changes invalidate the snapshot through the manifest diff.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
struct ViewFileSurface {
    language: String,
    exports: BTreeSet<String>,
    default_export: Option<String>,
    export_aliases: BTreeMap<String, String>,
    node_by_scoped: BTreeMap<String, String>,
    node_by_bare: BTreeMap<String, String>,
    node_kind_by_id: BTreeMap<String, String>,
    module_targets: BTreeMap<String, Option<String>>,
    declared_module_targets: BTreeMap<String, Option<String>>,
    reexports: Vec<(Option<String>, BTreeMap<String, String>, bool)>,
}

impl ViewFileSurface {
    fn capture(language: &str, index: &super::DbFileIndex) -> Self {
        Self {
            language: language.into(),
            exports: index.exports.iter().cloned().collect(),
            default_export: index.default_export.clone(),
            export_aliases: index.export_aliases.clone().into_iter().collect(),
            node_by_scoped: index.node_by_scoped.clone().into_iter().collect(),
            node_by_bare: index.node_by_bare.clone().into_iter().collect(),
            node_kind_by_id: index.node_kind_by_id.clone().into_iter().collect(),
            module_targets: index.module_targets.clone().into_iter().collect(),
            declared_module_targets: index.declared_module_targets.clone().into_iter().collect(),
            reexports: index
                .reexports
                .iter()
                .map(|r| {
                    (
                        r.target_file.clone(),
                        r.named.clone().into_iter().collect(),
                        r.wildcard,
                    )
                })
                .collect(),
        }
    }

    fn restore(&self) -> super::DbFileIndex {
        super::DbFileIndex {
            lang: language_id(&self.language),
            exports: self.exports.iter().cloned().collect(),
            default_export: self.default_export.clone(),
            export_aliases: self.export_aliases.clone().into_iter().collect(),
            node_by_scoped: self.node_by_scoped.clone().into_iter().collect(),
            node_by_bare: self.node_by_bare.clone().into_iter().collect(),
            node_kind_by_id: self.node_kind_by_id.clone().into_iter().collect(),
            module_targets: self.module_targets.clone().into_iter().collect(),
            declared_module_targets: self.declared_module_targets.clone().into_iter().collect(),
            reexports: self
                .reexports
                .iter()
                .map(|(target_file, named, wildcard)| super::ReexportIndex {
                    target_file: target_file.clone(),
                    named: named.clone().into_iter().collect(),
                    wildcard: *wildcard,
                })
                .collect(),
        }
    }
}

/// Configuration files read by the manifest resolver's workspace/package and
/// tsconfig lookup (callgraph.rs), and Rust crate lookup (callgraph_store).
/// Directory discovery uses a compact membership domain for these names. Their
/// content changes invalidate only callers that consulted changed fields.
pub(crate) fn view_resolution_config(path: &[u8]) -> bool {
    matches!(
        path.rsplit(|byte| *byte == b'/').next(),
        Some(b"package.json" | b"tsconfig.json" | b"pnpm-workspace.yaml" | b"Cargo.toml")
    )
}

/// Field identities are generation-owned. Raw-read paths are transient validation
/// evidence, cleared after classifying a caller so memo-hit timing is not persisted.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
struct ConfigConsultations {
    facts: BTreeSet<(String, String)>,
    reads: BTreeSet<String>,
    unattributed: bool,
}
impl ConfigConsultations {
    fn extend(&mut self, other: &Self) {
        self.facts.extend(other.facts.iter().cloned());
        self.reads.extend(other.reads.iter().cloned());
        self.unattributed |= other.unattributed;
    }
    fn unattributed(&self) -> bool {
        self.unattributed
            || self
                .reads
                .iter()
                .any(|path| !self.facts.iter().any(|(input, _)| input == path))
    }
}

#[derive(Clone, Default)]
struct ConsultationTrace {
    config: ConfigConsultations,
    probes: BTreeSet<String>,
}
type ConsultationMemoKey = (std::path::PathBuf, String, String);

/// Memo answers and their provenance belong to one immutable manifest join.
/// Replaying provenance on hits keeps missing candidates and facts attributable.
struct ViewBindingFacts<'a> {
    inner: Rc<dyn ProjectFacts + 'a>,
    probes: std::cell::RefCell<BTreeSet<String>>,
    consultations: std::cell::RefCell<ConfigConsultations>,
    memo_stack: std::cell::RefCell<Vec<(ConsultationMemoKey, ConsultationTrace)>>,
    memo_traces: std::cell::RefCell<BTreeMap<ConsultationMemoKey, ConsultationTrace>>,
    workspace_packages:
        std::cell::RefCell<BTreeMap<(std::path::PathBuf, String), Option<std::path::PathBuf>>>,
    workspace_members:
        std::cell::RefCell<BTreeMap<std::path::PathBuf, Arc<Vec<std::path::PathBuf>>>>,
    canonical_cache: std::cell::RefCell<HashMap<Vec<u8>, Option<Vec<u8>>>>,
    file_cache: std::cell::RefCell<HashMap<Vec<u8>, bool>>,
    config_cache: std::cell::RefCell<HashMap<Vec<u8>, Option<Arc<[u8]>>>>,
    directory_cache: std::cell::RefCell<HashMap<Vec<u8>, Vec<super::facts::DirEntry>>>,
}

impl<'a> ViewBindingFacts<'a> {
    fn new(inner: Rc<dyn ProjectFacts + 'a>) -> Self {
        Self {
            inner,
            probes: Default::default(),
            consultations: Default::default(),
            memo_stack: Default::default(),
            memo_traces: Default::default(),
            workspace_packages: Default::default(),
            workspace_members: Default::default(),
            canonical_cache: Default::default(),
            file_cache: Default::default(),
            config_cache: Default::default(),
            directory_cache: Default::default(),
        }
    }
    fn file_fact(&self, rel: &[u8]) -> bool {
        if let Some(value) = self.file_cache.borrow().get(rel) {
            return *value;
        }
        let value = self.inner.is_file(rel);
        self.file_cache.borrow_mut().insert(rel.to_vec(), value);
        value
    }

    fn record(&self, path: &[u8]) {
        // Directory discovery may probe thousands of missing package manifests.
        // One membership domain rechecks those bindings on config add/remove;
        // individual config content changes use the field consultations instead.
        if view_resolution_config(path) {
            self.record(VIEW_CONFIG_MEMBERSHIP_DOMAIN.as_bytes());
            return;
        }
        if let Ok(path) = std::str::from_utf8(path) {
            let mut parts = Vec::new();
            for part in path.split('/') {
                match part {
                    "" | "." => {}
                    ".." => {
                        parts.pop();
                    }
                    _ => parts.push(part),
                }
            }
            let path = parts.join("/");
            self.probes.borrow_mut().insert(path.clone());
            for (_, trace) in self.memo_stack.borrow_mut().iter_mut() {
                trace.probes.insert(path.clone());
            }
        }
    }

    fn take_config(&self) -> ConfigConsultations {
        let mut result = std::mem::take(&mut *self.consultations.borrow_mut());
        result.unattributed = result.unattributed();
        result.reads.clear();
        result
    }

    fn config_event(&self, path: &[u8], name: Option<&str>) {
        let Ok(path) = std::str::from_utf8(path) else {
            self.consultations.borrow_mut().unattributed = true;
            return;
        };
        let mut event = ConfigConsultations::default();
        if let Some(name) = name {
            event.facts.insert((path.into(), name.into()));
        } else {
            event.reads.insert(path.into());
        }
        self.consultations.borrow_mut().extend(&event);
        for (_, trace) in self.memo_stack.borrow_mut().iter_mut() {
            trace.config.extend(&event);
        }
    }

    fn take(&self) -> BTreeSet<String> {
        std::mem::take(&mut *self.probes.borrow_mut())
    }
}

impl ProjectFacts for ViewBindingFacts<'_> {
    fn records_config_facts(&self) -> bool {
        true
    }
    fn config_fact(&self, rel: &[u8], name: &str) {
        self.record(rel);
        if matches!(name, "workspaces" | "packages") {
            self.record(VIEW_CONFIG_MEMBERSHIP_DOMAIN.as_bytes());
        }
        self.config_event(rel, Some(name));
    }
    fn memo_start(&self, path: &Path, kind: &str, name: &str) {
        self.memo_stack.borrow_mut().push((
            (path.into(), kind.into(), name.into()),
            ConsultationTrace::default(),
        ));
    }
    fn memo_finish(&self, path: &Path, kind: &str, name: &str) {
        let (key, trace) = self
            .memo_stack
            .borrow_mut()
            .pop()
            .expect("balanced resolver memo recording");
        debug_assert_eq!(key, (path.into(), kind.into(), name.into()));
        self.memo_traces.borrow_mut().insert(key, trace);
    }
    fn memo_replay(&self, path: &Path, kind: &str, name: &str) {
        let traces = self.memo_traces.borrow();
        let Some(trace) = traces.get(&(path.into(), kind.into(), name.into())) else {
            self.consultations.borrow_mut().unattributed = true;
            return;
        };
        self.consultations.borrow_mut().extend(&trace.config);
        self.probes
            .borrow_mut()
            .extend(trace.probes.iter().cloned());
        for (_, parent) in self.memo_stack.borrow_mut().iter_mut() {
            parent.config.extend(&trace.config);
            parent.probes.extend(trace.probes.iter().cloned());
        }
    }
    fn workspace_package(&self, root: &Path, name: &str) -> Option<Option<std::path::PathBuf>> {
        self.workspace_packages
            .borrow()
            .get(&(root.into(), name.into()))
            .cloned()
    }
    fn remember_workspace_package(
        &self,
        root: &Path,
        name: &str,
        value: Option<std::path::PathBuf>,
    ) {
        self.workspace_packages
            .borrow_mut()
            .insert((root.into(), name.into()), value);
    }
    fn workspace_members(&self, root: &Path) -> Option<Arc<Vec<std::path::PathBuf>>> {
        self.workspace_members.borrow().get(root).cloned()
    }
    fn remember_workspace_members(&self, root: &Path, value: Arc<Vec<std::path::PathBuf>>) {
        self.workspace_members
            .borrow_mut()
            .insert(root.into(), value);
    }
    fn is_file(&self, rel: &[u8]) -> bool {
        let is_file = self.file_fact(rel);
        if is_file {
            self.record(rel);
        }
        is_file
    }
    fn is_dir(&self, rel: &[u8]) -> bool {
        self.inner.is_dir(rel)
    }
    fn config_bytes(&self, rel: &[u8]) -> Option<Arc<[u8]>> {
        self.consultations.borrow_mut().unattributed = true;
        for (_, trace) in self.memo_stack.borrow_mut().iter_mut() {
            trace.config.unattributed = true;
        }
        self.attributed_config_bytes(rel)
    }
    fn attributed_config_bytes(&self, rel: &[u8]) -> Option<Arc<[u8]>> {
        self.config_event(rel, None);
        self.record(rel);
        if let Some(value) = self.config_cache.borrow().get(rel) {
            return value.clone();
        }
        let value = self.inner.config_bytes(rel);
        self.config_cache
            .borrow_mut()
            .insert(rel.to_vec(), value.clone());
        value
    }
    fn symlink_target(&self, rel: &[u8]) -> Option<&[u8]> {
        self.inner.symlink_target(rel)
    }
    fn canonical(&self, rel: &[u8]) -> Option<Vec<u8>> {
        // FactPaths canonicalizes before testing existence, so misses must be
        // recorded here as well as in is_file (not only after canonicalization).
        let cached = self.canonical_cache.borrow().get(rel).cloned();
        let canonical = cached.unwrap_or_else(|| {
            let value = self.inner.canonical(rel);
            self.canonical_cache
                .borrow_mut()
                .insert(rel.to_vec(), value.clone());
            value
        });
        // Existing directory probes are workspace-discovery implementation detail.
        // Config add/remove rechecks that discovery through its membership domain;
        // source-file probes and misses remain caller-specific dependencies.
        if canonical.as_ref().is_none_or(|path| self.file_fact(path)) {
            self.record(rel);
        }
        canonical
    }
    fn list_dir(&self, rel: &[u8]) -> Vec<super::facts::DirEntry> {
        if let Some(value) = self.directory_cache.borrow().get(rel) {
            return value.clone();
        }
        let value = self.inner.list_dir(rel);
        self.directory_cache
            .borrow_mut()
            .insert(rel.to_vec(), value.clone());
        value
    }
}

/// Resolve selected callers against the complete symbol index. Cached binding
/// dependencies avoid resolving unchanged imports merely to rebuild that index.
/// `selected=None` is the cold path; otherwise the owner supplies the transitive
/// reverse-dependency closure and caches from the same base generation.
#[cfg(test)]
pub(crate) fn join_selected_manifest(
    manifest: &Manifest,
    blobs: &impl ManifestBlobReader,
    selected: Option<&BTreeSet<String>>,
    cached: &BTreeMap<String, ViewBindingDependencies>,
) -> Result<SelectedManifestJoin, ManifestJoinError> {
    join_manifest_with_surfaces(manifest, blobs, selected, cached, None)
}

/// Rebind only changed callers or callers that probed changed membership. Other
/// candidates replay their prior consumer-specific surface queries and retain
/// their reference rows when every answer is unchanged.
pub(crate) fn join_selected_manifest_reusing_surfaces(
    manifest: &Manifest,
    blobs: &impl ManifestBlobReader,
    selected: Option<&BTreeSet<String>>,
    cached: &BTreeMap<String, ViewBindingDependencies>,
    changed: &BTreeSet<String>,
    membership_changed: &BTreeSet<String>,
    fact_invalidated: &BTreeSet<String>,
) -> Result<SelectedManifestJoin, ManifestJoinError> {
    join_manifest_with_surfaces(
        manifest,
        blobs,
        selected,
        cached,
        Some((changed, membership_changed, fact_invalidated)),
    )
}

fn join_manifest_with_surfaces(
    manifest: &Manifest,
    blobs: &impl ManifestBlobReader,
    selected: Option<&BTreeSet<String>>,
    cached: &BTreeMap<String, ViewBindingDependencies>,
    reuse: Option<(&BTreeSet<String>, &BTreeSet<String>, &BTreeSet<String>)>,
) -> Result<SelectedManifestJoin, ManifestJoinError> {
    let mut profile = crate::views::materialization::profile::PhaseTimer::new("join");
    let loaded = std::cell::RefCell::new(BTreeMap::<BlobKey, Arc<[u8]>>::new());
    let load = |key: &BlobKey| -> Result<Arc<[u8]>, ManifestJoinError> {
        if let Some(bytes) = loaded.borrow().get(key) {
            return Ok(bytes.clone());
        }
        let bytes: Arc<[u8]> = blobs
            .read_callgraph_blob(key)?
            .ok_or_else(|| ManifestJoinError::MissingBlob(key.clone()))?
            .into();
        loaded.borrow_mut().insert(key.clone(), bytes.clone());
        Ok(bytes)
    };
    let read_error = std::cell::RefCell::new(None);
    let reader = |key: &BlobKey| match load(key) {
        Ok(bytes) => Some(bytes),
        Err(error) => {
            *read_error.borrow_mut() = Some(error);
            None
        }
    };
    profile.finish("load_payloads");
    let facts = Rc::new(ViewBindingFacts::new(Rc::new(ManifestFacts {
        manifest,
        blobs: &reader,
    })));
    let root = Path::new("/");
    let paths = FactPaths {
        root,
        facts: facts.as_ref(),
    };
    let mut extracts = HashMap::new();
    let mut files = HashMap::new();
    let mut work = Vec::new();
    let mut bindings = BTreeMap::new();
    let mut unbound_non_utf8_paths = Vec::new();
    let mut rebuilt_surface_entries = 0;
    let mut decoded_caller_blobs = 0;
    for (path, entry) in manifest.entries() {
        let ManifestEntry::Regular { planes, .. } = entry else {
            continue;
        };
        let Some(key) = &planes.callgraph else {
            continue;
        };
        let Ok(rel) = std::str::from_utf8(path.as_bytes()) else {
            if matches!(
                CallgraphBlob::from_bytes(&load(key)?)?,
                CallgraphBlob::Parse(_)
            ) {
                unbound_non_utf8_paths.push(path.as_bytes().to_vec());
            }
            continue;
        };
        let resolve = selected.is_none_or(|set| set.contains(rel));
        let cache = cached.get(rel).filter(|cache| {
            if let Some((changed, membership, fact_invalidated)) = reuse {
                selected.is_some()
                    && !changed.contains(rel)
                    && !fact_invalidated.contains(rel)
                    && cache.dependencies.is_disjoint(membership)
            } else {
                !resolve
            }
        });
        if let Some((cache, surface)) =
            cache.and_then(|cache| cache.surface.as_ref().map(|surface| (cache, surface)))
        {
            files.insert(rel.to_string(), surface.restore());
            bindings.insert(rel.to_string(), cache.clone());
            continue;
        }
        let CallgraphBlob::Parse(blob) = CallgraphBlob::from_bytes(&load(key)?)? else {
            continue;
        };
        decoded_caller_blobs += 1;
        facts.take();
        facts.take_config();
        let extract =
            blob.bind_with_dependencies(rel, &paths, cache.map(|cache| &cache.references))?;
        let file_index = super::DbFileIndex::from_extract(root, &extract, &paths);
        rebuilt_surface_entries += 1;
        let mut binding = cache.cloned().unwrap_or_default();
        binding.surface = Some(ViewFileSurface::capture(&blob.language, &file_index));
        files.insert(rel.to_string(), file_index);
        if cache.is_none() {
            binding.references = blob
                .refs
                .iter()
                .zip(&extract.raw_refs)
                .enumerate()
                .map(|(position, (_, bound))| {
                    (
                        u32::try_from(position).expect("reference vector fits u32"),
                        bound.dependencies.clone(),
                    )
                })
                .collect();
            binding.binding_probes = facts.take();
            binding.binding_facts = facts.take_config();
            binding.dependencies = binding.references.values().flatten().cloned().collect();
            binding
                .dependencies
                .extend(binding.binding_probes.iter().cloned());
        }
        bindings.insert(rel.to_string(), binding);
        if resolve {
            for (raw, bound) in blob.refs.iter().zip(&extract.raw_refs) {
                work.push((
                    CallerRefKey {
                        caller_blob_key: key.clone(),
                        ref_ordinal: raw.ordinal,
                        caller_path: path.as_bytes().to_vec(),
                    },
                    (raw.kind, bound.clone()),
                ));
            }
        }
        extracts.insert(rel.to_string(), extract);
    }
    profile.finish("decode_bind_index_entries");
    let index = ManifestProjectIndex::from_parts(
        root,
        files,
        HashMap::new(),
        super::WorkspaceCratePrefixCache::default(),
        facts.clone(),
    );
    let mut result = JoinResult {
        rows: BTreeSet::new(),
        resolution_order: Vec::new(),
        unbound_non_utf8_paths,
    };
    let resolved_callers = bindings
        .keys()
        .filter(|path| {
            if selected.is_some_and(|set| !set.contains(*path)) {
                return false;
            }
            let Some((changed, _, _)) = reuse else {
                return true;
            };
            if selected.is_none() || changed.contains(*path) {
                return true;
            }
            cached.get(*path).is_none_or(|old| {
                old.references != bindings[*path].references
                    || old
                        .surface_queries
                        .iter()
                        .any(|(query, expected)| query.answer(&index) != *expected)
            })
        })
        .cloned()
        .collect::<BTreeSet<_>>();
    for (path, binding) in &mut bindings {
        if resolved_callers.contains(path) {
            binding.resolved_dependencies.clear();
            binding.surface_queries.clear();
            binding.resolution_facts = ConfigConsultations::default();
        } else if let Some(old) = cached.get(path) {
            binding.resolved_dependencies = old.resolved_dependencies.clone();
            binding.surface_queries = old.surface_queries.clone();
        }
    }
    profile.finish("index_and_surface_replay");
    // Surface replay needs no call sites. Decode an unchanged caller only after
    // replay proves that its reference results may change.
    for caller in &resolved_callers {
        if extracts.contains_key(caller) {
            continue;
        }
        let path = RelPath::new(caller.as_bytes().to_vec()).expect("bound manifest path");
        let Some(ManifestEntry::Regular { planes, .. }) = manifest.get(&path) else {
            continue;
        };
        let key = planes.callgraph.as_ref().expect("bound caller key");
        let CallgraphBlob::Parse(blob) = CallgraphBlob::from_bytes(&load(key)?)? else {
            continue;
        };
        decoded_caller_blobs += 1;
        facts.take();
        facts.take_config();
        let extract =
            blob.bind_with_dependencies(caller, &paths, Some(&bindings[caller].references))?;
        for (raw, bound) in blob.refs.iter().zip(&extract.raw_refs) {
            work.push((
                CallerRefKey {
                    caller_blob_key: key.clone(),
                    ref_ordinal: raw.ordinal,
                    caller_path: caller.as_bytes().to_vec(),
                },
                (raw.kind, bound.clone()),
            ));
        }
        extracts.insert(caller.clone(), extract);
    }
    let index = ManifestProjectIndex::from_parts(
        root,
        index.files,
        extracts
            .iter()
            .map(|(path, extract)| (path.clone(), &extract.data))
            .collect(),
        super::WorkspaceCratePrefixCache::default(),
        facts.clone(),
    );
    profile.finish("decode_resolved_callers");
    let surface_index = ViewSurfaceIndex {
        inner: &index,
        queries: Default::default(),
    };
    let mut queries = BTreeMap::<String, BTreeMap<ViewSurfaceQuery, String>>::new();
    let bases: BTreeMap<_, BTreeSet<_>> = resolved_callers
        .iter()
        .map(|caller| {
            let binding = &bindings[caller];
            (
                caller.clone(),
                binding
                    .references
                    .values()
                    .flatten()
                    .chain(binding.binding_probes.iter())
                    .cloned()
                    .collect(),
            )
        })
        .collect();
    let mut resolutions = HashMap::<ViewResolutionBinding, (Option<String>, Option<String>)>::new();
    work.sort_by(|a, b| (&a.0, a.1 .0).cmp(&(&b.0, b.1 .0)));
    for (key, (kind, raw)) in work {
        let caller = std::str::from_utf8(&key.caller_path).expect("bound UTF-8 caller");
        if !resolved_callers.contains(caller) {
            continue;
        }
        let memo_key = ViewResolutionBinding::new(&raw, &extracts[caller].data);
        let binding = bindings.get_mut(caller).expect("bound caller dependencies");
        let basis = &bases[caller];
        // Dependencies belonging to a call site are not part of the memoized
        // target. Preserve them even when another reference resolved its binding.
        binding.resolved_dependencies.extend(
            raw.dependencies
                .iter()
                .filter(|dependency| !basis.contains(*dependency))
                .cloned(),
        );
        let (target_file, target_symbol) = match resolutions.entry(memo_key) {
            std::collections::hash_map::Entry::Occupied(entry) => entry.get().clone(),
            std::collections::hash_map::Entry::Vacant(entry) => {
                facts.take();
                facts.take_config();
                let resolved = super::resolve_ref(raw, &surface_index)
                    .map_err(|error| ManifestJoinError::Parse(error.to_string()))?;
                // The key includes the caller, so recording consultations once
                // per binding preserves the caller-owned union on cache hits.
                binding.resolution_facts.extend(&facts.take_config());
                queries
                    .entry(caller.to_string())
                    .or_default()
                    .extend(surface_index.take());
                binding.resolved_dependencies.extend(
                    resolved
                        .dependencies
                        .into_iter()
                        .chain(facts.take())
                        .filter(|dependency| !basis.contains(dependency)),
                );
                entry
                    .insert((resolved.target_file, resolved.target_symbol))
                    .clone()
            }
        };
        result.rows.insert(DerivedRow {
            caller_blob_key: key.caller_blob_key.clone(),
            ref_ordinal: key.ref_ordinal,
            caller_path: key.caller_path.clone(),
            kind,
            status: if target_file.is_some() {
                ResolutionStatus::Resolved
            } else {
                ResolutionStatus::Unresolved
            },
            target_path: target_file.map(String::into_bytes),
            target_symbol,
        });
        result.resolution_order.push(key);
    }
    profile.finish("resolve_and_record");
    for (path, binding) in &mut bindings {
        binding.consulted_facts = binding
            .binding_facts
            .facts
            .union(&binding.resolution_facts.facts)
            .cloned()
            .collect();
        binding.unattributed =
            binding.binding_facts.unattributed() || binding.resolution_facts.unattributed();
        if let Some(queries) = queries.remove(path) {
            binding.surface_queries = queries.into_iter().collect();
        }
        binding.dependencies = binding
            .references
            .values()
            .flatten()
            .cloned()
            .chain(binding.binding_probes.iter().cloned())
            .chain(binding.resolved_dependencies.iter().cloned())
            .chain(
                binding
                    .surface_queries
                    .iter()
                    .flat_map(|(query, _)| query.dependencies()),
            )
            .collect();
    }
    profile.finish("dependency_union");
    if let Some(error) = read_error.borrow_mut().take() {
        return Err(error);
    }
    Ok(SelectedManifestJoin {
        result,
        bindings,
        resolved_callers,
        rebuilt_surface_entries,
        decoded_caller_blobs,
        resolved_bindings: resolutions.len(),
    })
}

/// Consumer-specific export surface: record the answers the resolver actually
/// used, rather than invalidating every caller when an unrelated export changes.
/// Querying these answers against a new index is cheaper than walking references
/// and is sound only while the caller's immutable parse blob remains unchanged.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
enum ViewSurfaceQuery {
    Language(String),
    Module(String, String),
    Parent(String),
    Reexports(String),
    Node(String, String),
    Callable(String, String),
    Alias(String, String),
    Export(String, String),
    Default(String),
    Contains(String),
    Crate(String),
    CrateRoot(String),
    Inline(String, Vec<String>, String),
}

fn surface_value(value: &impl Serialize) -> String {
    blake3::hash(&serde_json::to_vec(value).expect("resolver surface serializes"))
        .to_hex()
        .to_string()
}

fn reexport_surface(value: &[super::ReexportIndex]) -> String {
    surface_value(
        &value
            .iter()
            .map(|entry| {
                (
                    &entry.target_file,
                    entry.named.iter().collect::<BTreeMap<_, _>>(),
                    entry.wildcard,
                )
            })
            .collect::<Vec<_>>(),
    )
}

pub(crate) const VIEW_CONFIG_MEMBERSHIP_DOMAIN: &str = "\0view:config-membership";
pub(crate) const VIEW_RUST_MODULE_DOMAIN: &str = "\0view:rust-module-index";

impl ViewSurfaceQuery {
    fn dependencies(&self) -> Vec<String> {
        match self {
            Self::Crate(_) => vec![VIEW_CONFIG_MEMBERSHIP_DOMAIN.into()],
            Self::CrateRoot(file) => {
                vec![file.clone(), VIEW_CONFIG_MEMBERSHIP_DOMAIN.into()]
            }
            Self::Parent(file) | Self::Inline(file, ..) => {
                vec![file.clone(), VIEW_RUST_MODULE_DOMAIN.into()]
            }
            Self::Language(file)
            | Self::Module(file, _)
            | Self::Reexports(file)
            | Self::Node(file, _)
            | Self::Callable(file, _)
            | Self::Alias(file, _)
            | Self::Export(file, _)
            | Self::Default(file)
            | Self::Contains(file) => vec![file.clone()],
        }
    }

    fn answer(&self, index: &impl super::ResolverIndex) -> String {
        match self {
            Self::Language(file) => {
                surface_value(&index.lang_for(file).map(|lang| format!("{lang:?}")))
            }
            Self::Module(file, module) => surface_value(&index.module_target(file, module)),
            Self::Parent(file) => surface_value(&index.module_parent(file)),
            Self::Reexports(file) => reexport_surface(&index.reexports_for(file)),
            Self::Node(file, symbol) => surface_value(&index.node_for_symbol(file, symbol)),
            Self::Callable(file, node) => surface_value(&index.node_is_callable(file, node)),
            Self::Alias(file, symbol) => surface_value(&index.export_alias(file, symbol)),
            Self::Export(file, symbol) => surface_value(&index.has_export(file, symbol)),
            Self::Default(file) => surface_value(&index.default_export(file)),
            Self::Contains(file) => surface_value(&index.contains_file(file)),
            Self::Crate(name) => surface_value(&index.crate_src_prefix(name)),
            Self::CrateRoot(file) => surface_value(&index.rust_crate_root_file(file)),
            Self::Inline(file, segments, symbol) => {
                surface_value(&index.inline_scoped_target(file, segments, symbol))
            }
        }
    }
}

struct ViewSurfaceIndex<'a, I> {
    inner: &'a I,
    queries: std::cell::RefCell<BTreeMap<ViewSurfaceQuery, String>>,
}

impl<I> ViewSurfaceIndex<'_, I> {
    fn record(&self, query: ViewSurfaceQuery, value: &impl Serialize) {
        self.queries
            .borrow_mut()
            .insert(query, surface_value(value));
    }
    fn take(&self) -> BTreeMap<ViewSurfaceQuery, String> {
        std::mem::take(&mut *self.queries.borrow_mut())
    }
}

impl<I: super::ResolverIndex> super::ResolverIndex for ViewSurfaceIndex<'_, I> {
    fn caller_data(&self, file: &str) -> Option<&FileCallData> {
        // resolve_ref reads only its own caller data; changed callers never reuse
        // surface answers, so the immutable blob itself guards this input.
        self.inner.caller_data(file)
    }
    fn lang_for(&self, file: &str) -> Option<LangId> {
        let value = self.inner.lang_for(file);
        self.record(
            ViewSurfaceQuery::Language(file.into()),
            &value.map(|lang| format!("{lang:?}")),
        );
        value
    }
    fn module_target(&self, file: &str, module: &str) -> Option<String> {
        let value = self.inner.module_target(file, module);
        self.record(ViewSurfaceQuery::Module(file.into(), module.into()), &value);
        value
    }
    fn module_parent(&self, file: &str) -> Option<(String, String)> {
        let value = self.inner.module_parent(file);
        self.record(ViewSurfaceQuery::Parent(file.into()), &value);
        value
    }
    fn reexports_for(&self, file: &str) -> Vec<super::ReexportIndex> {
        let value = self.inner.reexports_for(file);
        self.queries.borrow_mut().insert(
            ViewSurfaceQuery::Reexports(file.into()),
            reexport_surface(&value),
        );
        value
    }
    fn node_for_symbol(&self, file: &str, symbol: &str) -> Option<String> {
        let value = self.inner.node_for_symbol(file, symbol);
        self.record(ViewSurfaceQuery::Node(file.into(), symbol.into()), &value);
        value
    }
    fn node_is_callable(&self, file: &str, node: &str) -> bool {
        let value = self.inner.node_is_callable(file, node);
        self.record(ViewSurfaceQuery::Callable(file.into(), node.into()), &value);
        value
    }
    fn export_alias(&self, file: &str, symbol: &str) -> Option<String> {
        let value = self.inner.export_alias(file, symbol);
        self.record(ViewSurfaceQuery::Alias(file.into(), symbol.into()), &value);
        value
    }
    fn has_export(&self, file: &str, symbol: &str) -> bool {
        let value = self.inner.has_export(file, symbol);
        self.record(ViewSurfaceQuery::Export(file.into(), symbol.into()), &value);
        value
    }
    fn default_export(&self, file: &str) -> Option<String> {
        let value = self.inner.default_export(file);
        self.record(ViewSurfaceQuery::Default(file.into()), &value);
        value
    }
    fn contains_file(&self, file: &str) -> bool {
        let value = self.inner.contains_file(file);
        self.record(ViewSurfaceQuery::Contains(file.into()), &value);
        value
    }
    fn crate_src_prefix(&self, name: &str) -> Option<String> {
        let value = self.inner.crate_src_prefix(name);
        self.record(ViewSurfaceQuery::Crate(name.into()), &value);
        value
    }
    fn rust_crate_root_file(&self, file: &str) -> Option<String> {
        let value = self.inner.rust_crate_root_file(file);
        self.record(ViewSurfaceQuery::CrateRoot(file.into()), &value);
        value
    }
    fn inline_scoped_target(
        &self,
        file: &str,
        segments: &[String],
        symbol: &str,
    ) -> Option<(String, String)> {
        let value = self.inner.inline_scoped_target(file, segments, symbol);
        self.record(
            ViewSurfaceQuery::Inline(file.into(), segments.to_vec(), symbol.into()),
            &value,
        );
        value
    }
}

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

    #[test]
    fn opaque_config_read_is_unattributed_even_after_a_known_field_read() {
        let manifest = Manifest::new([(
            RelPath::new(b"package.json".to_vec()).unwrap(),
            ManifestEntry::Regular {
                mode: 0o100644,
                planes: crate::views::RegularPlanes {
                    callgraph: Some("config".into()),
                    semantic: None,
                },
                resolution_input: true,
            },
        )])
        .unwrap();
        let bytes: Arc<[u8]> = CallgraphBlob::config(b"{}".to_vec(), "fixture")
            .to_bytes()
            .unwrap()
            .into();
        let reader = |_: &BlobKey| Some(bytes.clone());
        let facts = ViewBindingFacts::new(Rc::new(ManifestFacts {
            manifest: &manifest,
            blobs: &reader,
        }));
        facts.config_fact(b"package.json", "name");
        assert!(facts.attributed_config_bytes(b"package.json").is_some());
        assert!(!facts.consultations.borrow().unattributed());
        facts.memo_start(Path::new("/"), "test", "");
        assert!(facts.config_bytes(b"package.json").is_some());
        facts.memo_finish(Path::new("/"), "test", "");
        assert!(facts.take_config().unattributed());
        facts.memo_replay(Path::new("/"), "test", "");
        assert!(facts.take_config().unattributed());
    }
}