faculties 0.2.0

Shared schemas, helpers, and widgets for triblespace-backed faculties.
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
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
#!/usr/bin/env -S rust-script
//! ```cargo
//! [dependencies]
//! anyhow = "1.0"
//! clap = { version = "4.5.4", features = ["derive", "env"] }
//! ed25519-dalek = "2.1.1"
//! hifitime = "4.2.3"
//! rand_core = "0.6.4"
//! itertools = "0.14"
//! regex = "1"
//! triblespace = "0.34.1"
//! typst = "0.14"
//! typst-syntax = "0.14"
//! comemo = "0.5.1"
//! ```

use anyhow::{Context, Result, bail};
use clap::{CommandFactory, Parser, Subcommand};
use ed25519_dalek::SigningKey;
use hifitime::Epoch;
use itertools::Itertools;
use hifitime::efmt::Formatter;
use hifitime::efmt::consts::ISO8601_DATE;
use rand_core::OsRng;
use std::collections::HashMap;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use triblespace::core::metadata;
use triblespace::core::repo::{Repository, Workspace};
use triblespace::macros::id_hex;
use triblespace::prelude::*;

// ── wiki branch name ──────────────────────────────────────────────────────
const WIKI_BRANCH_NAME: &str = "wiki";

// ── kinds ──────────────────────────────────────────────────────────────────
const KIND_VERSION_ID: Id = id_hex!("1AA0310347EDFED7874E8BFECC6438CF");

// ── tag vocabulary ────────────────────────────────────────────────────────
const TAG_ARCHIVED_ID: Id = id_hex!("480CB6A663C709478A26A8B49F366C3F");

const TAG_SPECS: [(Id, &str); 9] = [
    (KIND_VERSION_ID, "version"),
    (id_hex!("1A7FB717FBFCA81CA3AA7D3D186ACC8F"), "hypothesis"),
    (id_hex!("72CE6B03E39A8AAC37BC0C4015ED54E2"), "critique"),
    (id_hex!("243AE22C5E020F61EBBC8C0481BF05A4"), "finding"),
    (id_hex!("8871C1709EBFCDD2588369003D3964DE"), "paper"),
    (id_hex!("7D58EBA4E1E4A1EF868C3C4A58AEC22E"), "source"),
    (id_hex!("C86BCF906D270403A0A2083BB95B3552"), "concept"),
    (id_hex!("F8172CC4E495817AB52D2920199EF4BD"), "experiment"),
    (TAG_ARCHIVED_ID, "archived"),
];

type TextHandle = Value<valueschemas::Handle<valueschemas::Blake3, blobschemas::LongString>>;

// ── wiki attributes ────────────────────────────────────────────────────────
mod wiki {
    use super::*;
    attributes! {
        "EBFC56D50B748E38A14F5FC768F1B9C1" as fragment: valueschemas::GenId;
        "6DBBE746B7DD7A4793CA098AB882F553" as content: valueschemas::Handle<valueschemas::Blake3, blobschemas::LongString>;
        "78BABEF1792531A2E51A372D96FE5F3E" as title: valueschemas::Handle<valueschemas::Blake3, blobschemas::LongString>;
        "DEAFB7E307DF72389AD95A850F24BAA5" as links_to: valueschemas::GenId;
        // Content-hash reference: `files:<64-char-blake3>` points to file bytes directly.
        "C61CA2F2A70103FD79E97C2F88B854D8" as references_file_content: valueschemas::Handle<valueschemas::Blake3, blobschemas::FileBytes>;
        // File-entity reference: `files:<32-char-id>` points to a file entity with metadata.
        "C98FE0EF9151F196D8F7D816ABBBCC49" as references_file: valueschemas::GenId;
    }
}

// ── CLI ────────────────────────────────────────────────────────────────────
#[derive(Parser)]
#[command(name = "wiki", about = "A TribleSpace knowledge wiki faculty")]
struct Cli {
    /// Path to the pile file
    #[arg(long, env = "PILE")]
    pile: PathBuf,
    /// Branch id (hex). Overrides name-based lookup.
    #[arg(long)]
    branch_id: Option<String>,
    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand)]
enum Command {
    /// Create a new fragment with its first version
    Create {
        /// Fragment title
        title: String,
        /// Content text. Use @path for file input or @- for stdin.
        content: String,
        /// Tags (by name). Unknown tags are minted automatically.
        #[arg(long)]
        tag: Vec<String>,
        /// Allow links to fragment IDs (instead of requiring version IDs)
        #[arg(long)]
        force: bool,
    },
    /// Create a new version of an existing fragment
    Edit {
        /// Fragment or version id (full 32-char hex id)
        id: String,
        /// New content (optional; inherits previous if omitted). Use @path for file input or @- for stdin.
        content: Option<String>,
        /// New title (optional, inherits previous if omitted)
        #[arg(long)]
        title: Option<String>,
        /// Tags (replaces previous version's tags)
        #[arg(long)]
        tag: Vec<String>,
        /// Allow links to fragment IDs (instead of requiring version IDs)
        #[arg(long)]
        force: bool,
    },
    /// Show a fragment (latest version) or a specific version
    Show {
        /// Fragment or version id (full 32-char hex id)
        id: String,
        /// If id is a version, look up its fragment and show the latest version instead
        #[arg(long)]
        latest: bool,
    },
    /// Print raw content without metadata header
    Export {
        /// Fragment or version id (full 32-char hex id)
        id: String,
    },
    /// Compare two versions of a fragment
    Diff {
        /// Fragment id (full 32-char hex id)
        id: String,
        /// First version number (1-based, default: second-to-last)
        #[arg(long)]
        from: Option<usize>,
        /// Second version number (1-based, default: latest)
        #[arg(long)]
        to: Option<usize>,
    },
    /// Soft-delete a fragment (adds #archived tag)
    Archive {
        /// Fragment id (full 32-char hex id)
        id: String,
    },
    /// Restore an archived fragment (removes #archived tag)
    Restore {
        /// Fragment id (full 32-char hex id)
        id: String,
    },
    /// Revert a fragment to a previous version
    Revert {
        /// Fragment id (full 32-char hex id)
        id: String,
        /// Version number to revert to (1-based)
        #[arg(long)]
        to: usize,
    },
    /// Show links from/to a fragment (extracted from `[text](<faculty>:<hex>)` references)
    Links {
        /// Fragment id (full 32-char hex id)
        id: String,
    },
    /// List fragments, optionally filtered by tag and backlink structure
    List {
        /// Filter by tag name
        #[arg(long)]
        tag: Vec<String>,
        /// Only show fragments that have a backlink from a fragment with this tag
        #[arg(long)]
        with_backlink_tag: Vec<String>,
        /// Only show fragments that do NOT have a backlink from a fragment with this tag
        #[arg(long)]
        without_backlink_tag: Vec<String>,
        /// Only show fragments that have a typed backlink (e.g. "reviews", "cites")
        #[arg(long)]
        with_backlink_type: Vec<String>,
        /// Only show fragments that do NOT have a typed backlink of this type
        #[arg(long)]
        without_backlink_type: Vec<String>,
        /// Include archived fragments
        #[arg(long)]
        all: bool,
    },
    /// Show version history for a fragment
    History {
        /// Fragment id (full 32-char hex id)
        id: String,
    },
    /// Tag management: add, remove, list, mint
    Tag {
        #[command(subcommand)]
        command: TagCommand,
    },
    /// Import a file or directory of .typ files into the wiki
    Import {
        /// File or directory path
        path: PathBuf,
        /// Tags to apply to all imported fragments
        #[arg(long)]
        tag: Vec<String>,
    },
    /// Search fragment titles and content (substring, case-insensitive)
    Search {
        /// Search query
        query: String,
        /// Also show matching context lines
        #[arg(long, short = 'c')]
        context: bool,
        /// Include archived fragments
        #[arg(long)]
        all: bool,
    },
    /// Batch export/import all fragments (version-addressed for CAS safety)
    Batch {
        #[command(subcommand)]
        action: BatchAction,
    },
    /// Check all fragments for common issues: invalid typst, broken links,
    /// truncated IDs, missing format tags.
    Check {
        /// Also try compiling typst fragments (in-process, no external tools needed)
        #[arg(long)]
        compile: bool,
    },
    /// Resolve a list of scheme:prefix lines to full-length IDs.
    /// Input: one `wiki:<hex>` or `files:<hex>` per line (from @path or @-).
    /// Output: `old\tnew` mapping for each resolved prefix, one per line.
    /// Ambiguous or unresolvable prefixes are reported on stderr.
    FixTruncated {
        /// File with scheme:prefix lines. Use @path or @- for stdin.
        input: String,
    },
    /// Apply lint transforms (markdown→typst, expand short IDs) to all latest versions.
    /// Also rebuilds the `links_to` index when the stored edges drift from what the
    /// current extract_references regex would parse (e.g. after a lint rule change).
    Lint {
        /// Actually write fixed versions and link updates (default: dry-run)
        #[arg(long)]
        fix: bool,
        /// Only check for issues, don't show diffs (CI mode)
        #[arg(long)]
        check: bool,
    },
}

#[derive(clap::Subcommand)]
enum BatchAction {
    /// Export all fragments (version-addressed .typ files)
    Export {
        /// Output directory
        dir: PathBuf,
    },
    /// Re-import edited fragments (CAS check: aborts if versions changed)
    Import {
        /// Directory containing <version-id>.typ files
        dir: PathBuf,
    },
}

#[derive(Subcommand)]
enum TagCommand {
    /// Add a tag to a fragment (creates a new version)
    Add {
        /// Fragment id (full 32-char hex id)
        id: String,
        /// Tag name
        name: String,
    },
    /// Remove a tag from a fragment (creates a new version)
    Remove {
        /// Fragment id (full 32-char hex id)
        id: String,
        /// Tag name
        name: String,
    },
    /// List all tags with usage counts
    List,
    /// Mint and register a new tag name
    Mint {
        /// Tag name
        name: String,
    },
}

/// Resolve a tag ID to its name, or format as hex if unnamed.
fn tag_name(space: &TribleSet, ws: &mut Workspace<Pile<valueschemas::Blake3>>, id: Id) -> String {
    find!(h: TextHandle, pattern!(space, [{ id @ metadata::name: ?h }]))
        .next()
        .and_then(|h| ws.get::<View<str>, _>(h).ok())
        .map(|v| v.as_ref().to_string())
        .unwrap_or_else(|| format!("{:x}", id))
}

/// Format a list of tag IDs as a bracketed, comma-separated string of names.
fn format_tags(space: &TribleSet, ws: &mut Workspace<Pile<valueschemas::Blake3>>, tags: &[Id]) -> String {
    let names: Vec<String> = tags.iter().map(|t| tag_name(space, ws, *t)).collect();
    if names.is_empty() { String::new() } else { format!(" [{}]", names.join(", ")) }
}

/// Find a tag ID by name, or mint a new one if it doesn't exist.
fn resolve_tag(
    space: &TribleSet,
    ws: &mut Workspace<Pile<valueschemas::Blake3>>,
    name: &str,
    change: &mut TribleSet,
) -> Id {
    // Search all named entities for a matching name.
    for (id, handle) in find!(
        (id: Id, h: TextHandle),
        pattern!(space, [{ ?id @ metadata::name: ?h }])
    ) {
        if let Ok(view) = ws.get::<View<str>, _>(handle) {
            if view.as_ref().eq_ignore_ascii_case(name) {
                return id;
            }
        }
    }
    // Not found — mint a new tag.
    let tag_id = genid();
    let tag_ref = tag_id.id;
    let name_handle = ws.put(name.to_lowercase());
    *change += entity! { &tag_id @ metadata::name: name_handle };
    tag_ref
}

/// Resolve a list of tag names to IDs, minting unknown ones.
fn resolve_tags(
    space: &TribleSet,
    ws: &mut Workspace<Pile<valueschemas::Blake3>>,
    names: &[String],
    change: &mut TribleSet,
) -> Vec<Id> {
    names.iter()
        .filter(|n| !n.trim().is_empty())
        .map(|n| resolve_tag(space, ws, n.trim(), change))
        .collect()
}

/// Find a tag ID by name (returns None if not found).
fn find_tag_by_name(space: &TribleSet, ws: &mut Workspace<Pile<valueschemas::Blake3>>, name: &str) -> Option<Id> {
    for (id, handle) in find!(
        (id: Id, h: TextHandle),
        pattern!(space, [{ ?id @ metadata::name: ?h }])
    ) {
        if let Ok(view) = ws.get::<View<str>, _>(handle) {
            if view.as_ref().eq_ignore_ascii_case(name) {
                return Some(id);
            }
        }
    }
    None
}

// ── triblespace query helpers ──────────────────────────────────────────────

/// Check if an ID is a version entity (has KIND_VERSION tag).
fn is_version(space: &TribleSet, id: Id) -> bool {
    exists!(
        (frag: Id),
        pattern!(space, [{ id @ metadata::tag: &KIND_VERSION_ID, wiki::fragment: ?frag }])
    )
}

/// Get the fragment ID that a version belongs to.
fn version_fragment(space: &TribleSet, version_id: Id) -> Option<Id> {
    find!(
        (frag: Id),
        pattern!(space, [{ version_id @ wiki::fragment: ?frag }])
    )
    .next()
    .map(|(frag,)| frag)
}

/// Find the latest version ID for a fragment (by created_at).
fn latest_version_of(space: &TribleSet, fragment_id: Id) -> Option<Id> {
    find!(
        (vid: Id, ts: Lower),
        pattern!(space, [{
            ?vid @
            metadata::tag: &KIND_VERSION_ID,
            wiki::fragment: &fragment_id,
            metadata::created_at: ?ts,
        }])
    )
    .max_by_key(|(_, ts)| *ts)
    .map(|(vid, _)| vid)
}

/// All version IDs of a fragment, sorted oldest-first.
fn version_history_of(space: &TribleSet, fragment_id: Id) -> Vec<Id> {
    let mut versions: Vec<(Id, Lower)> = find!(
        (vid: Id, ts: Lower),
        pattern!(space, [{
            ?vid @
            metadata::tag: &KIND_VERSION_ID,
            wiki::fragment: &fragment_id,
            metadata::created_at: ?ts,
        }])
    )
    .collect();
    versions.sort_by_key(|(_, ts)| *ts);
    versions.into_iter().map(|(vid, _)| vid).collect()
}

/// Read title string for a version entity.
fn read_title(
    space: &TribleSet,
    ws: &mut Workspace<Pile<valueschemas::Blake3>>,
    vid: Id,
) -> Option<String> {
    let (h,) = find!(
        (h: TextHandle),
        pattern!(space, [{ vid @ wiki::title: ?h }])
    )
    .next()?;
    let view: View<str> = ws.get(h).ok()?;
    Some(view.as_ref().to_string())
}

/// Get the content handle for a version entity.
fn content_handle_of(space: &TribleSet, vid: Id) -> Option<TextHandle> {
    find!(
        (h: TextHandle),
        pattern!(space, [{ vid @ wiki::content: ?h }])
    )
    .next()
    .map(|(h,)| h)
}

/// Get created_at timestamp for a version entity.
fn created_at_of(space: &TribleSet, vid: Id) -> Option<Lower> {
    find!(
        (ts: Lower),
        pattern!(space, [{ vid @ metadata::created_at: ?ts }])
    )
    .next()
    .map(|(ts,)| ts)
}

/// Get tags for a version entity (excluding KIND_VERSION).
fn tags_of(space: &TribleSet, vid: Id) -> Vec<Id> {
    find!(
        tag: Id,
        pattern!(space, [{ vid @ metadata::tag: ?tag }])
    )
    .filter(|t| *t != KIND_VERSION_ID)
    .collect()
}

/// Get stored links_to targets for a version entity.
fn links_of(space: &TribleSet, vid: Id) -> Vec<Id> {
    find!(
        target: Id,
        pattern!(space, [{ vid @ wiki::links_to: ?target }])
    )
    .collect()
}

/// Expand a hex prefix into a min/max ID range for range queries.
/// E.g. prefix "ab55" → min=ab550000...00, max=ab55ffff...ff
fn prefix_to_range(hex_prefix: &str) -> Result<(Id, Id)> {
    let clean = hex_prefix.trim().to_lowercase();
    if clean.is_empty() || clean.len() > 32 {
        bail!("invalid prefix length: expected 1-32 hex chars, got {}", clean.len());
    }
    if !clean.chars().all(|c| c.is_ascii_hexdigit()) {
        bail!("invalid hex prefix '{clean}'");
    }
    // Pad to 32 hex chars (16 bytes) with 0s for min, Fs for max.
    let min_hex = format!("{:0<32}", clean);
    let max_hex = format!("{:f<32}", clean);
    let min = Id::from_hex(&min_hex)
        .ok_or_else(|| anyhow::anyhow!("failed to parse min id from prefix '{clean}'"))?;
    let max = Id::from_hex(&max_hex)
        .ok_or_else(|| anyhow::anyhow!("failed to parse max id from prefix '{clean}'"))?;
    Ok((min, max))
}

/// Resolve a hex prefix to an ID. Matches both version and fragment IDs.
/// Uses entity range queries on the EAV index for O(log n) lookup.
fn resolve_prefix(space: &TribleSet, input: &str) -> Result<Id> {
    let trimmed = input.trim().to_lowercase();
    // Fast path: full 32-char hex ID.
    if trimmed.len() == 32 {
        return Id::from_hex(&trimmed)
            .ok_or_else(|| anyhow::anyhow!("invalid id '{trimmed}'"));
    }
    let (min, max) = prefix_to_range(&trimmed)?;
    let mut matches = Vec::new();
    let mut seen_frags = std::collections::HashSet::new();
    // Use entity range to narrow the search to version IDs in the prefix range.
    for (vid, frag) in find!(
        (vid: Id, frag: Id),
        and!(
            pattern!(space, [{ ?vid @ metadata::tag: &KIND_VERSION_ID, wiki::fragment: ?frag }]),
            space.entity_in_range(vid, min, max),
        )
    ) {
        matches.push(vid);
        seen_frags.insert(frag);
    }
    // Also check if the prefix matches a fragment ID (stored as a value, not entity).
    // Fragment IDs are in the value position of wiki::fragment, so we need a separate scan.
    // Use the value range constraint for this.
    let frag_min_val: Value<valueschemas::GenId> = min.to_value();
    let frag_max_val: Value<valueschemas::GenId> = max.to_value();
    for (frag,) in find!(
        (frag: Id),
        and!(
            pattern!(space, [{ metadata::tag: &KIND_VERSION_ID, wiki::fragment: ?frag }]),
            space.value_in_range(frag, frag_min_val, frag_max_val),
        )
    ) {
        if seen_frags.insert(frag) {
            matches.push(frag);
        }
    }
    matches.sort();
    matches.dedup();
    match matches.len() {
        0 => bail!("no id matches '{input}'"),
        1 => Ok(matches[0]),
        n => bail!("ambiguous id '{input}' ({n} matches)"),
    }
}

/// Resolve a hex prefix to a fragment ID only (not version IDs).
/// Uses value range queries for O(log n) lookup on fragment IDs.
fn resolve_fragment_prefix(space: &TribleSet, input: &str) -> Result<Id> {
    let trimmed = input.trim().to_lowercase();
    // Fast path: full 32-char hex ID.
    if trimmed.len() == 32 {
        return Id::from_hex(&trimmed)
            .ok_or_else(|| anyhow::anyhow!("invalid id '{trimmed}'"));
    }
    let (min, max) = prefix_to_range(&trimmed)?;
    let frag_min_val: Value<valueschemas::GenId> = min.to_value();
    let frag_max_val: Value<valueschemas::GenId> = max.to_value();
    let mut matches: Vec<Id> = Vec::new();
    let mut seen = std::collections::HashSet::new();
    for (frag,) in find!(
        (frag: Id),
        and!(
            pattern!(space, [{ metadata::tag: &KIND_VERSION_ID, wiki::fragment: ?frag }]),
            space.value_in_range(frag, frag_min_val, frag_max_val),
        )
    ) {
        if seen.insert(frag) {
            matches.push(frag);
        }
    }
    matches.sort();
    matches.dedup();
    match matches.len() {
        0 => bail!("no fragment matches '{input}'"),
        1 => Ok(matches[0]),
        n => bail!("ambiguous fragment prefix '{input}' ({n} matches)"),
    }
}



/// Given an ID, resolve to the fragment it belongs to.
/// Identity for fragment IDs, lookup for version IDs.
fn to_fragment(space: &TribleSet, id: Id) -> Result<Id> {
    // Try as version first (direct entity lookup, O(1)).
    if let Some(frag) = version_fragment(space, id) {
        return Ok(frag);
    }
    // Check if it's a known fragment (reverse lookup via value index).
    let is_frag = exists!(
        (vid: Id),
        pattern!(space, [{ ?vid @ wiki::fragment: &id }])
    );
    if is_frag {
        return Ok(id);
    }
    bail!("no fragment for id {}", id)
}

/// Human-readable label for a link target (version or fragment).
fn link_label(
    space: &TribleSet,
    ws: &mut Workspace<Pile<valueschemas::Blake3>>,
    id: Id,
) -> String {
    if is_version(space, id) {
        let title = read_title(space, ws, id).unwrap_or_else(|| "?".into());
        let frag = version_fragment(space, id);
        let frag_str = frag.map(|f| format!(" of {}", f)).unwrap_or_default();
        format!("{title} [version {}{}]", id, frag_str)
    } else {
        // Fragment — show its latest version's title.
        let title = latest_version_of(space, id)
            .and_then(|vid| read_title(space, ws, vid))
            .unwrap_or_else(|| "?".into());
        format!("{title} ({})", id)
    }
}

// ── helpers ────────────────────────────────────────────────────────────────
use triblespace::core::value::schemas::time::Lower;

fn now_tai() -> Value<valueschemas::NsTAIInterval> {
    let now = Epoch::now().unwrap_or(Epoch::from_unix_seconds(0.0));
    (now, now).try_to_value().expect("TAI interval")
}

/// Build a map of fragment → (latest_version_id, timestamp) in one pass.
fn latest_versions(space: &TribleSet) -> HashMap<Id, (Id, Lower)> {
    find!(
        (vid: Id, frag: Id, ts: Lower),
        pattern!(space, [{
            ?vid @
            metadata::tag: &KIND_VERSION_ID,
            wiki::fragment: ?frag,
            metadata::created_at: ?ts,
        }])
    )
    .into_grouping_map_by(|(_, frag, _)| *frag)
    .max_by_key(|_, (_, _, ts)| *ts)
    .into_iter()
    .map(|(frag, (vid, _, ts))| (frag, (vid, ts)))
    .collect()
}


fn load_value_or_file(raw: &str, label: &str) -> Result<String> {
    if let Some(path) = raw.strip_prefix('@') {
        if path == "-" {
            let mut value = String::new();
            std::io::stdin()
                .read_to_string(&mut value)
                .with_context(|| format!("read {label} from stdin"))?;
            return Ok(value);
        }
        return fs::read_to_string(path).with_context(|| format!("read {label} from {path}"));
    }
    Ok(raw.to_string())
}

/// Format a `Lower` timestamp as ISO 8601 date (e.g. "2026-03-11").
fn format_date(ts: Lower) -> String {
    let epoch = Epoch::from_tai_duration(hifitime::Duration::from_total_nanoseconds(ts.0));
    Formatter::new(epoch, ISO8601_DATE).to_string()
}


/// Extract outgoing link facts from a version's content and return them as a
/// TribleSet rooted at `source_vid`. Everything — wiki edges, typed edges,
/// file-entity refs, and file-content refs — goes into the returned set.
///
/// STRICT: only matches `#link("<faculty>:...")` typst form with a full-length
/// hex (32 chars for GenIds, 64 chars for Blake3 content hashes). Markdown,
/// bare refs, and prefixes are NOT treated as links — lint is responsible for
/// repairing them first.
///
/// Edge kinds produced:
///   wiki:HEX32             → `wiki::links_to` (GenId)
///   wiki:<type>:HEX32      → `wiki::links_to` + derived attribute named `<type>`
///   files:HEX32            → `wiki::references_file` (GenId, points to a file entity)
///   files:HEX64            → `wiki::references_file_content` (Blake3 content handle)
fn extract_references(
    content: &str,
    space: &TribleSet,
    source_vid: Id,
) -> TribleSet {
    use regex::Regex;
    let re = Regex::new(
        r#"#link\("([a-zA-Z_][a-zA-Z0-9_]*):((?:[a-zA-Z_][a-zA-Z0-9_]*:)?)([0-9a-fA-F]{64}|[0-9a-fA-F]{32})"\)"#
    ).unwrap();

    let mut edges = TribleSet::new();
    for caps in re.captures_iter(content) {
        let faculty = &caps[1];
        let type_prefix = &caps[2];
        let hex = caps[3].to_lowercase();

        match (faculty, hex.len()) {
            ("wiki", 32) => {
                let Some(target) = Id::from_hex(&hex) else { continue; };
                if !is_version(space, target) && !is_fragment(space, target) { continue; }
                if target == source_vid { continue; }
                let eid = ExclusiveId::force_ref(&source_vid);
                edges += entity! { eid @ wiki::links_to: &target };
                if !type_prefix.is_empty() {
                    let type_name = &type_prefix[..type_prefix.len() - 1];
                    let attr = triblespace::core::attribute::Attribute::<valueschemas::GenId>::from_name(type_name);
                    let eid = ExclusiveId::force_ref(&source_vid);
                    edges += entity! { eid @ attr: &target };
                }
            }
            ("wiki", 64) => {
                // 64-char is a Blake3 hash; wiki targets are GenIds, not content
                // hashes, so ignore.
                continue;
            }
            ("files", 32) => {
                let Some(target) = Id::from_hex(&hex) else { continue; };
                let eid = ExclusiveId::force_ref(&source_vid);
                edges += entity! { eid @ wiki::references_file: &target };
            }
            ("files", 64) => {
                let Ok(hash) = valueschemas::Hash::<valueschemas::Blake3>::from_hex(&hex) else {
                    continue;
                };
                let handle: Value<valueschemas::Handle<valueschemas::Blake3, blobschemas::FileBytes>> =
                    valueschemas::Handle::from_hash(hash);
                let eid = ExclusiveId::force_ref(&source_vid);
                edges += entity! { eid @ wiki::references_file_content: handle };
            }
            _ => {}
        }
    }
    edges
}

/// Check whether an ID is a known fragment (has at least one version pointing to it).
fn is_fragment(space: &TribleSet, id: Id) -> bool {
    find!(
        (vid: Id),
        pattern!(space, [{ ?vid @ wiki::fragment: id }])
    ).next().is_some()
}

type Repo = Repository<Pile<valueschemas::Blake3>>;

/// Ensure all built-in tag/kind IDs have metadata::name entries.
fn ensure_tag_vocabulary(
    repo: &mut Repo,
    ws: &mut Workspace<Pile<valueschemas::Blake3>>,
) -> Result<()> {
    let space = ws
        .checkout(..)
        .map_err(|e| anyhow::anyhow!("checkout for tag names: {e:?}"))?;
    let existing: std::collections::HashSet<Id> = find!(
        (kind: Id),
        pattern!(&space, [{ ?kind @ metadata::name: _?handle }])
    )
    .map(|(kind,)| kind)
    .collect();

    let mut change = TribleSet::new();
    for (id, label) in TAG_SPECS {
        if existing.contains(&id) {
            continue;
        }
        let name_handle = ws.put(label.to_owned());
        change += entity! { ExclusiveId::force_ref(&id) @ metadata::name: name_handle };
    }

    if !change.is_empty() {
        ws.commit(change, "wiki: register tag names");
        repo.push(ws)
            .map_err(|e| anyhow::anyhow!("push tag names: {e:?}"))?;
    }
    Ok(())
}

// ── in-process typst validation ──────────────────────────────────────

mod typst_validate {
    use typst::foundations::{Bytes, Datetime};
    use typst::text::{Font, FontBook};
    use typst::syntax::{FileId, Source, VirtualPath};
    use typst::diag::FileResult;
    use typst::utils::LazyHash;
    use typst::{Library, LibraryExt, World};
    use typst::layout::PagedDocument;

    pub struct ValidateWorld {
        library: LazyHash<Library>,
        book: LazyHash<FontBook>,
        main_id: FileId,
        source: Source,
    }

    impl ValidateWorld {
        pub fn new(content: &str) -> Self {
            let main_id = FileId::new(None, VirtualPath::new("main.typ"));
            let source = Source::new(main_id, content.to_string());
            Self {
                library: LazyHash::new(Library::default()),
                book: LazyHash::new(FontBook::new()),
                main_id,
                source,
            }
        }

        pub fn validate(&self) -> Result<(), Vec<String>> {
            let result = typst::compile::<PagedDocument>(self);
            match result.output {
                Ok(_) => Ok(()),
                Err(errors) => {
                    let msgs: Vec<String> = errors.iter()
                        // Font errors are expected (minimal world has no fonts).
                        .filter(|e| !e.message.contains("no font"))
                        .map(|e| {
                            let mut msg = e.message.to_string();
                            if let Some(range) = self.source.range(e.span) {
                                let line = self.source.text()[..range.start]
                                    .chars().filter(|&c| c == '\n').count() + 1;
                                msg = format!("line {line}: {msg}");
                            }
                            msg
                        }).collect();
                    if msgs.is_empty() { Ok(()) } else { Err(msgs) }
                }
            }
        }
    }

    impl World for ValidateWorld {
        fn library(&self) -> &LazyHash<Library> { &self.library }
        fn book(&self) -> &LazyHash<FontBook> { &self.book }
        fn main(&self) -> FileId { self.main_id }
        fn source(&self, id: FileId) -> FileResult<Source> {
            if id == self.main_id {
                Ok(self.source.clone())
            } else {
                Err(typst::diag::FileError::NotFound(id.vpath().as_rootless_path().into()))
            }
        }
        fn file(&self, id: FileId) -> FileResult<Bytes> {
            Err(typst::diag::FileError::NotFound(id.vpath().as_rootless_path().into()))
        }
        fn font(&self, _index: usize) -> Option<Font> { None }
        fn today(&self, _offset: Option<i64>) -> Option<Datetime> { None }
    }
}

// ── lint / auto-fix ────────────────────────────────────────────────

/// Apply lint transforms to content: markdown→typst syntax, expand short IDs.
/// Returns the transformed content. The TribleSet is used for ID expansion.
fn lint_fix(content: &str, space: &TribleSet) -> String {
    let mut out = String::with_capacity(content.len());
    let mut in_code_block = false;
    for line in content.lines() {
        if line.trim_start().starts_with("```") {
            in_code_block = !in_code_block;
        }
        let fixed = if in_code_block {
            line.to_string() // Skip all transforms inside code blocks
        } else {
            lint_line(line, space)
        };
        out.push_str(&fixed);
        out.push('\n');
    }
    // Remove trailing newline if original didn't have one
    if !content.ends_with('\n') && out.ends_with('\n') {
        out.pop();
    }
    out
}

/// Transform a single line: headings, bold, links.
/// Bare `[wiki:HEX]`, `[wiki:<type>:HEX]` or `[files:HEX]` (no parenthesized URL, not
/// inside #link) → `#link("scheme:hex")[scheme:hex]`.
/// Must run BEFORE lint_links (which handles the markdown `[text](scheme:hex)` form).
fn lint_bare_brackets(line: &str, space: &TribleSet) -> String {
    use regex::Regex;
    // Match [wiki:HEX], [wiki:type:HEX], or [files:HEX] NOT followed by ( and NOT preceded by ") (inside a #link)
    let re_bare = Regex::new(
        r"\[(wiki|files):((?:[a-zA-Z_][a-zA-Z0-9_]*:)?[0-9a-fA-F]+)\]([^(]|$)"
    ).unwrap();
    let mut result = String::new();
    let mut last_end = 0;
    for caps in re_bare.captures_iter(line) {
        let m = caps.get(0).unwrap();
        // Skip if preceded by ") — this is the [text] part of an existing #link("...")[text]
        if m.start() > 0 && &line[m.start()-1..m.start()] == ")" {
            continue;
        }
        // Skip if preceded by a quote — inside #link("scheme:hex")
        if m.start() > 1 && &line[m.start()-1..m.start()] == "\"" {
            continue;
        }
        let scheme = &caps[1];
        let rest = &caps[2];
        let after = &caps[3];
        // Split optional type prefix: "reviews:HEX" vs "HEX"
        let (type_prefix, hex) = split_typed(rest);
        let full_hex = match try_expand_id(hex, space) {
            Ok(id) => format!("{:x}", id),
            Err(_) => hex.to_lowercase(),
        };
        result.push_str(&line[last_end..m.start()]);
        result.push_str(&format!(
            "#link(\"{scheme}:{type_prefix}{full_hex}\")[{scheme}:{type_prefix}{hex}]{after}"
        ));
        last_end = m.end();
    }
    result.push_str(&line[last_end..]);
    if result.is_empty() { line.to_string() } else { result }
}

/// Split a reference tail into (type_prefix_with_colon, hex). For `reviews:HEX`
/// returns `("reviews:", "HEX")`; for plain `HEX` returns `("", "HEX")`.
fn split_typed(rest: &str) -> (String, &str) {
    if let Some(colon) = rest.find(':') {
        let t = &rest[..colon];
        let h = &rest[colon + 1..];
        // Only treat as typed if the part before : is NOT all hex
        if !t.chars().all(|c| c.is_ascii_hexdigit()) {
            return (format!("{t}:"), h);
        }
    }
    (String::new(), rest)
}

/// Convert bare `wiki:HEX` / `wiki:<type>:HEX` references in prose to proper typst
/// `#link("wiki:HEX")[wiki:HEX]` form. Requires full-length (32+ char) hex to avoid
/// false positives on tag values or ambiguous prefixes. Skips matches already inside
/// `#link("…")` quotes or `[…]` brackets.
///
/// Must run AFTER lint_links / lint_bare_brackets so that any remaining bare reference
/// is definitely not part of an existing link construct.
fn lint_bare_refs(line: &str, space: &TribleSet) -> String {
    use regex::Regex;
    let re = Regex::new(
        r"\bwiki:((?:[a-zA-Z_][a-zA-Z0-9_]*:)?[0-9a-fA-F]{32,})\b"
    ).unwrap();
    let mut result = String::new();
    let mut last_end = 0;
    for caps in re.captures_iter(line) {
        let m = caps.get(0).unwrap();
        let start = m.start();
        // Skip if inside #link("…") quotes
        if start > 0 && &line[start-1..start] == "\"" {
            continue;
        }
        // Skip if inside [wiki:HEX] brackets (typically the [text] of an existing #link)
        if start > 0 && &line[start-1..start] == "[" {
            continue;
        }
        let rest = &caps[1];
        let (type_prefix, hex) = split_typed(rest);
        let full_hex = match try_expand_id(hex, space) {
            Ok(id) => format!("{:x}", id),
            Err(_) => hex.to_lowercase(),
        };
        result.push_str(&line[last_end..start]);
        result.push_str(&format!(
            "#link(\"wiki:{type_prefix}{full_hex}\")[wiki:{type_prefix}{hex}]"
        ));
        last_end = m.end();
    }
    result.push_str(&line[last_end..]);
    if result.is_empty() { line.to_string() } else { result }
}

/// `[text](https://url)` → `#link("https://url")[text]` — markdown web links to typst
fn lint_web_links(line: &str) -> String {
    use regex::Regex;
    let re = Regex::new(r"\[([^\]]+)\]\((https?://[^\)]+)\)").unwrap();
    re.replace_all(line, |caps: &regex::Captures| {
        let text = &caps[1];
        let url = &caps[2];
        format!("#link(\"{url}\")[{text}]")
    }).to_string()
}

fn lint_line(line: &str, space: &TribleSet) -> String {
    let mut s = lint_headings(line);
    s = lint_bold(&s);
    s = lint_bare_brackets(&s, space);
    s = lint_links(&s, space);
    s = lint_web_links(&s);
    // Run bare-ref repair LAST so that any remaining bare `wiki:HEX` in prose is
    // definitely not inside a link construct that the earlier passes built or
    // rewrote.
    s = lint_bare_refs(&s, space);
    s = lint_horizontal_rule(&s);
    s
}

/// `## Heading` → `== Heading` (only at line start, with space after #)
fn lint_headings(line: &str) -> String {
    if line.starts_with("### ") {
        format!("=== {}", &line[4..])
    } else if line.starts_with("## ") {
        format!("== {}", &line[3..])
    } else if line.starts_with("# ") {
        format!("= {}", &line[2..])
    } else {
        line.to_string()
    }
}

/// `**text**` → `*text*` (double-star bold only). Respects `\*` escapes so
/// that typst-escaped asterisks adjacent to real bold markers (e.g. `\**` at
/// the end of a table cell) are not mistaken for a markdown `**` pair.
fn lint_bold(line: &str) -> String {
    let mut result = String::with_capacity(line.len());
    let mut chars = line.char_indices().peekable();
    while let Some((i, c)) = chars.next() {
        // Backslash escape: emit the backslash and the next char literally.
        if c == '\\' {
            result.push('\\');
            if let Some((_, next)) = chars.next() {
                result.push(next);
            }
            continue;
        }
        if c == '*' {
            if let Some(&(_, '*')) = chars.peek() {
                // Found **, look for closing ** while respecting escapes.
                chars.next(); // consume second *
                if chars.peek().is_none() { break; }
                let mut found_close = false;
                let mut inner = String::new();
                while let Some((_, ic)) = chars.next() {
                    if ic == '\\' {
                        inner.push('\\');
                        if let Some((_, next)) = chars.next() {
                            inner.push(next);
                        }
                        continue;
                    }
                    if ic == '*' {
                        if let Some(&(_, '*')) = chars.peek() {
                            chars.next(); // consume closing **
                            found_close = true;
                            break;
                        }
                    }
                    inner.push(ic);
                }
                if found_close {
                    result.push('*');
                    result.push_str(&inner);
                    result.push('*');
                } else {
                    // No closing **, emit as-is
                    result.push_str(&line[i..]);
                    return result;
                }
            } else {
                result.push(c);
            }
        } else {
            result.push(c);
        }
    }
    result
}

/// `[text](wiki:ID)` → `#link("wiki:ID")[text]`; also handles `wiki:<type>:ID`
/// and `files:ID`. Expands short ID prefixes to full 32-char hex.
fn lint_links(line: &str, space: &TribleSet) -> String {
    use regex::Regex;
    let re = Regex::new(
        r"\[([^\]]+)\]\((wiki|files):((?:[a-zA-Z_][a-zA-Z0-9_]*:)?[0-9a-fA-F]+)\)"
    ).unwrap();
    re.replace_all(line, |caps: &regex::Captures| {
        let text = &caps[1];
        let scheme = &caps[2];
        let rest = &caps[3];
        let (type_prefix, hex) = split_typed(rest);
        let full_hex = match try_expand_id(hex, space) {
            Ok(id) => format!("{:x}", id),
            Err(_) => hex.to_lowercase(),
        };
        format!("#link(\"{scheme}:{type_prefix}{full_hex}\")[{text}]")
    }).to_string()
}

/// `---` alone on a line → removed (typst doesn't have horizontal rules by default)
fn lint_horizontal_rule(line: &str) -> String {
    let trimmed = line.trim();
    if trimmed == "---" || trimmed == "***" || trimmed == "___" {
        String::new()
    } else {
        line.to_string()
    }
}

/// Try to expand a hex prefix to a full ID using the space.
/// Prefers fragment IDs over version IDs for wiki: links.
/// Returns Ok(Id) if unique, Err if ambiguous/missing/already full.
fn try_expand_id(hex: &str, space: &TribleSet) -> Result<Id> {
    let clean = hex.trim().to_lowercase();
    if clean.len() == 32 {
        return Id::from_hex(&clean)
            .ok_or_else(|| anyhow::anyhow!("invalid hex"));
    }
    if clean.len() < 4 {
        bail!("prefix too short");
    }
    // Prefer fragment resolution (stable pointers) over version resolution
    match resolve_fragment_prefix(space, &clean) {
        Ok(id) => Ok(id),
        Err(_) => resolve_prefix(space, &clean), // Fall back to version IDs
    }
}

/// Validate typst content by compiling in-process. No temp files, no shell-out.
fn validate_typst(content: &str) -> Result<()> {
    let world = typst_validate::ValidateWorld::new(content);
    match world.validate() {
        Ok(()) => Ok(()),
        Err(errors) => bail!("typst compilation failed:\n{}", errors.join("\n")),
    }
}

/// Validate that every `wiki:HEX` link in the content points at an existing
/// fragment or version. Rejects truncated links (hex != 32 chars) and links
/// to IDs that don't exist in the current wiki space. This prevents
/// hallucinated IDs and stale references from being committed.
fn validate_wiki_links(content: &str, space: &TribleSet) -> Result<()> {
    use regex::Regex;
    let re = Regex::new(r"wiki:([0-9a-fA-F]+)").unwrap();

    let known_frags: std::collections::HashSet<Id> = find!(
        frag: Id,
        pattern!(space, [{ _?vid @ metadata::tag: &KIND_VERSION_ID, wiki::fragment: ?frag }])
    ).collect();
    let known_versions: std::collections::HashSet<Id> = find!(
        vid: Id,
        pattern!(space, [{ ?vid @ metadata::tag: &KIND_VERSION_ID }])
    ).collect();

    let mut errors = Vec::new();
    for caps in re.captures_iter(content) {
        let hex = &caps[1];
        if hex.len() != 32 {
            errors.push(format!("truncated link wiki:{hex} ({} chars, expected 32)", hex.len()));
            continue;
        }
        let Some(id) = Id::from_hex(hex) else {
            errors.push(format!("invalid hex in wiki:{hex}"));
            continue;
        };
        if !known_frags.contains(&id) && !known_versions.contains(&id) {
            errors.push(format!("broken link wiki:{hex} (target does not exist)"));
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        bail!("wiki link validation failed:\n  {}", errors.join("\n  "))
    }
}

fn commit_version(
    repo: &mut Repo,
    ws: &mut Workspace<Pile<valueschemas::Blake3>>,
    mut change: TribleSet,
    fragment_id: Id,
    title: &str,
    content: TextHandle,
    tags: &[Id],
    space: &TribleSet,
    message: &str,
    force_fragment_links: bool,
) -> Result<Id> {
    let mut tag_ids = tags.to_vec();
    tag_ids.push(KIND_VERSION_ID);
    tag_ids.sort();
    tag_ids.dedup();

    // Read content text for link extraction.
    let content_text: View<str> = ws
        .get(content)
        .map_err(|e| anyhow::anyhow!("read content for link extraction: {e:?}"))?;

    let title_handle = ws.put(title.to_owned());

    // Create the version entity. Edges (links_to + derived typed attrs) are
    // added separately after we know the version's ID.
    let version = entity! { _ @
        wiki::fragment: &fragment_id,
        wiki::title: title_handle,
        wiki::content: content,
        metadata::created_at: now_tai(),
        metadata::tag*: tag_ids.iter(),
    };
    let version_id = version.root().expect("version should be rooted");
    change += version;

    let edges = extract_references(content_text.as_ref(), space, version_id);

    // Reject links to fragments (should target versions for stable references).
    if !force_fragment_links {
        let bad_links: Vec<Id> = find!(
            target: Id,
            pattern!(&edges, [{ version_id @ wiki::links_to: ?target }])
        ).filter(|t| !is_version(space, *t)).collect();
        if !bad_links.is_empty() {
            let ids: Vec<String> = bad_links.iter().map(|id| format!("{:x}", id)).collect();
            bail!("link targets are fragments, not versions: {}. \
                Use version IDs for stable references, or pass --force to override.",
                ids.join(", "));
        }
    }

    change += edges;

    ws.commit(change, message);
    repo.push(ws).map_err(|e| anyhow::anyhow!("push: {e:?}"))?;
    Ok(version_id)
}

/// Outgoing and incoming links for an ID (fragment or version).
/// Returns (outgoing targets, incoming sources, external references).
fn find_links(
    space: &TribleSet,
    ws: &mut Workspace<Pile<valueschemas::Blake3>>,
    id: Id,
) -> Result<(Vec<Id>, Vec<Id>, Vec<(String, String)>)> {
    // Determine the version to read outgoing links from.
    let vid = if is_version(space, id) {
        id
    } else {
        latest_version_of(space, id)
            .ok_or_else(|| anyhow::anyhow!("no versions for {}", id))?
    };

    // Outgoing: stored links_to on this version, with content-parse fallback.
    let mut outgoing = links_of(space, vid);
    if outgoing.is_empty() {
        if let Some(ch) = content_handle_of(space, vid) {
            let content: View<str> = ws.get(ch)
                .map_err(|e| anyhow::anyhow!("read content: {e:?}"))?;
            let edges = extract_references(content.as_ref(), space, vid);
            outgoing = find!(
                target: Id,
                pattern!(&edges, [{ vid @ wiki::links_to: ?target }])
            ).filter(|&t| t != id).collect();
        }
    }
    outgoing.sort();
    outgoing.dedup();

    // Incoming: all entities that link_to this ID (direct conjunctive query).
    let mut incoming: Vec<Id> = find!(
        source: Id,
        pattern!(space, [{ ?source @ wiki::links_to: &id }])
    )
    .collect();
    // Also check for links to the fragment if id is a version (or vice versa).
    if is_version(space, id) {
        if let Some(frag) = version_fragment(space, id) {
            for s in find!(
                source: Id,
                pattern!(space, [{ ?source @ wiki::links_to: &frag }])
            ) {
                incoming.push(s);
            }
        }
    } else {
        // id is a fragment — also collect links to any of its versions.
        let versions: Vec<Id> = version_history_of(space, id);
        if !versions.is_empty() {
            let version_set: std::collections::HashSet<Id> = versions.into_iter().collect();
            incoming.extend(find!(
                source: Id,
                temp!((vid),
                    and!(
                        (&version_set).has(vid),
                        pattern!(space, [{ ?source @ wiki::links_to: ?vid }])
                    )
                )
            ));
        }
    }
    incoming.sort();
    incoming.dedup();

    // File references: stored as tribles on the version. Query both the
    // entity-reference index (references_file) and the content-hash index
    // (references_file_content) and return them in a uniform (faculty, hex) shape
    // for display.
    let mut external: Vec<(String, String)> = Vec::new();
    for (target,) in find!(
        (t: Id),
        pattern!(space, [{ vid @ wiki::references_file: ?t }])
    ) {
        external.push(("files".to_string(), format!("{:x}", target)));
    }
    for (handle,) in find!(
        (h: Value<valueschemas::Handle<valueschemas::Blake3, blobschemas::FileBytes>>),
        pattern!(space, [{ vid @ wiki::references_file_content: ?h }])
    ) {
        let hash: Value<valueschemas::Hash<valueschemas::Blake3>> =
            valueschemas::Handle::to_hash(handle);
        external.push((
            "files".to_string(),
            valueschemas::Hash::<valueschemas::Blake3>::to_hex(&hash),
        ));
    }
    external.sort();
    external.dedup();

    Ok((outgoing, incoming, external))
}

/// Determine the version to display for a given ID.
/// If `follow_latest` is true and id is a version, jump to the latest version
/// of its fragment instead.
fn resolve_to_show(space: &TribleSet, id: Id, follow_latest: bool) -> Result<Id> {
    if is_version(space, id) {
        if follow_latest {
            let frag = version_fragment(space, id)
                .ok_or_else(|| anyhow::anyhow!("version has no fragment"))?;
            latest_version_of(space, frag)
                .ok_or_else(|| anyhow::anyhow!("no versions for fragment"))
        } else {
            Ok(id)
        }
    } else {
        // Fragment — always show latest version.
        latest_version_of(space, id)
            .ok_or_else(|| anyhow::anyhow!("no versions for {}", id))
    }
}

// ── commands ───────────────────────────────────────────────────────────────

fn cmd_fix_truncated(repo: &mut Repo, bid: Id, raw_input: String) -> Result<()> {
    let input = load_value_or_file(&raw_input, "input")?;

    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;

    let mut resolved = 0u32;
    let mut ambiguous = 0u32;
    let mut already_full = 0u32;

    for line in input.lines() {
        let line = line.trim();
        if line.is_empty() { continue; }
        let Some((scheme, hex)) = line.split_once(':') else {
            eprintln!("SKIP: {line} (no scheme:prefix format)");
            continue;
        };
        let full_len = if scheme == "wiki" { 32 } else if scheme == "files" { 64 } else {
            eprintln!("SKIP: {line} (unknown scheme '{scheme}')");
            continue;
        };
        if hex.len() >= full_len {
            already_full += 1;
            continue; // already full length, nothing to do
        }
        match resolve_prefix(&space, hex) {
            Ok(id) => {
                println!("{}\t{}:{}", line, scheme, id);
                resolved += 1;
            }
            Err(e) => {
                eprintln!("AMBIGUOUS: {}{}", line, e);
                ambiguous += 1;
            }
        }
    }
    eprintln!("{} resolved, {} ambiguous, {} already full", resolved, ambiguous, already_full);
    Ok(())
}

fn cmd_check(repo: &mut Repo, bid: Id, try_compile: bool) -> Result<()> {
    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;

    let latest = latest_versions(&space);

    // Collect ALL known IDs for link checking (fragments + every version, not just latest)
    let all_frag_ids: std::collections::HashSet<Id> = latest.keys().copied().collect();
    let all_version_ids: std::collections::HashSet<Id> = find!(
        vid: Id,
        pattern!(&space, [{ ?vid @ metadata::tag: &KIND_VERSION_ID }])
    ).collect();

    // All fragments are typst — no markdown path

    let mut issues = 0u32;
    let mut checked = 0u32;
    let mut compile_ok = 0u32;
    let mut compile_fail = 0u32;

    let tmp_dir = std::env::temp_dir().join("wiki-check");
    if try_compile {
        let _ = fs::create_dir_all(&tmp_dir);
    }

    for (frag_id, (vid, _)) in &latest {
        let tags = tags_of(&space, *vid);
        if tags.contains(&TAG_ARCHIVED_ID) {
            continue;
        }
        checked += 1;
        let title = read_title(&space, &mut ws, *vid).unwrap_or_else(|| "?".into());
        let frag_hex = format!("{:x}", frag_id);

        // All fragments are typst (no markdown path)

        // Read content
        let Some(ch) = content_handle_of(&space, *vid) else {
            eprintln!("NO_CONTENT   {}  {}", frag_hex, title);
            issues += 1;
            continue;
        };
        let content: View<str> = ws.get(ch)
            .map_err(|e| anyhow::anyhow!("read content: {e:?}"))?;
        let content_str = content.as_ref();

        // Check: truncated links
        use regex::Regex;
        let re = Regex::new(r"(wiki|files):([0-9a-fA-F]+)").unwrap();
        for caps in re.captures_iter(content_str) {
            let scheme = &caps[1];
            let hex = &caps[2];
            // wiki: links must be 32 chars (entity ID)
            // files: links can be 32 chars (entity ID) or 64 chars (hash)
            let is_truncated = match scheme {
                "wiki" => hex.len() < 32,
                "files" => hex.len() != 32 && hex.len() != 64,
                _ => false,
            };
            if is_truncated {
                eprintln!("TRUNCATED    {}  {}:{}  in {}", frag_hex, scheme, hex, title);
                issues += 1;
            }
        }

        // Check: broken wiki links
        for caps in re.captures_iter(content_str) {
            let scheme = &caps[1];
            let hex = &caps[2];
            if scheme == "wiki" && hex.len() == 32 {
                if let Some(id) = Id::from_hex(hex) {
                    if !all_frag_ids.contains(&id) && !all_version_ids.contains(&id) {
                        eprintln!("BROKEN_LINK  {}  wiki:{}  in {}", frag_hex, hex, title);
                        issues += 1;
                    }
                }
            }
        }

        // Check: markdown-style links [text](faculty:hex) — should be typst #link("faculty:hex")[text]
        {
            let md_link_re = regex::Regex::new(r"\[([^\]]+)\]\(((?:wiki|files):[^)]+)\)").unwrap();
            for caps in md_link_re.captures_iter(content_str) {
                let text = &caps[1];
                let url = &caps[2];
                eprintln!("MD_LINK      {}  [{}]({})  in {}", frag_hex, text, url, title);
                issues += 1;
            }
        }

        // Check: typst compilation (in-process)
        if try_compile {
            let world = typst_validate::ValidateWorld::new(content_str);
            match world.validate() {
                Ok(()) => { compile_ok += 1; }
                Err(errors) => {
                    let first = errors.first().map(|s| s.as_str()).unwrap_or("unknown");
                    eprintln!("TYPST_ERROR  {}  {}  {}", frag_hex, title, first);
                    compile_fail += 1;
                    issues += 1;
                }
            }
        }
    }

    let _ = fs::remove_dir(&tmp_dir);

    // Check: orphaned fragments (no incoming or outgoing wiki edges)
    let mut has_outgoing: std::collections::HashSet<Id> = std::collections::HashSet::new();
    let mut has_incoming: std::collections::HashSet<Id> = std::collections::HashSet::new();
    for (frag_id, (vid, _)) in &latest {
        let tags = tags_of(&space, *vid);
        if tags.contains(&TAG_ARCHIVED_ID) { continue; }
        let outgoing = links_of(&space, *vid);
        if !outgoing.is_empty() {
            has_outgoing.insert(*frag_id);
        }
        for target in &outgoing {
            has_incoming.insert(*target);
            // Also mark the fragment that owns this version
            if let Some(target_frag) = version_fragment(&space, *target) {
                has_incoming.insert(target_frag);
            }
        }
    }
    let mut orphans = 0u32;
    for (frag_id, (vid, _)) in &latest {
        let tags = tags_of(&space, *vid);
        if tags.contains(&TAG_ARCHIVED_ID) { continue; }
        if !has_outgoing.contains(frag_id) && !has_incoming.contains(frag_id) {
            let title = read_title(&space, &mut ws, *vid).unwrap_or_else(|| "?".into());
            eprintln!("ORPHAN       {}  {}", frag_id, title);
            orphans += 1;
        }
    }

    println!();
    println!("Checked {} fragments, {} issues found", checked, issues);
    if orphans > 0 {
        println!("Orphans: {} (no incoming or outgoing wiki links)", orphans);
    }
    if try_compile {
        println!("Typst: {} ok, {} failed", compile_ok, compile_fail);
    }
    if issues == 0 && orphans == 0 {
        println!("All clear!");
    }
    Ok(())
}

fn cmd_lint(repo: &mut Repo, bid: Id, do_fix: bool, check_only: bool) -> Result<()> {
    // Dry-run and check modes: single pull, no commits.
    if !do_fix {
        let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
        let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
        let latest = latest_versions(&space);

        let mut changed = 0u32;
        let mut relinked = 0u32;
        let mut checked = 0u32;

        for (&frag_id, &(vid, _ts)) in &latest {
            let Some(ch) = content_handle_of(&space, vid) else { continue; };
            let Ok(content) = ws.get::<View<str>, _>(ch) else { continue; };
            let original = content.as_ref().to_string();
            checked += 1;

            let fixed = lint_fix(&original, &space);
            if fixed != original {
                changed += 1;
                let title = read_title(&space, &mut ws, vid).unwrap_or_default();
                if check_only {
                    eprintln!("LINT {:x}{title}", frag_id);
                } else {
                    println!("WOULD FIX {:x}{title}", frag_id);
                    let orig_lines: Vec<&str> = original.lines().collect();
                    let fixed_lines: Vec<&str> = fixed.lines().collect();
                    for (i, (o, f)) in orig_lines.iter().zip(fixed_lines.iter()).enumerate() {
                        if o != f {
                            println!("  L{}: - {}", i + 1, o);
                            println!("  L{}: + {}", i + 1, f);
                        }
                    }
                }
            } else {
                // Text unchanged: compute desired edges and subtract stored.
                let desired = extract_references(&original, &space, vid);
                let missing = desired.difference(&space);
                if !missing.is_empty() {
                    relinked += 1;
                    let title = read_title(&space, &mut ws, vid).unwrap_or_default();
                    let n = missing.len();
                    if check_only {
                        eprintln!("RELINK {:x} +{n} edges — {title}", frag_id);
                    } else {
                        println!("WOULD RELINK {:x} +{n} edges — {title}", frag_id);
                    }
                }
            }
        }

        println!();
        println!("Checked: {checked}, Changed: {changed}, Relinked: {relinked}");
        if check_only && (changed > 0 || relinked > 0) {
            bail!("{changed} fragments need lint fixes; {relinked} need relink");
        }
        return Ok(());
    }

    // Fix mode: CAS loop like cmd_import_all. Accumulate all changes, try_push
    // once, retry on conflict. No new tags needed — lint preserves existing tags.
    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;

    loop {
        let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
        let latest = latest_versions(&space);

        let mut change = TribleSet::new();
        let mut fixed_count = 0u32;
        let mut relinked_count = 0u32;
        let mut new_links_count = 0u32;
        let mut error_count = 0u32;
        let mut checked = 0u32;

        for (&frag_id, &(vid, _ts)) in &latest {
            let Some(ch) = content_handle_of(&space, vid) else { continue; };
            let Ok(content) = ws.get::<View<str>, _>(ch) else { continue; };
            let original = content.as_ref().to_string();
            checked += 1;

            let fixed = lint_fix(&original, &space);
            if fixed == original {
                // Text already clean: rebuild the desired link tribles and subtract
                // what's already in the space — add only the missing ones.
                let desired = extract_references(&original, &space, vid);
                let missing = desired.difference(&space);
                if missing.is_empty() {
                    continue;
                }

                let title = read_title(&space, &mut ws, vid).unwrap_or_default();
                let added = missing.len();
                change += missing;
                relinked_count += 1;
                new_links_count += added as u32;
                println!("RELINKED {:x} +{} edges — {title}", frag_id, added);
                continue;
            }

            let title = read_title(&space, &mut ws, vid).unwrap_or_default();

            if let Err(e) = validate_typst(&fixed) {
                eprintln!("LINT_TYPST_ERROR {:x}{title}: {e}", frag_id);
                error_count += 1;
                continue;
            }
            if let Err(e) = validate_wiki_links(&fixed, &space) {
                eprintln!("LINT_LINK_ERROR {:x}{title}: {e}", frag_id);
                error_count += 1;
                continue;
            }

            // Build new version entity directly (same pattern as cmd_import_all).
            let tag_ids = tags_of(&space, vid);
            let content_handle = ws.put(fixed);
            let content_text: View<str> = match ws.get(content_handle) {
                Ok(v) => v,
                Err(e) => {
                    eprintln!("LINT_READ_ERROR {:x}: {e:?}", frag_id);
                    error_count += 1;
                    continue;
                }
            };
            let mut all_tags = tag_ids;
            all_tags.push(KIND_VERSION_ID);
            all_tags.sort(); all_tags.dedup();
            let title_handle = ws.put(title.clone());
            let version = entity! { _ @
                wiki::fragment: &frag_id,
                wiki::title: title_handle,
                wiki::content: content_handle,
                metadata::created_at: now_tai(),
                metadata::tag*: all_tags.iter(),
            };
            let version_id = version.root().expect("version should be rooted");
            change += version;
            change += extract_references(content_text.as_ref(), &space, version_id);
            fixed_count += 1;
            println!("FIXED {:x}{title}", frag_id);
        }

        if fixed_count == 0 && relinked_count == 0 {
            println!("Checked: {checked}, Changed: 0, Errors: {error_count}");
            return Ok(());
        }

        ws.commit(change, "wiki lint --fix");
        match repo.try_push(&mut ws) {
            Ok(None) => {
                println!();
                println!(
                    "Checked: {checked}, Fixed: {fixed_count}, Relinked: {relinked_count} (+{new_links_count} links), Errors: {error_count}"
                );
                return Ok(());
            }
            Ok(Some(conflict_ws)) => {
                eprintln!("Push conflict — retrying...");
                ws = conflict_ws;
            }
            Err(e) => bail!("push failed: {e:?}"),
        }
    }
}

fn cmd_export_all(repo: &mut Repo, bid: Id, dir: PathBuf) -> Result<()> {
    fs::create_dir_all(&dir).context("create output directory")?;
    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let mut count = 0u32;
    let latest = latest_versions(&space);
    for (_frag_id, (vid, _)) in &latest {
        // Skip archived
        let tags = tags_of(&space, *vid);
        if tags.contains(&TAG_ARCHIVED_ID) {
            continue;
        }
        let Some(ch) = content_handle_of(&space, *vid) else { continue };
        let content: View<str> = ws.get(ch)
            .map_err(|e| anyhow::anyhow!("read content: {e:?}"))?;
        // Name by version ID so import-all can do CAS check.
        let path = dir.join(format!("{:x}.typ", vid));
        fs::write(&path, content.as_ref())
            .with_context(|| format!("write {}", path.display()))?;
        count += 1;
    }
    eprintln!("Exported {} fragments (version-addressed) to {}", count, dir.display());
    Ok(())
}

fn cmd_import_all(repo: &mut Repo, bid: Id, dir: PathBuf) -> Result<()> {
    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    ensure_tag_vocabulary(repo, &mut ws)?;

    // Build version->fragment map for filename resolution.
    let mut vid_to_frag: HashMap<Id, Id> = HashMap::new();
    for (vid, frag) in find!(
        (vid: Id, frag: Id),
        pattern!(&space, [{
            ?vid @
            metadata::tag: &KIND_VERSION_ID,
            wiki::fragment: ?frag,
        }])
    ) {
        vid_to_frag.insert(vid, frag);
    }

    let entries: Vec<_> = fs::read_dir(&dir)
        .with_context(|| format!("read dir {}", dir.display()))?
        .filter_map(|e| e.ok())
        .filter(|e| e.path().extension().is_some_and(|ext| ext == "typ"))
        .collect();

    // Parse version IDs from filenames and resolve to fragments.
    let mut work: Vec<(Id, Id, std::path::PathBuf)> = Vec::new(); // (frag_id, exported_vid, path)
    for entry in &entries {
        let stem = entry.path().file_stem()
            .and_then(|s| s.to_str())
            .map(str::to_string);
        let Some(hex) = stem else { continue };
        let Some(exported_vid) = Id::from_hex(hex.trim()) else {
            eprintln!("skip {}: invalid version id", entry.path().display());
            continue;
        };
        let Some(&frag_id) = vid_to_frag.get(&exported_vid) else {
            eprintln!("skip {}: unknown version (not in wiki)", entry.path().display());
            continue;
        };
        work.push((frag_id, exported_vid, entry.path()));
    }

    // CAS loop: checkout -> check versions -> build changes -> commit -> try_push.
    // On conflict, take the new workspace and retry.
    loop {
        let space = ws.checkout(..)
            .map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;

        let curr_latest = latest_versions(&space);

        // Build change set: only fragments whose latest version matches export.
        let mut change = TribleSet::new();
        let mut updated = 0u32;

        for (frag_id, exported_vid, path) in &work {
            let still_latest = curr_latest.get(frag_id)
                .map_or(false, |(current, _)| *current == *exported_vid);
            if !still_latest {
                eprintln!("CONFLICT {:x} — skipping", frag_id);
                continue;
            }

            let new_content = fs::read_to_string(path)
                .with_context(|| format!("read {}", path.display()))?;

            let existing_content = content_handle_of(&space, *exported_vid)
                .and_then(|ch| ws.get::<View<str>, _>(ch).ok())
                .map(|v| v.as_ref().to_string())
                .unwrap_or_default();
            if new_content == existing_content { continue; }

            // Lint-fix then validate typst
            let new_content = lint_fix(&new_content, &space);
            if let Err(e) = validate_typst(&new_content) {
                eprintln!("TYPST_ERROR {}: {}", path.display(), e);
                continue;
            }

            let tag_ids = tags_of(&space, *exported_vid);
            let title = read_title(&space, &mut ws, *exported_vid).unwrap_or_default();
            let content_handle = ws.put(new_content);
            let content_text = ws.get::<View<str>, _>(content_handle)
                .map_err(|e| anyhow::anyhow!("read: {e:?}"))?
                .as_ref()
                .to_string();
            let mut all_tags = tag_ids;
            all_tags.push(KIND_VERSION_ID);
            all_tags.sort(); all_tags.dedup();
            let title_handle = ws.put(title);
            let version = entity! { _ @
                wiki::fragment: frag_id,
                wiki::title: title_handle,
                wiki::content: content_handle,
                metadata::created_at: now_tai(),
                metadata::tag*: all_tags.iter(),
            };
            let version_id = version.root().expect("version should be rooted");
            change += version;
            change += extract_references(&content_text, &space, version_id);
            updated += 1;
        }

        if updated == 0 {
            eprintln!("Nothing to import (all unchanged or conflicted).");
            return Ok(());
        }

        ws.commit(change, "wiki import-all");
        match repo.try_push(&mut ws) {
            Ok(None) => {
                eprintln!("Imported: {} updated, {} total files", updated, entries.len());
                return Ok(());
            }
            Ok(Some(conflict_ws)) => {
                eprintln!("Push conflict — retrying...");
                ws = conflict_ws;
            }
            Err(e) => bail!("push failed: {e:?}"),
        }
    }
}

fn cmd_create(
    repo: &mut Repo,
    bid: Id,
    title: String,
    content: String,
    tags: Vec<String>,
    force: bool,
) -> Result<()> {
    let title = load_value_or_file(&title, "title")?;
    let content = load_value_or_file(&content, "content")?;

    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    ensure_tag_vocabulary(repo, &mut ws)?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let mut change = TribleSet::new();
    let tag_ids = resolve_tags(&space, &mut ws, &tags, &mut change);

    // Lint-fix then validate typst compilation and link targets.
    let content = lint_fix(&content, &space);
    validate_typst(&content)?;
    validate_wiki_links(&content, &space)?;

    let fragment_id = genid().id;
    let content_handle = ws.put(content);
    let vid = commit_version(
        repo, &mut ws, change, fragment_id, &title, content_handle, &tag_ids, &space, "wiki create", force,
    )?;

    println!("fragment {}", fragment_id);
    println!("version  {}", vid);
    Ok(())
}

fn cmd_edit(
    repo: &mut Repo,
    bid: Id,
    id: String,
    content: Option<String>,
    new_title: Option<String>,
    tags: Vec<String>,
    force: bool,
) -> Result<()> {
    let content = content.map(|c| load_value_or_file(&c, "content")).transpose()?;
    let new_title = new_title.map(|t| load_value_or_file(&t, "title")).transpose()?;
    if content.is_none() && new_title.is_none() && tags.is_empty() {
        bail!("nothing to change — provide content, --title, or --tag");
    }

    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let resolved = resolve_prefix(&space, &id)?;
    let fragment_id = to_fragment(&space, resolved)?;
    let prev_vid = latest_version_of(&space, fragment_id)
        .ok_or_else(|| anyhow::anyhow!("no versions for fragment {}", fragment_id))?;

    ensure_tag_vocabulary(repo, &mut ws)?;
    let mut change = TribleSet::new();
    let tag_ids = if tags.is_empty() {
        tags_of(&space, prev_vid)
    } else {
        resolve_tags(&space, &mut ws, &tags, &mut change)
    };

    let title = new_title.unwrap_or_else(|| {
        read_title(&space, &mut ws, prev_vid).unwrap_or_default()
    });
    // Validate typst if tagged (either explicitly or inherited)
    let content_handle = match &content {
        Some(text) => {
            // Lint-fix then validate typst compilation and link targets.
            let fixed = lint_fix(text, &space);
            validate_typst(&fixed)?;
            validate_wiki_links(&fixed, &space)?;
            ws.put(fixed)
        }
        None => content_handle_of(&space, prev_vid)
            .ok_or_else(|| anyhow::anyhow!("no content on previous version"))?,
    };
    let vid = commit_version(
        repo, &mut ws, change, fragment_id, &title, content_handle, &tag_ids, &space, "wiki edit", force,
    )?;

    println!("fragment {}", fragment_id);
    println!("version  {}", vid);
    Ok(())
}

fn cmd_show(repo: &mut Repo, bid: Id, id: String, follow_latest: bool) -> Result<()> {
    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let parsed_id = resolve_prefix(&space, &id)?;
    let vid = resolve_to_show(&space, parsed_id, follow_latest)?;
    let fragment_id = version_fragment(&space, vid)
        .ok_or_else(|| anyhow::anyhow!("version has no fragment"))?;

    let content_h = content_handle_of(&space, vid)
        .ok_or_else(|| anyhow::anyhow!("no content"))?;
    let content: View<str> = ws.get(content_h)
        .map_err(|e| anyhow::anyhow!("read content: {e:?}"))?;
    let title = read_title(&space, &mut ws, vid).unwrap_or_default();
    let tags = tags_of(&space, vid);
    let created_at = created_at_of(&space, vid).unwrap_or(Lower(0));

    println!("# {title}");
    println!(
        "fragment: {}  version: {}  date: {}",
        format!("{:x}", fragment_id), vid, format_date(created_at),
    );
    let tag_str = format_tags(&space, &mut ws, &tags);
    if !tag_str.is_empty() {
        println!("tags:{tag_str}");
    }
    println!();
    print!("{}", content.as_ref());

    let (outgoing, incoming, external) = find_links(&space, &mut ws, fragment_id)?;
    if !outgoing.is_empty() || !incoming.is_empty() || !external.is_empty() {
        println!("\n---");
    }
    for target in &outgoing {
        let label = link_label(&space, &mut ws, *target);
        println!("{label}");
    }
    for source in &incoming {
        let label = link_label(&space, &mut ws, *source);
        println!("{label}");
    }
    for (faculty, hex) in &external {
        println!("{faculty}:{hex}");
    }

    Ok(())
}

fn cmd_export(repo: &mut Repo, bid: Id, id: String) -> Result<()> {
    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let parsed_id = resolve_prefix(&space, &id)?;
    let vid = resolve_to_show(&space, parsed_id, false)?;
    let ch = content_handle_of(&space, vid)
        .ok_or_else(|| anyhow::anyhow!("no content"))?;
    let content: View<str> = ws.get(ch)
        .map_err(|e| anyhow::anyhow!("read content: {e:?}"))?;
    print!("{}", content.as_ref());
    Ok(())
}

fn cmd_diff(
    repo: &mut Repo,
    bid: Id,
    id: String,
    from: Option<usize>,
    to: Option<usize>,
) -> Result<()> {
    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let resolved = resolve_prefix(&space, &id)?;
    let fragment_id = to_fragment(&space, resolved)?;
    let history = version_history_of(&space, fragment_id);
    let n = history.len();
    if n < 2 {
        bail!(
            "fragment {} has only {n} version(s), need at least 2 to diff",
            format!("{:x}", fragment_id)
        );
    }

    let from_idx = from.map(|v| v.saturating_sub(1)).unwrap_or(n - 2);
    let to_idx = to.map(|v| v.saturating_sub(1)).unwrap_or(n - 1);
    if from_idx >= n || to_idx >= n {
        bail!("version index out of range (fragment has {n} versions)");
    }

    let old_vid = history[from_idx];
    let new_vid = history[to_idx];

    let old_ch = content_handle_of(&space, old_vid).ok_or_else(|| anyhow::anyhow!("no content"))?;
    let new_ch = content_handle_of(&space, new_vid).ok_or_else(|| anyhow::anyhow!("no content"))?;
    let old_content: View<str> = ws.get(old_ch).map_err(|e| anyhow::anyhow!("read old content: {e:?}"))?;
    let new_content: View<str> = ws.get(new_ch).map_err(|e| anyhow::anyhow!("read new content: {e:?}"))?;

    let old_title = read_title(&space, &mut ws, old_vid).unwrap_or_default();
    let new_title = read_title(&space, &mut ws, new_vid).unwrap_or_default();

    println!("--- v{} {}  {}", from_idx + 1, old_vid, old_title);
    println!("+++ v{} {}  {}", to_idx + 1, new_vid, new_title);

    let old_tags = format_tags(&space, &mut ws, &tags_of(&space, old_vid));
    let new_tags = format_tags(&space, &mut ws, &tags_of(&space, new_vid));
    if old_tags != new_tags {
        println!("- tags:{old_tags}");
        println!("+ tags:{new_tags}");
    }

    let old_lines: Vec<&str> = old_content.as_ref().lines().collect();
    let new_lines: Vec<&str> = new_content.as_ref().lines().collect();
    let hunks = unified_diff(&old_lines, &new_lines, 3);

    if hunks.is_empty() && old_tags == new_tags && old_title == new_title {
        println!("(no changes)");
    }
    for line in hunks {
        println!("{line}");
    }

    Ok(())
}

fn cmd_archive(repo: &mut Repo, bid: Id, id: String) -> Result<()> {
    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let resolved = resolve_prefix(&space, &id)?;
    let fragment_id = to_fragment(&space, resolved)?;
    let prev_vid = latest_version_of(&space, fragment_id)
        .ok_or_else(|| anyhow::anyhow!("no versions for fragment {}", fragment_id))?;
    let prev_tags = tags_of(&space, prev_vid);
    let prev_title = read_title(&space, &mut ws, prev_vid).unwrap_or_default();

    if prev_tags.contains(&TAG_ARCHIVED_ID) {
        println!("already archived: {} ({})", prev_title, fragment_id);
        return Ok(());
    }

    ensure_tag_vocabulary(repo, &mut ws)?;
    let mut tags = prev_tags;
    tags.push(TAG_ARCHIVED_ID);
    let prev_ch = content_handle_of(&space, prev_vid)
        .ok_or_else(|| anyhow::anyhow!("no content"))?;
    commit_version(
        repo, &mut ws, TribleSet::new(), fragment_id, &prev_title, prev_ch, &tags,
        &space, "wiki archive", true,
    )?;

    println!("archived: {} ({})", prev_title, fragment_id);
    Ok(())
}

fn cmd_restore(repo: &mut Repo, bid: Id, id: String) -> Result<()> {
    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let resolved = resolve_prefix(&space, &id)?;
    let fragment_id = to_fragment(&space, resolved)?;
    let prev_vid = latest_version_of(&space, fragment_id)
        .ok_or_else(|| anyhow::anyhow!("no versions for fragment {}", fragment_id))?;
    let prev_tags = tags_of(&space, prev_vid);
    let prev_title = read_title(&space, &mut ws, prev_vid).unwrap_or_default();

    if !prev_tags.contains(&TAG_ARCHIVED_ID) {
        println!("not archived: {} ({})", prev_title, fragment_id);
        return Ok(());
    }

    let tags: Vec<Id> = prev_tags.into_iter().filter(|t| *t != TAG_ARCHIVED_ID).collect();
    let prev_ch = content_handle_of(&space, prev_vid)
        .ok_or_else(|| anyhow::anyhow!("no content"))?;
    commit_version(
        repo, &mut ws, TribleSet::new(), fragment_id, &prev_title, prev_ch, &tags,
        &space, "wiki restore", true,
    )?;

    println!("restored: {} ({})", prev_title, fragment_id);
    Ok(())
}

fn cmd_revert(repo: &mut Repo, bid: Id, id: String, to: usize) -> Result<()> {
    if to == 0 {
        bail!("version number is 1-based");
    }

    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let resolved = resolve_prefix(&space, &id)?;
    let fragment_id = to_fragment(&space, resolved)?;
    let history = version_history_of(&space, fragment_id);

    let idx = to - 1;
    if idx >= history.len() {
        bail!(
            "fragment {} has {} version(s), cannot revert to v{to}",
            format!("{:x}", fragment_id), history.len(),
        );
    }

    let target_vid = history[idx];
    let target_title = read_title(&space, &mut ws, target_vid).unwrap_or_default();
    let target_ch = content_handle_of(&space, target_vid)
        .ok_or_else(|| anyhow::anyhow!("no content"))?;
    let target_tags = tags_of(&space, target_vid);
    let vid = commit_version(
        repo, &mut ws, TribleSet::new(), fragment_id, &target_title, target_ch,
        &target_tags, &space, "wiki revert", true,
    )?;

    println!("reverted {} ({}) to v{to}: {}", fragment_id, vid, target_title);
    Ok(())
}

fn cmd_links(repo: &mut Repo, bid: Id, id: String) -> Result<()> {
    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let resolved = resolve_prefix(&space, &id)?;
    let title = if is_version(&space, resolved) {
        read_title(&space, &mut ws, resolved).unwrap_or_else(|| "?".into())
    } else {
        latest_version_of(&space, resolved)
            .and_then(|vid| read_title(&space, &mut ws, vid))
            .unwrap_or_else(|| "?".into())
    };
    let (outgoing, incoming, external) = find_links(&space, &mut ws, resolved)?;

    println!("# Links for: {} ({})", title, resolved);

    if !outgoing.is_empty() {
        println!("\n→ outgoing:");
        for target in &outgoing {
            println!("{}", link_label(&space, &mut ws, *target));
        }
    }
    if !incoming.is_empty() {
        println!("\n← incoming:");
        for source in &incoming {
            println!("{}", link_label(&space, &mut ws, *source));
        }
    }
    if !external.is_empty() {
        println!("\n⇢ external:");
        for (faculty, hex) in &external {
            println!("{faculty}:{hex}");
        }
    }
    if outgoing.is_empty() && incoming.is_empty() && external.is_empty() {
        println!("\n(no links)");
    }

    Ok(())
}

fn cmd_list(
    repo: &mut Repo,
    bid: Id,
    filter_tags: Vec<String>,
    with_backlink_tag: Vec<String>,
    without_backlink_tag: Vec<String>,
    with_backlink_type: Vec<String>,
    without_backlink_type: Vec<String>,
    show_all: bool,
) -> Result<()> {
    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let filter_ids: Vec<Id> = filter_tags
        .iter()
        .filter_map(|name| {
            let name = name.trim().to_lowercase();
            find_tag_by_name(&space, &mut ws, &name)
        })
        .collect();

    let with_bl_ids: Vec<Id> = with_backlink_tag
        .iter()
        .filter_map(|name| find_tag_by_name(&space, &mut ws, &name.trim().to_lowercase()))
        .collect();
    let without_bl_ids: Vec<Id> = without_backlink_tag
        .iter()
        .filter_map(|name| find_tag_by_name(&space, &mut ws, &name.trim().to_lowercase()))
        .collect();
    // Derive attribute IDs for typed backlink filters.
    let with_bl_type_attrs: Vec<(String, triblespace::core::attribute::Attribute<valueschemas::GenId>)> =
        with_backlink_type.iter()
            .map(|name| (name.clone(), triblespace::core::attribute::Attribute::<valueschemas::GenId>::from_name(name)))
            .collect();
    let without_bl_type_attrs: Vec<(String, triblespace::core::attribute::Attribute<valueschemas::GenId>)> =
        without_backlink_type.iter()
            .map(|name| (name.clone(), triblespace::core::attribute::Attribute::<valueschemas::GenId>::from_name(name)))
            .collect();
    let has_backlink_filter = !with_bl_ids.is_empty() || !without_bl_ids.is_empty()
        || !with_bl_type_attrs.is_empty() || !without_bl_type_attrs.is_empty();

    let latest = latest_versions(&space);

    let mut entries: Vec<(Id, Id, Lower)> = latest.into_iter()
        .map(|(frag, (vid, ts))| (frag, vid, ts))
        .collect();
    entries.sort_by(|a, b| b.2.cmp(&a.2));

    // Set of latest version IDs for backlink filtering.
    let latest_vids: std::collections::HashSet<Id> =
        entries.iter().map(|(_, vid, _)| *vid).collect();

    for (frag_id, vid, created_at) in &entries {
        let tags = tags_of(&space, *vid);
        if !show_all && tags.contains(&TAG_ARCHIVED_ID) {
            continue;
        }
        if !filter_ids.is_empty() && !filter_ids.iter().all(|ft| tags.contains(ft)) {
            continue;
        }

        // Backlink tag filter: check tags of latest versions that link TO any
        // version of this fragment (or the fragment ID itself).
        if has_backlink_filter {
            // Targets = {frag_id} ∪ {every version of frag_id}. A single
            // pattern with `SortedSlice::has(target)` constrains the target
            // slot to any of these — one constraint, one pattern, no union.
            let mut targets: Vec<Id> = version_history_of(&space, *frag_id);
            targets.push(*frag_id);
            targets.sort();
            targets.dedup();
            let targets_slice = triblespace::core::query::sortedsliceconstraint::SortedSlice::new_unchecked(&targets);

            let all_backlinks: Vec<Id> = find!(
                src: Id,
                temp!((target),
                    and!(
                        pattern!(&space, [{ ?src @ wiki::links_to: ?target }]),
                        targets_slice.has(target),
                    )
                )
            ).collect();

            let mut backlink_tags: Vec<Id> = Vec::new();
            for &source_vid in &all_backlinks {
                if latest_vids.contains(&source_vid) {
                    backlink_tags.extend(tags_of(&space, source_vid));
                }
            }

            if !with_bl_ids.is_empty()
                && !with_bl_ids.iter().all(|t| backlink_tags.contains(t))
            {
                continue;
            }
            if !without_bl_ids.is_empty()
                && without_bl_ids.iter().any(|t| backlink_tags.contains(t))
            {
                continue;
            }

            // Typed backlink filter: does any latest-version entity have a
            // derived-attribute edge of the given type pointing to *any* version
            // of this fragment (or to the fragment id itself)? Same single-pattern
            // trick — target constrained to the sorted target slice.
            let check_type_target = |attr: &triblespace::core::attribute::Attribute<valueschemas::GenId>| -> bool {
                find!(
                    src: Id,
                    temp!((target),
                        and!(
                            pattern!(&space, [{ ?src @ attr: ?target }]),
                            targets_slice.has(target),
                        )
                    )
                ).any(|src| latest_vids.contains(&src))
            };
            if !with_bl_type_attrs.is_empty() {
                let all_present = with_bl_type_attrs.iter()
                    .all(|(_, attr)| check_type_target(attr));
                if !all_present { continue; }
            }
            if !without_bl_type_attrs.is_empty() {
                let any_present = without_bl_type_attrs.iter()
                    .any(|(_, attr)| check_type_target(attr));
                if any_present { continue; }
            }
        }

        let title = read_title(&space, &mut ws, *vid).unwrap_or_default();
        let tag_str = format_tags(&space, &mut ws, &tags);
        let n_versions = version_history_of(&space, *frag_id).len();
        let ver_str = if n_versions > 1 {
            format!(" (v{})", n_versions)
        } else {
            String::new()
        };

        println!(
            "{}  {}  {}{}{}",
            format!("{:x}", frag_id), format_date(*created_at), title, tag_str, ver_str,
        );

        if let Some(ch) = content_handle_of(&space, *vid) {
            if let Ok(view) = ws.get(ch) {
                let view: View<str> = view;
                if let Some(line) = view.as_ref().lines().find(|l| !l.trim().is_empty()) {
                    let preview = line.trim();
                    let truncated: String = preview.chars().take(77).collect();
                    if truncated.len() < preview.len() {
                        println!("    {truncated}...");
                    } else {
                        println!("    {preview}");
                    }
                }
            }
        }
    }
    Ok(())
}

fn cmd_history(repo: &mut Repo, bid: Id, id: String) -> Result<()> {
    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let resolved = resolve_prefix(&space, &id)?;
    let fragment_id = to_fragment(&space, resolved)?;
    let history = version_history_of(&space, fragment_id);

    let latest_title = history.last()
        .and_then(|vid| read_title(&space, &mut ws, *vid))
        .unwrap_or_else(|| "?".into());
    println!("# History: {} ({})", latest_title, fragment_id);
    println!();

    for (i, vid) in history.iter().enumerate() {
        let title = read_title(&space, &mut ws, *vid).unwrap_or_default();
        let ts = created_at_of(&space, *vid).unwrap_or(Lower(0));
        let tags = tags_of(&space, *vid);
        println!(
            "  v{}  {}  {}  {}{}",
            i + 1, vid, format_date(ts), title, format_tags(&space, &mut ws, &tags),
        );
    }
    Ok(())
}

fn cmd_tag_add(repo: &mut Repo, bid: Id, id: String, name: String) -> Result<()> {
    let name = name.trim().to_lowercase();
    if name.is_empty() {
        bail!("tag name cannot be empty");
    }
    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let resolved = resolve_prefix(&space, &id)?;
    let fragment_id = to_fragment(&space, resolved)?;
    let prev_vid = latest_version_of(&space, fragment_id)
        .ok_or_else(|| anyhow::anyhow!("no versions for fragment {}", fragment_id))?;

    ensure_tag_vocabulary(repo, &mut ws)?;
    let mut change = TribleSet::new();
    let new_tag = resolve_tags(&space, &mut ws, &[name.clone()], &mut change)[0];

    let prev_tags = tags_of(&space, prev_vid);
    if prev_tags.contains(&new_tag) {
        println!("already tagged: #{name}");
        return Ok(());
    }

    let mut tags = prev_tags;
    tags.push(new_tag);
    let prev_title = read_title(&space, &mut ws, prev_vid).unwrap_or_default();
    let prev_ch = content_handle_of(&space, prev_vid)
        .ok_or_else(|| anyhow::anyhow!("no content"))?;
    commit_version(
        repo, &mut ws, change, fragment_id, &prev_title, prev_ch, &tags,
        &space, "wiki tag add", true,
    )?;

    println!("added #{name} to {} ({})", prev_title, fragment_id);
    Ok(())
}

fn cmd_tag_remove(repo: &mut Repo, bid: Id, id: String, name: String) -> Result<()> {
    let name = name.trim().to_lowercase();
    if name.is_empty() {
        bail!("tag name cannot be empty");
    }
    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let resolved = resolve_prefix(&space, &id)?;
    let fragment_id = to_fragment(&space, resolved)?;
    let prev_vid = latest_version_of(&space, fragment_id)
        .ok_or_else(|| anyhow::anyhow!("no versions for fragment {}", fragment_id))?;

    let tag_id = find_tag_by_name(&space, &mut ws, &name)
        .ok_or_else(|| anyhow::anyhow!("unknown tag '{name}'"))?;
    let prev_tags = tags_of(&space, prev_vid);
    if !prev_tags.contains(&tag_id) {
        println!("not tagged: #{name}");
        return Ok(());
    }

    let tags: Vec<Id> = prev_tags.into_iter().filter(|t| *t != tag_id).collect();
    let prev_title = read_title(&space, &mut ws, prev_vid).unwrap_or_default();
    let prev_ch = content_handle_of(&space, prev_vid)
        .ok_or_else(|| anyhow::anyhow!("no content"))?;
    commit_version(
        repo, &mut ws, TribleSet::new(), fragment_id, &prev_title, prev_ch, &tags,
        &space, "wiki tag remove", true,
    )?;

    println!("removed #{name} from {} ({})", prev_title, fragment_id);
    Ok(())
}

fn cmd_tag_list(repo: &mut Repo, bid: Id) -> Result<()> {
    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let mut counts: HashMap<Id, usize> = HashMap::new();
    for (tag_id,) in find!(
        (tag_id: Id),
        pattern!(&space, [{ _?vid @ metadata::tag: &KIND_VERSION_ID, metadata::tag: ?tag_id }])
    ) {
        if tag_id != KIND_VERSION_ID {
            *counts.entry(tag_id).or_default() += 1;
        }
    }

    // Build name→id map from all named entities.
    let mut all_named: Vec<(String, Id, usize)> = Vec::new();
    for (id, handle) in find!(
        (id: Id, h: TextHandle),
        pattern!(&space, [{ ?id @ metadata::name: ?h }])
    ) {
        if let Ok(view) = ws.get::<View<str>, _>(handle) {
            let name = view.as_ref().to_string();
            let count = counts.get(&id).copied().unwrap_or(0);
            all_named.push((name, id, count));
        }
    }
    let mut entries = all_named;
    entries.sort_by(|a, b| b.2.cmp(&a.2).then(a.0.cmp(&b.0)));

    for (name, id, count) in entries {
        println!("{}  {}  ({})", id, name, count);
    }
    Ok(())
}

fn cmd_tag_mint(repo: &mut Repo, bid: Id, name: String) -> Result<()> {
    let name = name.trim().to_lowercase();
    if name.is_empty() {
        bail!("tag name cannot be empty");
    }

    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    if let Some(existing) = find_tag_by_name(&space, &mut ws, &name) {
        println!("tag '{}' already exists: {}", name, existing);
        return Ok(());
    }

    let tag_id = genid();
    let tag_ref = tag_id.id;
    let name_handle = ws.put(name.clone());
    let mut change = TribleSet::new();
    change += entity! { &tag_id @ metadata::name: name_handle };

    ws.commit(change, "wiki mint tag");
    repo.push(&mut ws)
        .map_err(|e| anyhow::anyhow!("push: {e:?}"))?;

    println!("{}  {}", tag_ref, name);
    Ok(())
}

fn cmd_import(repo: &mut Repo, bid: Id, path: PathBuf, tags: Vec<String>) -> Result<()> {
    let files = if path.is_dir() {
        let mut entries: Vec<PathBuf> = Vec::new();
        collect_typ_files(&path, &mut entries)?;
        entries.sort();
        entries
    } else {
        vec![path]
    };

    if files.is_empty() {
        println!("no .typ files found");
        return Ok(());
    }

    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    ensure_tag_vocabulary(repo, &mut ws)?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    for file in &files {
        let content = fs::read_to_string(file)
            .with_context(|| format!("read {}", file.display()))?;

        let title = content
            .lines()
            .find(|l| l.starts_with("= "))
            .map(|l| l.trim_start_matches('=').trim().to_string())
            .unwrap_or_else(|| {
                file.file_stem()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .to_string()
            });

        let mut change = TribleSet::new();
        let tag_ids = resolve_tags(&space, &mut ws, &tags, &mut change);
        let fragment_id = genid().id;
        let content_handle = ws.put(content);
        let vid = commit_version(
            repo, &mut ws, change, fragment_id, &title, content_handle, &tag_ids, &space, "wiki import", true,
        )?;

        println!("{}  {}  {}", fragment_id, vid, file.display());
    }

    Ok(())
}

fn collect_typ_files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
    for entry in fs::read_dir(dir).with_context(|| format!("read dir {}", dir.display()))? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            collect_typ_files(&path, out)?;
        } else if path.extension().is_some_and(|e| e == "typ") {
            out.push(path);
        }
    }
    Ok(())
}

fn cmd_search(
    repo: &mut Repo,
    bid: Id,
    query: String,
    show_context: bool,
    show_all: bool,
) -> Result<()> {
    let query_lower = query.to_lowercase();

    let mut ws = repo.pull(bid).map_err(|e| anyhow::anyhow!("pull: {e:?}"))?;
    let space = ws.checkout(..).map_err(|e| anyhow::anyhow!("checkout: {e:?}"))?;
    let latest = latest_versions(&space);

    let mut hits: Vec<(Id, Id, Lower, String, Vec<Id>, Vec<String>)> = Vec::new();

    for (&frag_id, &(vid, created_at)) in &latest {
        let tags = tags_of(&space, vid);
        if !show_all && tags.contains(&TAG_ARCHIVED_ID) {
            continue;
        }
        let title = read_title(&space, &mut ws, vid).unwrap_or_default();
        let ch = match content_handle_of(&space, vid) {
            Some(ch) => ch,
            None => continue,
        };
        let content: View<str> = ws.get(ch)
            .map_err(|e| anyhow::anyhow!("read content: {e:?}"))?;
        let content_str = content.as_ref();

        let title_match = title.to_lowercase().contains(&query_lower);
        let content_lower = content_str.to_lowercase();
        let content_match = content_lower.contains(&query_lower);

        if title_match || content_match {
            let mut context_lines = Vec::new();
            if show_context && content_match {
                for line in content_str.lines() {
                    if line.to_lowercase().contains(&query_lower) {
                        context_lines.push(line.to_string());
                    }
                }
            }
            hits.push((frag_id, vid, created_at, title, tags, context_lines));
        }
    }

    hits.sort_by(|a, b| b.2.cmp(&a.2));

    if hits.is_empty() {
        println!("no matches for '{query}'");
        return Ok(());
    }

    for (frag_id, _vid, created_at, title, tags, context_lines) in &hits {
        println!(
            "{}  {}  {}{}",
            format!("{:x}", frag_id), format_date(*created_at), title, format_tags(&space, &mut ws, tags),
        );
        for line in context_lines {
            println!("    {}", line.trim());
        }
    }

    Ok(())
}

// ── diff engine ────────────────────────────────────────────────────────────

enum DiffOp<'a> {
    Equal(&'a str),
    Add(&'a str),
    Remove(&'a str),
}

/// Produce unified-style diff lines with `context` lines of surrounding context.
fn unified_diff<'a>(old: &[&'a str], new: &[&'a str], context: usize) -> Vec<String> {
    let table = lcs_table(old, new);

    // Walk LCS table backwards to produce diff ops.
    let mut ops: Vec<DiffOp<'a>> = Vec::new();
    let (mut i, mut j) = (old.len(), new.len());
    while i > 0 || j > 0 {
        if i > 0 && j > 0 && old[i - 1] == new[j - 1] {
            ops.push(DiffOp::Equal(old[i - 1]));
            i -= 1;
            j -= 1;
        } else if j > 0 && (i == 0 || table[i][j - 1] >= table[i - 1][j]) {
            ops.push(DiffOp::Add(new[j - 1]));
            j -= 1;
        } else {
            ops.push(DiffOp::Remove(old[i - 1]));
            i -= 1;
        }
    }
    ops.reverse();

    // Mark which ops are near a change and should be shown.
    let change_indices: Vec<usize> = ops
        .iter()
        .enumerate()
        .filter(|(_, op)| !std::matches!(op, DiffOp::Equal(_)))
        .map(|(i, _)| i)
        .collect();

    if change_indices.is_empty() {
        return Vec::new();
    }

    let mut shown = vec![false; ops.len()];
    for &ci in &change_indices {
        let start = ci.saturating_sub(context);
        let end = (ci + context + 1).min(ops.len());
        for idx in start..end {
            shown[idx] = true;
        }
    }

    let mut lines = Vec::new();
    let mut in_hunk = false;
    for (idx, op) in ops.iter().enumerate() {
        if shown[idx] {
            if !in_hunk && idx > 0 {
                lines.push("---".to_string());
            }
            in_hunk = true;
            match op {
                DiffOp::Equal(line) => lines.push(format!(" {line}")),
                DiffOp::Add(line) => lines.push(format!("+{line}")),
                DiffOp::Remove(line) => lines.push(format!("-{line}")),
            }
        } else {
            in_hunk = false;
        }
    }

    lines
}

fn lcs_table(old: &[&str], new: &[&str]) -> Vec<Vec<usize>> {
    let (m, n) = (old.len(), new.len());
    let mut table = vec![vec![0usize; n + 1]; m + 1];
    for i in 1..=m {
        for j in 1..=n {
            table[i][j] = if old[i - 1] == new[j - 1] {
                table[i - 1][j - 1] + 1
            } else {
                table[i - 1][j].max(table[i][j - 1])
            };
        }
    }
    table
}

// ── main ───────────────────────────────────────────────────────────────────
fn main() -> Result<()> {
    let cli = Cli::parse();

    let Some(command) = cli.command else {
        let mut cmd = Cli::command();
        cmd.print_help()?;
        println!();
        return Ok(());
    };

    let pile = Pile::<valueschemas::Blake3>::open(&cli.pile)
        .map_err(|e| anyhow::anyhow!("open pile: {e:?}"))?;
    let signing_key = SigningKey::generate(&mut OsRng);
    let mut repo = Repository::new(pile, signing_key, TribleSet::new())
        .map_err(|e| anyhow::anyhow!("create repo: {e:?}"))?;

    let branch_id = if let Some(hex) = cli.branch_id.as_deref() {
        Id::from_hex(hex.trim()).ok_or_else(|| anyhow::anyhow!("invalid branch id"))?
    } else {
        repo.ensure_branch(WIKI_BRANCH_NAME, None)
            .map_err(|e| anyhow::anyhow!("ensure wiki branch: {e:?}"))?
    };

    let result = match command {
        Command::Create { title, content, tag, force } => {
            cmd_create(&mut repo, branch_id, title, content, tag, force)
        }
        Command::Edit {
            id,
            content,
            title,
            tag,
            force,
        } => cmd_edit(&mut repo, branch_id, id, content, title, tag, force),
        Command::Show { id, latest } => cmd_show(&mut repo, branch_id, id, latest),
        Command::Export { id } => cmd_export(&mut repo, branch_id, id),
        Command::Diff { id, from, to } => cmd_diff(&mut repo, branch_id, id, from, to),
        Command::Archive { id } => cmd_archive(&mut repo, branch_id, id),
        Command::Restore { id } => cmd_restore(&mut repo, branch_id, id),
        Command::Revert { id, to } => cmd_revert(&mut repo, branch_id, id, to),
        Command::Links { id } => cmd_links(&mut repo, branch_id, id),
        Command::List { tag, with_backlink_tag, without_backlink_tag, with_backlink_type, without_backlink_type, all } =>
            cmd_list(&mut repo, branch_id, tag, with_backlink_tag, without_backlink_tag, with_backlink_type, without_backlink_type, all),
        Command::History { id } => cmd_history(&mut repo, branch_id, id),
        Command::Tag { command: tag_cmd } => match tag_cmd {
            TagCommand::Add { id, name } => cmd_tag_add(&mut repo, branch_id, id, name),
            TagCommand::Remove { id, name } => cmd_tag_remove(&mut repo, branch_id, id, name),
            TagCommand::List => cmd_tag_list(&mut repo, branch_id),
            TagCommand::Mint { name } => cmd_tag_mint(&mut repo, branch_id, name),
        },
        Command::Import { path, tag } => cmd_import(&mut repo, branch_id, path, tag),
        Command::Search { query, context, all } => {
            cmd_search(&mut repo, branch_id, query, context, all)
        }
        Command::Check { compile } => cmd_check(&mut repo, branch_id, compile),
        Command::Batch { action } => match action {
            BatchAction::Export { dir } => cmd_export_all(&mut repo, branch_id, dir),
            BatchAction::Import { dir } => cmd_import_all(&mut repo, branch_id, dir),
        },
        Command::FixTruncated { input } => cmd_fix_truncated(&mut repo, branch_id, input),
        Command::Lint { fix, check } => cmd_lint(&mut repo, branch_id, fix, check),
    };

    repo.close().map_err(|e| anyhow::anyhow!("close: {e:?}"))?;
    result
}