hypersteeldb 0.5.4

A database that compiles questions instead of guessing answers: typed vocabulary discovered from your documents, queries type-checked before they run, roaring-bitmap set algebra over reified hyperedges, and Dempster-Shafer evidence with an explicit conflict guard.
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
//! **Step 0 in the browser** — the same Rust that runs in the CLI, compiled to WebAssembly.
//!
//! Paper §2 (Domain Typing via the Bitmap Symbol Table) is model-free and pure: given document text, field
//! sensing counts recurring labelled fields and returns the Vocabulary Space **V**. No file I/O, no network,
//! no model — which is exactly the property that lets it run client-side.
//!
//! This exists so the public demo can be a *static* page while still executing the real engine. A JavaScript
//! reimplementation of step 0 would demonstrate nothing: the claim under test is that the same code returns
//! the same vocabulary every time, so the demo has to run that code.
//!
//! Build (see `spaces/build-wasm.sh`):
//! ```text
//! cargo build --release --target wasm32-unknown-unknown --no-default-features --features wasm --lib
//! wasm-bindgen --target web --out-dir <out> target/wasm32-unknown-unknown/release/steeldb.wasm
//! ```

use wasm_bindgen::prelude::*;

use crate::linter::Linter;
use crate::vocabulary::{candidate_fields, field_spans, field_value_tokens, seed_from_sample};

/// Derive the Vocabulary Space from documents, returning the same JSON shape the `sense_ontology` binary
/// prints. `docs_text` holds the documents separated by a line containing `---`.
#[wasm_bindgen]
pub fn sense_ontology(docs_text: &str, min_support: usize) -> String {
    let samples: Vec<String> = docs_text
        .split("\n---")
        .map(|d| d.trim().to_string())
        .filter(|d| !d.is_empty())
        .collect();

    if samples.is_empty() {
        return serde_json::json!({ "error": "no documents" }).to_string();
    }

    let candidates = candidate_fields(&samples);
    let spec = seed_from_sample("pasted", &samples, min_support);

    serde_json::json!({
        "corpus": "pasted",
        "sampled_docs": samples.len(),
        "min_support": min_support,
        "entity_facets": spec.entity_facets.iter().map(|f| serde_json::json!({
            "name": f.name,
            "path": spec.facet_path(&f.name),
            "parent": f.parent,
            "description": f.description,
            "structural": f.structural,
            "examples": f.examples,
        })).collect::<Vec<_>>(),
        "relation_facets": spec.relation_facets.iter().map(|r| serde_json::json!({
            "name": r.name, "head": r.head, "tail": r.tail, "uri": format!("rel/{}/+", r.name),
        })).collect::<Vec<_>>(),
        "wildcard_stems": spec.valid_prefixes(),
        "taggable_facets": spec.taggable_facets(),
        "candidate_fields": candidates.iter().map(|(name, n)| serde_json::json!({
            "field": name, "support": n, "kept": *n >= min_support,
        })).collect::<Vec<_>>(),
        "valid": spec.validate().is_ok(),
        "validation_error": spec.validate().err().map(|e| e.to_string()),
    })
    .to_string()
}

/// Lint an IKL s-expression against a vocabulary derived from the same documents.
///
/// This is the payoff of step 0 and the reason the two are shown together: an atom can only be checked
/// because the previous step decided what exists. An unknown term comes back as a rejection *with
/// in-vocabulary alternatives*, never as a guess.
#[wasm_bindgen]
pub fn lint_expression(docs_text: &str, min_support: usize, expression: &str) -> String {
    let samples: Vec<String> = docs_text
        .split("\n---")
        .map(|d| d.trim().to_string())
        .filter(|d| !d.is_empty())
        .collect();
    let spec = seed_from_sample("pasted", &samples, min_support);

    // The symbol table a real corpus exposes: concrete `facet/value` tokens, not just stems. Seeding only
    // stems would make a perfectly valid `type/fire` look unknown, which misrepresents the linter.
    let facets: Vec<String> = spec.entity_facets.iter().map(|f| f.name.clone()).collect();
    let mut tokens = field_value_tokens(&samples, &facets);
    tokens.extend(facets.iter().map(|f| format!("{f}/*")));
    let linter = Linter::from_tokens(tokens.clone());
    let report = linter.lint(expression);

    serde_json::json!({
        "expression": expression,
        "ok": report.ok,
        "repaired": report.repaired,
        "errors": report.errors.iter().map(|e| serde_json::json!({
            "message": e.message,
        })).collect::<Vec<_>>(),
        "facets": linter.facet_names(),
        "symbol_table_size": tokens.len(),
    })
    .to_string()
}

/// Annotate the documents for a displaCy-style inline rendering.
///
/// Returns each document already **segmented** into an ordered list of chunks — `{text}` for plain text and
/// `{text, facet}` for a matched field value. Byte offsets are deliberately NOT exposed: Rust counts bytes
/// while JavaScript indexes UTF-16 code units, so any document containing `é` or `°` would render shifted
/// text. Segmenting here makes that class of bug unrepresentable in the caller.
#[wasm_bindgen]
pub fn annotate(docs_text: &str, min_support: usize) -> String {
    let samples: Vec<String> = docs_text
        .split("\n---")
        .map(|d| d.trim().to_string())
        .filter(|d| !d.is_empty())
        .collect();
    let spec = seed_from_sample("pasted", &samples, min_support);
    let kept: std::collections::HashSet<&str> = spec.entity_facets.iter().map(|f| f.name.as_str()).collect();

    let docs: Vec<serde_json::Value> = samples
        .iter()
        .map(|doc| {
            let mut spans = field_spans(doc);
            // only facets that cleared the support floor are part of the vocabulary
            spans.retain(|s| kept.contains(s.facet.as_str()));
            spans.sort_by_key(|s| s.start);

            let mut segments: Vec<serde_json::Value> = Vec::new();
            let mut cursor = 0usize;
            for s in &spans {
                if s.start < cursor || s.end > doc.len() {
                    continue; // overlapping or out of range: skip rather than corrupt the text
                }
                if s.start > cursor {
                    segments.push(serde_json::json!({ "text": &doc[cursor..s.start] }));
                }
                segments.push(serde_json::json!({ "text": &doc[s.start..s.end], "facet": s.facet }));
                cursor = s.end;
            }
            if cursor < doc.len() {
                segments.push(serde_json::json!({ "text": &doc[cursor..] }));
            }
            serde_json::json!({ "segments": segments, "matched": spans.len() })
        })
        .collect();

    serde_json::json!({
        "documents": docs,
        "facets": spec.entity_facets.iter().map(|f| f.name.clone()).collect::<Vec<_>>(),
        "sampled_docs": samples.len(),
        "min_support": min_support,
    })
    .to_string()
}

/// The discovered taxonomy as a dendrogram: leaves are the facets kept at the cut, internal nodes are the
/// merges that produced them.
#[wasm_bindgen]
pub fn hierarchy(docs_text: &str, n_terms: usize, n_clusters: usize) -> String {
    let docs: Vec<String> = docs_text
        .split("\n---")
        .map(|d| d.trim().to_string())
        .filter(|d| !d.is_empty())
        .collect();
    match crate::emergent::discover_hierarchy(&docs, n_terms, n_clusters) {
        Some(tree) => serde_json::to_string(&tree).unwrap_or_else(|_| "null".into()),
        None => "null".to_string(),
    }
}

/// Run the **real** ontology codebook on real typed spans: per kind, k-means prototypes then Sinkhorn
/// optimal transport on a `1 - cosine` cost, exactly as `spo_sinkhorn.py` does.
///
/// `spans_json` is the output of the native `export_spans` binary: the SPO tagger's typed spans with their
/// model2vec embeddings. Those two stages cannot compile to WebAssembly (ONNX Runtime, and a tokenizer that
/// links a C regex library), so they run natively and arrive here as data. Everything the ontology discovery
/// actually consists of runs here.
///
/// Clustering is per kind because the kinds ARE the facet axes: each within-kind cluster is a facet value.
/// Pooling them would cluster a place against a verb, which is the failure the earlier co-occurrence demo had.
///
/// The epsilon schedule is returned as frames so a viewer can watch the plan sharpen. Lowering epsilon is
/// what concentrates the assignment; more iterations only make it satisfy the marginals.
#[wasm_bindgen]
pub fn codebook(spans_json: &str, k_per_kind: usize) -> String {
    use crate::text::ot;

    let Ok(payload) = serde_json::from_str::<serde_json::Value>(spans_json) else {
        return serde_json::json!({ "error": "could not parse spans" }).to_string();
    };
    let empty: Vec<serde_json::Value> = Vec::new();
    let spans = payload["spans"].as_array().unwrap_or(&empty);

    // group by kind, l2-normalising as we go so cosine is a dot product
    let mut by_kind: std::collections::BTreeMap<String, (Vec<String>, Vec<Vec<f32>>, Vec<usize>)> =
        std::collections::BTreeMap::new();
    for sp in spans {
        let kind = sp["kind"].as_str().unwrap_or("?").to_string();
        let text = sp["text"].as_str().unwrap_or("").to_string();
        let count = sp["count"].as_u64().unwrap_or(1) as usize;
        let v: Vec<f32> = sp["vec"]
            .as_array()
            .map(|a| a.iter().filter_map(|x| x.as_f64()).map(|x| x as f32).collect())
            .unwrap_or_default();
        if text.is_empty() || v.is_empty() {
            continue;
        }
        let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt() + 1e-9;
        let unit: Vec<f32> = v.into_iter().map(|x| x / norm).collect();
        let e = by_kind.entry(kind).or_insert_with(|| (Vec::new(), Vec::new(), Vec::new()));
        e.0.push(text);
        e.1.push(unit);
        e.2.push(count);
    }

    let entropy = |plan: &Vec<Vec<f32>>, k: usize| -> f64 {
        let mut h = 0.0f64;
        let mut rows = 0usize;
        for row in plan {
            let sum: f32 = row.iter().sum();
            if sum <= 0.0 {
                continue;
            }
            for &x in row {
                let p = (x / sum) as f64;
                if p > 1e-12 {
                    h -= p * p.ln();
                }
            }
            rows += 1;
        }
        if rows == 0 { 0.0 } else { h / rows as f64 / (k as f64).ln().max(1e-9) }
    };

    // The sweep is a visualisation: the reference implementation runs a single epsilon, and annealing is how
    // this page shows what epsilon DOES — the plan sharpening from hedged to committed. So the last frame must
    // land exactly on the reference's value, or the figure ends somewhere the engine never runs.
    let schedule: [f32; 6] = [0.40, 0.26, 0.17, 0.11, 0.075, crate::emergent::DISCOVER_EPS];
    let mut kinds_out: Vec<serde_json::Value> = Vec::new();

    for (kind, (terms, vecs, counts)) in by_kind {
        let k = k_per_kind.clamp(2, terms.len().max(2)).min(terms.len());
        if terms.len() < 2 {
            continue;
        }
        // 60 Lloyd iterations and seed 1, matching `ot::codebook` and the reference's `kmeans(X, k, iters=60)`.
        // It ran 40 here, so the prototypes the figure drew were not the ones discovery would settle on.
        let protos = ot::kmeans(&vecs, k, 60, 1);
        // cost = 1 - cosine, the reference's `1.0 - X @ C.T`
        let cost: Vec<Vec<f32>> = vecs
            .iter()
            .map(|v| protos.iter().map(|c| 1.0 - v.iter().zip(c).map(|(a, b)| a * b).sum::<f32>()).collect())
            .collect();

        let mut frames: Vec<serde_json::Value> = Vec::new();
        let mut final_plan: Vec<Vec<f32>> = Vec::new();
        for &eps in &schedule {
            let (plan, c) = ot::sinkhorn(&cost, eps, 200);
            frames.push(serde_json::json!({
                "epsilon": eps,
                "entropy": entropy(&plan, k),
                "cost": c,
                "plan": plan.iter().map(|row| {
                    let sum: f32 = row.iter().sum::<f32>().max(1e-9);
                    row.iter().map(|x| (x / sum * 100.0).round() as i32).collect::<Vec<_>>()
                }).collect::<Vec<_>>(),
            }));
            final_plan = plan;
        }

        // each term joins the prototype it sends most mass to; the cluster is labelled by its nearest member
        let mut members: Vec<Vec<(String, usize, f32)>> = vec![Vec::new(); k];
        for (i, row) in final_plan.iter().enumerate() {
            let (best, mass) = row
                .iter()
                .enumerate()
                .max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal))
                .map(|(j, m)| (j, *m))
                .unwrap_or((0, 0.0));
            // proximity to the prototype decides the label, so it is the most representative member
            let closeness = 1.0 - cost[i][best];
            members[best].push((terms[i].clone(), counts[i], closeness.max(0.0)));
            let _ = mass;
        }

        let clusters: Vec<serde_json::Value> = members
            .into_iter()
            .enumerate()
            .filter(|(_, m)| !m.is_empty())
            .map(|(j, mut m)| {
                m.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));
                serde_json::json!({
                    "index": j,
                    "label": m.first().map(|(t, _, _)| t.clone()).unwrap_or_default(),
                    "size": m.len(),
                    "members": m.iter().take(8).map(|(t, c, _)| serde_json::json!({ "text": t, "count": c }))
                        .collect::<Vec<_>>(),
                })
            })
            .collect();

        kinds_out.push(serde_json::json!({
            "kind": kind,
            "terms": terms,
            "k": k,
            "clusters": clusters,
            "frames": frames,
        }));
    }

    serde_json::json!({
        "documents": payload["documents"].clone(),
        "dim": payload["dim"].clone(),
        "routed_away": payload["routed_away"].clone(),
        "numeric_rules": payload["numeric_rules"].clone(),
        "kinds": kinds_out,
        "source": payload["source"].clone(),
    })
    .to_string()
}

/// Sinkhorn optimal transport over the co-occurrence geometry, reported at increasing iteration counts so a
/// viewer can watch the transport plan sharpen and its entropy fall.
///
/// Rows are terms, columns are emerging topics, and a cell is how much of that term's mass is assigned to
/// that topic. Early on the mass is spread out (high entropy, the algorithm is undecided); as it iterates the
/// plan concentrates, and that concentration IS the ontology crystallising. Balanced marginals are what stop
/// one topic from swallowing everything.
#[wasm_bindgen]
pub fn transport(docs_text: &str, n_terms: usize, k: usize, eps: f32) -> String {
    use crate::text::ot;
    let docs: Vec<String> = docs_text
        .split("\n---")
        .map(|d| d.trim().to_string())
        .filter(|d| !d.is_empty())
        .collect();

    let (names, vecs) = crate::emergent::term_vectors(&docs, n_terms);
    if names.len() < k || k == 0 {
        return serde_json::json!({ "error": "not enough salient terms for that many topics" }).to_string();
    }

    // topic centroids from k-means over the same geometry
    let centroids = ot::kmeans(&vecs, k, 25, 7);
    // cost = 1 - cosine; vectors are L2-normalised so cosine is the dot product
    let cost: Vec<Vec<f32>> = vecs
        .iter()
        .map(|v| centroids.iter().map(|c| 1.0 - v.iter().zip(c).map(|(a, b)| a * b).sum::<f32>()).collect())
        .collect();

    // entropy of a plan, normalised so 1.0 = maximally spread and 0.0 = fully decided
    let entropy = |plan: &Vec<Vec<f32>>| -> f64 {
        let mut h = 0.0f64;
        let mut cells = 0usize;
        for row in plan {
            let sum: f32 = row.iter().sum();
            if sum <= 0.0 {
                continue;
            }
            for &x in row {
                let p = (x / sum) as f64;
                if p > 1e-12 {
                    h -= p * p.ln();
                }
            }
            cells += 1;
        }
        if cells == 0 { 0.0 } else { h / cells as f64 / (k as f64).ln().max(1e-9) }
    };

    // Anneal the regularisation rather than the iteration count. More iterations make Sinkhorn SATISFY the
    // marginals, which spreads mass and RAISES entropy — measured here rising 0.17 to 0.28, the opposite of
    // convergence. Sharpening comes from lowering eps: as eps falls the plan approaches a hard assignment.
    // Each step is run to convergence so what the viewer sees is the effect of eps alone.
    let schedule: Vec<f32> = vec![0.50, 0.34, 0.22, 0.15, 0.10, 0.065, 0.042, 0.028];
    let mut steps: Vec<serde_json::Value> = Vec::new();
    let mut final_plan: Vec<Vec<f32>> = Vec::new();
    let mut final_plans: Vec<Vec<Vec<f32>>> = Vec::new();
    for &e in &schedule {
        let kmat: Vec<Vec<f32>> = cost.iter().map(|row| row.iter().map(|v| (-v / e).exp()).collect()).collect();
        let _ = &kmat;
        let (plan, c) = ot::sinkhorn(&cost, e, 160);
        steps.push(serde_json::json!({ "epsilon": e, "entropy": entropy(&plan), "cost": c }));
        final_plans.push(plan.clone());
        final_plan = plan;
    }
    let _ = eps;

    // label each topic by the term that sends it the most mass
    let topic_labels: Vec<String> = (0..k)
        .map(|j| {
            let mut best = (0usize, -1f32);
            for (i, row) in final_plan.iter().enumerate() {
                if row.get(j).copied().unwrap_or(0.0) > best.1 {
                    best = (i, row[j]);
                }
            }
            names.get(best.0).cloned().unwrap_or_default()
        })
        .collect();

    serde_json::json!({
        "terms": names,
        "topics": topic_labels,
        "steps": steps,
        // row-normalised plans as percentages, one per annealing step, so a viewer can animate the sharpening
        "frames": final_plans.iter().map(|plan| plan.iter().map(|row| {
            let sum: f32 = row.iter().sum::<f32>().max(1e-9);
            row.iter().map(|x| (x / sum * 100.0).round() as i32).collect::<Vec<_>>()
        }).collect::<Vec<_>>()).collect::<Vec<_>>(),
        "plan": final_plan.iter().map(|row| {
            let sum: f32 = row.iter().sum::<f32>().max(1e-9);
            row.iter().map(|x| (x / sum * 100.0).round() as i32).collect::<Vec<_>>()
        }).collect::<Vec<_>>(),
    })
    .to_string()
}

/// The salience step alone: which words carry information about how this corpus divides up.
#[wasm_bindgen]
pub fn salient_terms(docs_text: &str, n_terms: usize) -> String {
    let docs: Vec<String> = docs_text
        .split("\n---")
        .map(|d| d.trim().to_string())
        .filter(|d| !d.is_empty())
        .collect();
    let terms: Vec<serde_json::Value> = crate::emergent::salient(&docs, n_terms)
        .into_iter()
        .map(|(term, idf, df)| serde_json::json!({ "term": term, "idf": idf, "documents": df }))
        .collect();
    serde_json::json!({ "documents": docs.len(), "terms": terms }).to_string()
}

/// Discover facets from PROSE, with no field markers and no model: TF-IDF salience, co-occurrence
/// clustering, then a TF-IDF label per cluster. Each cluster is then judged by the real MECE gate, so the
/// page shows a proposal and an independent decision rather than one blurred step.
#[wasm_bindgen]
pub fn discover_prose(docs_text: &str, n_terms: usize, n_clusters: usize, gain_threshold: f64) -> String {
    let docs: Vec<String> = docs_text
        .split("\n---")
        .map(|d| d.trim().to_string())
        .filter(|d| !d.is_empty())
        .collect();

    let clusters = crate::emergent::discover(&docs, n_terms, n_clusters);

    // Start from an empty vocabulary and let each cluster face the gate in turn. Adopting as we go is what
    // makes the test meaningful: a later cluster is measured against what has already been accepted, so a
    // near-duplicate of an earlier facet is rejected as redundant.
    let mut spec = crate::vocabulary::VocabularySpace {
        version: 1,
        corpus: "pasted".into(),
        entity_facets: Vec::new(),
        relation_facets: Vec::new(),
        gazetteer: Vec::new(),
        metrics: None,
    };

    let mut events: Vec<serde_json::Value> = Vec::new();
    for (round, c) in clusters.iter().enumerate() {
        let cand = crate::grow::Candidate {
            name: c.label.clone(),
            parent: None,
            description: format!("terms co-occurring with '{}'", c.label),
            examples: c.terms.clone(),
            worth_adding: true,
        };
        let scored = crate::grow::score_candidate_full(&spec, &docs, &cand);
        let (score, dup) = match scored {
            Some((s, d)) => (Some(s), d),
            None => (None, None),
        };
        let ev = crate::grow::gate_full(&spec, &cand, score.as_ref(), dup, gain_threshold, round);
        let accepted = ev.kept;
        let _ = &score;
        if accepted {
            crate::grow::adopt(&mut spec, &cand);
        }
        events.push(serde_json::json!({
            "label": c.label,
            "terms": c.terms,
            "coverage": c.coverage,
            "cohesion": c.cohesion,
            "accepted": accepted,
            "reason": ev.reason,
            "gain": ev.gain,
            "maxcos": ev.maxcos,
            "nearest": ev.nearest,
            "threshold": ev.threshold,
        }));
    }

    serde_json::json!({
        "documents": docs.len(),
        "clusters": events,
        "accepted": spec.entity_facets.iter().map(|f| f.name.clone()).collect::<Vec<_>>(),
        "gain_threshold": gain_threshold,
    })
    .to_string()
}

/// Run the engine against fixed inputs with known-correct answers, so a page can show that the real logic is
/// loaded and behaving rather than merely claiming it.
///
/// These exercise the path this demo actually runs. An earlier version asserted things about the
/// labelled-field parser, which the demo stopped using when it moved to prose — a passing check for code
/// nothing calls is worse than no check, because it reads as evidence.
#[wasm_bindgen]
pub fn self_test() -> String {
    let mut checks: Vec<serde_json::Value> = Vec::new();
    let mut all_ok = true;
    let mut check = |name: &str, ok: bool, detail: String| {
        if !ok {
            all_ok = false;
        }
        checks.push(serde_json::json!({ "name": name, "ok": ok, "detail": detail }));
    };

    let docs: Vec<String> = [
        "A survey in Sootopolis City recorded Aggron at an elevation of 1082 m",
        "Another survey in Sootopolis City measured 28 degrees at the same site",
        "Morty Shade defeated Wallace Gale during the Indigo Invitational",
    ]
    .iter()
    .map(|s| s.to_string())
    .collect();

    // whole mentions survive; their parts are not promoted on their own
    let gaz = crate::emergent::mine_gazetteer(&docs, 2);
    check(
        "whole entities",
        gaz.contains(&"Sootopolis City".to_string()) && !gaz.contains(&"City".to_string()),
        format!("{} kept intact, no fragments", gaz.len()),
    );

    // quantities keep their unit, and km is not read as m
    let q = crate::emergent::quantity_spans("at 1082 m and 500 km and 7 minutes");
    let fields: Vec<&str> = q.iter().map(|(_, _, f)| f.as_str()).collect();
    check(
        "quantities + units",
        fields.contains(&"length_m") && fields.contains(&"length_km") && fields.contains(&"minutes"),
        fields.join(", "),
    );

    // relation direction follows word order and reverses when the sentence does
    let mentions: Vec<String> = vec!["Morty Shade".into(), "Wallace Gale".into()];
    let fwd = crate::emergent::relation_spans("Morty Shade defeated Wallace Gale", &mentions);
    let rev = crate::emergent::relation_spans("Wallace Gale defeated Morty Shade", &mentions);
    check(
        "relation direction",
        fwd.first().map(|r| r.actor == "Morty Shade").unwrap_or(false)
            && rev.first().map(|r| r.actor == "Wallace Gale").unwrap_or(false),
        "actor and target swap with word order".into(),
    );

    // dates bucket, and a measurement is not mistaken for a year
    let t = crate::emergent::temporal_spans("held in Q3 2026, at 2369 m");
    let toks: Vec<&str> = t.iter().map(|(_, _, x)| x.as_str()).collect();
    check(
        "date buckets",
        toks.contains(&"time/2026/q3") && !toks.contains(&"time/2369"),
        toks.join(", "),
    );

    // the linter refuses a dimension the corpus does not have
    let linter = Linter::from_tokens(vec!["entity/sootopolis-city".to_string(), "quantity/temp_c".to_string()]);
    check(
        "refuses the unknown",
        !linter.lint("gene/brca1").ok && linter.lint("entity/sootopolis-city").ok,
        "unknown refused, known accepted".into(),
    );

    serde_json::json!({ "ok": all_ok, "checks": checks, "version": version() }).to_string()
}

#[wasm_bindgen]
pub struct Paper {
    corpus: crate::db::Corpus,
    facets: Vec<(String, Vec<String>)>,
    /// multi-word mentions mined from the corpus, longest first
    gazetteer: Vec<String>,
    documents: Vec<String>,
    doc_count: usize,
}

#[wasm_bindgen]
impl Paper {
    /// Discover the vocabulary from prose, then project every document into the index.
    ///
    /// This delegates to [`crate::SteelDb`] rather than projecting here. It used to do its own: the same six
    /// dimensions, written a second time, which is how the two drifted. The browser copy emitted
    /// argument-bound relation tokens the library did not, matched category terms case-sensitively where the
    /// library matched case-insensitively, invented numeric field names (`elevation_m` for what the library
    /// called `length_m`), and recognised epistemic cues the library missed. Every one of those was a silent
    /// difference between what this page demonstrates and what the crate does — so there is now one projection,
    /// and the page cannot describe behaviour the library does not have.
    #[wasm_bindgen(constructor)]
    pub fn new(docs_text: &str, n_terms: usize, n_clusters: usize, gain_threshold: f64) -> Paper {
        let docs: Vec<String> = docs_text
            .split("\n---")
            .map(|d| d.trim().to_string())
            .filter(|d| !d.is_empty())
            .collect();

        let opts = crate::api::Options {
            terms: n_terms,
            categories: n_clusters,
            min_gain: gain_threshold,
        };
        let gazetteer = crate::emergent::mine_gazetteer(&docs, 2);

        // An empty paste is a user action, not a bug. In wasm a panic aborts the module and every later cell
        // fails with no explanation, so this returns an empty Paper and lets the cells report nothing found.
        match crate::SteelDb::ingest_with(docs.clone(), opts) {
            Ok(db) => {
                let facets: Vec<(String, Vec<String>)> =
                    db.categories().into_iter().map(|c| (c.name.to_string(), c.words.to_vec())).collect();
                let doc_count = docs.len();
                Paper { corpus: db.into_corpus(), facets, gazetteer, doc_count, documents: docs }
            }
            Err(_) => Paper {
                corpus: crate::db::Corpus::new_incremental(
                    "documents",
                    vec!["document".into()],
                    crate::projector::CorpusKind::Text,
                ),
                facets: Vec::new(),
                gazetteer,
                doc_count: 0,
                documents: Vec::new(),
            },
        }
    }

    /// Vocabulary + index summary: what was discovered and what got stored.
    pub fn summary(&self) -> String {
        let st = self.corpus.stats();
        serde_json::json!({
            "documents": self.doc_count,
            "situations": st.situations,
            "tokens": st.vocab,
            "facets": self.facets.iter().map(|(f, t)| serde_json::json!({
                "name": f, "terms": t, "wildcard": format!("{f}/*"),
            })).collect::<Vec<_>>(),
            "numeric_fields": st.numeric_fields,
        })
        .to_string()
    }

    /// The document-by-token incidence matrix — the picture of what a bitmap index actually is.
    pub fn incidence(&self, limit_tokens: usize) -> String {
        let mut rows: Vec<serde_json::Value> = Vec::new();
        for (facet, _) in &self.facets {
            for (tok, _n) in self.corpus.facet_tokens(facet, limit_tokens) {
                let out = self.corpus.query(&tok, usize::MAX);
                let docs: Vec<u32> = out.hits.iter().map(|h| h.sid).collect();
                rows.push(serde_json::json!({ "token": tok, "facet": facet, "documents": docs }));
            }
        }
        serde_json::json!({ "total_documents": self.doc_count, "rows": rows }).to_string()
    }

    /// Run an IKL s-expression: the compiled bitmap program.
    pub fn query(&self, ikl: &str) -> String {
        let lint = self.corpus.linter().lint(ikl);
        if !lint.ok {
            return serde_json::json!({
                "ok": false,
                "errors": lint.errors.iter().map(|e| e.message.clone()).collect::<Vec<_>>(),
            })
            .to_string();
        }
        let out = self.corpus.query(ikl, 200);
        serde_json::json!({
            "ok": true,
            "count": out.count,
            "documents": out.hits.iter().map(|h| h.sid).collect::<Vec<_>>(),
            "preview": out.hits.iter().take(3).map(|h| h.cells.join(" ")).collect::<Vec<_>>(),
        })
        .to_string()
    }

    /// Belief and plausibility for a token, from the polarity layer (§4).
    pub fn belief(&self, token: &str) -> String {
        let (bel, pl) = self.corpus.belief_interval(token);
        serde_json::json!({ "token": token, "belief": bel, "plausibility": pl,
                            "ignorance": (pl - bel).max(0.0) })
            .to_string()
    }

    /// Tokens that co-occur with this one — the neighbourhood an s-path walks.
    pub fn cooccurs(&self, token: &str, k: usize) -> String {
        self.corpus.cooccurs(token, k).to_string()
    }

    /// Shortest connection between two tokens through shared documents (§3).
    pub fn s_path(&self, a: &str, b: &str, s: usize) -> String {
        self.corpus.s_path(a, b, s).to_string()
    }

    /// Annotate every document for a displaCy-style viewer: the text split into ordered chunks, where a
    /// chunk carrying a `facet` is a term the vocabulary actually matched.
    ///
    /// Returns segments rather than offsets on purpose. Rust counts bytes and JavaScript indexes UTF-16 code
    /// units, so handing offsets across would render shifted text on any document containing an accented
    /// character — and these documents contain "Pokémon".
    pub fn annotate(&self) -> String {
        let docs: Vec<serde_json::Value> = self
            .documents
            .iter()
            .map(|doc| {
                // Three layers, most specific first: quantities, then whole multi-word mentions, then the
                // single facet words. Sorting by start and then by DESCENDING length means a longer, more
                // specific match always claims the span, so "Sootopolis City" is never split into two.
                let mut hits: Vec<(usize, usize, String)> = Vec::new();
                for (s, e, field) in crate::emergent::quantity_spans(doc) {
                    hits.push((s, e, format!("quantity:{field}")));
                }
                for (s, e, _) in crate::emergent::temporal_spans(doc) {
                    hits.push((s, e, "time".to_string()));
                }
                for mention in &self.gazetteer {
                    for (s, e) in crate::emergent::word_spans(doc, mention) {
                        hits.push((s, e, "entity".to_string()));
                    }
                }
                for (facet, terms) in &self.facets {
                    for term in terms {
                        for (s, e) in crate::emergent::word_spans(doc, term) {
                            hits.push((s, e, facet.clone()));
                        }
                    }
                }
                hits.sort_by(|a, b| a.0.cmp(&b.0).then((b.1 - b.0).cmp(&(a.1 - a.0))));

                let mut segments: Vec<serde_json::Value> = Vec::new();
                let mut cursor = 0usize;
                for (s, e, facet) in hits {
                    if s < cursor || e > doc.len() {
                        continue; // overlapping match already covered
                    }
                    if s > cursor {
                        segments.push(serde_json::json!({ "text": &doc[cursor..s] }));
                    }
                    segments.push(serde_json::json!({ "text": &doc[s..e], "facet": facet }));
                    cursor = e;
                }
                if cursor < doc.len() {
                    segments.push(serde_json::json!({ "text": &doc[cursor..] }));
                }
                serde_json::json!({ "segments": segments })
            })
            .collect();

        let mut legend: Vec<String> = vec!["entity".into(), "time".into(), "quantity".into()];
        legend.extend(self.facets.iter().map(|(f, _)| f.clone()));
        serde_json::json!({
            "documents": docs,
            "facets": legend,
            "gazetteer": self.gazetteer.iter().take(20).collect::<Vec<_>>(),
            "gazetteer_size": self.gazetteer.len(),
        })
        .to_string()
    }

    /// The Vocabulary Space **V**, grouped into the paper's six dimensions, each token carrying the set of
    /// situations whose bit is set.
    ///
    /// This is the picture of what a bitmap index holds: one row per vocabulary term, one column per
    /// situation. Grouping the rows by dimension shows why the taxonomy is uniform — an agent combines
    /// `entity/...` and `time/...` and `state/...` with the same three operators, without learning a schema.
    ///
    /// Dimensions the in-browser pipeline cannot populate are reported as empty with a stated reason rather
    /// than quietly omitted: relational roles need the span tagger, and latent motifs need SPLADE. Showing a
    /// dimension as present when nothing fills it would misrepresent what is running.
    pub fn dimensions(&self) -> String {
        let row = |token: &str| -> serde_json::Value {
            let out = self.corpus.query(token, usize::MAX);
            serde_json::json!({
                "token": token,
                "situations": out.hits.iter().map(|h| h.sid).collect::<Vec<_>>(),
                "count": out.count,
            })
        };
        let collect = |prefixes: &[&str], limit: usize| -> Vec<serde_json::Value> {
            let mut rows: Vec<serde_json::Value> = Vec::new();
            for p in prefixes {
                for (tok, _) in self.corpus.facet_tokens(p, limit) {
                    rows.push(row(&tok));
                }
            }
            rows
        };

        // the discovered category facets are entity-like: concrete kinds the corpus talks about
        let mut entity_prefixes: Vec<&str> = vec!["entity"];
        let facet_names: Vec<String> = self.facets.iter().map(|(f, _)| f.clone()).collect();
        for f in &facet_names {
            entity_prefixes.push(f.as_str());
        }

        let dims = serde_json::json!([
            {
                "n": "2.1.1", "name": "Entities & artifacts",
                "example": "org/toyota · artifact/battery_cell",
                "note": "concrete nouns: the things the corpus is about",
                "rows": collect(&entity_prefixes, 6),
                "source": "mined gazetteer + discovered categories",
            },
            {
                "n": "2.1.2", "name": "Relational roles",
                "example": "rel/supplies/+ · rel/supplies/-",
                "note": "who acted on what: + marks the actor, - the target, so direction is explicit",
                "rows": collect(&["rel"], 8),
                "source": "pattern extraction: mention, relation verb, mention — direction from word order",
            },
            {
                "n": "2.1.3", "name": "Spatial & temporal loci",
                "example": "time/2026/q3 · geo/apac/brisbane",
                "note": "when and where, bucketed so a date becomes a set that can be intersected",
                "rows": collect(&["time", "geo"], 8),
                "source": "extracted deterministically from the text",
            },
            {
                "n": "2.1.4", "name": "Quantities & tolerances",
                "example": "qty/temp/celsius/20_to_30",
                "note": "measurements quantised into range buckets, so a comparison becomes a set match",
                "rows": collect(&["quantity"], 8),
                "source": "number + unit extraction",
            },
            {
                "n": "2.1.5", "name": "Epistemic modifiers",
                "example": "state/negated · trend/cost/decrease",
                "note": "whether the corpus asserts, hedges or denies the fact",
                "rows": collect(&["state", "trend"], 6),
                "source": "cue detection over the text",
            },
            {
                "n": "2.1.6", "name": "Latent motifs",
                "example": "motif/hazard/thermal",
                "note": "implicit themes with no shared keyword, from sparse neural activations",
                "rows": collect(&["motif"], 6),
                "source": "Sinkhorn optimal transport over the co-occurrence geometry",
            },
        ]);

        serde_json::json!({
            "dimensions": dims,
            "total_situations": self.doc_count,
            "total_tokens": self.corpus.stats().vocab,
        })
        .to_string()
    }

    /// The reified hyperedge for one document: its situation id and every tag it asserts, grouped by the
    /// dimension the tag belongs to.
    ///
    /// This is the output of annotation, made visible. The highlighted spans in a document are not the end
    /// product — they are evidence for a single fact that binds all of them at once, and this returns that
    /// fact. Grouping by dimension shows that one situation carries entities, roles, time, quantities and
    /// epistemic state together, which is exactly what a binary edge cannot represent.
    pub fn situation(&self, index: usize) -> String {
        let i = index.min(self.doc_count.saturating_sub(1));
        let Some(doc) = self.documents.get(i) else {
            return serde_json::json!({ "error": "no such situation" }).to_string();
        };

        // Recover the tags for this situation by asking the index which of its tokens contain this sid.
        // Reading them back out of the index rather than recomputing them means the panel shows what was
        // actually stored, not a second opinion about what should have been.
        let mut groups: std::collections::BTreeMap<&str, Vec<String>> = std::collections::BTreeMap::new();
        let dim_of = |tok: &str| -> &'static str {
            let stem = tok.split('/').next().unwrap_or("");
            match stem {
                "entity" => "entities",
                "rel" => "roles",
                "time" | "geo" => "loci",
                "quantity" => "quantities",
                "state" | "trend" => "epistemic",
                "motif" => "motifs",
                _ => "categories",
            }
        };

        let mut prefixes: Vec<String> =
            ["entity", "rel", "time", "geo", "quantity", "state", "trend", "motif"]
                .iter()
                .map(|s| s.to_string())
                .collect();
        prefixes.extend(self.facets.iter().map(|(f, _)| f.clone()));

        for p in &prefixes {
            for (tok, _) in self.corpus.facet_tokens(p, 200) {
                let out = self.corpus.query(&tok, usize::MAX);
                if out.hits.iter().any(|h| h.sid as usize == i) {
                    groups.entry(dim_of(&tok)).or_default().push(tok);
                }
            }
        }

        // the relations again, so the panel can show who acted on whom rather than only the bare role tags
        let rels: Vec<serde_json::Value> = crate::emergent::relation_spans(doc, &self.gazetteer)
            .into_iter()
            .map(|r| serde_json::json!({ "verb": r.verb, "actor": r.actor, "target": r.target }))
            .collect();

        let total: usize = groups.values().map(|v| v.len()).sum();
        serde_json::json!({
            "sid": i,
            "of": self.doc_count,
            "groups": groups,
            "relations": rels,
            "total_tags": total,
        })
        .to_string()
    }

    /// Plan a free-text question into slots, then run the whole chain.
    ///
    /// The planner here is deliberately dumb and deterministic: it finds negation cues and assigns the
    /// vocabulary terms it can link to either the include or the exclude slot. A tuned needle3 does this job
    /// properly — it reads intent rather than keywords — but it cannot run in a browser, so a page must either
    /// ship recorded model output or plan locally. This is the local option, and it is labelled as such
    /// wherever it appears.
    ///
    /// The important property is that swapping the planner changes nothing downstream. Expansion, type
    /// checking, compilation and traversal are identical whichever produced the slots, because the planner's
    /// only output is which constraints apply.
    pub fn plan_text(&self, question: &str, s_threshold: usize) -> String {
        const NEG_CUES: &[&str] = &["not", "without", "excluding", "except", "exclude", "no", "never"];
        let lower = question.to_lowercase();
        let words: Vec<&str> = lower.split(|c: char| !c.is_alphanumeric() && c != '-').filter(|w| !w.is_empty()).collect();

        // vocabulary the question may refer to: facet names, plus the epistemic states
        let mut include: Vec<String> = Vec::new();
        let mut exclude: Vec<String> = Vec::new();
        let mut categories: Vec<String> = Vec::new();

        // a cue puts the NEXT few recognised terms into exclude, until the clause ends
        let mut negating_for = 0usize;
        for w in &words {
            if NEG_CUES.contains(w) {
                // a cue governs the rest of its clause, approximated as the next three terms
                negating_for = 3;
                continue;
            }
            let facet = self.facets.iter().find(|(f, _)| f == w).map(|(f, _)| f.clone());
            // Emit the qualified token, not the bare word. Passing "negated" on for `compose` to entity-link
            // threw away something the planner already knew, and the lookup then failed for a reason unrelated
            // to the question: `state/negated` appears in enough documents to be treated as a common tag and
            // excluded from mention linking, so "city documents that are not negated" refused outright.
            let state = match *w {
                "negated" | "denied" | "refuted" => Some("state/negated".to_string()),
                "hedged" | "provisional" | "uncertain" => Some("state/hedged".to_string()),
                "asserted" | "stated" | "confirmed" => Some("state/asserted".to_string()),
                _ => None,
            };
            if let Some(st) = state {
                if negating_for > 0 {
                    exclude.push(st);
                    negating_for -= 1;
                } else {
                    include.push(st);
                }
                continue;
            }
            if let Some(f) = facet {
                if negating_for > 0 {
                    exclude.push(f);
                    negating_for -= 1;
                } else {
                    categories.push(f);
                }
                continue;
            }
            // an unrecognised word is not a constraint; it also does not consume the cue
            if negating_for > 0 && self.corpus.entity_link(w).is_empty() {
                continue;
            }
            if !self.corpus.entity_link(w).is_empty() {
                if negating_for > 0 {
                    exclude.push(w.to_string());
                    negating_for -= 1;
                } else {
                    include.push(w.to_string());
                }
            }
        }

        let plan = serde_json::json!({
            "include": include, "exclude": exclude, "any_of": Vec::<String>::new(), "categories": categories,
        });
        if include.is_empty() && exclude.is_empty() && categories.is_empty() {
            return serde_json::json!({
                "ok": false,
                "stage": "plan",
                "plan": plan,
                "reason": "nothing in the question matched this corpus vocabulary",
                "available": self.facets.iter().map(|(f, _)| f.clone()).collect::<Vec<_>>(),
            })
            .to_string();
        }

        let mut result: serde_json::Value = serde_json::from_str(&self.plan_and_traverse(
            &serde_json::to_string(&include).unwrap_or_default(),
            &serde_json::to_string(&exclude).unwrap_or_default(),
            "[]",
            &serde_json::to_string(&categories).unwrap_or_default(),
            s_threshold,
        ))
        .unwrap_or_default();
        result["plan"] = plan;
        result["question"] = serde_json::json!(question);
        result.to_string()
    }

    /// The full execution order: a plan of slots becomes an expression, the expression is type-checked and
    /// compiled to a row filter, and only then do the higher-order tools run — inside the filtered set.
    ///
    /// This is the paper's predicate pushdown, and the order is a requirement rather than a preference. Running
    /// traversal first means walking a structure whose size is the whole corpus; running it after the filter
    /// means walking whatever survived. The planner never touches bitmaps and never decides what is
    /// reachable — it only proposes which constraints apply.
    ///
    /// Returns each stage separately so a caller can show the row count collapsing before any traversal
    /// happens, and the neighbourhood computed only within the survivors.
    pub fn plan_and_traverse(
        &self,
        include: &str,
        exclude: &str,
        any_of: &str,
        categories: &str,
        s_threshold: usize,
    ) -> String {
        // stage 1-3: link the slots, compose the expression, lint it, run it
        let composed: serde_json::Value =
            serde_json::from_str(&self.compose(include, exclude, any_of, categories)).unwrap_or_default();
        if !composed["ok"].as_bool().unwrap_or(false) {
            return serde_json::json!({
                "ok": false,
                "stage": "check",
                "reason": composed["reason"].clone(),
                "unresolved": composed["unresolved"].clone(),
                "available": composed["available"].clone(),
            })
            .to_string();
        }
        let ikl = composed["ikl"].as_str().unwrap_or("").to_string();

        // stage 4: the surviving rows
        let out = self.corpus.query(&ikl, usize::MAX);
        let survivors: std::collections::BTreeSet<usize> =
            out.hits.iter().map(|h| h.sid as usize).collect();

        // stage 5: higher-order work, restricted to the survivors. Tags are collected only from those rows,
        // so the traversal cannot leave the filtered set even in principle.
        let mut tags_of: std::collections::BTreeMap<usize, std::collections::BTreeSet<String>> =
            std::collections::BTreeMap::new();
        let mut prefixes: Vec<String> =
            ["entity", "rel", "time", "geo", "quantity", "state", "motif"].iter().map(|x| x.to_string()).collect();
        prefixes.extend(self.facets.iter().map(|(f, _)| f.clone()));
        for p in &prefixes {
            for (tok, _) in self.corpus.facet_tokens(p, 300) {
                for h in self.corpus.query(&tok, usize::MAX).hits {
                    let sid = h.sid as usize;
                    if survivors.contains(&sid) {
                        tags_of.entry(sid).or_default().insert(tok.clone());
                    }
                }
            }
        }

        let ids: Vec<usize> = survivors.iter().copied().collect();
        let mut edges: Vec<serde_json::Value> = Vec::new();
        for i in 0..ids.len() {
            for j in (i + 1)..ids.len() {
                let (a, b) = (ids[i], ids[j]);
                let empty = std::collections::BTreeSet::new();
                let ta = tags_of.get(&a).unwrap_or(&empty);
                let tb = tags_of.get(&b).unwrap_or(&empty);
                let shared: Vec<String> = ta.intersection(tb).cloned().collect();
                if shared.len() >= s_threshold.max(1) {
                    edges.push(serde_json::json!({
                        "a": a, "b": b, "shared": shared.len(),
                        "via": shared.iter().take(3).collect::<Vec<_>>(),
                    }));
                }
            }
        }

        serde_json::json!({
            "ok": true,
            "ikl": ikl,
            "total_situations": self.doc_count,
            "survivors": ids,
            "survivor_count": ids.len(),
            "s": s_threshold.max(1),
            "edges": edges,
            // the comparison that justifies the ordering
            "pairs_if_unfiltered": self.doc_count * (self.doc_count.saturating_sub(1)) / 2,
            "pairs_examined": ids.len() * (ids.len().saturating_sub(1)) / 2,
        })
        .to_string()
    }

    /// Both topologies of the incidence matrix, swept over the overlap threshold `s`.
    ///
    /// The index is an incidence matrix: rows are tags, columns are situations. That single structure can be
    /// read two ways, and both are useful:
    ///
    /// * **primal** — situations are nodes, joined when they share at least `s` tags. "Which events are
    ///   related?"
    /// * **dual** — tags are nodes, joined when they co-occur in at least `s` situations. "Which concepts
    ///   belong together?"
    ///
    /// Nothing is rebuilt to switch between them; it is the same matrix transposed, which is why a hypergraph
    /// engine gets the dual for free where a pairwise graph would need a second index.
    ///
    /// Sweeping `s` is the **s-filtration**. At `s = 1` a single shared tag is enough and almost everything is
    /// connected, which is the regime where naive graph walks drift. Raising `s` demands more agreement per
    /// step and the graph thins toward only the genuinely related. Reporting connected components alongside
    /// edges shows structure appearing as the noise is removed.
    pub fn topology(&self, max_s: usize) -> String {
        // tags per situation (primal rows) and situations per tag (dual rows)
        let mut tags_of: Vec<std::collections::BTreeSet<String>> =
            vec![std::collections::BTreeSet::new(); self.doc_count];
        let mut sits_of: std::collections::BTreeMap<String, std::collections::BTreeSet<usize>> =
            std::collections::BTreeMap::new();

        let mut prefixes: Vec<String> =
            ["entity", "rel", "time", "geo", "quantity", "state", "motif"].iter().map(|s| s.to_string()).collect();
        prefixes.extend(self.facets.iter().map(|(f, _)| f.clone()));
        for p in &prefixes {
            for (tok, _) in self.corpus.facet_tokens(p, 300) {
                let out = self.corpus.query(&tok, usize::MAX);
                let sids: std::collections::BTreeSet<usize> =
                    out.hits.iter().map(|h| h.sid as usize).collect();
                for &i in &sids {
                    if i < self.doc_count {
                        tags_of[i].insert(tok.clone());
                    }
                }
                sits_of.insert(tok, sids);
            }
        }

        // count edges and connected components of a graph given an adjacency predicate
        fn components(n: usize, edges: &[(usize, usize)]) -> usize {
            let mut parent: Vec<usize> = (0..n).collect();
            fn find(p: &mut Vec<usize>, x: usize) -> usize {
                if p[x] != x {
                    let r = find(p, p[x]);
                    p[x] = r;
                }
                p[x]
            }
            for &(a, b) in edges {
                let (ra, rb) = (find(&mut parent, a), find(&mut parent, b));
                if ra != rb {
                    parent[ra] = rb;
                }
            }
            let mut seen = std::collections::BTreeSet::new();
            for i in 0..n {
                let r = find(&mut parent, i);
                seen.insert(r);
            }
            seen.len()
        }

        let tag_names: Vec<String> = sits_of.keys().cloned().collect();
        let mut levels: Vec<serde_json::Value> = Vec::new();

        for s_thr in 1..=max_s.clamp(1, 8) {
            // primal: situations sharing >= s tags
            let mut p_edges: Vec<(usize, usize)> = Vec::new();
            for i in 0..self.doc_count {
                for j in (i + 1)..self.doc_count {
                    if tags_of[i].intersection(&tags_of[j]).count() >= s_thr {
                        p_edges.push((i, j));
                    }
                }
            }
            // dual: tags co-occurring in >= s situations
            let mut d_edges: Vec<(usize, usize)> = Vec::new();
            for a in 0..tag_names.len() {
                for b in (a + 1)..tag_names.len() {
                    let (sa, sb) = (&sits_of[&tag_names[a]], &sits_of[&tag_names[b]]);
                    if sa.intersection(sb).count() >= s_thr {
                        d_edges.push((a, b));
                    }
                }
            }

            levels.push(serde_json::json!({
                "s": s_thr,
                "primal": {
                    "nodes": self.doc_count,
                    "edges": p_edges.len(),
                    "components": components(self.doc_count, &p_edges),
                    // a small sample so a viewer can draw the graph at this level
                    "sample": p_edges.iter().take(120).map(|(a, b)| vec![a, b]).collect::<Vec<_>>(),
                },
                "dual": {
                    "nodes": tag_names.len(),
                    "edges": d_edges.len(),
                    "components": components(tag_names.len(), &d_edges),
                    "sample": d_edges.iter().take(120).map(|(a, b)| vec![a, b]).collect::<Vec<_>>(),
                },
            }));
        }

        serde_json::json!({
            "situations": self.doc_count,
            "tags": tag_names.len(),
            "tag_names": tag_names,
            "levels": levels,
        })
        .to_string()
    }

    /// Link a free-text span to real vocabulary tokens.
    ///
    /// This is the join that makes a small extraction model useful. A 121M tool-calling model grounds its
    /// arguments by copying spans out of the question — it returns "sinnoh region", not `sinnoh/region`.
    /// Mapping a span onto the vocabulary is a deterministic lookup, so the engine does it rather than asking
    /// the model to memorise the token set.
    pub fn link(&self, text: &str) -> String {
        serde_json::json!(self.corpus.entity_link(text)).to_string()
    }

    /// Compose an s-expression from extracted slots, then lint and run it.
    ///
    /// The model supplies intent as slots; the ALGEBRA is built here, in code. That split is the point of the
    /// paper: a language model is unreliable at nesting brackets correctly but good at spotting which phrase
    /// is a requirement and which is an exclusion, so composition stays deterministic and the result is
    /// auditable.
    pub fn compose(&self, include: &str, exclude: &str, any_of: &str, categories: &str) -> String {
        let parse = |s: &str| -> Vec<String> {
            serde_json::from_str::<Vec<String>>(s).unwrap_or_default()
        };
        // every span is linked to real tokens; a span that links to nothing is reported, not guessed at
        let mut parts: Vec<String> = Vec::new();
        let mut unresolved: Vec<String> = Vec::new();
        let mut resolve = |spans: Vec<String>, out: &mut Vec<String>| {
            for span in spans {
                // A span that is already a qualified atom is a constraint the planner resolved itself. Asking
                // the mention linker about it would be asking the gazetteer to recognise a token name. The
                // linter is the right authority for "is this a valid atom here", and it is the same check the
                // query itself will face.
                if span.contains('/') && self.corpus.linter().lint(&span).ok {
                    out.push(span);
                    continue;
                }
                let linked: Vec<String> = self.corpus.entity_link(&span);
                if linked.is_empty() {
                    unresolved.push(span);
                } else {
                    out.extend(linked);
                }
            }
        };

        let (mut inc, mut exc, mut anyv) = (Vec::new(), Vec::new(), Vec::new());
        resolve(parse(include), &mut inc);
        resolve(parse(exclude), &mut exc);
        resolve(parse(any_of), &mut anyv);
        for c in parse(categories) {
            let name = c.split('/').next().unwrap_or(&c).trim().to_lowercase();
            if self.facets.iter().any(|(f, _)| *f == name) {
                parts.push(format!("{name}/*"));
            } else {
                unresolved.push(c);
            }
        }

        parts.extend(inc);
        if !anyv.is_empty() {
            parts.push(format!("(or {})", anyv.join(" ")));
        }
        for e in &exc {
            parts.push(format!("(not {e})"));
        }

        if parts.is_empty() {
            return serde_json::json!({
                "ok": false,
                "ikl": null,
                "unresolved": unresolved,
                "reason": "nothing in the question could be linked to this corpus",
                "available": self.facets.iter().map(|(f, _)| f.clone()).collect::<Vec<_>>(),
            })
            .to_string();
        }

        // ANY unlinkable slot must refuse. The query is a conjunction of constraints, so dropping one -
        // positive or negative - removes a filter and returns MORE documents than were asked for. My first
        // version only guarded exclusions, on the reasoning that a missing positive term merely narrows the
        // result; that was simply wrong, and a test showed it: dropping the unlinked term `species` turned
        // "species and not negated" into "not negated", widening 8 documents to 19. Silently answering a
        // weaker question than the one asked is the failure this whole system exists to prevent.
        if !unresolved.is_empty() {
            return serde_json::json!({
                "ok": false,
                "ikl": null,
                "unresolved": unresolved,
                "reason": "some terms could not be linked to this corpus; answering without them would \
                           return more documents than were asked for",
                "available": self.facets.iter().map(|(f, _)| f.clone()).collect::<Vec<_>>(),
            })
            .to_string();
        }

        let ikl = if parts.len() == 1 { parts[0].clone() } else { format!("(and {})", parts.join(" ")) };
        let lint = self.corpus.linter().lint(&ikl);
        let out = if lint.ok { Some(self.corpus.query(&ikl, 5)) } else { None };

        serde_json::json!({
            "ok": lint.ok,
            "ikl": ikl,
            "unresolved": unresolved,
            "errors": lint.errors.iter().map(|e| e.message.clone()).collect::<Vec<_>>(),
            "count": out.as_ref().map(|o| o.count),
            "available": self.facets.iter().map(|(f, _)| f.clone()).collect::<Vec<_>>(),
        })
        .to_string()
    }

    /// Every token in the index, so a page can offer real choices instead of invented ones.
    pub fn tokens(&self) -> String {
        let mut all: Vec<String> = Vec::new();
        for (facet, _) in &self.facets {
            for (tok, _) in self.corpus.facet_tokens(facet, 200) {
                all.push(tok);
            }
        }
        serde_json::json!(all).to_string()
    }
}

/// Version string, so a stale cached `.wasm` is visible rather than silently wrong.
#[wasm_bindgen]
pub fn version() -> String {
    format!("steeldb {} (wasm, step 0)", env!("CARGO_PKG_VERSION"))
}

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

    fn prose() -> String {
        [
            "Morty Shade defeated Wallace Gale at Ecruteak City during the Indigo Invitational in 2025.",
            "Bea Strike defeated Iris Draco at Ecruteak City during the Indigo Invitational in 2025.",
            "Lance Wing defeated Karen Dusk at Ecruteak City during the Indigo Invitational in 2025.",
            "A habitat survey recorded Aggron near Sootopolis City at an elevation of 1082 m.",
            "A habitat survey recorded Salamence near Sootopolis City at an elevation of 2369 m.",
            "A habitat survey recorded Metagross near Sootopolis City at an elevation of 640 m.",
            "Milotic is not permitted in Series 1 play for the 2025 season.",
            "Registeel is not permitted in Series 1 play for the 2025 season.",
        ]
        .join("\n---\n")
    }

    /// The page ships a question of exactly this shape, and it refused. The planner recognised "negated",
    /// then handed `compose` the bare word instead of the `state/negated` it had already resolved, and mention
    /// linking — correctly — would not match a token name.
    #[test]
    fn an_epistemic_state_in_a_question_resolves_without_mention_linking() {
        let p = Paper::new(&prose(), 90, 6, 0.05);
        let facet = p.facets.first().map(|(f, _)| f.clone()).expect("a category should be discovered");

        let r: serde_json::Value =
            serde_json::from_str(&p.plan_text(&format!("{facet} documents that are not negated"), 2)).unwrap();

        assert_eq!(r["ok"], true, "should plan, not refuse: {r}");
        let ikl = r["ikl"].as_str().unwrap_or_default();
        assert!(ikl.contains("(not state/negated)"), "the exclusion must survive into the expression: {ikl}");
        assert!(ikl.contains(&format!("{facet}/*")), "{ikl}");
    }

    /// A question naming nothing in the corpus must still refuse — the fix above must not turn the guard off.
    #[test]
    fn a_question_the_corpus_cannot_answer_is_still_refused() {
        let p = Paper::new(&prose(), 90, 6, 0.05);
        let r: serde_json::Value =
            serde_json::from_str(&p.plan_text("Which documents mention gene brca1", 2)).unwrap();
        assert_eq!(r["ok"], false, "{r}");
    }

    /// `Paper` exists to show the library running, so it must not have a vocabulary of its own.
    #[test]
    fn the_browser_layer_indexes_exactly_what_the_library_does() {
        let docs: Vec<String> = prose().split("\n---").map(|d| d.trim().to_string()).collect();
        let p = Paper::new(&prose(), 90, 6, 0.05);
        let db = crate::SteelDb::ingest(docs).expect("ingest");

        let from_paper: Vec<String> = p.facets.iter().map(|(f, _)| f.clone()).collect();
        let from_lib: Vec<String> = db.categories().iter().map(|c| c.name.to_string()).collect();
        assert_eq!(from_paper, from_lib, "the demo and the library must discover the same categories");

        let p_stats: serde_json::Value = serde_json::from_str(&p.summary()).unwrap();
        assert_eq!(
            p_stats["situations"].as_u64().unwrap_or_default() as usize,
            db.documents().len(),
            "and index the same number of situations"
        );
    }

    /// The transport figure is a teaching device, so its two claims have to hold: the plan sharpens as epsilon
    /// falls, and the sweep ends where the engine actually runs.
    #[test]
    fn the_transport_figure_sharpens_and_ends_at_the_reference_epsilon() {
        // Four well-separated directions in four dimensions, so k=4 is a partition the plan can actually
        // commit to. Two directions with four prototypes cannot sharpen, and the figure would look broken for
        // a reason that has nothing to do with the solver.
        let mut spans = Vec::new();
        for i in 0..40usize {
            let axis = i % 4;
            let mut v = [0.02f32; 4];
            v[axis] = 1.0;
            let n = v.iter().map(|x| x * x).sum::<f32>().sqrt();
            spans.push(serde_json::json!({
                "kind": "ENT",
                "text": format!("term{axis}_{i}"),
                "doc": i % 8,
                "count": 1,
                "vec": v.iter().map(|x| x / n).collect::<Vec<f32>>(),
            }));
        }
        let payload = serde_json::json!({ "dim": 4, "documents": 8, "spans": spans }).to_string();

        let out: serde_json::Value = serde_json::from_str(&codebook(&payload, 4)).unwrap();
        let kind = &out["kinds"][0];
        let frames = kind["frames"].as_array().expect("frames");
        assert!(frames.len() >= 2, "a sweep needs more than one frame");

        // ends exactly on the value discovery uses, or the figure finishes somewhere nothing runs
        let last = frames.last().unwrap()["epsilon"].as_f64().unwrap();
        assert!(
            (last - crate::emergent::DISCOVER_EPS as f64).abs() < 1e-6,
            "sweep ends at {last}, but discovery runs at {}",
            crate::emergent::DISCOVER_EPS
        );

        // sharpening: entropy must fall, never rise
        let entropies: Vec<f64> = frames.iter().map(|f| f["entropy"].as_f64().unwrap_or(0.0)).collect();
        for w in entropies.windows(2) {
            // 1e-6, not 1e-9: at convergence the last two frames differ by float noise
            assert!(w[1] <= w[0] + 1e-6, "entropy rose as epsilon fell: {entropies:?}");
        }
        assert!(
            entropies[0] - entropies[entropies.len() - 1] > 0.01,
            "the sweep barely changed anything: {entropies:?}"
        );

        // and the transport cost falls with it
        let costs: Vec<f64> = frames.iter().map(|f| f["cost"].as_f64().unwrap_or(0.0)).collect();
        for w in costs.windows(2) {
            assert!(w[1] <= w[0] + 1e-6, "transport cost rose: {costs:?}");
        }
    }

    #[test]
    fn a_malformed_span_payload_is_reported_not_panicked() {
        for bad in ["", "{}", "not json", "{\"spans\": 5}", "{\"spans\": [{\"kind\": 1}]}", "[]"] {
            let out = codebook(bad, 4);
            assert!(!out.is_empty(), "no output for {bad:?}");
            let _: serde_json::Value = serde_json::from_str(&out).expect("output must be json");
        }
    }
}