rete-wasm 0.3.2

Browser/WASM bindings for querying Rete graph files.
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
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
//! Browser bindings: load a `.rete` file's bytes (e.g. from `fetch`) and query
//! it entirely in the browser — the same engine the native CLI uses, compiled
//! to wasm. Results come back as JSON strings.

use rete_core::{
    batch_reach_serial, build_adjacency, build_dendrogram, choose_round_for_budget, eval_query,
    eval_query_reasoned, eval_select_communities, eval_sparql, project_graph, schema_classes,
    schema_summary, summary_query_shape, tile_by_community, validate_shacl, BlockCacheReader,
    ByteRange, CountingReader, DataGraph, Header, QueryOutput, RangeReader, Rete, ReteGraph,
    ShaclShapes, SliceReader, SummaryQueryShape, SummaryView, TripleProvenance, ValidationReport,
    DEFAULT_BLOCK, DEFAULT_TILE_BUDGET,
};
use wasm_bindgen::prelude::*;

/// Version of Rete-owned JSON object envelopes exposed by the browser API.
pub const JSON_SCHEMA_VERSION: u8 = 1;

/// Module init: route Rust panics to `console.error` with their message and
/// location. In release wasm a panic otherwise aborts as a bare
/// `RuntimeError: unreachable` with no clue where — this turns that into a
/// `rete-wasm panic: panicked at '…', src/…:line` line in the devtools console,
/// so an intermittent first-query crash (e.g. a parser tripping on a flaky
/// range read) can actually be diagnosed.
#[wasm_bindgen(start)]
pub fn __start() {
    // The asyncify build must NOT format in the panic hook: the fmt machinery
    // is asyncify-instrumented (everything that can reach panic_fmt is), so a
    // panic raised while the instance is unwinding/rewinding recurses through
    // garbage-returning fmt calls forever (stack overflow / null-function).
    // Report the raw location pointers through a LEAF import instead — no
    // formatting, no instrumented calls — then let panic=abort trap cleanly.
    #[cfg(feature = "asyncify")]
    std::panic::set_hook(Box::new(|info| {
        if let Some(loc) = info.location() {
            let f = loc.file();
            unsafe { rete_panic_report(f.as_ptr(), f.len(), loc.line()) };
        } else {
            unsafe { rete_panic_report(std::ptr::null(), 0, 0) };
        }
    }));
    #[cfg(not(feature = "asyncify"))]
    std::panic::set_hook(Box::new(|info| {
        web_sys::console::error_1(&JsValue::from_str(&format!("rete-wasm panic: {info}")));
    }));
}

/// Header summary as JSON: `{ "quads": N, "terms": N, "pyramidLevels": N }`.
#[wasm_bindgen]
pub fn info(bytes: &[u8]) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    let h = rete.header();
    Ok(format!(
        r#"{{"schemaVersion":1,"quads":{},"terms":{},"pyramidLevels":{},"namedGraphs":{}}}"#,
        h.quad_count,
        h.term_count,
        h.pyramid_levels,
        rete.graph_names().len()
    ))
}

/// The named-graph IRIs of a dataset, as a JSON array.
#[wasm_bindgen]
pub fn graph_names(bytes: &[u8]) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    serde_json::to_string(&rete.graph_names()).map_err(err)
}

/// Build a complete `.rete` file image from RDF text, entirely in the browser.
///
/// `format` is `"nt"` (N-Triples), `"nq"` (N-Quads; named graphs become a
/// dataset), or `"ttl"` (Turtle). Returns the file bytes (a `Uint8Array`),
/// ready to download or to hand straight back to the query functions. The wasm
/// build has no zstd *encoder*, so sections are written uncompressed (codec
/// `NONE`) — larger than a CLI build of the same data, but every reader
/// accepts it; rebuild with `rete build` for a compressed file.
#[wasm_bindgen]
pub fn build(text: &str, format: &str) -> Result<Vec<u8>, JsValue> {
    let quads = rete_core::ingest::parse_statements(text, format).map_err(err)?;
    if quads.is_empty() {
        return Err(js_error(
            "no statements parsed (empty input or only comments)",
        ));
    }
    let (bytes, _stats) = rete_core::ingest::assemble_dataset(quads, &[]);
    Ok(bytes)
}

/// Evaluate a triple pattern; `null`/`undefined` positions are wildcards.
/// Returns a JSON array of `[subject, predicate, object]` triples.
#[wasm_bindgen]
pub fn query_triples(
    bytes: &[u8],
    subject: Option<String>,
    predicate: Option<String>,
    object: Option<String>,
) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    let rows = rete.query(subject.as_deref(), predicate.as_deref(), object.as_deref());
    serde_json::to_string(&rows).map_err(err)
}

/// Explain why each triple-pattern match is present in the `.rete` file.
///
/// `null`/`undefined` positions are wildcards. The JSON uses browser-facing
/// camelCase fields:
/// `{ "pattern", "resultCount", "results": [{ "terms", "ids", "provenance" }] }`.
#[wasm_bindgen]
pub fn why_triples(
    bytes: &[u8],
    subject: Option<String>,
    predicate: Option<String>,
    object: Option<String>,
) -> Result<String, JsValue> {
    why_triples_json(
        bytes,
        subject.as_deref(),
        predicate.as_deref(),
        object.as_deref(),
    )
    .map_err(js_error)
}

/// Native-testable implementation for [`why_triples`].
pub fn why_triples_json(
    bytes: &[u8],
    subject: Option<&str>,
    predicate: Option<&str>,
    object: Option<&str>,
) -> Result<String, String> {
    use serde_json::json;

    let rete = Rete::open(bytes).map_err(|e| e.to_string())?;
    let results = rete.query_with_provenance(subject, predicate, object);
    let out = json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "pattern": {
            "subject": subject,
            "predicate": predicate,
            "object": object,
        },
        "resultCount": results.len(),
        "results": results.iter().map(provenance_json).collect::<Vec<_>>(),
    });
    serde_json::to_string(&out).map_err(|e| e.to_string())
}

/// Run a SPARQL SELECT; returns a JSON array of solution objects
/// (`{ "var": "value", ... }`).
#[wasm_bindgen]
pub fn query_sparql(bytes: &[u8], query: &str) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    let (_vars, solutions) = eval_sparql(&rete, query).map_err(err)?;
    serde_json::to_string(&solutions).map_err(err)
}

/// The ontology profile (the semantic coarse graph), as JSON:
/// `{ "classes": [["<iri>", count], ...],
///    "relations": [["sClass","pred","oClass", count], ...] }`.
/// The "overview first" payload — render it before fetching any detail.
#[wasm_bindgen]
pub fn schema(bytes: &[u8]) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    let classes = schema_classes(&rete);
    let relations = schema_summary(&rete);
    serde_json::to_string(&serde_json::json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "classes": classes,
        "relations": relations,
    }))
    .map_err(err)
}

/// Read the **baked** schema pyramid (classes + class-level relations) straight
/// from the file's schema block via a slice reader — no triple scan. The
/// in-memory twin of [`schema_url`]: a cached big graph gets its schema from a
/// few KB of the buffer instead of dumping every triple (seconds on a 150 MB
/// file). Errors when the file carries no schema pyramid, so callers fall back
/// to the scanning [`schema`].
#[wasm_bindgen]
pub fn schema_packed(bytes: &[u8]) -> Result<String, JsValue> {
    use serde_json::json;
    let (classes, relations) = rete_core::read_schema_summary_ranged(&SliceReader::new(bytes))
        .map_err(err)?
        .ok_or_else(|| js_error("file has no schema pyramid"))?;
    let classes: Vec<serde_json::Value> = classes.iter().map(|(c, n)| json!([c, n])).collect();
    let relations: Vec<serde_json::Value> = relations
        .iter()
        .map(|(s, p, o, n)| json!([s, p, o, n]))
        .collect();
    Ok(json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "classes": classes,
        "relations": relations,
    })
    .to_string())
}

/// The embedded **Dataset Card** — the file's own self-description (title,
/// description, license, provenance, counts, example queries) as the JSON text
/// it was written with, or `undefined` when the file carries none. Reads the
/// metadata section straight out of the buffer.
#[wasm_bindgen]
pub fn card(bytes: &[u8]) -> Result<Option<String>, JsValue> {
    let bytes = rete_core::read_metadata_ranged(&SliceReader::new(bytes)).map_err(err)?;
    Ok(bytes.map(|b| String::from_utf8_lossy(&b).into_owned()))
}

/// The embedded **Dataset Card of a remote `.rete`**, in **two small range
/// requests**: the header, then the metadata section it points at — never the
/// dictionary, index, or pyramid. This is the index-free CARD tier: a client
/// learns what a multi-gigabyte graph *is* for a few KB. `undefined` when the
/// file carries no card. Worker-only (synchronous XHR).
#[wasm_bindgen]
pub fn card_url(url: &str) -> Result<Option<String>, JsValue> {
    let reader = XhrRangeReader::open(url)?;
    let bytes = rete_core::read_metadata_ranged(&reader).map_err(err)?;
    Ok(bytes.map(|b| String::from_utf8_lossy(&b).into_owned()))
}

/// A `.rete` opened **once** and kept resident, so a client (the playground's
/// cached/in-memory mode) can run many queries on a big file without re-copying
/// the whole buffer into wasm and re-decoding its dictionary on every call. The
/// methods mirror the free functions above but operate on the already-open
/// [`Rete`]. The few index-free readers (`schema_packed`, `progressive_query`,
/// `check_schema`) stay free functions — they read small ranges from the buffer
/// and are called rarely (once at load / on demand), so a handle buys little.
#[wasm_bindgen]
pub struct Graph {
    rete: Rete,
    file_len: usize,
}

#[wasm_bindgen]
impl Graph {
    /// Open a `.rete` image and keep it resident for repeated querying.
    #[wasm_bindgen(constructor)]
    pub fn new(bytes: &[u8]) -> Result<Graph, JsValue> {
        Ok(Graph {
            rete: open(bytes)?,
            file_len: bytes.len(),
        })
    }

    /// See [`info`].
    pub fn info(&self) -> String {
        let h = self.rete.header();
        format!(
            r#"{{"schemaVersion":1,"quads":{},"terms":{},"pyramidLevels":{},"namedGraphs":{}}}"#,
            h.quad_count,
            h.term_count,
            h.pyramid_levels,
            self.rete.graph_names().len()
        )
    }

    /// See [`graph_names`].
    pub fn graph_names(&self) -> Result<String, JsValue> {
        serde_json::to_string(&self.rete.graph_names()).map_err(err)
    }

    /// See [`query`].
    pub fn query(&self, query: &str, format: &str) -> Result<String, JsValue> {
        query_json(&self.rete, query, format, "")
    }

    /// As [`query`], with OWL 2 QL entailment on (`rdfs:subClassOf` /
    /// `subPropertyOf` / `domain` / `range` reasoning by query rewriting).
    pub fn query_reasoned(&self, query: &str, format: &str) -> Result<String, JsValue> {
        query_json_reasoned(&self.rete, query, format, "")
    }

    /// See [`query_triples`].
    pub fn query_triples(
        &self,
        subject: Option<String>,
        predicate: Option<String>,
        object: Option<String>,
    ) -> Result<String, JsValue> {
        let rows = self
            .rete
            .query(subject.as_deref(), predicate.as_deref(), object.as_deref());
        serde_json::to_string(&rows).map_err(err)
    }

    /// See [`prefix_search`].
    pub fn prefix_search(&self, prefix: &str, limit: usize) -> Result<String, JsValue> {
        prefix_search_json(&self.rete, prefix, limit)
    }

    /// See [`text_search`].
    pub fn text_search(
        &self,
        words: Vec<String>,
        contains_prefix: Option<String>,
        limit: usize,
    ) -> Result<String, JsValue> {
        text_search_json(&self.rete, &words, contains_prefix.as_deref(), limit)
    }

    /// See [`why_triples`].
    pub fn why_triples(
        &self,
        subject: Option<String>,
        predicate: Option<String>,
        object: Option<String>,
    ) -> Result<String, JsValue> {
        use serde_json::json;
        let results = self.rete.query_with_provenance(
            subject.as_deref(),
            predicate.as_deref(),
            object.as_deref(),
        );
        let out = json!({
            "schemaVersion": JSON_SCHEMA_VERSION,
            "pattern": { "subject": subject, "predicate": predicate, "object": object },
            "resultCount": results.len(),
            "results": results.iter().map(provenance_json).collect::<Vec<_>>(),
        });
        serde_json::to_string(&out).map_err(err)
    }

    /// See [`schema`] — the live (scanning) profile; prefer `schema_packed` when
    /// the file carries a pyramid.
    pub fn schema(&self) -> Result<String, JsValue> {
        serde_json::to_string(&serde_json::json!({
            "schemaVersion": JSON_SCHEMA_VERSION,
            "classes": schema_classes(&self.rete),
            "relations": schema_summary(&self.rete),
        }))
        .map_err(err)
    }

    /// See [`card`] — the Dataset Card of the resident file.
    pub fn card(&self) -> Option<String> {
        self.rete
            .metadata()
            .map(|b| String::from_utf8_lossy(b).into_owned())
    }

    /// See [`query_communities`].
    pub fn query_communities(&self, query: &str, round: Option<usize>) -> Result<String, JsValue> {
        query_communities_value(&self.rete, query, round)
    }

    /// See [`reach`].
    pub fn reach(&self, predicate: &str, seeds: &str, reverse: bool) -> Result<String, JsValue> {
        reach_rete(&self.rete, predicate, seeds, reverse)
    }

    /// See [`shacl`].
    pub fn shacl(
        &self,
        shapes_turtle: &str,
        graph: Option<String>,
        format: &str,
    ) -> Result<String, JsValue> {
        shacl_rete(&self.rete, shapes_turtle, graph.as_deref(), format)
    }

    /// See [`reason`].
    pub fn reason(&self, graph: Option<String>) -> String {
        let base = self.rete.dump(graph.as_deref());
        reasoning_json(&rete_core::reason(&base), None)
    }

    /// See [`pyramid_tree`].
    pub fn pyramid_tree(&self) -> Result<String, JsValue> {
        pyramid_tree_value(&self.rete)
    }

    /// See [`file_layout`].
    pub fn file_layout(&self) -> Result<String, JsValue> {
        use serde_json::json;
        let segments: Vec<serde_json::Value> = self
            .rete
            .file_layout()
            .iter()
            .map(|s| json!({ "kind": s.kind, "label": s.label, "offset": s.offset, "len": s.len }))
            .collect();
        serde_json::to_string(&json!({
            "schemaVersion": JSON_SCHEMA_VERSION,
            "fileLength": self.file_len,
            "segments": segments,
        }))
        .map_err(err)
    }
}

/// A remote `.rete` opened **once over HTTP range** and kept resident in the
/// worker, so repeated queries on the same URL reuse (a) the block cache — any
/// 64 KiB block fetched once is served from memory by [`BlockCacheReader`] — and
/// (b) the lazily faulted index tiles + decoded dictionary chunks that live
/// inside the resident [`Rete`]. The free [`sparql_url`] re-opens the file on
/// every call, so its block cache dies after one query; this handle keeps it.
/// The counting reader stays reachable so the worker can read cumulative
/// bytes/requests and show how little a cache-hit query actually fetched.
/// **Worker-only** (synchronous range-read XHR).
#[wasm_bindgen]
pub struct RemoteGraph {
    reader: std::sync::Arc<CountingReader<XhrRangeReader>>,
    rete: Rete,
}

#[wasm_bindgen]
impl RemoteGraph {
    /// Open a remote `.rete` over HTTP range and keep it resident for repeated
    /// querying. The first query faults in the dictionary chunks + index tiles it
    /// needs; later queries on this handle reuse them and the block cache.
    #[wasm_bindgen(constructor)]
    pub fn new(url: &str) -> Result<RemoteGraph, JsValue> {
        let (reader, rete) = open_url(url)?;
        Ok(RemoteGraph { reader, rete })
    }

    /// `{ fileLength, bytes, requests }` — CUMULATIVE physical fetches since this
    /// session opened. The worker diffs successive calls to report a single
    /// query's traffic (a fully cached re-run adds ~0).
    pub fn stats(&self) -> String {
        format!(
            r#"{{"schemaVersion":1,"fileLength":{},"bytes":{},"requests":{}}}"#,
            self.reader.len(),
            self.reader.bytes_read(),
            self.reader.requests()
        )
    }

    /// The file's content hash (blake3-16, hex). The worker keys its session
    /// cache by this rather than the URL, so two URLs of the same file share the
    /// cache — and it's the stable key a future IndexedDB block store (L3) needs
    /// to survive page reloads.
    pub fn content_hash(&self) -> String {
        self.rete
            .header()
            .content_hash
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect()
    }

    /// See [`sparql_url`] — same query, but over the resident, cached handle.
    /// The incompleteness verdict is PER QUERY: reset the sticky failure flags
    /// first, so one transient fetch failure fails only the query it happened
    /// in — not every later query on this session (failed tiles/chunks are
    /// never cached, so they retry here).
    pub fn query(&self, query: &str, format: &str) -> Result<String, JsValue> {
        self.rete.reset_load_failures();
        let s = query_json(&self.rete, query, format, "")?;
        incomplete_guard(&self.rete, "query")?;
        Ok(s)
    }

    /// As [`query`], with OWL 2 QL entailment on (reason over the ontology while
    /// reading only the bytes the rewritten query touches).
    pub fn query_reasoned(&self, query: &str, format: &str) -> Result<String, JsValue> {
        self.rete.reset_load_failures();
        let s = query_json_reasoned(&self.rete, query, format, "")?;
        incomplete_guard(&self.rete, "query")?;
        Ok(s)
    }

    /// See [`prefix_search`] — over the resident, cached remote handle. Faults the
    /// pyramid (where the label index lives) on the first call, then serves the
    /// search from memory.
    pub fn prefix_search(&self, prefix: &str, limit: usize) -> Result<String, JsValue> {
        prefix_search_json(&self.rete, prefix, limit)
    }

    /// See [`text_search`] — over the resident remote handle. Faults the TEXT_INDEX
    /// token table on the first call, then fetches only the queried posting lists
    /// (never the whole postings blob), serving repeat searches from memory.
    pub fn text_search(
        &self,
        words: Vec<String>,
        contains_prefix: Option<String>,
        limit: usize,
    ) -> Result<String, JsValue> {
        text_search_json(&self.rete, &words, contains_prefix.as_deref(), limit)
    }

    /// See [`card_url`] — the Dataset Card, over the resident handle's reader
    /// (so the header range it already fetched is served from the block cache).
    pub fn card(&self) -> Result<Option<String>, JsValue> {
        let bytes = rete_core::read_metadata_ranged(&*self.reader).map_err(err)?;
        Ok(bytes.map(|b| String::from_utf8_lossy(&b).into_owned()))
    }

    /// See [`schema_url`] — the **baked** schema pyramid over the resident
    /// handle. Deliberately never falls back to the scanning [`schema`]: that
    /// would drag the whole remote file across the wire.
    pub fn schema(&self) -> Result<String, JsValue> {
        use serde_json::json;
        let (classes, relations) = rete_core::read_schema_summary_ranged(&*self.reader)
            .map_err(err)?
            .ok_or_else(|| js_error("file has no schema pyramid"))?;
        let classes: Vec<serde_json::Value> = classes.iter().map(|(c, n)| json!([c, n])).collect();
        let relations: Vec<serde_json::Value> = relations
            .iter()
            .map(|(s, p, o, n)| json!([s, p, o, n]))
            .collect();
        Ok(json!({
            "schemaVersion": JSON_SCHEMA_VERSION,
            "kind": "schema",
            "classes": classes,
            "relations": relations,
        })
        .to_string())
    }

    /// See [`info`] — read from the resident header, no extra fetch.
    pub fn info(&self) -> String {
        let h = self.rete.header();
        format!(
            r#"{{"schemaVersion":1,"quads":{},"terms":{},"pyramidLevels":{},"namedGraphs":{}}}"#,
            h.quad_count,
            h.term_count,
            h.pyramid_levels,
            self.rete.graph_names().len()
        )
    }

    /// See [`graph_names`].
    pub fn graph_names(&self) -> Result<String, JsValue> {
        serde_json::to_string(&self.rete.graph_names()).map_err(err)
    }

    /// See [`shacl_url`] — validate over the resident handle. The default graph
    /// validates lazily against the index (only the shapes' targets are
    /// fetched), so a shape over a huge remote file stays cheap.
    pub fn shacl(
        &self,
        shapes_turtle: &str,
        graph: Option<String>,
        format: &str,
    ) -> Result<String, JsValue> {
        self.rete.reset_load_failures();
        let out = shacl_rete(&self.rete, shapes_turtle, graph.as_deref(), format)?;
        incomplete_guard(&self.rete, "validation")?;
        Ok(out)
    }
}

/// Serialize a label prefix search as `[{"label":…,"subject":…}]`.
fn prefix_search_json(rete: &Rete, prefix: &str, limit: usize) -> Result<String, JsValue> {
    use serde_json::json;
    let hits: Vec<serde_json::Value> = rete
        .prefix_search(prefix, limit)
        .into_iter()
        .map(|(label, subject)| json!({ "label": label, "subject": subject }))
        .collect();
    serde_json::to_string(&hits).map_err(err)
}

/// Serialize a full-text (word/CONTAINS) search as `[{"subject":…}]`.
fn text_search_json(
    rete: &Rete,
    words: &[String],
    contains_prefix: Option<&str>,
    limit: usize,
) -> Result<String, JsValue> {
    use serde_json::json;
    let word_refs: Vec<&str> = words.iter().map(String::as_str).collect();
    let hits: Vec<serde_json::Value> = rete
        .text_search(&word_refs, contains_prefix, limit)
        .into_iter()
        .map(|subject| json!({ "subject": subject }))
        .collect();
    serde_json::to_string(&hits).map_err(err)
}

/// Parse the fixed-size header and report the byte ranges a *progressive*
/// client needs for the overview — the dictionary and the pyramid summary — plus
/// the (large) index range it can skip, and the metadata (Dataset Card) range.
/// JSON: `{ "dictOffset","dictLen","pyramidOffset","pyramidLen","indexOffset",
/// "indexLen","metadataOffset","metadataLen" }`.
/// The browser fetches bytes `0..HEADER_LEN`, calls this, then range-fetches only the
/// dict + pyramid — never the index. A host with its own byte reader (Node over a
/// local file, say) can use `metadataOffset`/`metadataLen` to read just the card.
#[wasm_bindgen]
pub fn header_ranges(head: &[u8]) -> Result<String, JsValue> {
    let h = Header::from_bytes(head).map_err(err)?;
    Ok(format!(
        r#"{{"schemaVersion":1,"dictOffset":{},"dictLen":{},"pyramidOffset":{},"pyramidLen":{},"indexOffset":{},"indexLen":{},"metadataOffset":{},"metadataLen":{}}}"#,
        h.dictionary_offset,
        h.dictionary_len,
        h.pyramid_meta_offset,
        h.pyramid_meta_len,
        h.root_dir_offset,
        h.root_dir_len,
        h.metadata_offset,
        h.metadata_len,
    ))
}

/// Build the coarse-graph overview from a buffer in which only the header,
/// dictionary, and pyramid-summary ranges are populated — the index region may be
/// absent (zero-filled), because the summary path provably never reads it (see
/// the `ranged` test in rete-core). Returns JSON:
/// `{ "round", "communities", "predicateTotals": [["<iri>", count], ...] }`.
/// This is the "overview first, drill down later" payload, fetched in ~3 ranges.
#[wasm_bindgen]
pub fn summary_overview(bytes: &[u8]) -> Result<String, JsValue> {
    let view = SummaryView::open_ranged(&SliceReader::new(bytes))
        .map_err(err)?
        .ok_or_else(|| js_error("file has no pyramid summary"))?;
    serde_json::to_string(&serde_json::json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "round": view.round,
        "communities": view.community_count(),
        "predicateTotals": view.predicate_totals(),
    }))
    .map_err(err)
}

/// Answer a conservative subset of SPARQL exactly from the pyramid summary,
/// without opening the triple index. Unsupported query shapes return an error
/// instead of silently falling back to a full scan.
#[wasm_bindgen]
pub fn progressive_query(bytes: &[u8], query: &str) -> Result<String, JsValue> {
    progressive_query_json(bytes, query).map_err(js_error)
}

/// Native-testable implementation for [`progressive_query`].
pub fn progressive_query_json(bytes: &[u8], query: &str) -> Result<String, String> {
    use serde_json::json;

    let shape = summary_query_shape(query)
        .map_err(|e| e.to_string())?
        .ok_or_else(|| "query is not exactly answerable from the summary".to_string())?;

    let reader = CountingReader::new(SliceReader::new(bytes));
    let file_bytes = reader.len();
    let view = SummaryView::open_ranged(&reader)
        .map_err(|e| e.to_string())?
        .ok_or_else(|| "file has no pyramid summary".to_string())?;

    let value = match shape {
        SummaryQueryShape::PredicateCount {
            predicate,
            variable,
        } => {
            let count = u64::from(view.predicate_total(&predicate));
            select_count_response(
                &variable,
                count,
                progressive_meta(
                    &reader,
                    file_bytes,
                    "predicate_count",
                    Some(&predicate),
                    json!(count),
                ),
            )
        }
        SummaryQueryShape::TripleCount { variable } => {
            let count = summary_total(&view);
            select_count_response(
                &variable,
                count,
                progressive_meta(&reader, file_bytes, "triple_count", None, json!(count)),
            )
        }
        SummaryQueryShape::PredicateTotals {
            predicate_variable,
            count_variable,
        } => {
            let totals = view.predicate_totals();
            select_predicate_totals_response(
                &predicate_variable,
                &count_variable,
                &totals,
                progressive_meta(
                    &reader,
                    file_bytes,
                    "predicate_totals",
                    None,
                    json!(&totals),
                ),
            )
        }
        SummaryQueryShape::PredicateList { variable } => {
            let predicates = predicate_list(&view);
            select_predicate_list_response(
                &variable,
                &predicates,
                progressive_meta(
                    &reader,
                    file_bytes,
                    "predicate_list",
                    None,
                    json!(&predicates),
                ),
            )
        }
        SummaryQueryShape::PredicateDistinctCount { variable } => {
            let count = predicate_count(&view);
            select_count_response(
                &variable,
                count,
                progressive_meta(
                    &reader,
                    file_bytes,
                    "predicate_distinct_count",
                    None,
                    json!(count),
                ),
            )
        }
        SummaryQueryShape::TripleExists => {
            let exists = summary_total(&view) > 0;
            json!({
                "schemaVersion": JSON_SCHEMA_VERSION,
                "kind": "ask",
                "boolean": exists,
                "progressive": progressive_meta(
                    &reader,
                    file_bytes,
                    "triple_exists",
                    None,
                    json!(exists),
                ),
            })
        }
        SummaryQueryShape::PredicateExists { predicate } => {
            let exists = view.predicate_total(&predicate) > 0;
            json!({
                "schemaVersion": JSON_SCHEMA_VERSION,
                "kind": "ask",
                "boolean": exists,
                "progressive": progressive_meta(
                    &reader,
                    file_bytes,
                    "predicate_exists",
                    Some(&predicate),
                    json!(exists),
                ),
            })
        }
        _ => return Err("summary query shape is not supported by this WASM build".to_string()),
    };

    serde_json::to_string(&value).map_err(|e| e.to_string())
}

/// Run any SPARQL form (SELECT / ASK / CONSTRUCT / DESCRIBE) and serialize the
/// result for the playground. Returns a JSON string the page parses; a `"kind"`
/// field (`"select"|"ask"|"construct"`) tells the UI how to render it.
///
/// `format` controls the construct serialization and the select fallback:
/// - SELECT → `{ "kind":"select", "vars":[...], "rows":[ {var:value,...} ] }`
///   (`format` is ignored for SELECT — the table view is always available).
/// - ASK → `{ "kind":"ask", "boolean": true|false }`.
/// - CONSTRUCT/DESCRIBE →
///   - `format=="ttl"`    → `{ "kind":"construct", "format":"ttl",    "text": "<turtle>" }`
///   - `format=="jsonld"` → `{ "kind":"construct", "format":"jsonld", "text": "<json-ld>" }`
///   - otherwise (`table`/`json`) → `{ "kind":"construct", "triples": [[s,p,o], ...] }`.
#[wasm_bindgen]
pub fn query(bytes: &[u8], query: &str, format: &str) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    query_json(&rete, query, format, "")
}

/// Prefix-search the label index of an embedded `.rete` image: the subjects whose
/// label starts with `prefix` (case-insensitive), as `[{"label":…,"subject":…}]`,
/// capped at `limit`. Answers from the bounded label-index block in the
/// pyramid-meta — no literal scan. Empty array when the file has no label index.
#[wasm_bindgen]
pub fn prefix_search(bytes: &[u8], prefix: &str, limit: usize) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    prefix_search_json(&rete, prefix, limit)
}

/// Full-text (word/CONTAINS) search over an embedded `.rete` image: the subjects
/// whose literals contain **every** word in `words` (whole-word, case-insensitive
/// — AND), optionally also a word starting with `contains_prefix`, as
/// `[{"subject":…}]`, capped at `limit`. Answers from the TEXT_INDEX section.
/// Empty array when the file has none (`build --text-index`).
#[wasm_bindgen]
pub fn text_search(
    bytes: &[u8],
    words: Vec<String>,
    contains_prefix: Option<String>,
    limit: usize,
) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    text_search_json(&rete, &words, contains_prefix.as_deref(), limit)
}

/// Evaluate any SPARQL form against an open [`Rete`] and serialize the playground
/// JSON envelope (shared by [`query`] and [`sparql_url`]). `extra` is a raw JSON
/// fragment of additional object members appended before the closing brace (e.g.
/// `,"remote":{…}` for [`sparql_url`]); pass `""` for none.
///
/// This writes the JSON **directly into a `String`** rather than building an
/// intermediate `serde_json::Value` tree and stringifying it: on a large SELECT
/// the tree path allocates ~25× the payload (a `BTreeMap` per row + two String
/// clones per cell) and costs more than the query itself; writing direct cuts the
/// serialization peak heap ~13× and the time ~10× (see `rete-bench --query-mem`).
fn query_json(rete: &Rete, query: &str, format: &str, extra: &str) -> Result<String, JsValue> {
    query_json_opt(rete, query, format, extra, false)
}

/// As [`query_json`], but with OWL 2 QL entailment on (the query is rewritten so
/// the answer includes ontology-entailed solutions, computed over the raw data).
fn query_json_reasoned(
    rete: &Rete,
    query: &str,
    format: &str,
    extra: &str,
) -> Result<String, JsValue> {
    query_json_opt(rete, query, format, extra, true)
}

fn query_json_opt(
    rete: &Rete,
    query: &str,
    format: &str,
    extra: &str,
    reason: bool,
) -> Result<String, JsValue> {
    let out = if reason {
        eval_query_reasoned(rete, query)
    } else {
        eval_query(rete, query)
    }
    .map_err(err)?;
    Ok(write_query_json(&out, format, extra))
}

/// Serialize an already-evaluated [`QueryOutput`] into the playground JSON
/// envelope. SELECT / ASK / `CONSTRUCT`-as-triples go through the shared,
/// host-tested `rete_core::results_envelope_json` (the allocation-lean direct
/// writer); a `CONSTRUCT` requested as Turtle / JSON-LD wraps the rendered text
/// (those serializers live here).
fn write_query_json(out: &QueryOutput, format: &str, extra: &str) -> String {
    let mut versioned_extra = format!(r#","schemaVersion":{JSON_SCHEMA_VERSION}"#);
    versioned_extra.push_str(extra);
    if let QueryOutput::Construct(triples) = out {
        let text = match format {
            "ttl" => Some(("ttl", to_turtle(triples))),
            "jsonld" => Some(("jsonld", to_jsonld(triples))),
            _ => None,
        };
        if let Some((fmt, text)) = text {
            let mut s = String::from(r#"{"kind":"construct","format":""#);
            s.push_str(fmt);
            s.push_str(r#"","text":"#);
            rete_core::push_json_string(&mut s, &text);
            s.push_str(&versioned_extra);
            s.push('}');
            return s;
        }
    }
    rete_core::results_envelope_json(out, &versioned_extra)
}

/// HTTP `Range` reader over **synchronous** XMLHttpRequest — the bridge that
/// lets the lazily-faulting `Rete::open_ranged_lazy` run in the browser with
/// the synchronous engine untouched. Browsers permit sync XHR with a binary
/// response **only inside Web Workers**: call [`sparql_url`] from a worker,
/// never the main thread (where the browser throws).
struct XhrRangeReader {
    url: String,
    len: u64,
}

// Asyncify variant only (feature = "asyncify"): one dedicated async import in
// module "env". The worker provides it as a `Promise.all` of `fetch` over the N
// ranges, writing the spans concatenated into `dst` and returning the total
// bytes. `wasm-opt --asyncify --pass-arg=asyncify-imports@env.rete_fetch_ranges`
// instruments every fn that can reach it to SUSPEND the wasm while the worker
// awaits the fetches, then RESUME — concurrent reads with no SAB / cross-origin
// isolation. Proven in dev/asyncify-wbg-probe (wasm-bindgen × Asyncify).
#[cfg(feature = "asyncify")]
#[link(wasm_import_module = "env")]
extern "C" {
    fn rete_fetch_ranges(
        url_ptr: *const u8,
        url_len: usize,
        offs_ptr: *const u64,
        lens_ptr: *const u32,
        n: usize,
        dst_ptr: *mut u8,
    ) -> usize;
    /// Async length probe (a `bytes=0-0` fetch; reads the total from
    /// `Content-Range`). Writes the u64 length to `out_ptr`, returns 1 on
    /// success. Lets the asyncify build open a file with NO sync XHR at all.
    fn rete_file_len(url_ptr: *const u8, url_len: usize, out_ptr: *mut u64) -> usize;
    /// LEAF panic reporter (deliberately NOT in asyncify-imports): the panic
    /// hook passes the raw `Location` pointers so the host can log file:line
    /// without any formatting — see `__start`.
    fn rete_panic_report(file_ptr: *const u8, file_len: usize, line: u32);
}

fn checked_async_layout(ranges: &[(u64, u64)]) -> std::io::Result<(Vec<u64>, Vec<u32>, usize)> {
    let offs: Vec<u64> = ranges.iter().map(|&(offset, _)| offset).collect();
    let lens: Vec<u32> = ranges
        .iter()
        .map(|&(_, len)| {
            u32::try_from(len).map_err(|_| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    format!("range length {len} exceeds the wasm32 u32 length type"),
                )
            })
        })
        .collect::<std::io::Result<_>>()?;
    let total = lens.iter().try_fold(0usize, |sum, &len| {
        sum.checked_add(len as usize).ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "range length sum overflow",
            )
        })
    })?;
    let _total_u32 = u32::try_from(total).map_err(|_| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "range response exceeds the wasm32 address space",
        )
    })?;
    Ok((offs, lens, total))
}

fn split_range_response(
    ranges: &[(u64, u64)],
    dst: Vec<u8>,
    got: usize,
    source: &str,
) -> std::io::Result<Vec<Vec<u8>>> {
    let (_, lens, total) = checked_async_layout(ranges)?;
    if dst.len() != total {
        return Err(std::io::Error::other(format!(
            "async fetch destination has {} bytes, expected {total} for {source}",
            dst.len()
        )));
    }
    if got != total {
        return Err(std::io::Error::other(format!(
            "async fetch returned {got} of {total} bytes for {source}"
        )));
    }

    let mut out = Vec::with_capacity(ranges.len());
    let mut pos = 0usize;
    for len in lens {
        let end = pos + len as usize;
        out.push(dst[pos..end].to_vec());
        pos = end;
    }
    Ok(out)
}

#[cfg(test)]
mod async_range_tests {
    use super::{checked_async_layout, split_range_response};

    #[test]
    fn rejects_a_range_larger_than_the_wasm32_length_type() {
        let error = checked_async_layout(&[(0, u64::from(u32::MAX) + 1)]).unwrap_err();
        assert!(error.to_string().contains("u32"));
    }

    #[test]
    fn rejects_a_total_larger_than_the_wasm32_address_space() {
        let error = checked_async_layout(&[(0, u64::from(u32::MAX)), (0, 1)]).unwrap_err();
        assert!(error.to_string().contains("address space"));
    }

    #[test]
    fn accepts_no_ranges_and_preserves_zero_length_ranges() {
        let (offs, lens, total) = checked_async_layout(&[]).unwrap();
        assert!(offs.is_empty());
        assert!(lens.is_empty());
        assert_eq!(total, 0);

        let (_, lens, total) = checked_async_layout(&[(7, 0), (9, 0)]).unwrap();
        assert_eq!(lens, vec![0, 0]);
        assert_eq!(total, 0);
    }

    #[test]
    fn rejects_a_short_javascript_response() {
        let error = split_range_response(&[(0, 4)], vec![1, 2, 3, 4], 3, "fixture").unwrap_err();
        assert!(error.to_string().contains("returned 3 of 4 bytes"));
    }
}

#[cfg(feature = "asyncify")]
impl XhrRangeReader {
    /// Fetch all `ranges` through the async import in one suspend/resume, then
    /// split the concatenated bytes back into per-range buffers.
    fn read_ranges_async(&self, ranges: &[(u64, u64)]) -> std::io::Result<Vec<Vec<u8>>> {
        let (offs, lens, total) = checked_async_layout(ranges)?;
        if total == 0 {
            return Ok(ranges.iter().map(|_| Vec::new()).collect());
        }
        let mut dst = vec![0u8; total];
        if offs.len() != ranges.len() || lens.len() != ranges.len() || dst.len() != total {
            return Err(std::io::Error::other(
                "async range layout does not match its allocated buffers",
            ));
        }
        // SAFETY: self.url, offs, and lens own their pointer/length pairs for
        // this call; dst owns exactly total writable bytes. The imported
        // function contract writes at most that concatenated length and returns
        // before any of these allocations leave scope.
        let got = unsafe {
            rete_fetch_ranges(
                self.url.as_ptr(),
                self.url.len(),
                offs.as_ptr(),
                lens.as_ptr(),
                ranges.len(),
                dst.as_mut_ptr(),
            )
        };
        let out = split_range_response(ranges, dst, got, &self.url)?;
        report_progress(total);
        Ok(out)
    }
}

impl XhrRangeReader {
    /// Probe the resource length. Some hosts reject `HEAD` (Hugging Face's
    /// signed-redirect storage answers `405`), so use a one-byte ranged `GET`
    /// and read the total from the `Content-Range` header (`bytes 0-0/TOTAL`),
    /// falling back to `Content-Length` if the host doesn't send a range.
    fn open(url: &str) -> Result<Self, JsValue> {
        // Asyncify build: probe the length via the async import — no sync XHR.
        #[cfg(feature = "asyncify")]
        {
            let mut len: u64 = 0;
            // SAFETY: url owns url.as_ptr() for exactly url.len() bytes and len
            // owns one writable u64. The import writes only that value and
            // returns before either borrowed allocation leaves scope.
            let ok = unsafe { rete_file_len(url.as_ptr(), url.len(), &mut len as *mut u64) };
            if ok == 0 || len == 0 {
                return Err(js_error(format!("could not determine length of {url}")));
            }
            Ok(Self {
                url: url.to_string(),
                len,
            })
        }
        #[cfg(not(feature = "asyncify"))]
        {
            // Prefer a HEAD: its `Content-Length` is the full file size AND is a
            // CORS-safelisted response header, so it is readable cross-origin even when
            // the host does NOT expose `Content-Range` (e.g. Zenodo). The ranged-GET
            // probe below cannot see a hidden `Content-Range` and would mis-read the
            // 1-byte partial `Content-Length` as the size ("range out of bounds"). Falls
            // through when the host rejects HEAD (HF's signed-redirect storage 405s it).
            if let Some(len) = Self::head_len(url) {
                return Ok(Self {
                    url: url.to_string(),
                    len,
                });
            }
            // Hugging Face's Space gateway is intermittently flaky on the length
            // probe (a 200 with no Content-Length, a chunked response with neither
            // header, …). A fresh ranged GET usually lands on a healthy response,
            // so retry a few times before surfacing the error.
            let mut last = format!("could not determine length of {url}");
            for _ in 0..4 {
                match Self::probe_len(url) {
                    Ok(len) => {
                        return Ok(Self {
                            url: url.to_string(),
                            len,
                        })
                    }
                    Err(e) => last = e,
                }
            }
            Err(js_error(last))
        }
    }

    /// A HEAD length probe: `Content-Length` is the full size and is CORS-safelisted
    /// (readable cross-origin with no `access-control-expose-headers` entry needed).
    /// Returns `None` on a non-2xx (some hosts 405 HEAD) or a missing/zero length, so
    /// the caller can fall back to the ranged-GET probe.
    #[cfg(not(feature = "asyncify"))]
    fn head_len(url: &str) -> Option<u64> {
        let xhr = web_sys::XmlHttpRequest::new().ok()?;
        xhr.open_with_async("HEAD", url, false).ok()?;
        xhr.send().ok()?;
        let status = xhr.status().ok()?;
        if !(200..300).contains(&status) {
            return None;
        }
        xhr.get_response_header("Content-Length")
            .ok()
            .flatten()
            .and_then(|v| v.parse::<u64>().ok())
            .filter(|&n| n > 0)
    }

    /// One length probe: a one-byte ranged `GET`, reading the total from
    /// `Content-Range` (`bytes 0-0/TOTAL`), falling back to `Content-Length`.
    #[cfg(not(feature = "asyncify"))]
    fn probe_len(url: &str) -> Result<u64, String> {
        let err = |m: &str| m.to_string();
        let xhr = web_sys::XmlHttpRequest::new().map_err(|_| err("xhr"))?;
        xhr.open_with_async("GET", url, false)
            .map_err(|_| err("open"))?;
        xhr.set_response_type(web_sys::XmlHttpRequestResponseType::Arraybuffer);
        xhr.set_request_header("Range", "bytes=0-0")
            .map_err(|_| err("range header"))?;
        xhr.send()
            .map_err(|_| format!("probe {url}: network error"))?;
        let status = xhr.status().map_err(|_| err("status"))?;
        if status != 206 && !(200..300).contains(&status) {
            return Err(format!("probe {url}: status {status}"));
        }
        // `Content-Range: bytes 0-0/12345` — the part after `/` is the total.
        xhr.get_response_header("Content-Range")
            .ok()
            .flatten()
            .and_then(|v| {
                v.rsplit('/')
                    .next()
                    .and_then(|t| t.trim().parse::<u64>().ok())
            })
            .or_else(|| {
                xhr.get_response_header("Content-Length")
                    .ok()
                    .flatten()
                    .and_then(|v| v.parse::<u64>().ok())
            })
            .ok_or_else(|| format!("could not determine length of {url}"))
    }
}

impl RangeReader for XhrRangeReader {
    fn len(&self) -> u64 {
        self.len
    }

    /// The asyncify build fires its batched ranges as one concurrent
    /// `Promise.all` of fetches; the sync build is serial XHR unless the
    /// opt-in COI fetch-worker pool (`globalThis.reteReadMany`) is installed.
    /// 16 matches the pool size and the CLI's thread fan-out.
    fn concurrency(&self) -> usize {
        #[cfg(feature = "asyncify")]
        {
            16
        }
        #[cfg(not(feature = "asyncify"))]
        {
            let has_pool =
                js_sys::Reflect::get(&js_sys::global(), &JsValue::from_str("reteReadMany"))
                    .map(|h| h.is_function())
                    .unwrap_or(false);
            if has_pool {
                16
            } else {
                1
            }
        }
    }

    fn read_at(&self, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
        if len == 0 {
            return Ok(Vec::new());
        }
        // Asyncify build: a single read is a 1-range async fetch (suspends).
        #[cfg(feature = "asyncify")]
        {
            Ok(self
                .read_ranges_async(&[(offset, len)])?
                .into_iter()
                .next()
                .unwrap())
        }
        #[cfg(not(feature = "asyncify"))]
        {
            let js = |e: JsValue| std::io::Error::other(format!("XHR error: {e:?}"));
            let xhr = web_sys::XmlHttpRequest::new().map_err(js)?;
            xhr.open_with_async("GET", &self.url, false).map_err(js)?;
            xhr.set_response_type(web_sys::XmlHttpRequestResponseType::Arraybuffer);
            let end = offset
                .checked_add(len - 1)
                .ok_or_else(|| std::io::Error::other("HTTP range end overflow"))?;
            xhr.set_request_header("Range", &format!("bytes={offset}-{end}"))
                .map_err(js)?;
            xhr.send().map_err(js)?;
            let status = xhr.status().map_err(js)?;
            // Same contract as the CLI's HttpRangeReader: a 200 means the server
            // ignored Range and is returning the whole body — reject it loudly
            // rather than silently mis-slicing.
            if status != 206 {
                return Err(std::io::Error::other(format!(
                    "server ignored Range (status {status}, expected 206 Partial Content) for {}; \
                 the host must support HTTP range requests",
                    self.url
                )));
            }
            let resp = xhr.response().map_err(js)?;
            let mut buf = js_sys::Uint8Array::new(&resp).to_vec();
            if (buf.len() as u64) < len {
                return Err(std::io::Error::other(format!(
                    "short range response: got {} of {len} bytes at offset {offset} from {}",
                    buf.len(),
                    self.url
                )));
            }
            let requested = usize::try_from(len)
                .map_err(|_| std::io::Error::other("range exceeds wasm32 memory"))?;
            buf.truncate(requested);
            // Report this fetch to an optional progress hook so a worker can stream
            // live "N requests · M bytes" updates to the UI *during* the otherwise
            // opaque synchronous query (postMessage works mid-sync-call).
            report_progress(buf.len());
            Ok(buf)
        }
    }

    /// Synchronous XHR can't run two requests at once on one thread, so the
    /// engine's sequential faults serialize their round trips. If the page
    /// installs `globalThis.reteReadMany(url, offsets, lens)` — a fetch-worker
    /// pool that fetches the ranges in parallel and blocks (via SAB/Atomics)
    /// until done — use it; it returns one buffer with the spans concatenated
    /// in order, or `null`/throws if it can't (no cross-origin isolation, a
    /// non-206, a short read). On `null` we fall back to the sequential reads
    /// below, which keep the rigorous per-range validation.
    fn read_many(&self, ranges: &[(u64, u64)]) -> std::io::Result<Vec<Vec<u8>>> {
        // Asyncify build: fetch the whole batch concurrently in one suspend.
        #[cfg(feature = "asyncify")]
        {
            self.read_ranges_async(ranges)
        }
        #[cfg(not(feature = "asyncify"))]
        {
            let (_, _, total) = checked_async_layout(ranges)?;
            if ranges.len() > 1 {
                if let Some(buf) = self.read_many_via_pool(ranges) {
                    if buf.len() == total {
                        return split_range_response(ranges, buf, total, "globalThis.reteReadMany");
                    }
                }
            }
            ranges.iter().map(|&(o, l)| self.read_at(o, l)).collect()
        }
    }
}

/// Notify an optional `globalThis.reteProgress(bytes)` hook of one completed
/// range fetch (the worker forwards it to the UI). A no-op when unset.
fn report_progress(bytes: usize) {
    let g = js_sys::global();
    if let Ok(f) = js_sys::Reflect::get(&g, &JsValue::from_str("reteProgress")) {
        if let Ok(f) = f.dyn_into::<js_sys::Function>() {
            let _ = f.call1(&JsValue::NULL, &JsValue::from_f64(bytes as f64));
        }
    }
}

#[cfg(not(feature = "asyncify"))]
impl XhrRangeReader {
    /// Call the optional JS parallel-fetch hook. Returns the concatenated span
    /// bytes on full success, or `None` if the hook is absent, threw, or
    /// returned anything other than a `Uint8Array` (→ sequential fallback).
    fn read_many_via_pool(&self, ranges: &[(u64, u64)]) -> Option<Vec<u8>> {
        let global = js_sys::global();
        let hook = js_sys::Reflect::get(&global, &JsValue::from_str("reteReadMany")).ok()?;
        if !hook.is_function() {
            return None;
        }
        let hook = hook.dyn_into::<js_sys::Function>().ok()?;
        let (_, checked_lens, _) = checked_async_layout(ranges).ok()?;
        let count = u32::try_from(ranges.len()).ok()?;
        let offs = js_sys::Float64Array::new_with_length(count);
        let lens = js_sys::Float64Array::new_with_length(count);
        const MAX_SAFE_JS_INTEGER: u64 = (1_u64 << 53) - 1;
        for (i, (&(offset, _), &len)) in ranges.iter().zip(&checked_lens).enumerate() {
            if offset > MAX_SAFE_JS_INTEGER {
                return None;
            }
            let index = u32::try_from(i).ok()?;
            offs.set_index(index, offset as f64);
            lens.set_index(index, f64::from(len));
        }
        let res = hook
            .call3(&JsValue::NULL, &JsValue::from_str(&self.url), &offs, &lens)
            .ok()?;
        if res.is_null() || res.is_undefined() {
            return None;
        }
        Some(js_sys::Uint8Array::new(&res).to_vec())
    }
}

/// The browser's [`rete_core::ServiceClient`]: a `SERVICE <endpoint> { … }`
/// block POSTs its sub-query to the endpoint over synchronous XHR (worker-only,
/// like every other read here — the engine is synchronous) and rete-core parses
/// the SPARQL JSON results. The endpoint must send CORS headers (the public
/// ones — Wikidata, DBpedia — do).
struct XhrServiceClient;

impl rete_core::ServiceClient for XhrServiceClient {
    fn query(&self, endpoint: &str, query: &str) -> Result<Vec<rete_core::Binding>, String> {
        let e = |m: &str| format!("{endpoint}: {m}");
        let xhr = web_sys::XmlHttpRequest::new().map_err(|_| e("xhr"))?;
        xhr.open_with_async("POST", endpoint, false)
            .map_err(|_| e("open"))?;
        xhr.set_request_header("Content-Type", "application/x-www-form-urlencoded")
            .map_err(|_| e("header"))?;
        xhr.set_request_header("Accept", "application/sparql-results+json")
            .map_err(|_| e("header"))?;
        let body = format!(
            "query={}",
            String::from(js_sys::encode_uri_component(query))
        );
        xhr.send_with_opt_str(Some(&body))
            .map_err(|_| e("network error (endpoint down or no CORS)"))?;
        let status = xhr.status().map_err(|_| e("status"))?;
        if !(200..300).contains(&status) {
            return Err(e(&format!("HTTP {status}")));
        }
        let text = xhr
            .response_text()
            .map_err(|_| e("read"))?
            .unwrap_or_default();
        rete_core::parse_sparql_json_results(&text).map_err(|m| e(&m))
    }
}

/// Run a SPARQL query against a **remote `.rete` URL**, fetching only the
/// byte ranges the query needs: header, dictionary chunk directories, tile
/// directories, then just the touched chunks and tiles (full scans coalesce
/// adjacent tiles into batched range reads). Returns the same JSON envelope
/// as [`query`], plus `"remote": { "fileLength", "bytes", "requests" }` —
/// how little of the file the query actually pulled.
///
/// **Worker-only.** This uses synchronous XHR (the engine is synchronous and
/// wasm cannot block on `fetch`); browsers allow that off the main thread
/// only, so call it from a Web Worker. A failed range fetch mid-query is an
/// error, never a silently incomplete result. The host must answer `Range`
/// requests with `206` (and send CORS headers if cross-origin).
/// Open a remote `.rete` lazily over HTTP range reads, returning the counting
/// reader (for byte/request stats) and the `Rete`. The seam every `*_url`
/// task shares with [`sparql_url`].
/// Auto-tune the block-cache size from the FILE SIZE — known for free at open
/// from the `Content-Range` of the single `bytes=0-0` request (one byte, no
/// download; it's what `stats().fileLength` reports). Remote reads are
/// round-trip-bound, so a bigger block means far fewer requests; benchmarked on
/// wikidata-1GB: 64 KiB = 262 reqs / 63 s, 256 KiB = 83 / 27 s, 512 KiB = 51 / 19 s.
/// Bigger files (bigger working sets + dictionaries) get bigger blocks as
/// multiples of the 64 KiB `DEFAULT_BLOCK`; small files keep over-fetch modest.
/// Per-query override comes via `RemoteGraph::with_block` (the Settings control).
fn auto_block(len: u64) -> u64 {
    const MB: u64 = 1 << 20;
    let mult: u64 = if len > 100 * MB {
        8 // 512 KiB — chebi, wikidata-100mb, ohm-full, wikidata-1GB, causenet
    } else if len > 10 * MB {
        4 // 256 KiB
    } else {
        2 // 128 KiB — small remotes (chemotion, getty-ulan)
    };
    mult * DEFAULT_BLOCK
}

fn open_url(url: &str) -> Result<(std::sync::Arc<CountingReader<XhrRangeReader>>, Rete), JsValue> {
    // `reader` counts the PHYSICAL fetches; a read-through block cache above it
    // turns the query's scattered range reads into a few aligned block fetches
    // (and reuses them) — working over any single-range backend (S3, a CDN),
    // not just a multi-range gateway. The block fetches still go through
    // `read_many`, so a multi-range host coalesces them further. The block size
    // is auto-tuned from the file size (known at open, no download).
    let reader = std::sync::Arc::new(CountingReader::new(XhrRangeReader::open(url)?));
    let cached = std::sync::Arc::new(BlockCacheReader::new(
        reader.clone(),
        auto_block(reader.len()),
    ));
    let mut rete = Rete::open_ranged_lazy(cached).map_err(err)?;
    // SERVICE blocks federate to remote SPARQL endpoints over sync XHR.
    rete.set_service_client(Box::new(XhrServiceClient));
    Ok((reader, rete))
}

/// Turn a partial lazy fetch into a hard error: a `*_url` task must never
/// return a result computed over silently-incomplete data.
fn incomplete_guard(rete: &Rete, what: &str) -> Result<(), JsValue> {
    if rete.index_incomplete() {
        return Err(js_error(format!(
            "a range fetch failed mid-{what}; refusing to return incomplete results"
        )));
    }
    Ok(())
}

/// Triple-pattern provenance over a **remote** `.rete` URL (lazy range reads):
/// which permutation/section/byte-ranges answer the pattern. Worker-only.
#[wasm_bindgen]
pub fn why_url(
    url: &str,
    subject: Option<String>,
    predicate: Option<String>,
    object: Option<String>,
) -> Result<String, JsValue> {
    let (reader, rete) = open_url(url)?;
    let out = why_triples_rete(
        &rete,
        subject.as_deref(),
        predicate.as_deref(),
        object.as_deref(),
    )
    .map_err(js_error)?;
    incomplete_guard(&rete, "query")?;
    let _ = reader;
    Ok(out)
}

/// Provenance over an already-open `Rete` (shared by [`why_triples`] in-memory
/// and [`why_url`] remote).
fn why_triples_rete(
    rete: &Rete,
    subject: Option<&str>,
    predicate: Option<&str>,
    object: Option<&str>,
) -> Result<String, String> {
    use serde_json::json;
    let results = rete.query_with_provenance(subject, predicate, object);
    let out = json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "pattern": { "subject": subject, "predicate": predicate, "object": object },
        "resultCount": results.len(),
        "results": results.iter().map(provenance_json).collect::<Vec<_>>(),
    });
    serde_json::to_string(&out).map_err(|e| e.to_string())
}

#[wasm_bindgen]
pub fn sparql_url(url: &str, query: &str, format: &str) -> Result<String, JsValue> {
    // Use the block-caching `open_url` seam so scattered range reads within this
    // one query that land in the same 64 KiB block fetch it once. (The resident
    // `RemoteGraph` extends this reuse across queries.)
    let (reader, rete) = open_url(url)?;
    let file_length = reader.len();
    // Evaluate first (this is what faults tiles), then refuse incomplete results.
    let out = eval_query(&rete, query).map_err(err)?;
    if rete.index_incomplete() {
        return Err(js_error(
            "a range fetch failed mid-query; refusing to return incomplete results",
        ));
    }
    // The `remote` member's values are plain numbers — no escaping needed.
    let extra = format!(
        r#","remote":{{"fileLength":{},"bytes":{},"requests":{}}}"#,
        file_length,
        reader.bytes_read(),
        reader.requests(),
    );
    Ok(write_query_json(&out, format, &extra))
}

/// Evaluate a SELECT with the **community-split strategy**: every basic graph
/// pattern is decomposed into subject stars, each star is evaluated per
/// pyramid community (the members pushed in as a VALUES binding), and the
/// stars are recombined with global hash joins — so multi-hop joins work and
/// cross-community solutions survive. FILTER / UNION / OPTIONAL / MINUS
/// recurse; paths and GRAPH blocks evaluate globally inside the split; GROUP
/// BY / ORDER BY / LIMIT / DISTINCT run once on the merged rows. Answers are
/// identical to [`query`]'s. Refused only when nothing in the query can
/// split (no BGP with a variable subject) or for FROM / FROM NAMED. JSON:
/// the SELECT envelope plus `"communities": [{ "community", "subjects",
/// "rows" }, …]` (rows contributed per community across all split stars).
#[wasm_bindgen]
pub fn query_communities(
    bytes: &[u8],
    query: &str,
    round: Option<usize>,
) -> Result<String, JsValue> {
    query_communities_value(&open(bytes)?, query, round)
}

/// [`query_communities`] against an already-open [`Rete`] (shared with [`Graph`]).
fn query_communities_value(
    rete: &Rete,
    query: &str,
    round: Option<usize>,
) -> Result<String, JsValue> {
    use serde_json::{json, Map, Value};
    let (mut vars, solutions, partials) =
        eval_select_communities(rete, query, round).map_err(err)?;
    if vars.is_empty() {
        let mut seen = std::collections::BTreeSet::new();
        for s in &solutions {
            for k in s.keys() {
                if seen.insert(k.clone()) {
                    vars.push(k.clone());
                }
            }
        }
    }
    let rows: Vec<Value> = solutions
        .iter()
        .map(|s| {
            let mut obj = Map::new();
            for var in &vars {
                if let Some(term) = s.get(var) {
                    obj.insert(var.clone(), Value::String(term.clone()));
                }
            }
            Value::Object(obj)
        })
        .collect();
    let communities: Vec<Value> = partials
        .iter()
        .map(|p| json!({ "community": p.community, "subjects": p.subjects, "rows": p.rows }))
        .collect();
    serde_json::to_string(&json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "kind": "select",
        "vars": vars,
        "rows": rows,
        "communities": communities,
    }))
    .map_err(err)
}

/// The file's byte layout, for the playground's byte-map view. JSON:
/// `{ "fileLength": N, "segments": [ { "kind", "label", "offset", "len" } ] }`
/// — segments sorted by offset; uncovered bytes are container framing.
#[wasm_bindgen]
pub fn file_layout(bytes: &[u8]) -> Result<String, JsValue> {
    use serde_json::json;
    let rete = open(bytes)?;
    let segments: Vec<serde_json::Value> = rete
        .file_layout()
        .iter()
        .map(|s| json!({ "kind": s.kind, "label": s.label, "offset": s.offset, "len": s.len }))
        .collect();
    serde_json::to_string(&json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "fileLength": bytes.len(),
        "segments": segments,
    }))
    .map_err(err)
}

/// The full community pyramid as a tree — the "cluster of clusters" view.
/// Per dendrogram round (index 0 = finest, last = coarsest), every community
/// with its member-node count, triple count (triples whose subject belongs to
/// it), and its parent community at the next-coarser round (`null` at the
/// top). JSON:
/// `{ "rounds": N, "levels": [ [ { "id", "nodes", "triples", "parent" } ] ] }`.
#[wasm_bindgen]
pub fn pyramid_tree(bytes: &[u8]) -> Result<String, JsValue> {
    pyramid_tree_value(&open(bytes)?)
}

/// [`pyramid_tree`] against an already-open [`Rete`] (shared with [`Graph`]).
fn pyramid_tree_value(rete: &Rete) -> Result<String, JsValue> {
    use serde_json::json;
    use std::collections::BTreeMap;
    let dict = rete.dictionary();
    let ids = rete.match_ids((None, None, None));
    let g = project_graph(dict, &ids);
    let dend = build_dendrogram(&g);
    let rounds = dend.rounds();
    if rounds == 0 {
        return serde_json::to_string(&json!({
            "schemaVersion": JSON_SCHEMA_VERSION,
            "rounds": 0,
            "levels": [],
        }))
        .map_err(err);
    }
    let n = g.node_count();
    let mut levels = Vec::with_capacity(rounds);
    for r in 0..rounds {
        let mut nodes_per: BTreeMap<usize, usize> = BTreeMap::new();
        let mut rep: BTreeMap<usize, usize> = BTreeMap::new();
        for node in 0..n {
            let c = dend.base_community(node, r);
            *nodes_per.entry(c).or_default() += 1;
            rep.entry(c).or_insert(node);
        }
        let mut triples_per: BTreeMap<usize, usize> = BTreeMap::new();
        for &(s, _, _) in &ids {
            let c = dend.base_community(dict.subject_node(s) as usize, r);
            *triples_per.entry(c).or_default() += 1;
        }
        let level: Vec<serde_json::Value> = nodes_per
            .iter()
            .map(|(&c, &nodes)| {
                let parent = if r + 1 < rounds {
                    json!(dend.base_community(rep[&c], r + 1))
                } else {
                    json!(null)
                };
                json!({
                    "id": c,
                    "nodes": nodes,
                    "triples": triples_per.get(&c).copied().unwrap_or(0),
                    "parent": parent,
                })
            })
            .collect();
        levels.push(level);
    }
    serde_json::to_string(&json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "rounds": rounds,
        "levels": levels,
    }))
    .map_err(err)
}

/// Recompute the Louvain community decomposition and report, per community, its
/// member-subject count and triple count. Powers the "split by community"
/// strategy view in the playground. JSON:
/// `[{ "community": N, "size": M, "triples": K }, ...]`, ordered by community id.
///
/// `round` selects the dendrogram granularity; `None` chooses the round for the
/// default tile budget (the same choice the native build makes).
#[wasm_bindgen]
pub fn communities(bytes: &[u8], round: Option<usize>) -> Result<String, JsValue> {
    use std::collections::HashSet;
    let rete = open(bytes)?;
    let dict = rete.dictionary();
    let ids = rete.match_ids((None, None, None));
    let g = project_graph(dict, &ids);
    let dend = build_dendrogram(&g);
    let round =
        round.unwrap_or_else(|| choose_round_for_budget(dict, &ids, &dend, DEFAULT_TILE_BUDGET));
    let tiles = tile_by_community(dict, &ids, &dend, round);
    let arr: Vec<serde_json::Value> = tiles
        .iter()
        .map(|t| {
            let members: HashSet<u32> = t.triples.iter().map(|&(s, _, _)| s).collect();
            serde_json::json!({
                "community": t.community,
                "size": members.len(),
                "triples": t.triples.len(),
            })
        })
        .collect();
    serde_json::to_string(&arr).map_err(err)
}

/// Multi-source transitive reachability over one relation, run **serially**
/// (the browser engine is single-threaded — the native CLI's
/// `rete reach --parallel` fans one task per seed). For each seed, the set of
/// nodes it transitively reaches; with `reverse`, the set that reaches it
/// (impact analysis).
///
/// - `predicate` — the relation IRI token, e.g. `<http://ex/dependsOn>`.
/// - `seeds` — a JSON array of seed IRI tokens (e.g. `["<http://ex/app>"]`); a
///   bare single IRI string is also accepted.
/// - `reverse` — traverse edges backward ("who reaches the seed?").
///
/// Returns a JSON array, one entry per seed in input order:
/// `[{ "seed":"<iri>", "reached":["<iri>",...], "count":N }, ...]`.
/// A seed not present in the graph yields `{ "seed":"...", "error":"not in graph" }`
/// instead of failing the whole call.
#[wasm_bindgen]
pub fn reach(bytes: &[u8], predicate: &str, seeds: &str, reverse: bool) -> Result<String, JsValue> {
    reach_rete(&open(bytes)?, predicate, seeds, reverse)
}

/// Multi-source reachability over a **remote** `.rete` URL (lazy HTTP range
/// reads): builds adjacency for `predicate` by faulting only that predicate's
/// tiles, then BFS from each seed. Worker-only (synchronous XHR).
#[wasm_bindgen]
pub fn reach_url(
    url: &str,
    predicate: &str,
    seeds: &str,
    reverse: bool,
) -> Result<String, JsValue> {
    let (reader, rete) = open_url(url)?;
    let out = reach_rete(&rete, predicate, seeds, reverse)?;
    incomplete_guard(&rete, "reach")?;
    let _ = reader;
    Ok(out)
}

fn reach_rete(rete: &Rete, predicate: &str, seeds: &str, reverse: bool) -> Result<String, JsValue> {
    use std::collections::HashMap;
    let dict = rete.dictionary();

    // Accept either a JSON array of IRIs or a single bare IRI string.
    let seed_iris: Vec<String> = match serde_json::from_str::<Vec<String>>(seeds) {
        Ok(v) => v,
        Err(_) => match serde_json::from_str::<String>(seeds) {
            Ok(s) => vec![s],
            Err(_) => vec![seeds.to_string()],
        },
    };

    // Adjacency in unified node space for the chosen direction.
    let adj: HashMap<u32, Vec<u32>> = if reverse {
        let mut m: HashMap<u32, Vec<u32>> = HashMap::new();
        for (s, o) in rete.predicate_pairs(predicate) {
            m.entry(o).or_default().push(s); // who points at o
        }
        m
    } else {
        build_adjacency(rete, predicate)
    };

    // Resolve known seeds to node ids; remember unknowns to report inline.
    let mut known_idx: Vec<usize> = Vec::new();
    let mut seed_nodes: Vec<u32> = Vec::new();
    for (i, iri) in seed_iris.iter().enumerate() {
        if let Some(n) = dict.node_of_term(iri) {
            known_idx.push(i);
            seed_nodes.push(n);
        }
    }

    let sets = batch_reach_serial(&adj, &seed_nodes);

    // Map known-seed position -> its reach set, then assemble in input order.
    let mut by_input: HashMap<usize, &std::collections::BTreeSet<u32>> = HashMap::new();
    for (k, &i) in known_idx.iter().enumerate() {
        by_input.insert(i, &sets[k]);
    }

    let arr: Vec<serde_json::Value> = seed_iris
        .iter()
        .enumerate()
        .map(|(i, iri)| match by_input.get(&i) {
            Some(set) => {
                let reached: Vec<String> = set.iter().filter_map(|&n| dict.node_term(n)).collect();
                serde_json::json!({
                    "seed": iri,
                    "count": reached.len(),
                    "reached": reached,
                })
            }
            None => serde_json::json!({ "seed": iri, "error": "not in graph" }),
        })
        .collect();

    serde_json::to_string(&arr).map_err(err)
}

/// Validate a `.rete` graph against SHACL Core shapes written in Turtle.
///
/// The default graph is validated unless `graph` names a dataset graph IRI.
/// `format` is one of:
/// - `"json"`: structured validation report from rete-core
/// - `"ttl"`: Turtle validation report
/// - anything else: compact text report
///
/// A non-conformant graph returns a report; it is not a JS exception. Exceptions
/// are reserved for parse/open errors.
#[wasm_bindgen]
pub fn shacl(
    bytes: &[u8],
    shapes_turtle: &str,
    graph: Option<String>,
    format: &str,
) -> Result<String, JsValue> {
    shacl_rete(&open(bytes)?, shapes_turtle, graph.as_deref(), format)
}

/// Validate a **remote** `.rete` graph (lazy HTTP range reads) against SHACL
/// Core shapes written in Turtle. Validating the **default** graph routes every
/// lookup as a range read ([`ReteGraph`]), so a targeted shape faults only the
/// tiles holding its targets — not the whole graph. A named graph (`graph`) still
/// materializes (the routed view is default-graph only). Worker-only (sync XHR).
#[wasm_bindgen]
pub fn shacl_url(
    url: &str,
    shapes_turtle: &str,
    graph: Option<String>,
    format: &str,
) -> Result<String, JsValue> {
    let (reader, rete) = open_url(url)?;
    let out = shacl_rete(&rete, shapes_turtle, graph.as_deref(), format)?;
    incomplete_guard(&rete, "validation")?;
    let _ = reader;
    Ok(out)
}

fn shacl_rete(
    rete: &Rete,
    shapes_turtle: &str,
    graph: Option<&str>,
    format: &str,
) -> Result<String, JsValue> {
    let shapes = ShaclShapes::parse_turtle(shapes_turtle).map_err(err)?;
    // Default graph: validate over the index directly (lazy — fetch only targets).
    // A named graph still materializes (ReteGraph views the default graph only).
    let report = match graph {
        None => validate_shacl(&ReteGraph::new(rete), &shapes),
        Some(g) => validate_shacl(&DataGraph::from_rete(rete, Some(g)), &shapes),
    };
    Ok(format_report(&report, format))
}

fn shacl_over(data: DataGraph, shapes_turtle: &str, format: &str) -> Result<String, JsValue> {
    let shapes = ShaclShapes::parse_turtle(shapes_turtle).map_err(err)?;
    Ok(format_report(&validate_shacl(&data, &shapes), format))
}

fn format_report(report: &ValidationReport, format: &str) -> String {
    match format {
        "json" => report.to_json(),
        "ttl" => report.to_turtle(),
        _ => format_shacl_text(report),
    }
}

/// **Chain a SPARQL subset, then SHACL over it.** Evaluates a `CONSTRUCT` over
/// the remote `.rete` (touching only the tiles its patterns need), then validates
/// the resulting subgraph against the Turtle `shapes`. Where [`shacl_url`] selects
/// by *shape target* (validate every Person…), this selects by an explicit
/// `CONSTRUCT` — "validate just the slice this query carves out, in place".
/// Worker-only (synchronous XHR).
#[wasm_bindgen]
pub fn shacl_construct_url(
    url: &str,
    construct: &str,
    shapes_turtle: &str,
    format: &str,
) -> Result<String, JsValue> {
    let (reader, rete) = open_url(url)?;
    let triples = match eval_query(&rete, construct).map_err(err)? {
        QueryOutput::Construct(t) => t,
        _ => {
            return Err(js_error(
                "the subset query must be a CONSTRUCT — it builds the subgraph SHACL validates",
            ))
        }
    };
    incomplete_guard(&rete, "query")?;
    let out = shacl_over(DataGraph::from_triples(triples), shapes_turtle, format)?;
    let _ = reader;
    Ok(out)
}

// --- OWL RL / RDFS coherence checking ----------------------------------------
//
// The reasoner (`rete_core::reason`) is already slice-shaped, so these are near
// twins of the SHACL functions above: `reason`/`reason_url` materialize the whole
// graph (Tier-2, the complete check), while `reason_construct_url` validates only
// the slice a CONSTRUCT selects (Tier-1, selective range reads).

/// The fixed, **selective** coherence subgraph for [`reason_construct_url`]
/// (Tier-1). A UNION of constant-predicate branches: each routes to exactly one
/// predicate's index tiles, so the client faults only `rdf:type` + the class/
/// equality T-Box predicates over one warm lazy cache — not the whole graph.
///
/// The T-Box branches are MANDATORY: the reasoner finds disjoint-class clashes
/// only *after* `subClassOf` type-propagation, so omitting `subClassOf`/
/// `disjointWith`/`sameAs` would silently miss propagation-dependent
/// contradictions. Property-characteristic axioms (Functional/Symmetric/
/// Transitive) ride inside the `rdf:type` slice. Instance-level
/// FunctionalProperty / domain / range clashes need the property's own
/// assertions — use [`reason_url`] (Tier-2) for those.
pub const COHERENCE_CONSTRUCT: &str = r#"
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
CONSTRUCT {
  ?x rdf:type ?c .
  ?sub rdfs:subClassOf ?sup .
  ?c1 owl:disjointWith ?c2 .
  ?s1 owl:sameAs ?s2 .
  ?f1 owl:differentFrom ?f2 .
}
WHERE {
  { ?x rdf:type ?c }
  UNION { ?sub rdfs:subClassOf ?sup }
  UNION { ?c1 owl:disjointWith ?c2 }
  UNION { ?s1 owl:sameAs ?s2 }
  UNION { ?f1 owl:differentFrom ?f2 }
}
"#;

/// Build the playground JSON envelope for a [`rete_core::Reasoning`] result,
/// shared by the in-memory and remote entrypoints. `remote` is
/// `(fileLength, bytes, requests)` for the `*_url` variants, `None` in-memory.
/// JSON: `{ "kind":"reasoning", "coherent":bool, "inferredCount":N,
/// "inconsistencies":[{"kind","detail"}], ["remote":{...}] }`.
fn reasoning_json(r: &rete_core::Reasoning, remote: Option<(u64, u64, u64)>) -> String {
    use serde_json::json;
    let inconsistencies: Vec<serde_json::Value> = r
        .inconsistencies
        .iter()
        .map(|i| json!({ "kind": i.kind, "detail": i.detail }))
        .collect();
    let mut v = json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "kind": "reasoning",
        "coherent": r.inconsistencies.is_empty(),
        "inferredCount": r.inferred.len(),
        "inconsistencies": inconsistencies,
    });
    if let (Some(obj), Some((file_length, bytes, requests))) = (v.as_object_mut(), remote) {
        obj.insert(
            "remote".to_string(),
            json!({ "fileLength": file_length, "bytes": bytes, "requests": requests }),
        );
    }
    v.to_string()
}

/// Run the OWL RL / RDFS reasoner over an **in-memory** `.rete` and report the
/// inferred-triple count plus any incoherent points (logical contradictions).
/// `graph` selects a named graph; the default graph is used when omitted. This is
/// the complete (Tier-2) check — it materializes the whole graph. Returns the
/// `reasoning_json` envelope (no `remote` block).
#[wasm_bindgen]
pub fn reason(bytes: &[u8], graph: Option<String>) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    let base = rete.dump(graph.as_deref());
    let result = rete_core::reason(&base);
    Ok(reasoning_json(&result, None))
}

/// Run the reasoner over a **remote** `.rete` URL — the complete (Tier-2) check.
/// It materializes the whole graph, so this faults in the dataset's chunks/tiles
/// as it reads (≈ the whole file); use [`reason_construct_url`] for the cheaper
/// selective check. Worker-only (synchronous XHR). A failed range fetch mid-read
/// is an error, never a silently-incomplete (and thus possibly false "coherent")
/// result. JSON adds `"remote": { fileLength, bytes, requests }`.
#[wasm_bindgen]
pub fn reason_url(url: &str, graph: Option<String>) -> Result<String, JsValue> {
    let (reader, rete) = open_url(url)?;
    let base = rete.dump(graph.as_deref());
    let result = rete_core::reason(&base);
    incomplete_guard(&rete, "reasoning")?;
    let out = reasoning_json(
        &result,
        Some((reader.len(), reader.bytes_read(), reader.requests())),
    );
    let _ = reader;
    Ok(out)
}

/// **Selective (Tier-1) coherence check** over a remote `.rete`: evaluate a
/// CONSTRUCT (touching only the tiles its constant-predicate patterns need), then
/// reason over just that subgraph. Pass [`COHERENCE_CONSTRUCT`] for the standard
/// class/equality coherence slice, or a custom CONSTRUCT to scope the check
/// further. Unlike [`reason_url`] (which materializes the whole graph), this
/// fetches only the slice the CONSTRUCT selects. Worker-only (synchronous XHR).
#[wasm_bindgen]
pub fn reason_construct_url(url: &str, construct: &str) -> Result<String, JsValue> {
    let (reader, rete) = open_url(url)?;
    let triples =
        match eval_query(&rete, construct).map_err(err)? {
            QueryOutput::Construct(t) => t,
            _ => return Err(js_error(
                "the subset query must be a CONSTRUCT — it builds the subgraph the reasoner checks",
            )),
        };
    incomplete_guard(&rete, "query")?;
    let result = rete_core::reason(&triples);
    let out = reasoning_json(
        &result,
        Some((reader.len(), reader.bytes_read(), reader.requests())),
    );
    let _ = reader;
    Ok(out)
}

/// Build the Tier-0 schema-coherence JSON envelope from the incoherent points.
/// `remote` is `(fileLength, bytes, requests)` for the `*_url` variant.
fn schema_coherence_json(
    points: &[rete_core::Inconsistency],
    remote: Option<(u64, u64, u64)>,
) -> String {
    use serde_json::json;
    let schema_points: Vec<serde_json::Value> = points
        .iter()
        .map(|i| json!({ "kind": i.kind, "detail": i.detail }))
        .collect();
    let mut v = json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "kind": "schemaCoherence",
        "coherent": points.is_empty(),
        "schemaPoints": schema_points,
        // The defining property: this answer never touched the index OR dictionary.
        "readsIndex": false,
    });
    if let (Some(obj), Some((file_length, bytes, requests))) = (v.as_object_mut(), remote) {
        obj.insert(
            "remote".to_string(),
            json!({ "fileLength": file_length, "bytes": bytes, "requests": requests }),
        );
    }
    v.to_string()
}

/// **Index-free schema coherence (Tier-0)** over an in-memory `.rete`: read only
/// the header + pyramid-meta (never the dictionary or the triple index) and report
/// schema-level incoherent points (subClassOf cycles, unsatisfiable classes).
/// Errors if the file ships no schema pyramid.
#[wasm_bindgen]
pub fn check_schema(bytes: &[u8]) -> Result<String, JsValue> {
    let points = rete_core::read_schema_coherence_ranged(&SliceReader::new(bytes))
        .map_err(err)?
        .ok_or_else(|| js_error("file has no schema pyramid"))?;
    Ok(schema_coherence_json(&points, None))
}

/// **Index-free schema coherence (Tier-0) over a remote `.rete` URL.** Reads only
/// TWO ranges — the header and the trailing schema block (the header records its
/// length) — never the dictionary, the community summary, or the triple index. So
/// it's a flat **~1–8 KB at any graph size** (8.1 KB of a 48.8 MB file; see
/// docs/BENCHMARK.md), making it the cheap "is the ontology coherent?" gate.
/// Worker-only (synchronous XHR); a failed range fetch is an error, never a false
/// "coherent".
#[wasm_bindgen]
pub fn check_schema_url(url: &str) -> Result<String, JsValue> {
    let reader = CountingReader::new(XhrRangeReader::open(url)?);
    let points = rete_core::read_schema_coherence_ranged(&reader)
        .map_err(err)?
        .ok_or_else(|| js_error("file has no schema pyramid"))?;
    Ok(schema_coherence_json(
        &points,
        Some((reader.len(), reader.bytes_read(), reader.requests())),
    ))
}

/// The schema summary (classes + relations) read from the schema pyramid over
/// HTTP range — a Schema view of a remote graph without downloading it.
/// Worker-only (synchronous XHR). JSON:
/// `{ "kind":"schema", "classes":[[iri,count]], "relations":[[s,p,o,count]], "remote":{…} }`.
#[wasm_bindgen]
pub fn schema_url(url: &str) -> Result<String, JsValue> {
    use serde_json::json;
    let reader = CountingReader::new(XhrRangeReader::open(url)?);
    let (classes, relations) = rete_core::read_schema_summary_ranged(&reader)
        .map_err(err)?
        .ok_or_else(|| js_error("file has no schema pyramid"))?;
    let classes: Vec<serde_json::Value> = classes.iter().map(|(c, n)| json!([c, n])).collect();
    let relations: Vec<serde_json::Value> = relations
        .iter()
        .map(|(s, p, o, n)| json!([s, p, o, n]))
        .collect();
    Ok(json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "kind": "schema",
        "classes": classes,
        "relations": relations,
        "remote": { "fileLength": reader.len(), "bytes": reader.bytes_read(), "requests": reader.requests() },
    })
    .to_string())
}

fn format_shacl_text(report: &ValidationReport) -> String {
    if report.conforms {
        return "conforms: true\n".to_string();
    }
    let mut out = format!("conforms: false\nresults: {}\n", report.results.len());
    for result in &report.results {
        out.push_str("\n- focus: ");
        out.push_str(&result.focus_node);
        if let Some(value) = &result.value_node {
            out.push_str("\n  value: ");
            out.push_str(value);
        }
        if let Some(path) = &result.result_path {
            out.push_str("\n  path: ");
            out.push_str(path);
        }
        out.push_str("\n  component: ");
        out.push_str(&result.source_constraint_component);
        out.push_str("\n  severity: ");
        out.push_str(&result.severity.iri());
        for message in &result.messages {
            out.push_str("\n  message: ");
            out.push_str(message);
        }
        out.push('\n');
    }
    out
}

// --- EXPERIMENTAL: real browser-thread parallelism (feature = "threads") ------
//
// Only compiled when the `threads` feature is on (a nightly + build-std wasm
// build, served cross-origin-isolated). The default build never sees any of
// this, so it stays single-threaded and `file://`-able.

/// Re-export wasm-bindgen-rayon's thread-pool initializer. JS MUST
/// `await initThreadPool(n)` once (after the module `init()`) before calling
/// [`reach_parallel`], or any rayon use will panic. Backed by Web Workers +
/// `SharedArrayBuffer`, so the page must be cross-origin isolated (COOP/COEP).
#[cfg(feature = "threads")]
pub use wasm_bindgen_rayon::init_thread_pool;

/// Multi-source transitive reachability run on **real browser threads** via
/// `wasm-bindgen-rayon` — the threaded twin of [`reach`]. Same arguments, same
/// JSON result shape; the only difference is it calls
/// [`rete_core::parallel::batch_reach_parallel`] (one rayon task per seed)
/// instead of the serial loop. Use it to benchmark the 14× batch-reachability
/// workload against [`reach`] in the browser.
///
/// Requires `await initThreadPool(navigator.hardwareConcurrency)` first.
#[cfg(feature = "threads")]
#[wasm_bindgen]
pub fn reach_parallel(
    bytes: &[u8],
    predicate: &str,
    seeds: &str,
    reverse: bool,
) -> Result<String, JsValue> {
    use std::collections::HashMap;
    let rete = open(bytes)?;
    let dict = rete.dictionary();

    // Accept either a JSON array of IRIs or a single bare IRI string (mirrors `reach`).
    let seed_iris: Vec<String> = match serde_json::from_str::<Vec<String>>(seeds) {
        Ok(v) => v,
        Err(_) => match serde_json::from_str::<String>(seeds) {
            Ok(s) => vec![s],
            Err(_) => vec![seeds.to_string()],
        },
    };

    // Adjacency in unified node space for the chosen direction.
    let adj: HashMap<u32, Vec<u32>> = if reverse {
        let mut m: HashMap<u32, Vec<u32>> = HashMap::new();
        for (s, o) in rete.predicate_pairs(predicate) {
            m.entry(o).or_default().push(s); // who points at o
        }
        m
    } else {
        build_adjacency(&rete, predicate)
    };

    // Resolve known seeds to node ids; remember unknowns to report inline.
    let mut known_idx: Vec<usize> = Vec::new();
    let mut seed_nodes: Vec<u32> = Vec::new();
    for (i, iri) in seed_iris.iter().enumerate() {
        if let Some(n) = dict.node_of_term(iri) {
            known_idx.push(i);
            seed_nodes.push(n);
        }
    }

    // The one line that differs from serial `reach`: real-thread fan-out.
    let sets = rete_core::parallel::batch_reach_parallel(&adj, &seed_nodes);

    // Map known-seed position -> its reach set, then assemble in input order.
    let mut by_input: HashMap<usize, &std::collections::BTreeSet<u32>> = HashMap::new();
    for (k, &i) in known_idx.iter().enumerate() {
        by_input.insert(i, &sets[k]);
    }

    let arr: Vec<serde_json::Value> = seed_iris
        .iter()
        .enumerate()
        .map(|(i, iri)| match by_input.get(&i) {
            Some(set) => {
                let reached: Vec<String> = set.iter().filter_map(|&n| dict.node_term(n)).collect();
                serde_json::json!({
                    "seed": iri,
                    "count": reached.len(),
                    "reached": reached,
                })
            }
            None => serde_json::json!({ "seed": iri, "error": "not in graph" }),
        })
        .collect();

    serde_json::to_string(&arr).map_err(err)
}

// --- CONSTRUCT serializers (mirrored from rete-cli, kept minimal) ------------

const RDF_TYPE_IRI: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";
const XSD_INTEGER_IRI: &str = "http://www.w3.org/2001/XMLSchema#integer";

fn summary_total(view: &SummaryView) -> u64 {
    view.summary.iter().map(|edge| u64::from(edge.count)).sum()
}

fn predicate_list(view: &SummaryView) -> Vec<String> {
    view.predicate_totals()
        .into_iter()
        .map(|(predicate, _)| predicate)
        .collect()
}

fn predicate_count(view: &SummaryView) -> u64 {
    view.predicate_totals().len() as u64
}

fn select_count_response(
    variable: &str,
    count: u64,
    progressive: serde_json::Value,
) -> serde_json::Value {
    use serde_json::{json, Map, Value};

    let mut row = Map::new();
    row.insert(variable.to_string(), Value::String(integer_literal(count)));
    json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "kind": "select",
        "vars": [variable],
        "rows": [Value::Object(row)],
        "progressive": progressive,
    })
}

fn select_predicate_list_response(
    variable: &str,
    predicates: &[String],
    progressive: serde_json::Value,
) -> serde_json::Value {
    use serde_json::{json, Map, Value};

    let rows: Vec<Value> = predicates
        .iter()
        .map(|predicate| {
            let mut row = Map::new();
            row.insert(variable.to_string(), Value::String(predicate.clone()));
            Value::Object(row)
        })
        .collect();

    json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "kind": "select",
        "vars": [variable],
        "rows": rows,
        "progressive": progressive,
    })
}

fn select_predicate_totals_response(
    predicate_variable: &str,
    count_variable: &str,
    totals: &[(String, u32)],
    progressive: serde_json::Value,
) -> serde_json::Value {
    use serde_json::{json, Map, Value};

    let rows: Vec<Value> = totals
        .iter()
        .map(|(predicate, count)| {
            let mut row = Map::new();
            row.insert(
                predicate_variable.to_string(),
                Value::String(predicate.clone()),
            );
            row.insert(
                count_variable.to_string(),
                Value::String(integer_literal(u64::from(*count))),
            );
            Value::Object(row)
        })
        .collect();

    json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "kind": "select",
        "vars": [predicate_variable, count_variable],
        "rows": rows,
        "progressive": progressive,
    })
}

fn progressive_meta<R: RangeReader>(
    reader: &CountingReader<R>,
    file_bytes: u64,
    query_shape: &str,
    predicate: Option<&str>,
    value: serde_json::Value,
) -> serde_json::Value {
    use serde_json::{json, Map, Value};

    let mut meta = Map::new();
    meta.insert("stage".into(), json!("summary"));
    meta.insert("exact".into(), json!(true));
    meta.insert("readsIndex".into(), json!(false));
    meta.insert("queryShape".into(), json!(query_shape));
    meta.insert("value".into(), value);
    meta.insert("bytes".into(), json!(reader.bytes_read()));
    meta.insert("requests".into(), json!(reader.requests()));
    meta.insert("fileBytes".into(), json!(file_bytes));
    if let Some(predicate) = predicate {
        meta.insert("predicate".into(), json!(predicate));
    }
    Value::Object(meta)
}

fn integer_literal(value: u64) -> String {
    format!("\"{}\"^^<{}>", value, XSD_INTEGER_IRI)
}

fn provenance_json(m: &TripleProvenance) -> serde_json::Value {
    use serde_json::json;

    let tile = match (&m.tile, m.tile_range) {
        (Some(id), Some(range)) => json!({
            "available": true,
            "id": id,
            "range": range_json(range),
        }),
        (Some(id), None) => json!({
            "available": true,
            "id": id,
        }),
        _ => json!({
            "available": false,
            "reason": "not_materialized",
        }),
    };

    json!({
        "terms": {
            "subject": m.terms.0,
            "predicate": m.terms.1,
            "object": m.terms.2,
        },
        "ids": {
            "subject": m.ids.0,
            "predicate": m.ids.1,
            "object": m.ids.2,
        },
        "provenance": {
            "graph": m.graph.as_deref().unwrap_or("default"),
            "matchedPattern": {
                "subject": m.matched_pattern.0,
                "predicate": m.matched_pattern.1,
                "object": m.matched_pattern.2,
            },
            "indexPermutation": m.index_permutation.name(),
            "indexSection": m.index_permutation.section_index(),
            "dictionaryRange": range_json(m.dictionary_range),
            "indexRange": range_json(m.index_range),
            "indexSectionRange": range_json(m.index_section_range),
            "pyramidRange": m.pyramid_range.map(range_json),
            "tile": tile,
        },
    })
}

fn range_json(range: ByteRange) -> serde_json::Value {
    serde_json::json!({
        "offset": range.offset,
        "len": range.len,
        "end": range.end(),
    })
}

/// Serialize a triple list (canonical N-Triples tokens) to Turtle: group by
/// subject, sort predicates/objects, abbreviate `rdf:type` to `a`. The tokens are
/// already valid Turtle term syntax, so they pass through verbatim.
fn to_turtle(triples: &[(String, String, String)]) -> String {
    use std::collections::BTreeMap;
    let mut by_subject: BTreeMap<&str, BTreeMap<&str, Vec<&str>>> = BTreeMap::new();
    for (s, p, o) in triples {
        by_subject
            .entry(s)
            .or_default()
            .entry(p)
            .or_default()
            .push(o);
    }
    let mut out = String::new();
    for (s, preds) in &by_subject {
        out.push_str(s);
        out.push('\n');
        let pred_count = preds.len();
        for (i, (p, objs)) in preds.iter().enumerate() {
            let pred = if *p == RDF_TYPE_IRI { "a" } else { p };
            let objects = objs.join(" , ");
            let terminator = if i + 1 == pred_count { " ." } else { " ;" };
            out.push_str(&format!("    {pred} {objects}{terminator}\n"));
        }
        out.push('\n');
    }
    out
}

/// Serialize a triple list to expanded JSON-LD (array of node objects keyed by
/// `@id`; literals as `@value` + optional `@type`/`@language`).
fn to_jsonld(triples: &[(String, String, String)]) -> String {
    use serde_json::{json, Map, Value};
    use std::collections::BTreeMap;
    let mut nodes: BTreeMap<String, BTreeMap<String, Vec<Value>>> = BTreeMap::new();
    for (s, p, o) in triples {
        let id = node_id(s);
        let pred = p
            .strip_prefix('<')
            .and_then(|x| x.strip_suffix('>'))
            .unwrap_or(p)
            .to_string();
        nodes
            .entry(id)
            .or_default()
            .entry(pred)
            .or_default()
            .push(object_to_jsonld(o));
    }
    let arr: Vec<Value> = nodes
        .into_iter()
        .map(|(id, preds)| {
            let mut obj = Map::new();
            obj.insert("@id".into(), json!(id));
            for (pred, vals) in preds {
                obj.insert(pred, Value::Array(vals));
            }
            Value::Object(obj)
        })
        .collect();
    serde_json::to_string_pretty(&Value::Array(arr)).unwrap_or_default()
}

/// JSON-LD `@id` for a subject token: bare IRI for `<iri>`, `_:b` verbatim.
fn node_id(token: &str) -> String {
    token
        .strip_prefix('<')
        .and_then(|s| s.strip_suffix('>'))
        .map(str::to_string)
        .unwrap_or_else(|| token.to_string())
}

/// Classify an object token into a JSON-LD value object.
fn object_to_jsonld(token: &str) -> serde_json::Value {
    use serde_json::{json, Map, Value};
    if let Some(iri) = token.strip_prefix('<').and_then(|s| s.strip_suffix('>')) {
        return json!({ "@id": iri });
    }
    if let Some(b) = token.strip_prefix("_:") {
        return json!({ "@id": format!("_:{b}") });
    }
    if token.starts_with('"') {
        let bytes = token.as_bytes();
        let mut i = 1;
        while i < bytes.len() {
            match bytes[i] {
                b'\\' => i += 2,
                b'"' => break,
                _ => i += 1,
            }
        }
        let value = unescape_nt(&token[1..i.min(token.len())]);
        let rest = token.get(i + 1..).unwrap_or("");
        let mut obj = Map::new();
        obj.insert("@value".into(), Value::String(value));
        if let Some(dt) = rest.strip_prefix("^^<").and_then(|s| s.strip_suffix('>')) {
            obj.insert("@type".into(), json!(dt));
        } else if let Some(lang) = rest.strip_prefix('@') {
            obj.insert("@language".into(), json!(lang));
        }
        return Value::Object(obj);
    }
    json!({ "@value": token })
}

/// Resolve the N-Triples escape sequences in a literal's body to actual chars.
fn unescape_nt(s: &str) -> String {
    rete_core::terms::unescape_literal(s)
}

fn open(bytes: &[u8]) -> Result<Rete, JsValue> {
    let mut rete = Rete::open(bytes).map_err(err)?;
    // SERVICE blocks federate to remote SPARQL endpoints over sync XHR.
    rete.set_service_client(Box::new(XhrServiceClient));
    Ok(rete)
}

fn err<E: std::fmt::Display>(e: E) -> JsValue {
    js_error(e.to_string())
}

fn js_error(message: impl AsRef<str>) -> JsValue {
    js_sys::Error::new(message.as_ref()).into()
}