areev-server 1.6.0

Web console and sync-hub server for Areev.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
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
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
<!doctype html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Areev</title>
<link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAL60lEQVR42u1be5RVVRn/fXufc+65j3ncecIwzAzD8NAZRtFa4KuVDx4+UCrQBAEthSTLzDIr16rVWpWR4aqlS0vMFDMzxSwUNRIwclFBvAQGGAYGgRma98x9nnP2/vpjoCSBewYYHqv51tr/3H324/fbv/N93/7WucCADdiADdiA/f8anc7Fqr+wGawVjFABSBgf6WetoJLtABG2P/dJeInWft+TOB3AR81eiYsfciEDObCyhwKsDQDWRxubgbxKGMEooheMQ809W899BQSLx6B63kZ4iTYoJz5ESGsGiC4FKHCUxxWYNzLUYiGD2+P/Wg4VS6FhyZxzl4Dq+f+ENPPBWpUKw34WJK7KPIo3M3t3kDDXERE2PFJ8br4CgWgl3NguGMFSkGHN8gceAGgMQd7nJVtML9WJ4KALzk0F1MzfDBHIBliVkQguA+h8/6O5hbV3HUis1W4K7z82/NxSgLRzoFItMIJlILJm9A08AFAhkfzsuAdLwCp17img5os7IUwbgB5GwloG0Ki+z8J7WXuTAdqm3QTef3zkuaMA5cRhZQ0GkXnbiYEHACoDyZuNUAGU03PuKKBm/jYIKwtgriJpLAOo6oQnY65j5UwCYa8Ta0Ld0+PPfgVoN4lg4RBAiNknBR4AiEZDGFOFlY25i8ad/Qqo/sJmyEAOwDySpPUmiIad9KTMf9Ne8nqA2tKdDdix+OqzUwF2/igoJ46cEUMBYcw5JeB7VXARCXOisMIIl3z81EarUznZyNkrYITykWrrHC2E+SMQ5WYYkgbrehDlZVCjJELQS7S9qpyYFyquRdfOpWeXAsKl46HdBIbfVA4S5hwQVWSWtn5Pa/fzAH+QWQXiEzKQdYVh5yJr2NVnnwKqpi+BGSlGR137KCGth/2cPrP6thUufFO7yTIQXZKBAQsAUm11fwSRFjKA+IG/nx0KCBXVQqU6MfgT5SBhzQKJCh+e7R3W7htusg3M6jmAmzK7Ajk5kDtsrBkqRMFFd549r0DZlKcQyBuBppX1o0jIGT6GJAB+UpjBmE63I92+fhNYv+rDGRaSNGdu+mkZVLIDdv6oM09AqKgWbqwZWWUVIMP+LEj48fzvMHvLWbsQZgR2/sWaWT8LcEtmDoxPjflS/WgrtwLlU5468wSU37gIoeJadDfuGk4kZ/o7ff0UCSshrQia/voTeOkuOF171oHZjwrKSAamBQvKkfzXljNLQO99vxnhkgoIw54BEiN8eP63tRNfrt0k4vvXomXt45BmBIFolQL0rwC0+vAF05Mtu0pyqiZhxMxlZ46AymkvIVhUi/j+hkoieZuPIT3M6gkRyE4YdhQ7np8AAGh693tQ6U648eZ/gPXrPkJiDUn7BsPOQ+lVk88MAYHcYfASzQgWlINk4FYQjfRx+m+qVMcqlexA+9bf/ufnlvWLIO0ozHCJp5XzNMAdmfZNJGd6ydbc1o27UTH1mdOfB4y+46+wsobCTbRXCmH9GET5GdB3a+V8Qwayd8pANrb/6oojeg07D2bWYHjJ9iYZyKklEjUZ3oNBEGKtMOy6cPF5aFq94PQpQAbzoNNdsKJloN4q78jMh6+WubH9f3HjzWjb9PxH+vev+BbMrCGwo8Nd1u6vAU5kEiGRmKWdtoCXbMOQqx8+fQoYc88WSDsfKtU1goTxY4DyMsDvYuU8YAQL6oUZws7nJx71KTNcBCurBNpLNgkzdDllDqklENZqEnZjsKgWB9cs7H8F5NXMBKsUjFAJiKSv+z5rtdTpObDaix886ukftn3Lv45Bl9UgkFPRA+29AEBl8IY5BDHLTbRIrZLIq5nR/woYfvMSSDMC7XaPJpILgAw5P3MHa/drRih/N0kT9S9OOf6JWBdBWhGAVTMJczKIijNUNIYIaf+ZpNWUXXlNn1Ug+ib9erBy0bRmIQHyTsDHjQ+81Eu0r1GpLnTvzByzd/32JqQ6d8MuqGpi1kt8FAuKicTMhxYOBmuvfytCtffuBYQEGBeTEEsBGpQBfAcr90aQWK29tO/a/vlz18MI5oNZXyiMwFsAFWVYZy9rbxIg6thLY/NjladeAVWz/gRmDZXuESTEXZnBA2B+3Ut3r9FuAm6syfemtv5iLLSXgnZiW8C8wsc5lhHJW41wIdhL9Y8Cxnx5D0iaAOvxJIw/AFSY0fNrbypAK0ECYN3bevvArAEICGn2zksC4P+UVaG9TpDIAmvv0ySMFwAEMqxXz8qbBKIGN9aMbYs+5guX4cvxTX8VrBxop8c0gvl3ZwYPgHktmJvAugICADOYmQ4TANYEAhisiZk/hB4AO2DnoPaSGqAVRHI9iDLUw6kKRNPMUMGCzp3LTq0Cau6phzCDgFZXkDRfAyjqY1g3gA6ABUCH0DH9z9rc20d85O/cxtqZQyQ2kxEEe+n7QeIRH6n2Ju0lrwXoQLq9Hjt+PfHkfUDphEegnRiczkYTJOf6BA8A2QDKARoKoKy30dAPtdL/9nH5h1oZgLEgOXvjo6XQTgLM6jWAd/u4JI0hYU41woW46dBF66QVcMF9+wAIaJW+Skh7CYhycFqMG1m5E0G0o23rSyiovvVxkJjvQwVrvHT3DUTUlmjegIZXbjlxBQyduBBuogVO154ACXPe6QMPAFROwvhcomUDFVTfCga/DKDHhwo+Js3gFDM8CGXX3XxyCrjway1g7UF7qWuEYb8CUPZJIPIA7AGwFcB2EMWPtj5rTxNJApGAVnu0l3wBJNMAR4S0XwXRNZn9r1qlkp1TIURnbM9KNL5xd98JqJiyCOHSS8DKsY1w0WIiOe0EgTsArwLrxQCvZO01SzvfPWa8FhJgDWYGEQFEMEJ58OJt0Cp9F5F8MrPv4jQr5zZhhl6WgRys+77VdwIu+mYMyomDvfS1JM2XAIqcwHu8k1k/DO3+joxQD7QLrRx0734bjX+ch0jppR8ZoVUKJCzQodzBCBeh+JKvIhCtBJhLSVpvA3SeDxUs9RKtt5AwEj0Ny7H3rXv9E1B1yysIFl8I1ioszciLIHFD37HzamZ9jzACG7WbgAzkItmyCXXPXH5iBZjb30XOiCuQam36IUg86GMDMdbeNBLmWwCwceEg/04we/i1kGYWhBmaABJXnwD4d7WXvAPgjU73fmgvjfULsk8YfG8RJh/J1gNg7S4B2McXlBQhkne48YOWl2rH4Mu+6o+A0be/Bzd2AMrpiBCJuQCCfQS/hVnNJ2nVm+ECSDsX7z8+4qRjwp7fz4FKtsFLHNwA1u/4CyQ0yQhGx8tALorG3e+PgOCgWggzCyTDkwG6so9H38qsHhCGvaWrYQWcrn3Y/LPyUxIU401rEYgOh5ld4bL2XgQ47YOBXBLGbO22SO0ljlowOYKA6nmb4CVaoZ1ELpGcD5DdlzDHWi2Y9OiQN7xECyKDL8Tmx6pwKq1l3ZNQyXYoJ76Smf/pM5+4URh5Y4UMo3TCD45PQLCoBsIMgwxrCogu75vy1SvK6XnizS83AEJgy8/HnPLU6IO378e25y6HnTeiA9pb4pOAQhJythvfRKzSMEIFxybA6d4H7cbzCWIeANM/er2NlfNdaWXFhBHE+4+NQn/ZsCnPwun+AFo5fwDrRp8kfMYI19SQjOD8uRuOTQBJC0JaN2S+eh6BvpO195ARLKg7sOo76NzxWr8myPW/uR5Oz350bV+yk1n7vPdSCUHOjA4rAWt1HCdIBABh/8VS3sFa3Zc4uOX3TlcjCsbeicbX7+73W4JhRxGtnsmsvZ+A9SqfEWFWR8P+aiHN4xREmMHAbwhsAVR97EyRHTBvZdbLpB3dZedVglmh7peXnJZrUvyD95A/9nPwEq31rNzbSNB0gKu5938Ih/coD9VeDiNWzLoIgrccMxO84P6Dh8pWAqQZrNzDqjiCJGFHoLULVi7c2AHIQE6/fMZ6PDvvrnWwo1VQTg9ImBg0rghv3fLfvdqFNWRGhiBn+AQCGG5PM8JDx3PDy9P5uKlw7Vf2grXqrQAdQwCsXKTbd4FZY8fiK3Embcy9jZBWBPF9f4MTO/AhxQsAAkYwCjBDuQmwdgEw9rx2OwZswAZswAZswIB/A76DD3Wl5sBCAAAAAElFTkSuQmCC">
<style>
  /* ── Console v2 · "cobalt" ────────────────────────────────────────────
     Pure white surfaces, one saturated cobalt carrying every action.
     Burnt orange = needs attention, red = destructive, teal = content
     address. Monospace is reserved for developer mode. Light is
     canonical; dark mirrors it token for token. Design source of truth
     is the Paper file "Areev", page "Console v2 — Redesign". */
  :root {
    color-scheme: light;
    --bg:#F6F7FB; --surface:#FFFFFF; --raise:#F1F3F8; --well:#F7F8FC;
    --line:#E3E6ED; --line2:#D5DAE6; --hair:#EDEFF4;
    --ink:#0B0D12; --text:#3E4657; --muted:#5A6072; --dim:#6E7686; --faint:#8B92A3; --ghost:#A8AEBC;
    --accent:#2F72E8; --accent-hover:#2861C5; --accent-soft:#EAF1FD; --accent-line:#C5DAF9;
    --ok:#0F8A5F; --ok-soft:#E9F6F0; --ok-line:#CBE8DA;
    --warn:#C2410C; --warn-soft:#FFF3EC; --warn-line:#FBDCC8;
    --danger:#C81E1E; --danger-soft:#FDECEC; --danger-line:#F6CDCD;
    --hash:#0E8F82;
    --cat-person:#2F72E8; --cat-org:#0E8F82; --cat-project:#7A3BE0;
    --cat-thing:#B45309; --cat-note:#F2542D;
    --sel:rgba(47,114,232,.20);
    --shadow:0 10px 30px rgba(11,13,18,.10);
    --card-shadow:0 1px 2px rgba(11,13,18,.04), 0 2px 6px rgba(11,13,18,.05);
    --sans:'Inter',-apple-system,system-ui,'Segoe UI',Roboto,sans-serif;
    --mono:ui-monospace,'SF Mono',SFMono-Regular,Menlo,Consolas,monospace;
    /* Layout measures. Widen with the viewport, but never past the point
       where a line of prose becomes tiring to read. */
    --col:880px; --wide:1500px;
  }
  @media (min-width:1500px) { :root { --col:1000px; --wide:1700px; } }
  @media (min-width:1800px) { :root { --col:1100px; --wide:1900px; } }
  @media (min-width:2200px) { :root { --col:1200px; --wide:2100px; } }
  @media (prefers-color-scheme: dark) { :root { color-scheme: dark;
    --bg:#0B0E14; --surface:#111621; --raise:#171D2A; --well:#0D121B;
    --line:#222A38; --line2:#333C4D; --hair:#1C2431;
    --ink:#F2F5FA; --text:#C9D1DE; --muted:#9AA4B7; --dim:#8B95A8; --faint:#79839A; --ghost:#5F6980;
    --accent:#7EA8F1; --accent-hover:#A3C1F5; --accent-soft:#122744; --accent-line:#2D4E80;
    --ok:#3DD68C; --ok-soft:#12251C; --ok-line:#255140;
    --warn:#F59E5B; --warn-soft:#2A1A11; --warn-line:#5A3A22;
    --danger:#F87171; --danger-soft:#2B1517; --danger-line:#5E2B2E;
    --hash:#3FCFC0;
    --cat-person:#7EA8F1; --cat-org:#3FCFC0; --cat-project:#B39BFF;
    --cat-thing:#E0A458; --cat-note:#FF8A66;
    --sel:rgba(126,168,241,.32);
    --shadow:0 10px 30px rgba(0,0,0,.45);
    --card-shadow:0 1px 2px rgba(0,0,0,.30);
  } }
  :root[data-theme="light"] { color-scheme: light;
    --bg:#F6F7FB; --surface:#FFFFFF; --raise:#F1F3F8; --well:#F7F8FC;
    --line:#E3E6ED; --line2:#D5DAE6; --hair:#EDEFF4;
    --ink:#0B0D12; --text:#3E4657; --muted:#5A6072; --dim:#6E7686; --faint:#8B92A3; --ghost:#A8AEBC;
    --accent:#2F72E8; --accent-hover:#2861C5; --accent-soft:#EAF1FD; --accent-line:#C5DAF9;
    --ok:#0F8A5F; --ok-soft:#E9F6F0; --ok-line:#CBE8DA;
    --warn:#C2410C; --warn-soft:#FFF3EC; --warn-line:#FBDCC8;
    --danger:#C81E1E; --danger-soft:#FDECEC; --danger-line:#F6CDCD;
    --hash:#0E8F82;
    --cat-person:#2F72E8; --cat-org:#0E8F82; --cat-project:#7A3BE0;
    --cat-thing:#B45309; --cat-note:#F2542D;
    --sel:rgba(47,114,232,.20);
    --shadow:0 10px 30px rgba(11,13,18,.10);
    --card-shadow:0 1px 2px rgba(11,13,18,.04), 0 2px 6px rgba(11,13,18,.05);
  }
  :root[data-theme="dark"] { color-scheme: dark;
    --bg:#0B0E14; --surface:#111621; --raise:#171D2A; --well:#0D121B;
    --line:#222A38; --line2:#333C4D; --hair:#1C2431;
    --ink:#F2F5FA; --text:#C9D1DE; --muted:#9AA4B7; --dim:#8B95A8; --faint:#79839A; --ghost:#5F6980;
    --accent:#7EA8F1; --accent-hover:#A3C1F5; --accent-soft:#122744; --accent-line:#2D4E80;
    --ok:#3DD68C; --ok-soft:#12251C; --ok-line:#255140;
    --warn:#F59E5B; --warn-soft:#2A1A11; --warn-line:#5A3A22;
    --danger:#F87171; --danger-soft:#2B1517; --danger-line:#5E2B2E;
    --hash:#3FCFC0;
    --cat-person:#7EA8F1; --cat-org:#3FCFC0; --cat-project:#B39BFF;
    --cat-thing:#E0A458; --cat-note:#FF8A66;
    --sel:rgba(126,168,241,.32);
    --shadow:0 10px 30px rgba(0,0,0,.45);
    --card-shadow:0 1px 2px rgba(0,0,0,.30);
  }

  * { box-sizing:border-box; margin:0; }
  html, body { height:100%; }
  /* The reading surface is the brightest plane; nav and developer chrome sit
     one step back on the tint. (The reverse reads as an unfinished page.) */
  body { background:var(--surface); color:var(--text); font:15px/1.55 var(--sans); -webkit-font-smoothing:antialiased; }
  a { color:var(--accent); text-decoration:none; }
  ::-webkit-scrollbar { width:10px; height:10px; }
  ::-webkit-scrollbar-thumb { background:var(--line2); border-radius:8px; border:3px solid transparent; background-clip:content-box; }
  :focus-visible { outline:2px solid var(--accent); outline-offset:2px; border-radius:4px; }
  @media (prefers-reduced-motion: reduce) { * { transition:none !important; animation:none !important; } }
  /* Developer mode: hidden by default, revealed by html.dev. Explicit
     display values (not `revert`, which would drop id-level flex rules). */
  /* Belt and braces against stored values that have no wrap opportunities
     (JSON, hashes, URLs): flex children must be allowed to shrink, and text
     must be allowed to break mid-token. Nothing may scroll the page sideways. */
  .mrow .say, .mrow .prov, .srow .t, .evi-row .t, .ev .say, .ans-text,
  .kv .v, #ginspect .meta { min-width:0; overflow-wrap:anywhere; }
  .mrow, .srow, .evi-row, .ev, .acts { min-width:0; }
  .dev-only { display:none !important; }
  html.dev .dev-only { display:block !important; }
  html.dev .dev-flex { display:flex !important; }

  /* ── shell ── */
  #shell { display:flex; min-height:100vh; align-items:stretch; }
  #rail { width:260px; flex-shrink:0; background:var(--bg); border-right:1px solid var(--line);
          padding:26px 18px 20px 22px; display:flex; flex-direction:column; gap:26px; position:sticky; top:0; height:100vh; }
  #main { flex:1; min-width:0; display:flex; flex-direction:column; }
  .page { padding:44px 56px 56px 48px; display:flex; flex-direction:column; gap:24px; }
  /* One reading column, centred in whatever space the rail leaves. A cap
     keeps line length sane; auto margins stop it hugging the rail on a wide
     monitor, where a left-pinned column just looks like a broken page. */
  .col { width:100%; max-width:var(--col); margin-left:auto; margin-right:auto; }
  .wide { width:100%; max-width:var(--wide); margin-left:auto; margin-right:auto; }
  /* ── query workbench ── */
  /* The composer is one surface holding the editor and everything you can do
     to it, so Run reads as the act and the rest as afterthoughts. */
  /* No overflow:hidden here — the Format menu is absolutely positioned inside
     the action bar, and clipping the composer clips the menu. Round the
     children instead. */
  .composer { background:var(--surface); border:1px solid var(--line2); border-radius:12px;
              box-shadow:var(--card-shadow); }
  /* The editor is a transparent textarea over a highlighted mirror: the caret,
     selection and IME stay native, the colour comes from the layer beneath. */
  .qedit { position:relative; }
  #qhl, #qtext { font-family:var(--mono); font-size:13px; line-height:21px;
                 padding:16px 18px; white-space:pre-wrap; overflow-wrap:break-word;
                 border:0; margin:0; }
  #qhl { position:absolute; inset:0; pointer-events:none; overflow:hidden;
         color:var(--text); border-radius:12px 12px 0 0; }
  #qtext { position:relative; width:100%; display:block; resize:none; overflow-y:auto;
           background:none; color:transparent; caret-color:var(--ink);
           border-radius:12px 12px 0 0; min-height:88px; max-height:340px; }
  #qtext::selection { background:var(--sel); }
  #qtext:focus { outline:none; }
  #qtext::placeholder { color:var(--faint); }
  #qhl .k { color:var(--ink); font-weight:600; }   /* RECALL, WHERE, LIMIT … */
  #qhl .s { color:var(--hash); }                   /* "quoted strings" */
  #qhl .n { color:var(--warn); }                   /* numbers */
  #qhl .c { color:var(--faint); }                  /* -- comments */
  .composer .cbar { display:flex; align-items:center; gap:9px; flex-wrap:wrap;
                    padding:11px 14px; border-top:1px solid var(--line);
                    background:var(--well); border-radius:0 0 12px 12px; }
  .composer .kbd { font-size:11.5px; font-weight:500; opacity:.75; }
  /* ── the on-ramp: what the page offers before you have run anything ── */
  .onramp { display:flex; flex-direction:column; gap:12px; }
  .qsec { display:flex; align-items:center; gap:11px; padding-top:10px; }
  .qsec i { flex:1; height:1px; background:var(--line); }
  /* Two across so the four questions read as a block, not a ragged row — and
     sized to hold two even when the developer rail takes 330px off the width. */
  .starters { display:grid; grid-template-columns:repeat(auto-fit, minmax(340px, 1fr)); gap:12px; }
  .starter { text-align:left; background:var(--surface); border:1px solid var(--line);
             border-radius:11px; padding:15px 16px; display:flex; flex-direction:column; gap:10px;
             cursor:pointer; transition:border-color .12s, box-shadow .12s; }
  .starter:hover { border-color:var(--accent-line); box-shadow:var(--card-shadow); }
  .starter b { font-size:15px; font-weight:600; color:var(--ink); line-height:21px; }
  /* the CAL each question writes, shown so the answer teaches the language */
  .starter code { font-family:var(--mono); font-size:11.5px; color:var(--muted); background:var(--bg);
                  border:0; border-radius:6px; padding:8px 10px; display:block;
                  white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
  /* ── analytics: the grain-type census, namespace breakdown, growth trend
     and recall-leg status that used to live as a small "WHAT'S IN THIS
     MEMORY" teaser on this very page — moved to its own tab so it could
     cover all 12 grain types instead of 4, without crowding the on-ramp.
     `.crow` is the shared row shape for both the grain-type census
     and the namespace breakdown — a mono key, an optional gloss, a bar
     proportional to that list's own max (not a global constant), and a
     right-aligned count. */
  .stiles { display:grid; grid-template-columns:repeat(4, minmax(200px, 1fr)); gap:14px; }
  .stile { padding:18px 20px; display:flex; flex-direction:column; gap:6px; }
  .stile .lbl { font-size:11.5px; font-weight:600; color:var(--dim); letter-spacing:.09em; }
  .stile .n { font-size:28px; font-weight:700; color:var(--ink); letter-spacing:-.02em; font-variant-numeric:tabular-nums; }
  .stile .sub { font-size:12.5px; color:var(--faint); }
  .census { display:flex; flex-direction:column; margin-top:6px; }
  .crow { display:flex; align-items:center; gap:14px; padding:9px 0; border:0; background:none;
          width:100%; text-align:left; font-family:inherit; cursor:pointer; }
  .crow .k { width:150px; flex-shrink:0; font-family:var(--mono); font-size:12.5px; color:var(--ink); }
  .crow .k.wide { width:200px; }
  .crow .g { width:230px; flex-shrink:0; font-size:12.5px; color:var(--faint);
             overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
  .crow .track { flex:1; height:8px; background:var(--raise); border-radius:4px; }
  .crow .bar { height:100%; background:var(--accent); border-radius:4px; }
  .crow .bar.zero { background:var(--line); }
  .crow .n { width:40px; flex-shrink:0; text-align:right; font-size:14px; font-weight:600;
             color:var(--ink); font-variant-numeric:tabular-nums; }
  .crow .n.zero { color:var(--faint); font-weight:500; }
  .gchart { display:flex; align-items:flex-end; gap:6px; height:100px; margin-top:22px; }
  .gbar { flex:1; background:var(--accent-line); border-radius:4px 4px 0 0; }
  .gbar.today { background:var(--accent); }
  .legs { display:flex; gap:14px; }
  .leg { flex:1; padding:16px 18px; display:flex; flex-direction:column; gap:8px; }
  .leg .hd { display:flex; align-items:center; gap:8px; }
  .leg .dot { width:7px; height:7px; border-radius:4px; flex-shrink:0; }
  .leg b { font-size:14px; font-weight:600; color:var(--ink); }
  .leg .d { font-size:12.5px; color:var(--faint); line-height:18px; }
  /* minmax(0,·) or a long description sets the column's min-content width and
     the two halves stop being halves. */
  .recents { display:grid; grid-template-columns:repeat(2, minmax(0, 1fr)); gap:12px 26px; }
  .rrow { display:flex; flex-direction:column; gap:3px; padding:9px 0; text-align:left;
          background:none; border:0; border-bottom:1px solid var(--hair); cursor:pointer; width:100%; }
  .rrow:hover .rq, .rrow:hover .rn { color:var(--accent); }
  /* A recent run is code and reads as code; a saved query has a human name. */
  .rrow .rq { font-family:var(--mono); font-size:11.5px; color:var(--text);
              white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
  .rrow .rn { font-size:14px; color:var(--ink); font-weight:500;
              white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
  .rrow .rm { font-size:12.5px; color:var(--faint);
              white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
  .rempty { padding:9px 0; font-size:13px; color:var(--faint); }
  /* Restate the query in plain words, so a non-technical reader can tell at a
     glance whether the CAL asked what they meant. */
  .qsum { display:flex; flex-direction:column; gap:3px; padding-bottom:13px; }
  .qsum .h { font-size:19px; font-weight:600; color:var(--ink); letter-spacing:-.01em; }
  .qsum .h em { font-style:normal; font-weight:400; font-size:15px; color:var(--muted); }
  #qbar { display:flex; align-items:center; gap:12px; flex-wrap:wrap;
          padding:12px 0; border-bottom:1px solid var(--line); }
  #qmore { padding:16px 0; }
  #qerr { background:var(--danger-soft); border:1px solid var(--danger-line); border-radius:10px;
          padding:12px 14px; font-size:13px; }
  #qerr .code { font-family:var(--mono); font-size:11px; color:var(--danger);
                border:1px solid var(--danger-line); border-radius:5px; padding:1px 6px; margin-right:8px; }
  #qerr pre { margin-top:8px; font-family:var(--mono); font-size:12.5px; color:var(--muted); white-space:pre-wrap; }
  #qerr .hint { margin-top:7px; color:var(--warn); }
  code { font-family:var(--mono); font-size:.92em; background:var(--raise); border:1px solid var(--line);
         border-radius:5px; padding:1px 5px; }
  .menuwrap { position:relative; display:inline-block; }
  /* A drawn chevron rather than the ▾ glyph, which renders thin and pale at
     this size and disappears against a ghost button. */
  .btn.hasmenu::after { content:''; width:6px; height:6px; flex-shrink:0; margin-left:2px;
                        border-right:1.7px solid currentColor; border-bottom:1.7px solid currentColor;
                        transform:translateY(-2px) rotate(45deg); }
  /* JSON is the developer's view of the answer — colour it the way the rest of
     this console colours values, so the meanings carry across. */
  .jsonv { line-height:19px; }
  .jsonv .jk { color:var(--ink); font-weight:600; }
  .jsonv .js { color:var(--hash); }
  .jsonv .jn { color:var(--warn); }
  .jsonv .jb { color:var(--ok); font-weight:500; }
  .jsonv .jz { color:var(--faint); }
  .menu { position:absolute; z-index:30; top:calc(100% + 6px); right:0; background:var(--surface);
          border:1px solid var(--line2); border-radius:11px; min-width:300px; max-width:460px;
          max-height:340px; overflow-y:auto; box-shadow:var(--shadow); padding:5px; }
  .menu .mi { padding:8px 11px; border-radius:8px; cursor:pointer; font-size:13px; color:var(--text); }
  .menu .mi:hover { background:var(--raise); }
  .menu .mi small { display:block; font-family:var(--mono); font-size:11px; color:var(--dim);
                    white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin-top:2px; }
  .menu .sep { padding:8px 11px 4px; font-size:11px; font-weight:600; letter-spacing:.09em; color:var(--dim); }
  /* order-preserving masonry: cards keep result order, heights vary with content */
  #qcards { display:grid; grid-template-columns:repeat(auto-fill, minmax(300px, 1fr));
            grid-auto-rows:8px; gap:0 16px; }
  /* `layoutMasonry()` reserves a gutter's worth of extra rows past each
     card's own content height — but a grid item stretches to fill its full
     row-span by default, so without `align-self:start` the card's own box
     grows to swallow that reserved space and the "gap" never becomes a gap. */
  .qcard { align-self:start; background:var(--surface); border:1px solid var(--line); border-radius:12px;
           padding:14px 16px; display:flex; flex-direction:column; gap:8px;
           box-shadow:var(--card-shadow); overflow:hidden; }
  .qcard .hd { display:flex; align-items:center; gap:8px; }
  .qcard .kind { font-size:11px; font-weight:600; letter-spacing:.06em; text-transform:uppercase; }
  .qcard .say { font-size:15px; line-height:22px; color:var(--ink); overflow-wrap:anywhere; }
  .qcard .kv { display:flex; gap:8px; font-size:12.5px; padding:3px 0; border-top:1px solid var(--hair); }
  .qcard .kv b { flex-shrink:0; min-width:84px; color:var(--dim); font-weight:500; }
  .qcard .kv span { color:var(--text); overflow-wrap:anywhere; min-width:0; }
  #qtable { width:100%; border-collapse:collapse; font-size:13.5px; }
  #qtable th { text-align:left; font-size:11px; font-weight:600; letter-spacing:.06em; color:var(--dim);
               text-transform:uppercase; padding:8px 12px 8px 0; border-bottom:1px solid var(--line2); white-space:nowrap; }
  #qtable td { padding:9px 12px 9px 0; border-bottom:1px solid var(--hair); vertical-align:top;
               max-width:340px; overflow-wrap:anywhere; }
  .seg.sm button { height:26px; padding:0 11px; font-size:12.5px; }
  /* The graph is a canvas, not prose — let it use the width, within reason. */
  #graphView { width:100%; max-width:var(--wide); margin-left:auto; margin-right:auto; }

  /* ── rail ── */
  /* Nav items carry their own 11px left padding (room for the hover/active
     pill around the icon), and the rail footer already insets by that same
     11px to match — the brand row was the one place that didn't, so its
     icon sat 11px left of every nav icon below it. */
  .brand { display:flex; align-items:center; gap:9px; padding-left:11px; border:0; background:none;
           font-family:inherit; text-align:left; cursor:pointer; width:100%; border-radius:9px;
           padding-top:4px; padding-bottom:4px; margin:-4px 0; transition:background .12s; }
  .brand:hover { background:var(--raise); }
  .brand .mark { width:22px; height:22px; flex-shrink:0; display:block; }
  .brand b { font-size:17px; font-weight:700; color:var(--ink); letter-spacing:-.02em; }
  .nav { display:flex; flex-direction:column; gap:2px; }
  .nav-item { display:flex; align-items:center; gap:11px; padding:9px 11px; border-radius:9px;
              cursor:pointer; color:var(--text); font-size:15px; font-weight:500; border:0; background:none;
              width:100%; text-align:left; font-family:inherit; transition:background .12s; }
  .nav-item:hover { background:var(--raise); }
  .nav-item.on { background:var(--accent-soft); color:var(--accent); font-weight:600; }
  .nav-item svg { flex-shrink:0; stroke:currentColor; }
  .nav-item .grow { flex:1; }
  .pill { display:inline-flex; align-items:center; justify-content:center; min-width:20px; height:20px;
          padding:0 6px; border-radius:10px; background:var(--warn); color:#fff; font-size:11px; font-weight:600; }
  .pill.soft { background:var(--raise); color:var(--dim); }
  .nav-item.on .pill.soft { background:var(--surface); color:var(--accent); }
  .sec-label { font-size:11.5px; font-weight:600; color:var(--dim); letter-spacing:.09em; }
  #entities { display:flex; flex-direction:column; gap:1px; overflow-y:auto; min-height:0; }
  .ent { display:flex; align-items:center; gap:10px; padding:7px 11px; border-radius:8px; cursor:pointer;
         border:0; background:none; width:100%; text-align:left; font-family:inherit; transition:background .12s; }
  .ent:hover { background:var(--raise); }
  .ent.on { background:var(--accent-soft); }
  .ent .av { display:flex; align-items:center; justify-content:center; width:22px; height:22px; flex-shrink:0;
             border-radius:11px; background:var(--raise); color:var(--muted); font-size:10.5px; font-weight:600; }
  .ent.on .av { background:var(--accent); color:#fff; }
  .ent .nm { flex:1; font-size:14.5px; font-weight:500; color:var(--ink); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
  .ent .ct { width:22px; flex-shrink:0; text-align:right; font-size:13px; color:var(--faint); font-variant-numeric:tabular-nums; }
  .rail-foot { margin-top:auto; display:flex; flex-direction:column; gap:14px; padding:0 11px 2px; }
  .health { display:flex; align-items:center; gap:8px; font-size:13px; color:var(--muted); cursor:pointer; }
  .dot { width:7px; height:7px; border-radius:4px; background:var(--ghost); flex-shrink:0; }
  .toggle-row { display:flex; align-items:center; gap:10px; padding-top:14px; border-top:1px solid var(--line); }
  .toggle-row span { flex:1; font-size:13.5px; color:var(--dim); }
  .sw { width:34px; height:20px; flex-shrink:0; border-radius:10px; background:var(--line2); padding:2px;
        display:flex; align-items:center; cursor:pointer; border:0; transition:background .15s; }
  .sw i { width:16px; height:16px; border-radius:8px; background:#fff; display:block; transition:transform .15s; }
  .sw.on { background:var(--accent); }
  .sw.on i { transform:translateX(14px); }

  /* ── type ── */
  h1 { font:700 31px/38px var(--sans); color:var(--ink); letter-spacing:-.025em; }
  h2 { font:700 15px var(--sans); color:var(--ink); letter-spacing:-.01em; }
  .sub { font-size:14.5px; line-height:22px; color:var(--muted); }
  .meta { font-size:13px; color:var(--dim); }
  .tiny { font-size:12.5px; color:var(--faint); }
  .mono { font-family:var(--mono); font-size:11.5px; color:var(--hash); }

  /* ── page header: one breadcrumb line — home icon, prior pages, then the
     current page as the trail's own last segment (not a separate display
     headline below it) — followed by a description line. Every page's
     title block, one component. All trail text shares one font size; color
     and weight carry the hierarchy instead: prior pages read legibly rather
     than near-invisible, the current-page segment is the cleanest, darkest,
     boldest text in the row, and the description recedes a step further
     neutral than either. ── */
  .pagehead { display:flex; flex-direction:column; gap:3px; }
  .pagehead .trail { display:flex; flex-wrap:wrap; align-items:center; gap:6px; row-gap:2px; }
  .pagehead .trail .home { display:flex; align-items:center; padding:2px; margin-left:-2px; border:0; background:none; color:var(--dim); border-radius:5px; transition:color .12s; }
  .pagehead .trail .home:hover { color:var(--accent); }
  /* The "›" sits 1px low against the icon/text either side of it — nudge
     it down that 1px rather than the icon (which is already centred). */
  .pagehead .trail .sep { font-size:13.5px; color:var(--faint); padding-bottom:1px; }
  .pagehead .trail .link { border:0; background:none; padding:0; font:500 13.5px var(--sans); color:var(--dim); cursor:pointer; }
  .pagehead .trail .link:hover { color:var(--accent); }
  .pagehead .ctitle { font:600 13.5px/19px var(--sans); color:var(--ink); letter-spacing:-.01em; }
  .pagehead .cdesc { font-size:13.5px; line-height:20px; color:var(--muted); margin-top:2px; }
  /* Editable title/description (Workflows only): the same element throughout
     hover and focus — never swapped for a different tag — so turning it into
     an active field never shifts anything around it. The padding/negative-
     margin pair keeps the text sitting in exactly the same spot whether or
     not the hover/focus background is showing. The input never carries its
     own width: it sits in a grid cell sized by an invisible twin (::after,
     same text via data-value) so the field hugs its content and the edit/
     lock icons sit right after the text instead of stranded at the row's
     far edge. */
  .pagehead .edit-row { display:inline-flex; align-items:center; gap:5px; max-width:100%; vertical-align:middle; }
  /* The sizer span carries the same ctitle/cdesc class as the input inside
     it, so it (and its ::after, which inherits font from it for free) picks
     up the exact same font as the real title/description text below —
     no font:inherit here, that would out-specificity .pagehead .ctitle/
     .cdesc and silently fall back to an ambient size. ::after and the input
     also share identical padding/border so the ghost's measured width
     already includes the room the input's own padding will eat into. */
  .pagehead .input-sizer { display:inline-grid; align-items:center; min-width:1em; max-width:100%; }
  .pagehead .input-sizer::after, .pagehead .input-sizer input {
    grid-area:1/1; box-sizing:border-box; padding:1px 5px; border:1px solid transparent; }
  .pagehead .input-sizer::after { content:attr(data-value) ' '; visibility:hidden; white-space:pre; }
  .pagehead input.ctitle, .pagehead input.cdesc {
    display:block; width:100%; min-width:1em; height:auto; background:none;
    border-radius:6px; margin:-1px -5px; cursor:pointer; }
  .pagehead input.ctitle:hover:not(:focus):not(:disabled), .pagehead input.cdesc:hover:not(:focus):not(:disabled) {
    background:var(--raise); border-color:var(--line); cursor:text; }
  .pagehead input.ctitle:focus, .pagehead input.cdesc:focus {
    background:var(--surface); border-color:var(--accent-line); box-shadow:0 0 0 3px var(--accent-soft); cursor:text; outline:none; }
  .pagehead input.ctitle:disabled, .pagehead input.cdesc:disabled { color:var(--dim); cursor:default; }
  .pagehead input.ctitle::placeholder, .pagehead input.cdesc::placeholder { color:var(--faint); }
  .pagehead .edit-icon { display:flex; align-items:center; flex-shrink:0; color:var(--faint); opacity:0; transition:opacity .12s; cursor:pointer; }
  .pagehead .edit-row:hover .edit-icon { opacity:1; }
  .pagehead .lock-hint { display:flex; align-items:center; flex-shrink:0; color:var(--warn); cursor:help; margin-left:2px; }

  /* ── controls ── */
  button { font-family:inherit; cursor:pointer; }
  .btn { display:inline-flex; align-items:center; justify-content:center; gap:7px; height:40px; padding:0 20px;
         border-radius:10px; background:var(--accent); color:#fff; border:0; font-size:14.5px; font-weight:600;
         transition:background .12s; white-space:nowrap; flex-shrink:0; }
  .btn:hover { background:var(--accent-hover); }
  .btn.sm { height:34px; padding:0 15px; font-size:13px; border-radius:9px; }
  .btn.ghost { background:var(--surface); border:1px solid var(--line2); color:var(--text); font-weight:500; }
  .btn.ghost:hover { background:var(--raise); }
  .btn.danger { background:none; border:0; color:var(--danger); font-weight:600; padding:0; height:auto; }
  .btn:disabled { opacity:.5; cursor:default; }
  .chip { padding:6px 13px; border-radius:16px; border:1px solid var(--line); background:var(--surface);
          font-size:13.5px; color:var(--text); cursor:pointer; transition:border-color .12s, color .12s; }
  .chip:hover { border-color:var(--line2); }
  .chip.on { background:var(--accent); border-color:var(--accent); color:#fff; font-weight:600; }
  .seg { display:inline-flex; padding:3px; border-radius:10px; background:var(--raise); }
  .seg button { height:30px; padding:0 15px; border-radius:8px; border:0; background:none; color:var(--muted);
                font-size:13.5px; font-weight:500; }
  .seg button.on { background:var(--surface); color:var(--accent); font-weight:600; box-shadow:0 1px 2px rgba(11,13,18,.06); }
  .tabs { display:flex; align-items:flex-end; gap:26px; border-bottom:1px solid var(--line); }
  .tabs button { padding:0 0 11px; border:0; background:none; font-size:14.5px; font-weight:500; color:var(--muted); }
  .tabs button.on { color:var(--accent); font-weight:600; box-shadow:inset 0 -2px 0 var(--accent); }
  input[type=text], textarea { font-family:inherit; background:var(--surface); border:1px solid var(--line2);
    border-radius:10px; color:var(--ink); padding:9px 12px; font-size:14px; width:100%; }
  input[type=text]:focus, textarea:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px var(--accent-soft); }
  /* A native <select>, restyled to match every other control here instead of
     the browser's own chrome — `appearance:none` plus a drawn chevron.
     Chrome renders no pseudo-elements on <select>, so the chevron is a real
     sibling span (`.sel-wrap`/`.sel-arrow`), the same shape `.ns-combo`'s
     own arrow already uses, not a ::after. */
  select { appearance:none; -webkit-appearance:none; font-family:inherit; background:var(--surface);
    border:1px solid var(--line2); border-radius:10px; color:var(--ink); padding:9px 30px 9px 12px;
    font-size:14px; width:100%; cursor:pointer; }
  select:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px var(--accent-soft); }
  select:disabled { cursor:default; opacity:.6; }
  .sel-wrap { position:relative; display:block; }
  .sel-arrow { position:absolute; right:11px; top:0; height:100%; display:flex; align-items:center;
               pointer-events:none; color:var(--faint); }

  /* ── ask ── */
  .askbar { display:flex; align-items:center; gap:13px; height:56px; padding:0 14px 0 18px; background:var(--surface);
            border:1px solid var(--line2); border-radius:13px; transition:border-color .12s, box-shadow .12s; }
  .askbar:focus-within { border-color:var(--accent); box-shadow:0 0 0 3px var(--accent-soft); }
  .askbar input { border:0; background:none; padding:0; font-size:16px; flex:1; height:100%; }
  .askbar input:focus { outline:none; box-shadow:none; }
  .askbar input::placeholder { color:var(--faint); }
  .examples { display:flex; align-items:center; gap:8px; flex-wrap:wrap; padding:0 2px; }
  .examples .tiny { flex-shrink:0; }

  /* ── cards & banners ── */
  /* On a white page a card needs its own lift, not fill contrast. */
  .card { background:var(--surface); border:1px solid var(--line); border-radius:14px; box-shadow:var(--card-shadow); }
  .banner { display:flex; align-items:center; gap:12px; padding:13px 16px; border-radius:11px;
            background:var(--warn-soft); border:1px solid var(--warn-line); }
  .banner .grow { flex:1; font-size:14.5px; color:var(--text); }
  .banner b { color:var(--ink); font-weight:600; }
  .banner .go { flex-shrink:0; font-size:14px; font-weight:600; color:var(--accent); cursor:pointer; }
  .empty { padding:34px 0; text-align:center; color:var(--dim); font-size:14px; }
  .planv { display:flex; flex-direction:column; padding-top:6px; }
  .prow { display:flex; gap:14px; padding:10px 0; border-bottom:1px solid var(--hair); font-size:13.5px; }
  .prow b { width:104px; flex-shrink:0; color:var(--dim); font-weight:500; }
  .prow span { color:var(--text); font-family:var(--mono); font-size:12.5px; }
  .pnote { margin-top:14px; padding:12px 14px; background:var(--warn-soft);
           border:1px solid var(--warn-line); border-radius:9px; font-size:13px;
           line-height:20px; color:var(--text); }
  /* A query that matched nothing is a normal outcome, not an error — say what
     was asked and offer the next thing to try, rather than a dead end. */
  .nores { display:flex; flex-direction:column; align-items:flex-start; gap:9px;
           padding:30px 26px; background:var(--surface); border:1px solid var(--line);
           border-radius:12px; }
  .nores .t { font-size:17px; font-weight:600; color:var(--ink); }
  .nores .d { font-size:14px; line-height:21px; color:var(--muted); max-width:62ch; }
  .nores .acts { display:flex; gap:9px; flex-wrap:wrap; padding-top:4px; }
  /* Colour carries meaning here, never decoration: teal is a content address
     everywhere in this console, burnt orange is "needs attention". */
  .v-hash { color:var(--hash); font-family:var(--mono); font-size:11.5px; }
  .v-time { color:var(--dim); }
  .v-yes  { color:var(--ok); font-weight:500; }
  .v-no   { color:var(--warn); font-weight:500; }
  .v-num  { color:var(--ink); font-weight:500; font-variant-numeric:tabular-nums; }

  /* ── memory list ── */
  .grp-head { display:flex; align-items:baseline; gap:10px; padding:22px 0 10px; }
  .grp-head:first-child { padding-top:6px; }
  .mrow { display:flex; align-items:flex-start; gap:18px; padding:14px 8px 14px 0; border-top:1px solid var(--hair);
          cursor:pointer; border-radius:8px; transition:background .1s; }
  .mrow:hover { background:var(--raise); }
  .mrow.sel { background:var(--accent-soft); }
  .mrow .body { flex:1; display:flex; flex-direction:column; gap:4px; min-width:0; }
  .mrow .say { font-size:16.5px; line-height:25px; color:var(--ink); }
  .mrow .prov { font-size:13px; line-height:20px; color:var(--dim); }
  .mrow .when { width:96px; flex-shrink:0; text-align:right; font-size:13px; color:var(--dim); padding-top:4px; }
  .mrow.gone .say { color:var(--ghost); text-decoration:line-through; }
  .mrow.sup .say { color:var(--muted); }

  /* ── answer ── */
  #answer { display:flex; flex-direction:column; padding:28px 30px 0; }
  .ans-label { font-size:11.5px; font-weight:600; color:var(--accent); letter-spacing:.09em; }
  .ans-text { font-size:20px; line-height:31px; color:var(--ink); letter-spacing:-.01em; }
  .srow { display:flex; align-items:center; gap:14px; padding:11px 0; border-bottom:1px solid var(--hair); cursor:pointer; }
  .srow:last-child { border-bottom:0; }
  .srow .t { flex:1; font-size:15px; color:var(--ink); }
  .srow .w { width:96px; flex-shrink:0; text-align:right; font-size:13px; color:var(--dim); }
  .disclose { display:flex; align-items:center; gap:10px; padding:15px 0 18px; border-top:1px solid var(--hair);
              cursor:pointer; font-size:14px; color:var(--text); }
  .disclose .grow { flex:1; }
  .disclose .caret { transition:transform .15s; }
  .disclose.open .caret { transform:rotate(90deg); }
  pre.code { font-family:var(--mono); font-size:13px; line-height:21px; color:var(--ink); background:var(--well);
             border:1px solid var(--hair); border-radius:10px; padding:14px 16px; overflow-x:auto; white-space:pre-wrap;
             word-break:break-word; }

  /* ── graph ── */
  #gwrap { background:var(--well); border:1px solid var(--line); border-radius:16px; overflow:hidden; }
  /* The query workbench draws its own result graph (#qstage/#qcanvas/#qzoom);
     it shares this chrome so the two graphs read — and handle — the same. */
  #gstage, #qstage { position:relative; }
  #gcanvas { display:block; width:100%; height:560px; cursor:grab; }
  #qcanvas { display:block; width:100%; height:460px; cursor:grab;
             background:var(--well); border:1px solid var(--line); border-radius:14px; }
  #gcanvas.grabbing, #qcanvas.grabbing { cursor:grabbing; }
  .float { position:absolute; background:var(--surface); border:1px solid var(--line); border-radius:12px; box-shadow:var(--shadow); }
  #gtools { top:16px; left:16px; display:flex; align-items:center; gap:10px; background:none; border:0; box-shadow:none; }
  #glegend { bottom:16px; left:16px; display:flex; align-items:center; gap:14px; height:34px; padding:0 14px; border-radius:17px; }
  #glegend span { display:flex; align-items:center; gap:6px; font-size:12.5px; color:var(--text); white-space:nowrap; }
  #gzoom { bottom:16px; right:16px; display:flex; align-items:center; height:34px; padding:0 4px; border-radius:17px; }
  #qzoom { bottom:14px; right:14px; display:flex; align-items:center; height:34px; padding:0 4px; border-radius:17px; }
  #gzoom button, #qzoom button { width:30px; height:28px; border:0; background:none; color:var(--text); font-size:16px; border-radius:14px; }
  #gzoom button.lbl, #qzoom button.lbl { width:auto; padding:0 10px; font-size:12px; font-weight:600; color:var(--accent); }
  #ginspect { top:16px; right:16px; width:288px; padding:18px; display:flex; flex-direction:column; gap:14px; }
  #gscrub { display:flex; flex-direction:column; gap:11px; padding:16px 20px 18px; background:var(--surface); border-top:1px solid var(--line); }
  #gscrub input[type=range] { width:100%; accent-color:var(--accent); }
  .scrub-ticks { display:flex; justify-content:space-between; font-size:11.5px; color:var(--faint); }

  /* ── workflows ── */
  /* The plan list reuses .starter (query page's card) — a workflow card is
     the same shape: a bold label plus a code-styled gloss line. */
  #wfList { display:grid; grid-template-columns:repeat(auto-fit, minmax(300px, 1fr)); gap:12px; align-items:start; }
  #wfwrap { background:var(--well); border:1px solid var(--line); border-radius:16px; overflow:hidden; }
  #wfstage { position:relative; }
  /* The canvas is the reason this page exists — give it the room, not a
     token box. Scales with the viewport rather than a fixed guess, with a
     floor for short windows. */
  #wfcanvas { display:block; width:100%; height:calc(100vh - 260px); min-height:480px; cursor:default; }
  #wfcanvas.connecting { cursor:crosshair; }
  #wftools { top:16px; left:16px; display:flex; align-items:center; gap:9px; background:none; border:0; box-shadow:none; }
  #wflegend { bottom:16px; left:16px; display:flex; align-items:center; flex-wrap:wrap; gap:8px 14px;
              min-height:34px; max-width:min(560px, 62%); padding:7px 14px; border-radius:15px; }
  #wflegend span { display:flex; align-items:center; gap:6px; font-size:12.5px; color:var(--text); white-space:nowrap; }
  #wflegend .legsep { color:var(--ghost); }
  #wfzoom { bottom:16px; right:16px; display:flex; align-items:center; height:34px; padding:0 4px; border-radius:17px; }
  #wfzoom button { width:30px; height:28px; border:0; background:none; color:var(--text); font-size:16px; border-radius:14px; }
  #wfzoom button.lbl { width:auto; padding:0 10px; font-size:12px; font-weight:600; color:var(--accent); }
  #wfinspect { top:16px; right:16px; width:302px; padding:18px; display:flex; flex-direction:column; gap:13px; max-height:488px; overflow-y:auto; }
  .wf-badge { display:inline-flex; align-items:center; gap:6px; padding:3px 10px; border-radius:10px; font-size:11.5px; font-weight:600; width:fit-content; }
  .wf-field { display:flex; flex-direction:column; gap:5px; }
  .wf-field .tiny { color:var(--dim); }
  /* A read-only inspector row: the trigger panel is all of these, because a
     trigger cannot be authored through CAL and so must not offer inputs that
     look editable. */
  .wf-ro { display:flex; flex-direction:column; gap:3px; }
  .wf-ro .k { font-size:12.5px; color:var(--dim); }
  .wf-ro .v { font-size:13.5px; color:var(--ink); overflow-wrap:anywhere; }
  .wf-ro .v.mono { font-family:var(--mono); font-size:12px; color:var(--text); }

  /* ── the run bar: which run the canvas is tinted by ──
     It sits in the page header rather than floating over the canvas, where it
     would collide with the tools (top-left) and the inspector (top-right) at
     narrow widths. */
  .runbar { display:flex; align-items:center; gap:10px; height:34px; padding:0 6px 0 12px;
            border:1px solid var(--line2); border-radius:9px; background:var(--surface); flex-shrink:0; }
  .runbar .dot { width:8px; height:8px; border-radius:5px; flex-shrink:0; }
  .runbar .lbl { font-size:12.5px; color:var(--text); white-space:nowrap; }
  .runbar .lbl b { color:var(--ink); font-weight:600; }
  .runbar .tally { font-size:12px; color:var(--dim); white-space:nowrap; }
  .runbar select { height:26px; width:auto; max-width:230px; border:0; background:none; color:var(--ink);
                   font-size:12.5px; font-weight:600; font-family:inherit; padding:0 24px 0 8px;
                   line-height:26px; text-overflow:ellipsis; border-radius:7px; }
  .runbar select:hover { background:var(--raise); }
  .runbar .sel-wrap { display:flex; align-items:center; width:auto; height:26px; }
  .runbar .sel-arrow { right:7px; }
  .runbar .go { border:0; background:none; color:var(--accent); font-size:12.5px; font-weight:600;
                padding:0 8px; height:26px; border-radius:7px; white-space:nowrap; }
  .runbar .go:hover { background:var(--accent-soft); }

  /* ── runs ── */
  /* Grouped, not one flat grid: "waiting on you" is a different kind of thing
     from "finished last Tuesday", and a single list buries the first in the
     second. */
  .rungroup { display:flex; flex-direction:column; gap:12px; }
  .rungroup + .rungroup { margin-top:30px; }
  .rungroup > .hd { display:flex; align-items:baseline; gap:10px; }
  .rungroup > .hd h3 { font-size:13px; font-weight:600; color:var(--dim); letter-spacing:.07em;
                       text-transform:uppercase; }
  .rungroup > .hd .tiny { color:var(--faint); }
  .rungrid { display:grid; grid-template-columns:repeat(auto-fit, minmax(400px, 1fr)); gap:12px; align-items:start; }
  .runcard { padding:0; overflow:hidden; display:flex; flex-direction:column; }
  .runcard .top { display:flex; align-items:center; gap:11px; padding:15px 18px 13px; }
  .runcard .top .plan { flex:1; min-width:0; font-size:15px; font-weight:600; color:var(--ink);
                        overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
  .runcard .top .plan .rid { display:block; font-size:12px; font-weight:400; color:var(--faint);
                             font-family:var(--mono); }
  .runcard .meta { display:flex; flex-wrap:wrap; gap:5px 14px; padding:0 18px 14px; font-size:12.5px; color:var(--dim); }
  .runcard .steps { display:flex; gap:3px; padding:0 18px 15px; }
  .runcard .steps i { height:4px; flex:1; border-radius:2px; background:var(--line); }
  .runcard .foot { display:flex; align-items:center; gap:14px; padding:12px 18px;
                   border-top:1px solid var(--hair); background:var(--well); }
  .runcard .foot .grow { flex:1; }
  .ask { margin:0 18px 16px; padding:13px 15px; border-radius:10px;
         background:var(--warn-soft); border:1px solid var(--warn-line); }
  .ask b { color:var(--ink); font-weight:600; font-size:13.5px; }
  .ask .who { font-size:12.5px; color:var(--muted); margin-top:3px; }
  .ask .acts { display:flex; gap:14px; align-items:center; margin-top:11px; }
  .status-tag { display:inline-flex; align-items:center; gap:6px; padding:3px 10px; border-radius:10px;
                font-size:11.5px; font-weight:600; flex-shrink:0; }

  /* ── tools ── */
  #toolBody { display:flex; flex-direction:column; gap:14px; }
  .toolgrid { display:grid; grid-template-columns:repeat(auto-fit, minmax(340px, 1fr)); gap:12px; align-items:start; }
  .toolcard { text-align:left; background:var(--surface); border:1px solid var(--line); border-radius:14px;
              box-shadow:var(--card-shadow); padding:16px 18px; display:flex; flex-direction:column; gap:8px;
              cursor:pointer; font-family:inherit; }
  .toolcard:hover { border-color:var(--accent-line); }
  .toolcard .hd { display:flex; align-items:center; gap:10px; }
  .toolcard .hd b { flex:1; min-width:0; font-size:15px; font-weight:600; color:var(--ink);
                    overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
  .toolcard .desc { font-size:13.5px; color:var(--text); line-height:19px; }
  .toolcard .use { font-size:12.5px; color:var(--faint); }
  /* One execution = one line. A run of 40 calls has to stay scannable, so the
     detail opens in place rather than each row carrying its payload. */
  .exec { display:flex; align-items:center; gap:12px; width:100%; padding:11px 16px; border:0; background:none;
          border-top:1px solid var(--hair); text-align:left; font-family:inherit; cursor:pointer; }
  .exec:first-child { border-top:0; }
  .exec:hover { background:var(--raise); }
  .exec .bar { width:3px; align-self:stretch; border-radius:2px; flex-shrink:0; }
  .exec .nm { flex:1; min-width:0; font-size:13.5px; color:var(--ink); font-weight:500;
              overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
  .exec .nm span { color:var(--faint); font-weight:400; }
  .exec .when { font-size:12px; color:var(--faint); white-space:nowrap; flex-shrink:0; }
  .execwrap { display:flex; flex-direction:column; }
  .execdet { padding:2px 16px 16px 31px; display:flex; flex-direction:column; gap:12px; background:var(--well);
             border-top:1px solid var(--hair); }
  /* Reuses the query workbench's own JSON block (pre.code.jsonv) — same
     highlighting, just tighter, because these sit inside a list row. */
  .execdet pre.code { font-size:11.5px; line-height:17.5px; background:var(--surface);
                      border:1px solid var(--line); border-radius:9px; padding:11px 13px;
                      max-height:300px; overflow:auto; white-space:pre-wrap; overflow-wrap:anywhere; }
  .execdet .lab { font-size:11.5px; font-weight:600; color:var(--dim); letter-spacing:.07em; }
  .schema { display:flex; flex-direction:column; }
  .schema .r { display:flex; align-items:baseline; gap:12px; padding:7px 0; border-top:1px solid var(--hair); }
  .schema .r:first-child { border-top:0; }
  .schema .r .n { width:170px; flex-shrink:0; font-family:var(--mono); font-size:12.5px; color:var(--ink); }
  .schema .r .t { font-size:12.5px; color:var(--hash); font-family:var(--mono); }
  .schema .r .req { font-size:11px; font-weight:600; color:var(--warn); }
  .schema .r .d { flex:1; min-width:0; font-size:12.5px; color:var(--dim); }

  /* ── namespace combobox: a real dropdown (known namespaces, click to
     pick) that is also just a text field — type a prefix pattern like
     "org.*" and it's accepted the same as any exact name. Shared by every
     page with a namespace picker, rendered as one pill ("Namespace: value
     ⌄") rather than each page inventing its own label placement — that
     drift was exactly what made the header row's height/position jump
     between pages that have this control and pages that don't. */
  .ns-combo { position:relative; display:inline-flex; align-items:stretch; height:34px;
              border-radius:9px; background:var(--surface); border:1px solid var(--line2);
              cursor:text; flex-shrink:0; }
  /* A shaded, static tag for "Namespace" — its own background, rounded to
     match the pill's own left corners (no `overflow:hidden` on `.ns-combo`
     for that — the dropdown menu is an absolutely-positioned child of it and
     would get clipped too), and a hairline border to its right — so it
     reads as the fixed label, leaving the plain-background value beside it
     looking like the part you can edit. */
  .ns-combo .lbl { display:flex; align-items:center; padding:0 11px; background:var(--raise);
                   color:var(--dim); font-size:13px; flex-shrink:0; border-right:1px solid var(--line2);
                   border-radius:8px 0 0 8px; }
  .ns-combo .value { display:flex; align-items:center; gap:8px; padding:0 12px; }
  /* Auto-width value: an invisible ::after twin (same text, via data-value)
     sizes the grid cell the input shares with it, so the pill hugs "caller"
     as tightly as it hugs "org.billing" — the same trick the editable page
     title uses (see .pagehead .input-sizer above). `input[type=text]`'s own
     rule outranks a single `.ns-combo-input` class on specificity, so every
     override below is scoped through `.ns-combo` to actually win. */
  .ns-combo .sizer { display:inline-grid; align-items:center; min-width:1em; }
  .ns-combo .sizer::after, .ns-combo .ns-combo-input { grid-area:1/1; box-sizing:border-box; }
  .ns-combo .sizer::after { content:attr(data-value) ' '; visibility:hidden; white-space:pre; font:inherit; }
  .ns-combo .ns-combo-input { border:0; background:none; padding:0; height:auto; width:100%; min-width:1em;
                              font:600 13px var(--sans); color:var(--ink); cursor:text; }
  .ns-combo .ns-combo-input:focus { outline:none; box-shadow:none; }
  .ns-combo-arrow { display:flex; align-items:center; color:var(--faint); flex-shrink:0; pointer-events:none; }
  .ns-combo-menu { position:absolute; z-index:20; top:calc(100% + 4px); right:0; left:auto; min-width:240px;
                   background:var(--surface); border:1px solid var(--line2); border-radius:10px;
                   box-shadow:var(--shadow); max-height:230px; overflow-y:auto; padding:4px; }
  .ns-combo-opt { padding:7px 9px; border-radius:7px; font-size:13px; color:var(--text); cursor:pointer; }
  .ns-combo-opt:hover, .ns-combo-opt.on { background:var(--raise); }
  .ns-combo-opt.hint { color:var(--accent); font-family:var(--mono); font-size:12px; }
  .ns-combo-empty { padding:7px 9px; font-size:13px; color:var(--faint); }

  /* ── suggestions ── */
  /* Page-level stacks own the rhythm between blocks; `.stack` is an inner
     group whose own rows carry their separators, so it takes no gap. */
  #sugList, #conBody { display:flex; flex-direction:column; gap:16px; }
  .stack { display:flex; flex-direction:column; }
  .sug { display:flex; flex-direction:column; gap:16px; padding:24px 28px 22px; }
  .tag { display:inline-flex; align-items:center; gap:7px; padding:4px 10px 4px 8px; border-radius:14px; font-size:12px; font-weight:600; }
  .evi { display:flex; flex-direction:column; background:var(--well); border:1px solid var(--hair); border-radius:11px; padding:2px 16px; }
  .evi-row { display:flex; align-items:center; gap:12px; padding:12px 0; border-bottom:1px solid var(--hair); }
  .evi-row:last-child { border-bottom:0; }
  .evi-row .t { flex:1; font-size:15px; color:var(--ink); }
  .evi-row .w { width:140px; flex-shrink:0; text-align:right; font-size:13px; color:var(--dim); }
  .acts { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
  .acts .note { flex:1; text-align:right; font-size:13.5px; color:var(--dim); }
  /* The confirm step replaces the action row rather than sitting under it —
     three live buttons at once is a guessing game. */
  .reason { display:flex; flex-direction:column; gap:9px; padding:14px 16px;
            background:var(--well); border:1px solid var(--line); border-radius:11px; }
  .reason .line { display:flex; align-items:center; gap:10px; }

  /* ── activity ── */
  .ev { display:flex; align-items:flex-start; gap:16px; padding:14px 0; border-top:1px solid var(--hair); }
  .ev .at { width:52px; flex-shrink:0; font-size:13px; color:var(--dim); padding-top:3px; }
  .ev .ic { width:18px; flex-shrink:0; display:flex; justify-content:center; padding-top:5px; }
  .ev .body { flex:1; display:flex; flex-direction:column; gap:3px; min-width:0; }
  .ev .say { font-size:15.5px; color:var(--ink); }
  .ev-tags { display:flex; align-items:center; gap:8px; flex-shrink:0; padding-top:4px; }
  .ev-tags .tag { padding:3px 9px; border-radius:8px; font-size:11px; }

  /* ── connect ── */
  .apps { display:flex; gap:16px; }
  .app { flex:1; display:flex; flex-direction:column; gap:8px; background:var(--well); border:1px solid var(--line);
         border-radius:12px; padding:14px 16px; }
  .app .hd { display:flex; align-items:center; gap:9px; }
  .app .hd b { flex:1; font-size:14.5px; font-weight:600; color:var(--ink); }
  .conns { display:flex; }
  .conns div { flex:1; display:flex; justify-content:center; }
  .conns i { width:2px; height:22px; background:var(--line2); display:block; border-radius:1px; }
  .hubbar { display:flex; align-items:center; gap:14px; background:var(--accent-soft); border:1.5px solid var(--accent);
            border-radius:12px; padding:16px 18px; }
  .kv { display:flex; align-items:baseline; gap:12px; padding:9px 0; border-top:1px solid var(--hair); }
  .kv .k { width:190px; flex-shrink:0; font-size:13.5px; color:var(--dim); }
  .kv .v { flex:1; font-size:14px; color:var(--ink); word-break:break-word; }

  /* ── panel ── */
  #panelWrap { position:fixed; inset:0; z-index:40; }
  #panelShade { position:absolute; inset:0; background:rgba(11,13,18,.35); backdrop-filter:blur(2px); }
  #panel { position:absolute; top:0; right:0; bottom:0; width:min(430px,96vw); background:var(--surface);
           border-left:1px solid var(--line2); box-shadow:var(--shadow); padding:28px 30px 32px; overflow-y:auto;
           display:flex; flex-direction:column; gap:24px; }
  .pgroup { display:flex; flex-direction:column; gap:14px; padding-top:20px; border-top:1px solid var(--hair); }
  .step { display:flex; gap:14px; }
  .step .rail { display:flex; flex-direction:column; align-items:center; width:10px; flex-shrink:0; gap:4px; }
  .step .bul { width:10px; height:10px; border-radius:5px; background:var(--ok); flex-shrink:0; }
  .step .bul.past { background:var(--surface); border:1.5px solid var(--line2); }
  .step .ln { width:1px; flex:1; background:var(--line); }

  /* ── dev sidebar ── */
  #devbar { width:330px; flex-shrink:0; background:var(--bg); border-left:1px solid var(--line);
            padding:26px 22px 28px; display:flex; flex-direction:column; gap:24px; position:sticky; top:0;
            height:100vh; overflow-y:auto; }
  .oprow { display:flex; align-items:center; gap:10px; padding:7px 0; border-bottom:1px solid var(--hair);
           cursor:pointer; font-family:var(--mono); font-size:11.5px; }
  .oprow .t { width:30px; flex-shrink:0; color:var(--ghost); }
  .oprow .o { width:70px; flex-shrink:0; }
  /* What the operation wrote, in words — the address is on hover. Sans, because
     this is prose now; teal mono only when we fall back to a bare hash. */
  .oprow .h { flex:1; min-width:0; font-family:var(--sans); font-size:12.5px; color:var(--text);
              overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
  .oprow .h.addr { font-family:var(--mono); font-size:11.5px; color:var(--hash); }
  .oprow .h.sys { color:var(--faint); }   /* the engine talking to itself */

  /* ── toast ── */
  #toast { position:fixed; bottom:24px; left:50%; transform:translateX(-50%); background:var(--ink); color:var(--bg);
           border-radius:10px; padding:10px 20px; font-size:14px; z-index:99; box-shadow:var(--shadow); display:none; }

  @media (max-width:1180px) { #devbar { display:none !important; } }
  @media (max-width:900px) { #rail { display:none; } .page { padding:28px 22px 44px; } }

  /* Last word: `hidden` must beat every id-level display rule above. */
  [hidden] { display:none !important; }
</style>
<script>
(function () {
  var q = new URLSearchParams(location.search);
  var t = q.get('theme') || localStorage.getItem('areev.theme');
  if (t === 'light' || t === 'dark') document.documentElement.dataset.theme = t;
  var d = q.get('dev');
  if (d === '1' || (d !== '0' && localStorage.getItem('areev.dev') === '1'))
    document.documentElement.classList.add('dev');
})();
</script>

<div id="shell">
  <nav id="rail">
    <button class="brand" id="brandBtn" type="button" title="Memory">
      <img class="mark" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAL60lEQVR42u1be5RVVRn/fXufc+65j3ncecIwzAzD8NAZRtFa4KuVDx4+UCrQBAEthSTLzDIr16rVWpWR4aqlS0vMFDMzxSwUNRIwclFBvAQGGAYGgRma98x9nnP2/vpjoCSBewYYHqv51tr/3H324/fbv/N93/7WucCADdiADdiA/f8anc7Fqr+wGawVjFABSBgf6WetoJLtABG2P/dJeInWft+TOB3AR81eiYsfciEDObCyhwKsDQDWRxubgbxKGMEooheMQ809W899BQSLx6B63kZ4iTYoJz5ESGsGiC4FKHCUxxWYNzLUYiGD2+P/Wg4VS6FhyZxzl4Dq+f+ENPPBWpUKw34WJK7KPIo3M3t3kDDXERE2PFJ8br4CgWgl3NguGMFSkGHN8gceAGgMQd7nJVtML9WJ4KALzk0F1MzfDBHIBliVkQguA+h8/6O5hbV3HUis1W4K7z82/NxSgLRzoFItMIJlILJm9A08AFAhkfzsuAdLwCp17img5os7IUwbgB5GwloG0Ki+z8J7WXuTAdqm3QTef3zkuaMA5cRhZQ0GkXnbiYEHACoDyZuNUAGU03PuKKBm/jYIKwtgriJpLAOo6oQnY65j5UwCYa8Ta0Ld0+PPfgVoN4lg4RBAiNknBR4AiEZDGFOFlY25i8ad/Qqo/sJmyEAOwDySpPUmiIad9KTMf9Ne8nqA2tKdDdix+OqzUwF2/igoJ46cEUMBYcw5JeB7VXARCXOisMIIl3z81EarUznZyNkrYITykWrrHC2E+SMQ5WYYkgbrehDlZVCjJELQS7S9qpyYFyquRdfOpWeXAsKl46HdBIbfVA4S5hwQVWSWtn5Pa/fzAH+QWQXiEzKQdYVh5yJr2NVnnwKqpi+BGSlGR137KCGth/2cPrP6thUufFO7yTIQXZKBAQsAUm11fwSRFjKA+IG/nx0KCBXVQqU6MfgT5SBhzQKJCh+e7R3W7htusg3M6jmAmzK7Ajk5kDtsrBkqRMFFd549r0DZlKcQyBuBppX1o0jIGT6GJAB+UpjBmE63I92+fhNYv+rDGRaSNGdu+mkZVLIDdv6oM09AqKgWbqwZWWUVIMP+LEj48fzvMHvLWbsQZgR2/sWaWT8LcEtmDoxPjflS/WgrtwLlU5468wSU37gIoeJadDfuGk4kZ/o7ff0UCSshrQia/voTeOkuOF171oHZjwrKSAamBQvKkfzXljNLQO99vxnhkgoIw54BEiN8eP63tRNfrt0k4vvXomXt45BmBIFolQL0rwC0+vAF05Mtu0pyqiZhxMxlZ46AymkvIVhUi/j+hkoieZuPIT3M6gkRyE4YdhQ7np8AAGh693tQ6U648eZ/gPXrPkJiDUn7BsPOQ+lVk88MAYHcYfASzQgWlINk4FYQjfRx+m+qVMcqlexA+9bf/ufnlvWLIO0ozHCJp5XzNMAdmfZNJGd6ydbc1o27UTH1mdOfB4y+46+wsobCTbRXCmH9GET5GdB3a+V8Qwayd8pANrb/6oojeg07D2bWYHjJ9iYZyKklEjUZ3oNBEGKtMOy6cPF5aFq94PQpQAbzoNNdsKJloN4q78jMh6+WubH9f3HjzWjb9PxH+vev+BbMrCGwo8Nd1u6vAU5kEiGRmKWdtoCXbMOQqx8+fQoYc88WSDsfKtU1goTxY4DyMsDvYuU8YAQL6oUZws7nJx71KTNcBCurBNpLNgkzdDllDqklENZqEnZjsKgWB9cs7H8F5NXMBKsUjFAJiKSv+z5rtdTpObDaix886ukftn3Lv45Bl9UgkFPRA+29AEBl8IY5BDHLTbRIrZLIq5nR/woYfvMSSDMC7XaPJpILgAw5P3MHa/drRih/N0kT9S9OOf6JWBdBWhGAVTMJczKIijNUNIYIaf+ZpNWUXXlNn1Ug+ib9erBy0bRmIQHyTsDHjQ+81Eu0r1GpLnTvzByzd/32JqQ6d8MuqGpi1kt8FAuKicTMhxYOBmuvfytCtffuBYQEGBeTEEsBGpQBfAcr90aQWK29tO/a/vlz18MI5oNZXyiMwFsAFWVYZy9rbxIg6thLY/NjladeAVWz/gRmDZXuESTEXZnBA2B+3Ut3r9FuAm6syfemtv5iLLSXgnZiW8C8wsc5lhHJW41wIdhL9Y8Cxnx5D0iaAOvxJIw/AFSY0fNrbypAK0ECYN3bevvArAEICGn2zksC4P+UVaG9TpDIAmvv0ySMFwAEMqxXz8qbBKIGN9aMbYs+5guX4cvxTX8VrBxop8c0gvl3ZwYPgHktmJvAugICADOYmQ4TANYEAhisiZk/hB4AO2DnoPaSGqAVRHI9iDLUw6kKRNPMUMGCzp3LTq0Cau6phzCDgFZXkDRfAyjqY1g3gA6ABUCH0DH9z9rc20d85O/cxtqZQyQ2kxEEe+n7QeIRH6n2Ju0lrwXoQLq9Hjt+PfHkfUDphEegnRiczkYTJOf6BA8A2QDKARoKoKy30dAPtdL/9nH5h1oZgLEgOXvjo6XQTgLM6jWAd/u4JI0hYU41woW46dBF66QVcMF9+wAIaJW+Skh7CYhycFqMG1m5E0G0o23rSyiovvVxkJjvQwVrvHT3DUTUlmjegIZXbjlxBQyduBBuogVO154ACXPe6QMPAFROwvhcomUDFVTfCga/DKDHhwo+Js3gFDM8CGXX3XxyCrjway1g7UF7qWuEYb8CUPZJIPIA7AGwFcB2EMWPtj5rTxNJApGAVnu0l3wBJNMAR4S0XwXRNZn9r1qlkp1TIURnbM9KNL5xd98JqJiyCOHSS8DKsY1w0WIiOe0EgTsArwLrxQCvZO01SzvfPWa8FhJgDWYGEQFEMEJ58OJt0Cp9F5F8MrPv4jQr5zZhhl6WgRys+77VdwIu+mYMyomDvfS1JM2XAIqcwHu8k1k/DO3+joxQD7QLrRx0734bjX+ch0jppR8ZoVUKJCzQodzBCBeh+JKvIhCtBJhLSVpvA3SeDxUs9RKtt5AwEj0Ny7H3rXv9E1B1yysIFl8I1ioszciLIHFD37HzamZ9jzACG7WbgAzkItmyCXXPXH5iBZjb30XOiCuQam36IUg86GMDMdbeNBLmWwCwceEg/04we/i1kGYWhBmaABJXnwD4d7WXvAPgjU73fmgvjfULsk8YfG8RJh/J1gNg7S4B2McXlBQhkne48YOWl2rH4Mu+6o+A0be/Bzd2AMrpiBCJuQCCfQS/hVnNJ2nVm+ECSDsX7z8+4qRjwp7fz4FKtsFLHNwA1u/4CyQ0yQhGx8tALorG3e+PgOCgWggzCyTDkwG6so9H38qsHhCGvaWrYQWcrn3Y/LPyUxIU401rEYgOh5ld4bL2XgQ47YOBXBLGbO22SO0ljlowOYKA6nmb4CVaoZ1ELpGcD5DdlzDHWi2Y9OiQN7xECyKDL8Tmx6pwKq1l3ZNQyXYoJ76Smf/pM5+4URh5Y4UMo3TCD45PQLCoBsIMgwxrCogu75vy1SvK6XnizS83AEJgy8/HnPLU6IO378e25y6HnTeiA9pb4pOAQhJythvfRKzSMEIFxybA6d4H7cbzCWIeANM/er2NlfNdaWXFhBHE+4+NQn/ZsCnPwun+AFo5fwDrRp8kfMYI19SQjOD8uRuOTQBJC0JaN2S+eh6BvpO195ARLKg7sOo76NzxWr8myPW/uR5Oz350bV+yk1n7vPdSCUHOjA4rAWt1HCdIBABh/8VS3sFa3Zc4uOX3TlcjCsbeicbX7+73W4JhRxGtnsmsvZ+A9SqfEWFWR8P+aiHN4xREmMHAbwhsAVR97EyRHTBvZdbLpB3dZedVglmh7peXnJZrUvyD95A/9nPwEq31rNzbSNB0gKu5938Ih/coD9VeDiNWzLoIgrccMxO84P6Dh8pWAqQZrNzDqjiCJGFHoLULVi7c2AHIQE6/fMZ6PDvvrnWwo1VQTg9ImBg0rghv3fLfvdqFNWRGhiBn+AQCGG5PM8JDx3PDy9P5uKlw7Vf2grXqrQAdQwCsXKTbd4FZY8fiK3Embcy9jZBWBPF9f4MTO/AhxQsAAkYwCjBDuQmwdgEw9rx2OwZswAZswAZswIB/A76DD3Wl5sBCAAAAAElFTkSuQmCC" alt="" aria-hidden="true">
      <b>Areev</b>
    </button>

    <div class="nav" id="nav">
      <button class="nav-item on" data-page="memory">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M5 4.5A1.5 1.5 0 016.5 3H17a1.5 1.5 0 011.5 1.5V21l-6.5-3.4L5.5 21V4.5z" stroke-width="1.7" stroke-linejoin="round"/></svg>
        <span class="grow">Memory</span>
      </button>
      <button class="nav-item" data-page="query">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M4.5 6.5h15M4.5 12h9M4.5 17.5h12" stroke-width="1.7" stroke-linecap="round"/><path d="M16.5 15.5l2.2 2.2" stroke-width="1.7" stroke-linecap="round"/><circle cx="15" cy="14" r="2.6" stroke-width="1.7"/></svg>
        <span class="grow">Query</span>
      </button>
      <button class="nav-item" data-page="activity">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M3 12.5h4.2l2.6-7 4.2 13 2.4-6h4.6" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
        <span class="grow">Activity</span>
      </button>
      <!-- Plan before run before catalog: the order you meet them in. A
           trigger has no nav item of its own — it is only meaningful next to
           the plan it starts, so it lives on the workflow canvas. -->
      <button class="nav-item" data-page="workflows">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><circle cx="5.5" cy="6" r="2.3" stroke-width="1.7"/><circle cx="18.5" cy="6" r="2.3" stroke-width="1.7"/><circle cx="12" cy="18" r="2.3" stroke-width="1.7"/><path d="M7.6 7.2L11 16M16.4 7.2L13 16M7.8 6h8.4" stroke-width="1.7" stroke-linecap="round"/></svg>
        <span class="grow">Workflows</span>
        <span class="pill soft" id="wfTrgPill" hidden>0</span>
      </button>
      <button class="nav-item" data-page="runs">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M5 4.5v15l13-7.5-13-7.5z" stroke-width="1.7" stroke-linejoin="round"/></svg>
        <span class="grow">Runs</span>
        <span class="pill" id="runPill" hidden>0</span>
      </button>
      <button class="nav-item" data-page="tools">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M9 2.8v5.4M15 2.8v5.4" stroke-width="1.7" stroke-linecap="round"/><path d="M5.8 8.2h12.4v3.2a6.2 6.2 0 01-12.4 0V8.2z" stroke-width="1.7" stroke-linejoin="round"/><path d="M12 17.6v3.6" stroke-width="1.7" stroke-linecap="round"/></svg>
        <span class="grow">Tools</span>
      </button>
      <button class="nav-item" data-page="suggestions">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M12 3.5l1.9 4.9 4.9 1.9-4.9 1.9L12 17.1l-1.9-4.9L5.2 10.3l4.9-1.9L12 3.5z" stroke-width="1.7" stroke-linejoin="round"/></svg>
        <span class="grow">Suggestions</span>
        <span class="pill" id="sugPill" hidden>0</span>
      </button>
      <button class="nav-item" data-page="analytics">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M5 19V13.5M11.5 19V8.5M18 19V5" stroke-width="1.7" stroke-linecap="round"/></svg>
        <span class="grow">Analytics</span>
      </button>
      <button class="nav-item" data-page="settings">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="3" stroke-width="1.7"/><path d="M19.4 13.5a1.7 1.7 0 000-3l-1-.2a6.7 6.7 0 00-.7-1.7l.6-.9a1.7 1.7 0 00-2.4-2.4l-.9.6a6.7 6.7 0 00-1.7-.7l-.2-1a1.7 1.7 0 00-3 0l-.2 1a6.7 6.7 0 00-1.7.7l-.9-.6a1.7 1.7 0 00-2.4 2.4l.6.9a6.7 6.7 0 00-.7 1.7l-1 .2a1.7 1.7 0 000 3l1 .2c.15.6.4 1.17.7 1.7l-.6.9a1.7 1.7 0 002.4 2.4l.9-.6c.53.3 1.1.55 1.7.7l.2 1a1.7 1.7 0 003 0l.2-1c.6-.15 1.17-.4 1.7-.7l.9.6a1.7 1.7 0 002.4-2.4l-.6-.9c.3-.53.55-1.1.7-1.7l1-.2z" stroke-width="1.7" stroke-linejoin="round"/></svg>
        <span class="grow">Settings</span>
      </button>
    </div>

    <div class="rail-foot">
      <div class="health" id="health" title="check every stored memory against its content address">
        <span class="dot" id="hdot"></span><span id="htext">checking…</span>
      </div>
      <div class="toggle-row" id="whorow" style="display:none;border:0;padding-top:0">
        <span id="whoami" title="the principal this session is bound to">…</span>
        <button id="signbtn" style="background:none;border:0;color:var(--accent);cursor:pointer;font:inherit;padding:0">Sign in</button>
      </div>
      <span class="tiny" id="dblabel" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{DB}}</span>
    </div>
  </nav>

  <main id="main">
    <!-- ── MEMORY ── -->
    <section class="page" id="page-memory">
      <div style="display:flex;align-items:flex-end;gap:16px" class="wide">
        <div id="memCrumb" style="flex:1;min-width:0"></div>
        <div class="seg" id="mview">
          <button class="on" data-v="list">List</button>
          <button data-v="graph">Graph</button>
        </div>
      </div>

      <div id="listView" style="display:flex;flex-direction:column;gap:24px">
        <div class="wide" style="display:flex;flex-direction:column;gap:11px">
          <div class="askbar">
            <svg width="19" height="19" viewBox="0 0 24 24" fill="none" style="flex-shrink:0"><circle cx="11" cy="11" r="6.6" stroke="var(--accent)" stroke-width="1.8"/><path d="M16 16l4.2 4.2" stroke="var(--accent)" stroke-width="1.8" stroke-linecap="round"/></svg>
            <input type="text" id="ask" placeholder="Search your memories — or ask a question and press Enter" autocomplete="off">
            <button class="btn sm" id="askBtn">Ask</button>
          </div>
          <div class="examples" id="examples"></div>
        </div>

        <div class="banner wide" id="sugBanner" hidden>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" style="flex-shrink:0"><path d="M12 3.5l1.9 4.9 4.9 1.9-4.9 1.9L12 17.1l-1.9-4.9L5.2 10.3l4.9-1.9L12 3.5z" stroke="var(--warn)" stroke-width="1.7" stroke-linejoin="round"/></svg>
          <span class="grow" id="sugBannerText"></span>
          <span class="go" id="sugBannerGo">Review →</span>
        </div>

        <div class="wide" id="filterBar" hidden></div>
        <div class="card wide" id="answer" hidden></div>
        <div class="wide" id="memList"><div class="empty">loading…</div></div>
      </div>

      <div id="graphView" hidden>
        <div id="gwrap">
         <div id="gstage">
          <canvas id="gcanvas"></canvas>
          <div class="float" id="gtools">
            <div style="display:flex;align-items:center;gap:9px;height:36px;width:250px;padding:0 12px;background:var(--surface);border:1px solid var(--line);border-radius:10px">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" style="flex-shrink:0"><circle cx="11" cy="11" r="6.6" stroke="var(--dim)" stroke-width="1.9"/><path d="M16 16l4.2 4.2" stroke="var(--dim)" stroke-width="1.9" stroke-linecap="round"/></svg>
              <input type="text" id="gjump" placeholder="Jump to anyone…" style="border:0;background:none;padding:0;font-size:13.5px">
            </div>
            <div class="seg" id="gdepth" style="background:var(--surface);border:1px solid var(--line)">
              <button class="on" data-d="1">Direct</button><button data-d="2">2 steps</button>
            </div>
          </div>
          <div class="float" id="glegend"></div>
          <div class="float" id="gzoom">
            <button id="gout" title="zoom out">−</button><button id="gin" title="zoom in">+</button><button class="lbl" id="gfit">Fit</button>
          </div>
          <div class="float" id="ginspect" hidden></div>
         </div>
          <div id="gscrub">
            <div style="display:flex;align-items:center;gap:9px">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" style="flex-shrink:0"><circle cx="12" cy="12" r="8.5" stroke="var(--muted)" stroke-width="1.8"/><path d="M12 7.5V12l3 2" stroke="var(--muted)" stroke-width="1.8" stroke-linecap="round"/></svg>
              <b style="font-size:13.5px;color:var(--ink)">Rewind</b>
              <span class="meta" style="flex:1">drag to see what your agent knew at any point — nothing is ever deleted from the history</span>
              <span class="chip on" id="gnow" style="height:26px;padding:0 12px;display:inline-flex;align-items:center">now</span>
            </div>
            <input type="range" id="grange" min="0" max="100" value="100">
            <div class="scrub-ticks" id="gticks"></div>
          </div>
        </div>
      </div>
    </section>

    <!-- ── ANALYTICS ── -->
    <section class="page" id="page-analytics" hidden>
      <div class="wide" style="display:flex;align-items:flex-start;gap:16px">
        <div id="anCrumb" style="flex:1;min-width:0"></div>
        <span id="anNsHost"></span>
      </div>

      <div class="wide stiles" id="anTiles"></div>

      <div class="wide qsec"><span class="sec-label">WHAT'S IN THIS MEMORY</span><i></i>
        <span class="tiny">All 12 grain types this memory can hold — click one to run it in Query</span></div>
      <div class="wide census" id="anCensus"></div>

      <div class="wide qsec"><span class="sec-label">NAMESPACES</span><i></i>
        <span class="tiny">Every namespace this session can read — click one to scope the page to it</span></div>
      <div class="wide census" id="anNsBreakdown"></div>

      <div class="wide qsec"><span class="sec-label">GROWTH</span><i></i>
        <span class="tiny" id="anGrowthCaption"></span></div>
      <div class="wide" id="anGrowth"></div>

      <div class="wide qsec"><span class="sec-label">HOW IT CAN BE QUERIED</span><i></i>
        <span class="tiny">The recall legs active on this file</span></div>
      <div class="wide legs" id="anLegs"></div>
    </section>

    <!-- ── ACTIVITY ── -->
    <section class="page" id="page-activity" hidden>
      <div class="wide" style="display:flex;align-items:flex-start;gap:16px">
        <div id="actCrumb" style="flex:1;min-width:0"></div>
        <span id="actNsHost"></span>
      </div>
      <div class="examples wide" id="actFilters"></div>
      <div class="wide" id="actList"><div class="empty">loading…</div></div>
    </section>

    <!-- ── SUGGESTIONS ── -->
    <section class="page" id="page-suggestions" hidden>
      <div id="sugCrumb" class="wide"></div>
      <div class="wide" style="display:flex;align-items:center;gap:16px">
        <div class="tabs" id="sugTabs" style="flex:1">
          <button class="on" data-s="pending">Needs review</button>
          <button data-s="applied">Applied</button>
          <button data-s="rejected">Dismissed</button>
        </div>
        <button class="btn sm" id="runLoop">Run analysis</button>
      </div>
      <div class="wide" id="sugList"><div class="empty">loading…</div></div>
    </section>

    <!-- ── RUNS: the governed runtime viewer + HITL approval queue ── -->
    <section class="page" id="page-runs" hidden>
      <div id="runCrumb" class="wide"></div>
      <div class="wide" id="runList"><div class="empty">loading…</div></div>
    </section>

    <!-- ── WORKFLOWS: plans as an editable graph ──
         One action slot, top right, for whatever this view's primary act is:
         "New workflow" on the list, "Save as new plan" in the editor. -->
    <!-- Tools: what a step can call, and every call that was made. Both are
         Tool grains split by `kind` — one catalog answering two questions
         ("what can run" / "what did run"), so two tabs rather than two pages.
         The namespace picker is deliberately the SAME state the Workflows
         page uses (WF_NS): a plan and the tools it binds are one operations
         surface, and two independent pickers on the same rows drift. -->
    <section class="page" id="page-tools" hidden>
      <div id="toolCrumb" class="wide"></div>
      <div class="wide" style="display:flex;align-items:center;gap:16px" id="toolTabsRow">
        <div class="tabs" id="toolTabs" style="flex:1">
          <button class="on" data-t="catalog">Catalog</button>
          <button data-t="executions">Executions</button>
        </div>
        <span id="toolNsHost"></span>
      </div>
      <div class="wide" id="toolBody"></div>
    </section>

    <section class="page" id="page-workflows" hidden>
      <div class="wide" style="display:flex;align-items:flex-start;gap:16px">
        <div id="wfCrumb" style="flex:1;min-width:0"></div>
        <span id="wfRunHost"></span>
        <span id="wfNsHost"></span>
        <button class="btn sm" id="wfNewBtn">New workflow</button>
        <button class="btn sm" id="wfSave" hidden>Save as new plan</button>
      </div>

      <div class="wide" id="wfList"><div class="empty">loading…</div></div>
      <div class="wide" id="wfOrphans" hidden></div>

      <div id="wfEditorWrap" hidden style="display:flex;flex-direction:column;gap:12px;flex:1;min-height:0;">
        <div class="wide" id="wfwrap" style="flex:1;min-height:0;">
          <div id="wfstage">
            <canvas id="wfcanvas"></canvas>
            <div class="float" id="wftools">
              <button class="btn sm" id="wfAddNode">+ Node</button>
              <button class="btn ghost sm" id="wfResetLayout">Reset layout</button>
              <span class="tiny" id="wfHint">Drag a step's dot to connect it</span>
            </div>
            <div class="float" id="wflegend"></div>
            <div class="float" id="wfzoom">
              <button id="wfout" title="zoom out">−</button><button id="wfin" title="zoom in">+</button><button class="lbl" id="wffit">Fit</button>
            </div>
            <div class="float" id="wfinspect" hidden></div>
          </div>
        </div>
        <div class="col" id="wfReasonBox"></div>
      </div>
    </section>

    <!-- ── SETTINGS (formerly "Connect" — Agent/Sync tabs plus General,
         which now also carries what used to sit in the rail-foot:
         developer mode and dark mode) ── -->
    <section class="page" id="page-settings" hidden>
      <div id="setCrumb" class="wide"></div>
      <div class="tabs wide" id="conTabs">
        <button class="on" data-c="agent">Your agent</button>
        <button data-c="sync">Sync across apps</button>
        <button data-c="general">General</button>
      </div>
      <div class="wide" id="conBody"></div>
    </section>

    <!-- ── QUERY ── -->
    <section class="page" id="page-query" hidden>
      <div class="wide" style="display:flex;align-items:center;gap:16px">
        <div id="queryCrumb" style="flex:1;min-width:0"></div>
        <button class="btn ghost sm" id="qreset" hidden>New query</button>
      </div>
      <span class="wide sub" id="qintro">Ask the memory a precise question. Every view in this console
        runs the same language underneath — start from an example below and edit it.</span>

      <div class="wide composer">
        <div class="qedit">
          <div id="qhl" aria-hidden="true"></div>
          <textarea id="qtext" spellcheck="false" rows="3"
            placeholder='RECALL facts WHERE subject = "john" LIMIT 20'></textarea>
        </div>
        <div class="cbar">
          <button class="btn sm" id="qrun">Run <span class="kbd">⌘⏎</span></button>
          <button class="btn ghost sm" id="qexplain">Explain</button>
          <button class="btn ghost sm" id="qsave">Save</button>
          <div class="menuwrap"><button class="btn ghost sm hasmenu" id="fmtBtn">Format</button>
            <div class="menu" id="fmtMenu" hidden></div></div>
          <div style="flex:1"></div>
          <span class="tiny" id="qnotice"></span>
        </div>
      </div>
      <div class="wide" id="qerr" hidden></div>

      <div class="wide onramp" id="qonramp">
        <div class="qsec"><span class="sec-label">START FROM A QUESTION</span><i></i>
          <span class="tiny">Each one writes real CAL into the editor — edit it from there</span></div>
        <div class="starters" id="qstarters"></div>
        <div class="qsec"><span class="sec-label">SAVED &amp; RECENT</span><i></i>
          <div class="menuwrap"><button class="btn ghost sm hasmenu" id="savedBtn">All saved</button>
            <div class="menu" id="savedMenu" hidden></div></div>
          <div class="menuwrap"><button class="btn ghost sm hasmenu" id="histBtn">Full history</button>
            <div class="menu" id="histMenu" hidden></div></div></div>
        <div class="recents" id="qrecents"></div>
      </div>

      <div class="wide" id="qresult" hidden>
        <div id="qsummary"></div>
        <div id="qbar"></div>
        <div id="qbody"></div>
        <div id="qmore" hidden></div>
      </div>
    </section>
  </main>

  <aside id="devbar" class="dev-only dev-flex">
    <div style="display:flex;flex-direction:column;gap:11px">
      <span class="sec-label">STORE</span>
      <div id="devStats"></div>
    </div>
    <div style="display:flex;flex-direction:column;gap:0">
      <span class="sec-label" style="padding-bottom:12px">OP LOG</span>
      <div id="devLog"></div>
    </div>
    <div style="display:flex;flex-direction:column;gap:9px;margin-top:auto">
      <span class="sec-label">CAL</span>
      <span class="tiny">Every view here runs CAL underneath. The full workbench —
        history, saved queries, templates and every output format — lives on the Query page.</span>
      <button class="btn ghost sm" id="devQuery">Open Query →</button>
    </div>
  </aside>
</div>

<div id="panelWrap" hidden><div id="panelShade"></div><aside id="panel"></aside></div>
<div id="toast"></div>

<script>
'use strict';
const $ = id => document.getElementById(id);
const esc = s => String(s == null ? '' : s).replace(/&/g,'&amp;').replace(/</g,'&lt;')
  .replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
const el = (tag, cls, txt) => { const n = document.createElement(tag); if (cls) n.className = cls;
  if (txt != null) n.textContent = txt; return n; };
/* Wrap a native <select> with a drawn chevron (see the `select`/`.sel-wrap`
   CSS) so it reads as one of this console's own controls rather than the
   browser's default box — real native behavior underneath, just restyled. */
function styledSelect(select) {
  const wrap = el('div', 'sel-wrap');
  wrap.appendChild(select);
  const arrow = el('span', 'sel-arrow');
  arrow.innerHTML = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none"><path d="M5 9l7 7 7-7" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
  wrap.appendChild(arrow);
  return wrap;
}

/* ══ page header ══════════════════════════════════════════════════════
   One component for every page: a breadcrumb trail (home icon › section ›
   optional current item) plus a description line beneath it. Every page
   calls this instead of hand-rolling its own <h1>/.sub — home always jumps
   to Memory; crumbs is an array of {label, onClick?} with the trailing,
   onClick-less entry rendered as the bold "you are here" segment. */
const HOME_ICON = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M4 11.5L12 4l8 7.5M6.5 10v9h11v-9" '
  + 'stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>';
const EDIT_ICON = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none"><path d="M16.5 3.5l4 4L8 20l-5 1 1-5L16.5 3.5z" '
  + 'stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/></svg>';
const LOCK_ICON = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none"><rect x="5" y="11" width="14" height="9" rx="2" stroke="currentColor" stroke-width="1.8"/>'
  + '<path d="M8 11V7a4 4 0 018 0v4" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>';
/* An inline-editable title/description field: always the same <input>, in
   display state or focused/active state — never swapped for another
   element — so becoming editable never shifts the layout around it. A
   pencil icon fades in on row hover as the "this is editable" cue; clicking
   the text itself works just as well. cfg: {value, placeholder, disabled,
   onCommit(newValue)}. lockHint, if given, adds a small icon carrying it as
   a native tooltip (used for "why can't I edit this"). */
function editableField(cls, cfg, lockHint) {
  const row = el('div', 'edit-row');
  // The sizer's data-value drives an invisible ::after twin (same text, same
  // font) that the input shares a grid cell with — the cell (and so the
  // input) is exactly as wide as the text/placeholder, never wider, so the
  // edit/lock icons that follow sit right against the text instead of
  // stranded at the far edge of a full-width field.
  const sizer = el('span', 'input-sizer ' + cls);
  sizer.dataset.value = cfg.value || cfg.placeholder || '';
  const input = document.createElement('input');
  input.type = 'text'; input.className = cls; input.autocomplete = 'off';
  input.value = cfg.value || '';
  input.placeholder = cfg.placeholder || '';
  input.disabled = !!cfg.disabled;
  input.addEventListener('input', () => { sizer.dataset.value = input.value || cfg.placeholder || ''; });
  input.addEventListener('blur', () => {
    const v = input.value.trim();
    if (v !== (cfg.value || '')) cfg.onCommit(v);
  });
  input.addEventListener('keydown', e => {
    if (e.key === 'Enter') { e.preventDefault(); input.blur(); }
    else if (e.key === 'Escape') { input.value = cfg.value || ''; sizer.dataset.value = cfg.value || cfg.placeholder || ''; input.blur(); }
  });
  sizer.appendChild(input);
  row.appendChild(sizer);
  if (!cfg.disabled) {
    const icon = el('span', 'edit-icon'); icon.innerHTML = EDIT_ICON;
    icon.onclick = () => input.focus();
    row.appendChild(icon);
  }
  if (lockHint) {
    const lock = el('span', 'lock-hint'); lock.innerHTML = LOCK_ICON; lock.title = lockHint;
    row.appendChild(lock);
  }
  return row;
}
/* opts (optional): { editTitle, editDesc: <editableField cfg>, lockHint }.
   The current-page segment (either the last crumb's plain label, or the
   editable title field when editTitle is set) renders IN the trail row,
   right after its own leading "›" — one line, home icon through to "you
   are here" — never a separate headline below it. descHtml (or editDesc)
   is the one line beneath. */
function renderCrumbHeader(hostId, crumbs, descHtml, opts) {
  const host = $(hostId); if (!host) return;
  opts = opts || {};
  host.textContent = '';
  const wrap = el('div', 'pagehead');
  const trail = el('div', 'trail');
  const home = el('button', 'home'); home.innerHTML = HOME_ICON; home.title = 'Memory'; home.onclick = () => go('memory');
  trail.appendChild(home);
  const priorCrumbs = opts.editTitle ? crumbs : crumbs.slice(0, -1);
  for (const c of priorCrumbs) {
    trail.appendChild(el('span', 'sep', '›'));
    if (c.onClick) { const b = el('button', 'link', c.label); b.onclick = c.onClick; trail.appendChild(b); }
    else trail.appendChild(el('span', 'link', c.label));
  }
  trail.appendChild(el('span', 'sep', '›'));
  if (opts.editTitle) trail.appendChild(editableField('ctitle', opts.editTitle, opts.lockHint));
  else trail.appendChild(el('span', 'ctitle', crumbs[crumbs.length - 1].label));
  wrap.appendChild(trail);
  if (opts.editDesc) wrap.appendChild(editableField('cdesc', opts.editDesc, null));
  else if (descHtml) { const d = el('div', 'cdesc'); d.innerHTML = descHtml; wrap.appendChild(d); }
  host.appendChild(wrap);
}

/* ══ api ══════════════════════════════════════════════════════════════ */
let TOKEN = sessionStorage.getItem('areev.token') || '';
async function api(url, opts) {
  opts = Object.assign({}, opts);
  if (TOKEN) opts.headers = Object.assign({}, opts.headers, { Authorization: 'Bearer ' + TOKEN });
  let r;
  try { r = await fetch(url, opts); } catch (e) { return { ok: false, error: 'network error' }; }
  if (r.status === 401) {
    const t = window.prompt('This console is protected. Paste its token:');
    if (t) { TOKEN = t; sessionStorage.setItem('areev.token', t); return api(url, opts); }
    return { ok: false, error: 'not authorised' };
  }
  try { return await r.json(); } catch (e) { return { ok: false, error: 'bad response' }; }
}
const cal = q => api('/api/cal', { method: 'POST', headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ query: q }) });

/* Identity: in multi-principal mode (areev ui --auth) the rail shows who
   this session is bound to; Sign in stores a bearer token, Sign out
   drops back to the read-only anonymous session. */
async function refreshWhoami() {
  const w = await api('/api/whoami');
  if (!w || !w.ok || w.mode !== 'credentials') return;
  const row = $('whorow'); row.style.display = '';
  $('whoami').textContent = w.owner ? 'Owner session' : w.principal;
  $('signbtn').textContent = TOKEN ? 'Sign out' : 'Sign in';
}
document.addEventListener('DOMContentLoaded', () => {
  const btn = $('signbtn');
  if (btn) btn.addEventListener('click', () => {
    if (TOKEN) { TOKEN = ''; sessionStorage.removeItem('areev.token'); }
    else {
      const t = window.prompt('Paste your access token:');
      if (!t) return;
      TOKEN = t; sessionStorage.setItem('areev.token', t);
    }
    location.reload();
  });
  refreshWhoami();
});

/* ══ helpers ══════════════════════════════════════════════════════════ */
function toast(msg) {
  const t = $('toast'); t.textContent = msg; t.style.display = 'block';
  clearTimeout(toast._h); toast._h = setTimeout(() => { t.style.display = 'none'; }, 2000);
}
function copyText(s, label) {
  if (!navigator.clipboard) { toast('copy unavailable'); return; }
  navigator.clipboard.writeText(s).then(() => toast((label || 'Copied') + ' ✓'), () => toast('Copy failed'));
}
function download(name, text, mime) {
  const a = document.createElement('a');
  a.href = URL.createObjectURL(new Blob([text], { type: mime || 'application/json' }));
  a.download = name; a.click(); URL.revokeObjectURL(a.href);
}
const hlcMs = h => Math.floor((h || 0) / 65536);
const shortHash = h => h ? h.slice(0, 12) + '…' : '';
const cap = s => s ? s.charAt(0).toUpperCase() + s.slice(1) : '';
/* Capitalise names that read as words ("john" → "John"), but leave
   identifiers alone — "Payment_gateway" and "Contract-9107" look wrong. */
const titleize = s => /^[a-z]+( [a-z]+)*$/.test(String(s || '')) ? cap(s) : String(s || '');
const lowerFirst = s => s ? s.charAt(0).toLowerCase() + s.slice(1) : '';
function relTime(ms) {
  if (!ms) return '';
  const d = Date.now() - ms;
  if (d < 45000) return 'just now';
  const m = Math.floor(d / 60000); if (m < 60) return m + (m === 1 ? ' minute ago' : ' minutes ago');
  const h = Math.floor(m / 60); if (h < 24) return h + (h === 1 ? ' hour ago' : ' hours ago');
  const dd = Math.floor(h / 24); if (dd < 30) return dd + (dd === 1 ? ' day ago' : ' days ago');
  const mo = Math.floor(dd / 30); return mo + (mo === 1 ? ' month ago' : ' months ago');
}
const shortWhen = ms => {
  if (!ms) return '';
  const d = Date.now() - ms;
  if (d < 45000) return 'now';
  const m = Math.floor(d / 60000); if (m < 60) return m + 'm';
  const h = Math.floor(m / 60); if (h < 24) return h + 'h';
  const dd = Math.floor(h / 24); if (dd < 30) return dd + 'd';
  return Math.floor(dd / 30) + 'mo';
};
const dayKey = ms => new Date(ms).toDateString();
function dayLabel(ms) {
  const k = dayKey(ms), today = new Date().toDateString();
  const y = new Date(Date.now() - 86400000).toDateString();
  if (k === today) return 'TODAY';
  if (k === y) return 'YESTERDAY';
  return new Date(ms).toLocaleDateString(undefined, { day: 'numeric', month: 'long' }).toUpperCase();
}
const clock = ms => new Date(ms).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
const isoTitle = ms => ms ? new Date(ms).toISOString() : '';
/* created_at rides as epoch millis (a number) on stored grains, but an ISO
   string on anything hand-written — accept both, never NaN. */
function createdMs(f) {
  const c = f && f.created_at;
  if (typeof c === 'number') return c;
  if (typeof c === 'string') { const p = Date.parse(c); return isNaN(p) ? 0 : p; }
  return 0;
}
/* Some writers (areev remember, memory-tool imports) tuck the human text
   inside `context` rather than a top-level field. Dig for it — a memory
   that renders as an empty row is worse than no row at all. */
function ctxText(f) {
  const c = f && f.context;
  if (!c || typeof c !== 'object') return '';
  for (const k of ['content', 'text', 'message', 'summary', 'description']) {
    if (typeof c[k] === 'string' && c[k].trim()) return c[k];
  }
  return '';
}
function preview(f) {
  if (!f) return '';
  const v = f.object != null ? f.object : f.content != null ? f.content
    : f.description != null ? f.description : f.tool_content != null ? f.tool_content
    : f.summary != null ? f.summary : f.title != null ? f.title
    : ctxText(f) ? ctxText(f)
    : f.data != null ? JSON.stringify(f.data) : '';
  const s = typeof v === 'string' ? v : JSON.stringify(v);
  return s.length > 140 ? s.slice(0, 140) + '…' : s;
}
const cssVar = n => getComputedStyle(document.documentElement).getPropertyValue(n).trim();

/* ══ language: a triple, said out loud ════════════════════════════════ */
const REL_PHRASE = {
  prefers: 'Prefers {o}', likes: 'Likes {o}', dislikes: 'Dislikes {o}',
  works_at: 'Works at {o}', employed_by: 'Works at {o}', member_of: 'Is a member of {o}',
  lives_in: 'Lives in {o}', based_in: 'Is based in {o}', headquartered_in: 'Headquartered in {o}',
  owns_project: 'Owns the {o} project', maintains: 'Maintains {o}', works_on: 'Works on {o}',
  collaborates_with: 'Collaborates with {o}', knows: 'Knows {o}', reports_to: 'Reports to {o}',
  asked_about: 'Asked about {o}', email: 'Email is {o}', phone: 'Phone number is {o}',
  role: 'Role is {o}', title: 'Title is {o}', speaks: 'Speaks {o}', located_in: 'Is located in {o}',
};
/* No sentence is allowed to be a wall of text. A fact's object can be a
   serialized record (the loop stores recommendations as Facts), and an
   unbroken 1.5 KB of JSON has no wrap opportunities — it just blows the
   column out sideways. */
const MAX_SAY = 180;
const clampText = s => s.length > MAX_SAY ? s.slice(0, MAX_SAY).trimEnd() + '…' : s;
function predicate(g) {
  const f = g.fields || {};
  if (g.type === 'fact') {
    const r = f.relation || '', o = f.object;
    const os = clampText(typeof o === 'string' ? o : JSON.stringify(o == null ? '' : o));
    const tpl = REL_PHRASE[r];
    if (tpl) return tpl.replace('{o}', os);
    if (!r) return os;
    return cap(r.replace(/_/g, ' ')) + ' ' + os;
  }
  const fallback = 'A ' + (g.type || 'memory') + ' with no readable text';
  if (g.type === 'tool') {
    const name = f.tool_name || 'A tool';
    const body = f.tool_content || ctxText(f) || '';
    return name + (f.is_error ? ' failed' : ' ran') + (body ? ' — ' + clampText(body) : '');
  }
  /* A run checkpoint is the runtime's own bookkeeping — its body is the
     scheduler's serialized state, which has no sentence in it. Say which run
     and which step it belongs to instead of calling it unreadable. */
  if (g.type === 'state' && f.checkpoint && f.run_id != null)
    return 'Checkpoint of run ' + f.run_id + (f.superstep != null ? ' \u00b7 step ' + f.superstep : '');
  if (g.type === 'observation') return f.content || f.object || ctxText(f) || fallback;
  if (g.type === 'event') return f.content || f.description || preview(f) || fallback;
  if (g.type === 'goal') return f.description || f.content || preview(f) || fallback;
  return preview(f) || fallback;
}
function sentence(g) {
  const f = g.fields || {}, p = predicate(g);
  if (!f.subject) return p;
  const s = String(f.subject);
  /* Observations and events are free text that usually names the subject
     already — prefixing it again gives "john john asked about…". */
  if (p.toLowerCase().startsWith(s.toLowerCase())) return cap(p);
  return titleize(s) + ' ' + lowerFirst(p);
}
/* Where did this come from, in words a human can check. Returned in parts so
   callers that already show a timestamp can drop the "Learned …" one. */
function provenanceParts(g) {
  const f = g.fields || {}, bits = [];
  const prevGrain = f.derived_from && BYHASH[f.derived_from];
  const was = g._prevValue
    || (prevGrain ? (typeof (prevGrain.fields || {}).object === 'string'
        ? prevGrain.fields.object : preview(prevGrain.fields)) : null);
  if (was) bits.push('Changed from ' + was);
  const when = createdMs(f) || hlcMs(g.hlc);
  if (!bits.length) bits.push('Learned ' + relTime(when));
  if (g.type === 'observation') bits.push('noticed by your agent, not confirmed');
  if (f.namespace && f.namespace !== 'shared') bits.push('in ' + f.namespace);
  if (typeof f.confidence === 'number' && f.confidence < 0.75) bits.push('low confidence');
  return bits;
}
const provenance = g => provenanceParts(g).join(' · ');

/* ══ state ════════════════════════════════════════════════════════════ */
let BROWSE = [], BYHASH = {}, STATS = {}, CONFIG = null, LOG = [], RECS = {}, TELEMETRY = null;
let PAGE = 'memory', MVIEW = 'list', SUGTAB = 'pending', CONTAB = 'agent', ACTFILTER = 'all';
let TOOLTAB = 'catalog', TOOL_SEL = null;
let ENTITY = null, ANSWER = null, SEL = null, ACTIVE_ENTS = [];
const isGone = g => !!(g.forgotten || g.missing || g.op === 'forget');
const isCurrent = g => !isGone(g) && !g.superseded_by && !g._stale;
/* Areev Loop keeps its own bookkeeping in the file (namespace "areev-loop",
   subject "__loop_state__"). It is a real grain, but it is not something
   the agent remembers *about anyone* — keep it out of the human views.
   It stays reachable from the op-log and the CAL console. */
const INTERNAL_NS = new Set(['areev-loop']);
function isInternal(g) {
  const f = g.fields || {};
  if (INTERNAL_NS.has(f.namespace)) return true;
  const s = f.subject;
  return typeof s === 'string' && /^__.*__$/.test(s);
}
const currentGrains = () => BROWSE.filter(g => isCurrent(g) && !isInternal(g));

/* The store keeps one head per (namespace, subject, relation) — a plain
   re-ADD of the same pair replaces the old value without logging a
   SUPERSEDE, so /api/browse cannot tell us which row is live. Resolve it
   the same way the store does: within a key, the newest op wins. Without
   this the list shows a replaced value as if it were current. */
function headHashes(grains) {
  const best = new Map();
  for (const g of grains) {
    if (isGone(g) || (g.type && g.type !== 'fact')) continue;
    const f = g.fields || {};
    if (!f.subject || !f.relation) continue;
    const k = (f.namespace || '') + '\0' + f.subject + '\0' + f.relation;
    const cur = best.get(k);
    if (!cur || (g.op_seq || 0) > (cur.op_seq || 0)) best.set(k, g);
  }
  const out = new Set();
  for (const g of best.values()) out.add(g.hash);
  return out;
}
function markHeads() {
  const heads = headHashes(BROWSE);
  const byKey = new Map();
  for (const g of BROWSE) {
    g._stale = false; g._prevValue = null;
    if (isGone(g) || (g.type && g.type !== 'fact')) continue;
    const f = g.fields || {};
    if (!f.subject || !f.relation) continue;
    const k = (f.namespace || '') + '\0' + f.subject + '\0' + f.relation;
    if (!byKey.has(k)) byKey.set(k, []);
    byKey.get(k).push(g);
  }
  for (const list of byKey.values()) {
    list.sort((a, b) => (a.op_seq || 0) - (b.op_seq || 0));
    list.forEach((g, i) => {
      g._stale = !heads.has(g.hash);
      if (!g._stale && i > 0) {
        const p = list[i - 1].fields || {};
        g._prevValue = typeof p.object === 'string' ? p.object : null;
      }
    });
  }
}

/* ══ entities ═════════════════════════════════════════════════════════ */
const PERSONISH = new Set(['prefers','likes','dislikes','works_at','lives_in','employed_by','knows',
  'collaborates_with','owns_project','reports_to','asked_about','email','phone','speaks','role','title']);
const ORGISH = new Set(['works_at','employed_by','member_of','customer_of']);
const PROJECTISH = new Set(['owns_project','maintains','works_on','assigned_to']);
const PLACEISH = new Set(['lives_in','based_in','headquartered_in','located_in']);
/* A tool call carries no subject, but it is plainly *about* the tool —
   without this every tool call falls into one anonymous "Everything else"
   heap. The graph opts out (a tool with no relations would be a lone dot). */
const subjectOf = (g, withTools) => {
  const f = g.fields || {};
  return f.subject || (withTools !== false && g.type === 'tool' ? f.tool_name : null) || null;
};
function buildEntities(grains, opts) {
  const withTools = !(opts && opts.tools === false);
  const map = new Map();
  const ensure = n => { if (!map.has(n)) map.set(n, { name: n, kind: 'thing', count: 0, deg: 0 }); return map.get(n); };
  for (const g of grains) {
    const f = g.fields || {};
    const s = subjectOf(g, withTools);
    if (s) ensure(s).count++;
    if (g.type === 'fact' && typeof f.object === 'string' && f.object && f.object.length <= 64) ensure(f.object).deg++;
  }
  for (const g of grains) {
    const f = g.fields || {}, r = f.relation || '';
    if (f.subject && PERSONISH.has(r)) ensure(f.subject).kind = 'person';
    if (g.type === 'fact' && typeof f.object === 'string' && map.has(f.object)) {
      const e = map.get(f.object);
      if (ORGISH.has(r)) e.kind = 'org';
      else if (PROJECTISH.has(r)) e.kind = 'project';
      else if (PLACEISH.has(r)) e.kind = 'org';
    }
  }
  return [...map.values()].sort((a, b) => (b.count - a.count) || (b.deg - a.deg) || a.name.localeCompare(b.name));
}
const KIND_VAR = { person: '--cat-person', org: '--cat-org', project: '--cat-project',
  thing: '--cat-thing', note: '--cat-note' };

/* ══ boot ═════════════════════════════════════════════════════════════ */
async function boot() {
  /* The server hands us the full path; show the file name and keep the
     path in the tooltip so the rail stays readable. */
  const full = ($('dblabel').textContent || '').trim();
  DB_PATH = full;
  $('dblabel').textContent = full.split('/').pop() || full;
  $('dblabel').title = full;
  wireChrome();
  applyHash();
  await Promise.all([loadStats(), loadBrowse(), loadLog(), loadConfig(), loadCaps(), loadNamespaces()]);
  verify();
  await loadRecs('pending');
  if (WF_DEEPLINK) { wfOpen(WF_DEEPLINK); WF_DEEPLINK = null; }
  if (PAGE === 'settings' && CONTAB === 'sync') await loadSegments();
  if (PAGE === 'suggestions' && !RECS[SUGTAB]) await loadRecs(SUGTAB);
  render();
  if (PAGE === 'memory' && MVIEW === 'graph') Graph.mount();
  addEventListener('hashchange', () => {
    if (applyHash()) {
      if (WF_DEEPLINK) { wfOpen(WF_DEEPLINK); WF_DEEPLINK = null; }
      render();
      if (MVIEW === 'graph') Graph.mount();
    }
  });
}
let DB_PATH = '';
async function loadStats() { STATS = await api('/api/stats') || {}; }
async function loadConfig() { CONFIG = await api('/api/config'); }
/* Every namespace this session can read, for the namespace pickers on
   Activity/Workflows/etc. `null` = couldn't load (e.g. a very old build with
   no /api/namespaces route) — pickers fall back to just the bound default. */
let NAMESPACES = null;
async function loadNamespaces() {
  const r = await api('/api/namespaces');
  NAMESPACES = (r && r.ok && Array.isArray(r.namespaces)) ? r.namespaces : null;
}
/* A namespace <select>, shared by every page that filters by it. `current`
   is the bound value (falls back to the session default); onChange gets the
   picked namespace or '*' for "all namespaces this session can read". */
/* A namespace picker that is a dropdown AND a text field at once: click it
   for the known-namespace list (with live counts), or just type — a prefix
   pattern like "org.*" is accepted exactly like an exact name, since the
   server (not this control) is what actually validates and gates it. */
function nsCombo(id, current, onChange) {
  const bound = boundNamespace();
  const isOwner = !!(CONFIG && CONFIG.session && CONFIG.session.is_owner);
  const list = NAMESPACES && NAMESPACES.length ? NAMESPACES : [{ namespace: bound, count: null }];
  const options = list.map(n => ({ value: n.namespace, label: n.namespace + (typeof n.count === 'number' ? ' (' + n.count + ')' : '') }));
  if (isOwner) options.unshift({ value: '*', label: 'All namespaces' });
  const known = new Set(options.map(o => o.value));

  const wrap = el('div', 'ns-combo'); wrap.id = id;
  wrap.title = 'Scope this page to one namespace, or type a prefix like "org.*" to include its descendants too.';
  wrap.appendChild(el('span', 'lbl', 'Namespace'));
  const sizer = el('span', 'sizer');
  const input = document.createElement('input');
  input.type = 'text'; input.className = 'ns-combo-input'; input.autocomplete = 'off'; input.spellcheck = false;
  input.placeholder = 'namespace, or prefix.*';
  input.value = current || bound;
  sizer.dataset.value = input.value;
  sizer.appendChild(input);
  const arrow = el('span', 'ns-combo-arrow');
  arrow.innerHTML = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none"><path d="M5 9l7 7 7-7" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
  const menu = el('div', 'ns-combo-menu'); menu.hidden = true;

  function renderMenu() {
    const typed = input.value.trim();
    const f = typed.toLowerCase();
    menu.textContent = '';
    for (const o of options) {
      if (f && !o.label.toLowerCase().includes(f) && !o.value.toLowerCase().includes(f)) continue;
      const row = el('div', 'ns-combo-opt' + (o.value === input.value ? ' on' : ''), o.label);
      row.onmousedown = e => { e.preventDefault(); commit(o.value); };
      menu.appendChild(row);
    }
    if (typed && !known.has(typed)) {
      const row = el('div', 'ns-combo-opt hint', (typed.endsWith('*') ? 'Use prefix ' : 'Use ') + '"' + typed + '"');
      row.onmousedown = e => { e.preventDefault(); commit(typed); };
      menu.appendChild(row);
    }
    if (!menu.childElementCount) menu.appendChild(el('div', 'ns-combo-empty', 'No matching namespace'));
  }
  function commit(v) {
    v = (v || '').trim() || (current || bound);
    input.value = v; sizer.dataset.value = v; menu.hidden = true;
    if (v !== current) onChange(v);
  }
  input.addEventListener('focus', () => { renderMenu(); menu.hidden = false; });
  input.addEventListener('input', () => { sizer.dataset.value = input.value; renderMenu(); });
  input.addEventListener('keydown', e => {
    if (e.key === 'Enter') { e.preventDefault(); commit(input.value); input.blur(); }
    else if (e.key === 'Escape') { input.value = current || bound; sizer.dataset.value = input.value; menu.hidden = true; input.blur(); }
  });
  input.addEventListener('blur', () => commit(input.value));
  // The arrow (and the label, and the pill's own padding) aren't the
  // input — a plain click there hits the pill, not the field inside it, and
  // does nothing. Forward it to the input's own focus, which is what
  // actually opens the menu.
  wrap.addEventListener('mousedown', e => { if (e.target === input) return; e.preventDefault(); input.focus(); });
  const value = el('div', 'value'); value.appendChild(sizer); value.appendChild(arrow);
  wrap.appendChild(value); wrap.appendChild(menu);
  return wrap;
}
const boundNamespace = () => (CONFIG && CONFIG.session && CONFIG.session.namespace) || 'shared';
/* Per-namespace browse cache for pages with a namespace picker. The bound
   session default always reads the already-loaded global BROWSE — no extra
   fetch, and it stays what the rail/entities/graph use. A different
   namespace fetches once and caches (switching back and forth is instant). */
const NS_BROWSE_CACHE = new Map();
async function browseForNamespace(ns) {
  if (!ns || ns === boundNamespace()) return BROWSE;
  if (NS_BROWSE_CACHE.has(ns)) return NS_BROWSE_CACHE.get(ns);
  const r = await api('/api/browse?limit=2000&ns=' + encodeURIComponent(ns));
  const rows = (r && r.ok && r.grains) ? r.grains : [];
  NS_BROWSE_CACHE.set(ns, rows);
  return rows;
}
async function loadBrowse() {
  const r = await api('/api/browse?limit=2000');
  BROWSE = (r && r.ok && r.grains) ? r.grains : [];
  BYHASH = {};
  for (const g of BROWSE) BYHASH[g.hash] = g;
  markHeads();
}
async function loadLog() { const r = await api('/api/log?limit=400'); LOG = Array.isArray(r) ? r : []; }
/* "Needs review" also covers `approved` — a recommendation you approved but
   whose apply did not land would otherwise belong to no tab at all. */
const TAB_STATUS = { pending: ['pending', 'approved'], applied: ['applied'], rejected: ['rejected'] };
async function loadRecs(tab) {
  const out = [];
  for (const s of (TAB_STATUS[tab] || [tab])) {
    const r = await api('/api/loop/recommendations?status=' + encodeURIComponent(s));
    if (r && r.ok && Array.isArray(r.recommendations)) out.push(...r.recommendations);
  }
  RECS[tab] = out;
  if (tab === 'pending') {
    const n = out.length;
    $('sugPill').hidden = !n; $('sugPill').textContent = n;
  }
}
async function verify() {
  const v = await api('/api/verify');
  const ok = v && v.integrity === 'ok';
  $('hdot').style.background = ok ? 'var(--ok)' : 'var(--danger)';
  $('htext').textContent = ok ? 'All memories verified' : 'Integrity problem — click';
  $('health').title = v && v.integrity
    ? 'integrity ' + v.integrity + ' · ' + v.grains + ' grains · ' + v.hash_mismatches + ' mismatches'
    : 'verification unavailable';
}
async function refresh() {
  await Promise.all([loadStats(), loadBrowse(), loadLog()]);
  await loadRecs('pending');
  render();
}

/* ══ chrome ═══════════════════════════════════════════════════════════ */
function wireChrome() {
  $('brandBtn').onclick = () => go('memory');
  $('nav').querySelectorAll('.nav-item').forEach(b => { b.onclick = () => go(b.dataset.page); });
  $('mview').querySelectorAll('button').forEach(b => {
    b.onclick = () => { MVIEW = b.dataset.v; render(); if (MVIEW === 'graph') Graph.mount(); };
  });
  /* Developer mode / Dark mode toggles now live in Settings → General
     (renderConnectGeneral), rebuilt fresh each visit — see settingsToggle(). */
  $('health').onclick = verify;

  $('askBtn').onclick = () => runAsk($('ask').value);
  // The bar is 56px tall, the input's own line-box is much shorter — click
  // the bar's own padding above/below the text and it should still focus
  // the field, not just the exact pixels the glyphs occupy.
  $('ask').closest('.askbar').addEventListener('mousedown', e => {
    if (e.target === $('ask')) return; e.preventDefault(); $('ask').focus();
  });
  $('ask').addEventListener('keydown', e => { if (e.key === 'Enter') runAsk($('ask').value); });
  $('ask').addEventListener('input', () => { if (!$('ask').value) { ANSWER = null; }
    renderExamples(); renderMemList(); });
  $('sugBannerGo').onclick = () => go('suggestions');
  $('sugTabs').querySelectorAll('button').forEach(b => {
    b.onclick = async () => { SUGTAB = b.dataset.s; if (!RECS[SUGTAB]) await loadRecs(SUGTAB); render(); };
  });
  $('conTabs').querySelectorAll('button').forEach(b => { b.onclick = () => { CONTAB = b.dataset.c; render(); }; });
  $('toolTabs').querySelectorAll('button').forEach(b => { b.onclick = () => { TOOLTAB = b.dataset.t; TOOL_SEL = null; render(); }; });
  $('runLoop').onclick = runAnalysis;
  /* the run button is a write too — gate it once config lands */
  $('panelShade').onclick = closePanel;
  $('qrun').onclick = () => runQuery();
  $('qtext').addEventListener('input', () => { syncEditor(); queryNotice(); });
  $('qtext').addEventListener('scroll', () => { $('qhl').scrollTop = $('qtext').scrollTop; });
  $('qtext').addEventListener('keydown', e => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) runQuery(); });
  $('qexplain').onclick = () => { const t = $('qtext').value.trim();
    if (t) runQuery(/^EXPLAIN\b/i.test(t) ? t : 'EXPLAIN ' + t); };
  $('qsave').onclick = saveCurrentQuery;
  $('qreset').onclick = resetQuery;
  $('fmtBtn').onclick = () => openMenu('fmtMenu', buildFormatMenu);
  $('histBtn').onclick = () => openMenu('histMenu', buildHistoryMenu);
  $('savedBtn').onclick = () => openMenu('savedMenu', buildSavedMenu);
  addEventListener('resize', () => { if (PAGE === 'query' && Q.view === 'cards') layoutMasonry(); });
  $('devQuery').onclick = () => go('query');
  document.addEventListener('keydown', e => {
    if (e.key === 'Escape') closePanel();
    if (e.key === '/' && document.activeElement === document.body) { e.preventDefault(); $('ask').focus(); }
  });
  Graph.wire();
  WFGraph.wire();
  $('wfNewBtn').onclick = wfNew;
  $('wfAddNode').onclick = wfAddNode;
  $('wfResetLayout').onclick = () => { WFGraph.resetOverrides(); WFGraph.mount(); };
  $('wfSave').onclick = wfArmSave;
}
/* Deep links: #memory · #graph · #activity · #suggestions · #connect/sync */
/* Set by applyHash when the URL names a specific plan (#workflows/<hash>);
   consumed once BROWSE has loaded (boot() and the hashchange listener both
   need to open it, since a deep link can arrive either way). */
let WF_DEEPLINK = null;
function applyHash() {
  const raw = (location.hash || '').replace(/^#/, '');
  if (!raw) return false;
  const [head, tail] = raw.split('/');
  if (head === 'graph') { PAGE = 'memory'; MVIEW = 'graph'; return true; }
  /* #triggers was its own page until triggers moved onto the canvas. Keep
     the old link alive rather than dead-ending a bookmark: it now means "show
     me what starts things", which is the plan list. */
  if (head === 'triggers') { PAGE = 'workflows'; WF_SEL = null; WF_DRAFT = null; WF_PICK = null; return true; }
  if (['memory', 'analytics', 'activity', 'runs', 'tools', 'workflows', 'suggestions', 'settings', 'query'].includes(head)) {
    PAGE = head;
    if (head === 'memory') MVIEW = 'list';
    if (head === 'settings' && ['agent', 'sync', 'general'].includes(tail)) CONTAB = tail;
    if (head === 'suggestions' && ['pending', 'applied', 'rejected'].includes(tail)) SUGTAB = tail;
    if (head === 'tools') {
      if (['catalog', 'executions'].includes(tail)) TOOLTAB = tail;
      TOOL_SEL = null;
    }
    if (head === 'workflows') {
      if (tail && /^[0-9a-f]{8,64}$/i.test(tail)) WF_DEEPLINK = tail;
      else { WF_SEL = null; WF_DRAFT = null; WF_PICK = null; }
    }
    return true;
  }
  return false;
}
function syncHash() {
  const h = PAGE === 'memory' ? (MVIEW === 'graph' ? 'graph' : 'memory')
    : PAGE === 'settings' ? 'settings/' + CONTAB
    : PAGE === 'suggestions' ? 'suggestions/' + SUGTAB
    : PAGE === 'tools' ? 'tools/' + TOOLTAB
    : PAGE === 'workflows' ? 'workflows' + (WF_SEL ? '/' + WF_SEL : '') : PAGE;
  if (location.hash.replace(/^#/, '') !== h) history.replaceState(null, '', '#' + h);
}
function go(page) {
  PAGE = page;
  if (page === 'suggestions' && !RECS[SUGTAB]) loadRecs(SUGTAB).then(render);
  if (page === 'settings' && CONTAB === 'sync') loadSegments();
  // Same reset applyHash() already does for a bare "#workflows" — without
  // it, the sidebar's generic nav click left an open draft/selection in
  // place, so "Workflows" looked like it wasn't navigating at all when you
  // were mid-edit (it re-rendered the same editor you were already on).
  if (page === 'workflows') { WF_SEL = null; WF_DRAFT = null; WF_PICK = null; }
  render();
}

/* ══ runs: the governed runtime ═══════════════════════════════════════
   ONE index, loaded once, shared by this page and the workflow canvas's run
   overlay. Two surfaces asking the server the same question separately is
   exactly how they drift: the tint on a canvas node and the strip on a card
   here are the same three facts, so they read them from the same place.

   `/api/run/list` returns id + outcome only, so which plan a run executed
   comes from `inspect` — one request per run, but also the only place
   plan_hash, the principal and the pending asks exist. Where inspect can't
   say (an older journal), the plan is recovered from the run's own step
   grains, which name it in `related_to`. */
let RUNIDX = null, RUNIDX_INFLIGHT = null;

/* Run-journal Tool grains: the store's record of what each step actually did.
   `isCurrent` alone leaves exactly one row per (run, node) — the journal
   writes the intent as Pending and then SUPERSEDES it with the result, so the
   superseded intent drops out and what survives IS the step's current state.
   No head-resolution needed; that is the invariant doing the work. */
function runStepGrains() {
  return wfRows().filter(g => {
    const f = g.fields || {};
    return g.type === 'tool' && f.kind !== 'definition' && f.run_id && f.node && isCurrent(g);
  });
}
/** The plan a step grain was recorded against, via `mg:step_action:<node>`. */
function stepPlanHash(f) {
  for (const r of (Array.isArray(f.related_to) ? f.related_to : [])) {
    if (r && typeof r.relation_type === 'string' && r.relation_type.startsWith('mg:step_action:')) {
      return String(r.hash || '').replace(/^sha256:/, '');
    }
  }
  return null;
}
/* Four states, because "pending" means two different things. A step still
   Pending in a run that is *open* is waiting on someone; the same row in a
   run that was canceled or failed is simply where it stopped, and colouring
   that orange would invite an approval that can never arrive. */
const STEP_TONE = { done: 'ok', waiting: 'warn', failed: 'danger', stopped: 'ghost' };
const STEP_WORD = { done: 'done', waiting: 'waiting on a person', failed: 'failed', stopped: 'not finished' };
function stepState(f, outcome) {
  if (f.is_error === true) return 'failed';
  const st = String(f.status || 'completed');
  if (st === 'failed' || st === 'error') return 'failed';
  if (st !== 'pending') return 'done';
  return outcome && outcome !== 'open' ? 'stopped' : 'waiting';
}
/** node → { state, grain } for one run. Latest attempt wins. */
function runStepStates(runId, outcome) {
  const out = new Map();
  for (const g of runStepGrains()) {
    const f = g.fields;
    if (f.run_id !== runId) continue;
    const prev = out.get(f.node);
    const rank = (f.superstep || 0) * 1e13 + (f.attempt || 0) * 1e11 + (createdMs(f) || 0);
    if (prev && prev.rank >= rank) continue;
    out.set(f.node, { state: stepState(f, outcome), grain: g, rank });
  }
  return out;
}

async function loadRuns(force) {
  if (force) { RUNIDX = null; RUNIDX_INFLIGHT = null; }
  if (RUNIDX) return RUNIDX;
  if (RUNIDX_INFLIGHT) return RUNIDX_INFLIGHT;
  RUNIDX_INFLIGHT = (async () => {
    const idx = { runs: [], byId: new Map(), byPlan: new Map(), error: null };
    const list = await api('/api/run/list');
    if (!list || !list.ok) {
      idx.error = (list && list.error) || 'failed to load runs';
      RUNIDX = idx; RUNIDX_INFLIGHT = null; return idx;
    }
    const rows = Array.isArray(list.runs) ? list.runs : [];
    const details = await Promise.all(rows.map(r =>
      api('/api/run/inspect?run_id=' + encodeURIComponent(r.run_id)).catch(() => null)));
    /* One pass over the step grains rather than a scan per run — a memory
       with a few thousand executions makes the nested version quadratic. */
    const firstSeen = new Map(), planFromGrains = new Map();
    for (const g of runStepGrains()) {
      const f = g.fields, t = createdMs(f);
      const cur = firstSeen.get(f.run_id);
      if (cur == null || (t && t < cur)) firstSeen.set(f.run_id, t);
      if (!planFromGrains.has(f.run_id)) {
        const h = stepPlanHash(f);
        if (h) planFromGrains.set(f.run_id, h);
      }
    }
    rows.forEach((r, i) => {
      const d = (details[i] && details[i].ok) ? details[i] : {};
      const run = {
        run_id: r.run_id,
        outcome: r.outcome || 'unknown',
        plan_hash: d.plan_hash ? String(d.plan_hash).replace(/^sha256:/, '') : (planFromGrains.get(r.run_id) || null),
        principal: d.principal || null,
        checkpoints: d.checkpoints, journal_entries: d.journal_entries,
        started_ms: firstSeen.get(r.run_id) || null,
        asks: (d.pending_asks && typeof d.pending_asks === 'object')
          ? Object.values(d.pending_asks).map(a => (a && a.ask) ? a.ask : a) : [],
      };
      idx.runs.push(run);
      idx.byId.set(run.run_id, run);
      if (run.plan_hash) {
        if (!idx.byPlan.has(run.plan_hash)) idx.byPlan.set(run.plan_hash, []);
        idx.byPlan.get(run.plan_hash).push(run);
      }
    });
    for (const list2 of idx.byPlan.values()) list2.sort((a, b) => (b.started_ms || 0) - (a.started_ms || 0));
    RUNIDX = idx; RUNIDX_INFLIGHT = null; return idx;
  })();
  return RUNIDX_INFLIGHT;
}

const OUTCOME_TONE = { completed: 'ok', open: 'warn', canceled: 'ghost', failed: 'danger' };
function outcomeTone(o) { return OUTCOME_TONE[o] || 'danger'; }
function statusTag(word, tone) {
  const t = el('span', 'status-tag', word);
  t.style.cssText = 'background:var(--' + (tone === 'ghost' ? 'raise' : tone + '-soft') + ');color:var(--'
    + (tone === 'ghost' ? 'dim' : tone) + ')';
  return t;
}
/** The plan a run executed, by whatever name it has. */
function planLabel(hash) {
  const g = hash && wfByHash()[hash];
  return g ? wfLabel(g) : (hash ? shortHash(hash) : 'unknown plan');
}

async function renderRuns() {
  renderCrumbHeader('runCrumb', [{ label: 'Runs' }],
    'Every execution of a plan: journaled, checkpointed, pausable. A run waiting on a person shows its '
    + 'approval below — approving requires your own sign-in, because the approver’s identity <em>is</em> '
    + 'the audit record and a shared console token is not an identity.');
  const box = $('runList');
  if (!RUNIDX) box.innerHTML = '<div class="empty">loading…</div>';
  const idx = await loadRuns();
  if (PAGE !== 'runs') return;                 // navigated away while loading
  const open = idx.runs.filter(r => r.outcome === 'open');
  const pill = $('runPill');
  pill.hidden = open.length === 0; pill.textContent = open.length;

  box.textContent = '';
  if (idx.error) { box.innerHTML = '<div class="empty">' + esc(idx.error) + '</div>'; return; }
  if (!idx.runs.length) {
    box.innerHTML = '<div class="empty">No runs recorded in this memory yet. A run is one execution of a plan '
      + '— start one with <code>areev run start</code>, or let a trigger start it.</div>';
    return;
  }
  const waiting = idx.runs.filter(r => r.asks.length);
  const active = idx.runs.filter(r => !r.asks.length && r.outcome === 'open');
  const done = idx.runs.filter(r => !r.asks.length && r.outcome !== 'open');
  const groups = [
    ['Waiting on you', waiting, 'A step bound to a human-approval tool has paused the run.'],
    ['In flight', active, 'Started, not finished, nothing asked of you yet.'],
    ['Finished', done, null],
  ];
  for (const [title, rows, gloss] of groups) {
    if (!rows.length) continue;
    const grp = el('div', 'rungroup');
    const hd = el('div', 'hd');
    hd.appendChild(el('h3', null, title + ' · ' + rows.length));
    if (gloss) hd.appendChild(el('span', 'tiny', gloss));
    grp.appendChild(hd);
    const grid = el('div', 'rungrid');
    for (const run of rows) grid.appendChild(runCard(run));
    grp.appendChild(grid);
    box.appendChild(grp);
  }
}

function runCard(run) {
  const card = el('div', 'card runcard');
  const top = el('div', 'top');
  const plan = el('div', 'plan');
  plan.appendChild(document.createTextNode(planLabel(run.plan_hash)));
  const rid = el('span', 'rid', run.run_id);
  plan.appendChild(rid);
  top.appendChild(plan);
  top.appendChild(statusTag(run.outcome, outcomeTone(run.outcome)));
  card.appendChild(top);

  const meta = el('div', 'meta');
  const bits = [];
  if (run.principal) bits.push('started by ' + run.principal);
  if (run.started_ms) bits.push(relTime(run.started_ms));
  if (run.checkpoints != null) bits.push(run.checkpoints + ' checkpoints');
  if (run.journal_entries != null) bits.push(run.journal_entries + ' journal entries');
  for (const b of bits) meta.appendChild(el('span', null, b));
  card.appendChild(meta);

  /* The same overlay the canvas draws, one bar per step in plan order — so a
     glance at the card and a glance at the graph agree about where the run
     got to. */
  const planG = run.plan_hash && wfByHash()[run.plan_hash];
  const order = planG && Array.isArray((planG.fields || {}).nodes) ? planG.fields.nodes : [];
  if (order.length) {
    const states = runStepStates(run.run_id, run.outcome);
    const strip = el('div', 'steps');
    for (const id of order) {
      const st = states.get(id);
      const i = el('i');
      i.title = id + (st ? ' — ' + STEP_WORD[st.state] : ' — not reached');
      if (st) i.style.background = 'var(--' + STEP_TONE[st.state] + ')';
      strip.appendChild(i);
    }
    card.appendChild(strip);
  }

  for (const ask of run.asks) card.appendChild(askBlock(run.run_id, ask));

  const foot = el('div', 'foot');
  foot.appendChild(el('span', 'grow'));
  if (run.plan_hash) {
    const b = el('button', 'btn ghost sm', 'Open plan ▸');
    b.onclick = () => { WF_RUN = run.run_id; location.hash = '#workflows/' + run.plan_hash; };
    foot.appendChild(b);
  }
  card.appendChild(foot);
  return card;
}

/* Separation of duties is the whole point of this control, so when it is
   unavailable it has to say WHICH credential is missing. `lock()`'s generic
   read-only reason is not it: `run.respond` refuses a shared console token
   even when that token can write everything else. */
const RESPOND_WHY = 'Approving needs your own sign-in (areev ui --auth). A shared console token '
  + 'and an anonymous caller are both refused here, because the approver’s identity is the audit record.';
function askBlock(runId, ask) {
  const box = el('div', 'ask');
  box.appendChild(el('b', null, 'Waiting on a person'));
  const node = ask.node || '';
  const tool = ask.tool_name || '';
  box.appendChild(el('div', 'who', node && tool && node !== tool ? node + ' · ' + tool : (node || tool || 'an approval step')));
  const acts = el('div', 'acts');
  const btn = (cls, label, refuse) => {
    const b = lock(el('button', cls, label));
    b.title = RESPOND_WHY;
    b.onclick = () => respondRun(runId, ask.tool_call_id, refuse);
    return b;
  };
  acts.appendChild(btn('btn sm', 'Approve', false));
  acts.appendChild(btn('btn danger', 'Refuse', true));
  box.appendChild(acts);
  return box;
}

async function respondRun(id, ask, refuse) {
  const r = await api('/api/run/respond', {
    method: 'POST', headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      run_id: id, tool_call_id: ask,
      result: refuse ? { refused: true } : { approved: true },
      is_error: refuse,
    }),
  });
  if (!r.ok) { toast(r.error || 'response refused'); return; }
  toast('Recorded as ' + (r.responder || 'you') + ' — resume the run to continue.');
  await loadRuns(true); render();
}

/* ══ analytics ════════════════════════════════════════════════════════
   The Query page's "WHAT'S IN THIS MEMORY" on-ramp, grown into its own
   page: every grain type it offers as a starter (not just the 4), every
   namespace, a growth trend, and the recall legs this file has active.
   Stat tiles and the namespace breakdown are always whole-file — STATS and
   the effective config have no per-namespace form. Composition and growth
   follow the namespace picker, the same convention Activity/Workflows use. */
const ANALYTICS_TYPES = [
  ['facts', 'fact', "Things it holds as true"],
  ['tools', 'tool', "Every tool call it made"],
  ['observations', 'observation', "Things it noticed, unconfirmed"],
  ['events', 'event', "Things that happened, in order"],
  ['goals', 'goal', "Objectives it's working toward"],
  ['states', 'state', "A snapshot of context, taken whole"],
  ['workflows', 'workflow', "Procedures it can follow, as a graph"],
  ['skills', 'skill', "Capabilities it has learned"],
  ['reasonings', 'reasoning', "Chains of thought behind a decision"],
  ['consensuses', 'consensus', "Agreements reached among agents"],
  ['consents', 'consent', "Permissions granted or withdrawn"],
  ['recommendations', 'recommendation', "Changes the loop proposed to itself"],
];
let AN_NS = null;
async function anSetNamespace(ns) {
  AN_NS = (!ns || ns === boundNamespace()) ? null : ns;
  await renderAnalytics();
}
/* A census row: mono key, optional gloss, a bar proportional to `max` (that
   list's own largest count — so the grain census and the namespace
   breakdown each fill their own width instead of one dwarfing the other),
   and a right-aligned count. `count == null` means "couldn't count it on
   this build" (mirrors the vocab cards' own honesty about COUNT failing) —
   shown as "—" and treated as 0 for the bar, never a lie. */
function censusRow(host, key, gloss, count, max, onClick) {
  const r = el('button', 'crow');
  r.appendChild(el('span', 'k' + (gloss == null ? ' wide' : ''), key));
  if (gloss != null) r.appendChild(el('span', 'g', gloss));
  const track = el('div', 'track');
  const bar = el('div', 'bar' + (count ? '' : ' zero'));
  bar.style.width = Math.max(max ? ((count || 0) / max) * 100 : 0, 3) + '%';
  track.appendChild(bar); r.appendChild(track);
  r.appendChild(el('span', 'n' + (count ? '' : ' zero'), count == null ? '—' : String(count)));
  if (onClick) r.onclick = onClick;
  host.appendChild(r);
}
/* nsCombo fires its onChange once per commit path (option click, Enter,
   blur-on-change) — on a fast synchronous page two of those firing for one
   pick is invisible, but this page's render does several sequential
   network round trips, wide enough for a second, newer call to land while
   an older one is still mid-flight. AN_GEN guards against that: every call
   takes a ticket, does ALL its awaiting up front, and only writes to the
   DOM if its ticket is still the latest — an overtaken call discards its
   (now-stale) results instead of appending duplicate rows on top of the
   newer render's. */
let AN_GEN = 0;
async function renderAnalytics() {
  const gen = ++AN_GEN;
  const nsList = NAMESPACES || [];
  const scope = AN_NS || boundNamespace();
  const rows = await browseForNamespace(scope);

  // Composition: one COUNT per grain type, scoped to the picked namespace.
  // CAL has no "every namespace at once" wildcard on a RECALL WHERE clause
  // (recall is exact-namespace or a registered "org.*" prefix, never a bare
  // "*" — that lift-the-filter form is `/api/browse?ns=*`'s own owner-gated
  // server route, not CAL) — so "All namespaces" sums one COUNT per real
  // namespace instead of asking CAL for a wildcard it will refuse.
  const esc = s => String(s).replace(/"/g, '\\"');
  const scopeNs = AN_NS === '*' ? nsList.map(n => n.namespace) : [scope];
  async function scopedCount(plural) {
    const perNs = await Promise.all(scopeNs.map(ns =>
      cal('RECALL ' + plural + ' WHERE namespace = "' + esc(ns) + '" COUNT')));
    let total = 0, anyOk = false;
    for (const r of perNs) {
      if (r && r.ok && r.result && typeof r.result.count === 'number') { total += r.result.count; anyOk = true; }
    }
    return anyOk ? total : null;
  }
  const typeCounts = await Promise.all(ANALYTICS_TYPES.map(([plural]) => scopedCount(plural)));

  if (gen !== AN_GEN) return; // superseded — a newer namespace pick (or re-render) already won

  renderCrumbHeader('anCrumb', [{ label: 'Analytics' }],
    "The shape of what's stored here — composition, growth, and what it can be queried by.");
  const nsHost = $('anNsHost'); nsHost.textContent = '';
  nsHost.appendChild(nsCombo('anNs', scope, anSetNamespace));

  const tiles = $('anTiles'); tiles.textContent = '';
  const tile = (label, value, sub, color) => {
    const t = el('div', 'card stile');
    t.appendChild(el('span', 'lbl', label));
    const n = el('span', 'n', String(value)); if (color) n.style.color = color; t.appendChild(n);
    t.appendChild(el('span', 'sub', sub));
    tiles.appendChild(t);
  };
  const topNs = nsList.length ? nsList.slice().sort((a, b) => b.count - a.count)[0] : null;
  tile('Total memories', STATS.grains != null ? STATS.grains : '?',
    (STATS.current != null ? STATS.current : '?') + ' live now');
  tile('Namespaces', nsList.length, topNs ? 'most of it is in ' + topNs.namespace : 'nothing scoped yet');
  tile('Operations logged', STATS.ops != null ? STATS.ops : '?', 'adds, supersessions, forgets');
  // Whole-file, like its three siblings above — `rows` (below) is the
  // picker-scoped source the Growth *chart* uses; mixing scopes within one
  // tile row would make the tiles look inconsistent with each other.
  const weekAgo = Date.now() - 7 * 86400000;
  const recent = BROWSE.filter(g => g.op === 'add' && !isInternal(g) && hlcMs(g.hlc) >= weekAgo).length;
  tile('Last 7 days', '+' + recent, 'new memories written', 'var(--ok)');

  const census = $('anCensus'); census.textContent = '';
  const withCounts = ANALYTICS_TYPES.map(([plural, name, gloss], i) => [plural, name, gloss, typeCounts[i]])
    .sort((a, b) => (b[3] || 0) - (a[3] || 0));
  const maxCount = Math.max(1, ...withCounts.map(w => w[3] || 0));
  for (const [plural, name, gloss, n] of withCounts) {
    censusRow(census, name, gloss, n, maxCount, () => {
      const s = 'RECALL ' + plural + (scopeNs.length === 1 ? ' WHERE namespace = "' + esc(scopeNs[0]) + '"' : '') + ' LIMIT 20';
      go('query'); setQueryText(s); runQuery(s);
    });
  }

  // Namespaces: always whole-file (this is the one section that shows every
  // namespace at once) — clicking a row focuses the picker, and so every
  // other section, on it.
  const nsBox = $('anNsBreakdown'); nsBox.textContent = '';
  if (!nsList.length) nsBox.appendChild(el('div', 'empty', 'No namespace list on this build.'));
  const maxNs = Math.max(1, ...nsList.map(n => n.count || 0));
  for (const n of nsList.slice().sort((a, b) => b.count - a.count)) {
    censusRow(nsBox, n.namespace, null, n.count, maxNs, () => anSetNamespace(n.namespace));
  }

  // Growth: the last 14 days of "add" ops in the picked scope. `rows` is
  // whatever window browseForNamespace loaded (2,000 ops, same cap the
  // Graph/Activity views already accept) — captioned honestly rather than
  // implying a full-history count.
  const gHost = $('anGrowth'); gHost.textContent = '';
  const days = [];
  for (let i = 13; i >= 0; i--) days.push(dayKey(Date.now() - i * 86400000));
  const perDay = Object.fromEntries(days.map(d => [d, 0]));
  for (const g of rows) {
    if (g.op !== 'add' || isInternal(g)) continue;
    const k = dayKey(hlcMs(g.hlc));
    if (k in perDay) perDay[k]++;
  }
  const maxDay = Math.max(1, ...days.map(d => perDay[d]));
  const chart = el('div', 'gchart');
  days.forEach((d, i) => {
    const b = el('div', 'gbar' + (i === days.length - 1 ? ' today' : ''));
    b.style.height = Math.max((perDay[d] / maxDay) * 100, perDay[d] ? 4 : 2) + 'px';
    b.title = d + ': ' + perDay[d];
    chart.appendChild(b);
  });
  gHost.appendChild(chart);
  const axis = el('div'); axis.style.cssText = 'display:flex;justify-content:space-between;margin-top:8px';
  axis.appendChild(el('span', 'tiny', '14 days ago'));
  const todayLbl = el('span', 'tiny', 'today'); todayLbl.style.cssText = 'color:var(--accent);font-weight:600';
  axis.appendChild(todayLbl);
  gHost.appendChild(axis);
  $('anGrowthCaption').textContent = 'Memories written per day, '
    + (scope === '*' ? 'across every namespace' : 'in ' + scope)
    + ' — from the ' + rows.length + ' most recent operations loaded';

  // Recall legs: whole-file, from the effective config — not affected by
  // the namespace picker (recall configuration is per-file, not per-ns).
  const legs = $('anLegs'); legs.textContent = '';
  const r = CONFIG && CONFIG.recall && CONFIG.recall.legs;
  const leg = (dotColor, title, desc) => {
    const c = el('div', 'card leg');
    const hd = el('div', 'hd');
    const dot = el('span', 'dot'); dot.style.background = dotColor; hd.appendChild(dot);
    hd.appendChild(el('b', null, title));
    c.appendChild(hd);
    c.appendChild(el('span', 'd', desc));
    legs.appendChild(c);
  };
  leg('var(--ok)', 'Structural', 'Exact-match recall by subject, relation, namespace. Always on.');
  leg(r && r.bm25 ? 'var(--ok)' : 'var(--ghost)', 'Full-text (BM25)',
    r && r.bm25 ? 'Plain-words search over indexed content. On for this file.' : 'Off — this file has no text index built.');
  leg(r && r.vector ? 'var(--ok)' : 'var(--ghost)', 'Vector',
    r && r.vector ? 'Semantic similarity search. On for this file.' : 'Dormant — no embedding backend installed.');
}

/* ══ render ═══════════════════════════════════════════════════════════ */
function render() {
  syncHash();
  for (const p of ['memory', 'analytics', 'activity', 'runs', 'tools', 'workflows', 'suggestions', 'settings', 'query']) $('page-' + p).hidden = PAGE !== p;
  $('nav').querySelectorAll('.nav-item').forEach(b => b.classList.toggle('on', b.dataset.page === PAGE));
  const trgN = triggerGrains().length;
  $('wfTrgPill').hidden = trgN === 0; $('wfTrgPill').textContent = String(trgN);
  $('listView').hidden = MVIEW !== 'list';
  $('graphView').hidden = MVIEW !== 'graph';
  $('mview').querySelectorAll('button').forEach(b => b.classList.toggle('on', b.dataset.v === MVIEW));
  $('sugTabs').querySelectorAll('button').forEach(b => b.classList.toggle('on', b.dataset.s === SUGTAB));
  $('toolTabs').querySelectorAll('button').forEach(b => b.classList.toggle('on', b.dataset.t === TOOLTAB));
  $('conTabs').querySelectorAll('button').forEach(b => b.classList.toggle('on', b.dataset.c === CONTAB));
  renderRail(); renderHeader(); renderExamples(); renderBanner(); renderFilterBar();
  if (PAGE === 'memory') { renderAnswer(); renderMemList(); if (MVIEW === 'graph') Graph.rebuild(); }
  if (PAGE === 'analytics') renderAnalytics();
  if (PAGE === 'activity') renderActivity();
  if (PAGE === 'runs') renderRuns();
  if (PAGE === 'tools') renderTools();
  if (PAGE === 'workflows') renderWorkflows();
  if (PAGE === 'suggestions') { renderSuggestions(); lock($('runLoop')); }
  if (PAGE === 'settings') renderSettingsPage();
  if (PAGE === 'query') {
    renderCrumbHeader('queryCrumb', [{ label: 'Query' }], null);
    queryNotice(); syncEditor(); renderQueryResult(); renderOnramp();
    const sv = $('qsave');
    sv.disabled = !stmtSupported('DEFINE') || !canWrite();
    sv.title = !stmtSupported('DEFINE')
      ? 'This build has no saved-query registry (DEFINE is not a supported statement)'
      : (!canWrite() ? READONLY_WHY : 'Save this query into the memory file');
  }
  if (document.documentElement.classList.contains('dev')) renderDevbar();
}

/* The rail no longer lists entities (moved out to declutter — the graph
   page's inspector and the ask bar's examples reach the same filter), but
   ACTIVE_ENTS itself stays: renderExamples() still uses it for suggested
   questions. */
function renderRail() {
  ACTIVE_ENTS = buildEntities(currentGrains()).filter(e => e.count > 0).slice(0, 40);
}
function renderHeader() {
  const n = currentGrains().length;
  const db = ($('dblabel').textContent || '').trim();
  const desc = n
    ? esc(n + (n === 1 ? ' memory' : ' memories')) + ', kept in <b style="color:var(--text);font-weight:500">'
      + esc(db) + '</b> — nothing here is ever overwritten, only added to.'
    : 'Nothing stored yet. Connect an agent and what it learns will show up here.';
  const crumbs = ENTITY
    ? [{ label: 'Memory', onClick: () => { ENTITY = null; render(); } }, { label: ENTITY }]
    : [{ label: 'Memory' }];
  renderCrumbHeader('memCrumb', crumbs, desc);
}
/* Only suggest questions the console can actually answer: a name it knows,
   or the time-based one that reads the op-log. */
function renderExamples() {
  const host = $('examples'); host.textContent = '';
  if (!currentGrains().length) return;
  const typed = ($('ask').value || '').trim();
  if (typed) {
    host.appendChild(el('span', 'tiny', 'Filtering as you type — press Enter to ask “' +
      (typed.length > 44 ? typed.slice(0, 44) + '…' : typed) + '”'));
    return;
  }
  const qs = ACTIVE_ENTS.slice(0, 2).map(e => 'what do you know about ' + e.name + '?');
  qs.push('what changed today?');
  host.appendChild(el('span', 'tiny', 'Try'));
  for (const q of qs.slice(0, 3)) {
    const c = el('span', 'chip', q);
    c.onclick = () => { $('ask').value = q; runAsk(q); };
    host.appendChild(c);
  }
}
/* When a filter is on, say so and give a way out — otherwise arriving from
   the graph's "See all" looks like nothing happened. */
function renderFilterBar() {
  const host = $('filterBar');
  host.textContent = '';
  host.hidden = !ENTITY;
  if (!ENTITY) return;
  const chip = el('div');
  chip.style.cssText = 'display:inline-flex;align-items:center;gap:10px;padding:7px 8px 7px 14px;'
    + 'border-radius:18px;background:var(--accent-soft);border:1px solid var(--accent-line)';
  const t = el('span', null, 'Showing only ' + ENTITY);
  t.style.cssText = 'font-size:13.5px;font-weight:600;color:var(--accent)';
  chip.appendChild(t);
  const x = el('button', null, 'Show everything ✕');
  x.style.cssText = 'border:0;background:var(--surface);color:var(--text);font-family:inherit;'
    + 'font-size:12.5px;font-weight:500;padding:4px 11px;border-radius:14px';
  x.onclick = () => { ENTITY = null; render(); };
  chip.appendChild(x);
  host.appendChild(chip);
}
function renderBanner() {
  const n = (RECS.pending || []).length;
  $('sugBanner').hidden = !n || PAGE !== 'memory';
  if (n) {
    const kinds = [...new Set((RECS.pending || []).map(r => analyzerWord(r.analyzer)))].slice(0, 3);
    $('sugBannerText').innerHTML = '<b>' + n + (n === 1 ? ' suggestion</b>' : ' suggestions</b>')
      + ' to make this memory more reliable' + (kinds.length ? ' — ' + esc(kinds.join(', ')) : '') + '.';
  }
}

/* ── memory list ── */
function visibleGrains() {
  const needle = ($('ask').value || '').toLowerCase().trim();
  let rows = currentGrains();
  if (ENTITY) rows = rows.filter(g => {
    const f = g.fields || {};
    return subjectOf(g) === ENTITY || (typeof f.object === 'string' && f.object === ENTITY);
  });
  if (needle && !ANSWER) rows = rows.filter(g => sentence(g).toLowerCase().includes(needle));
  return rows;
}
function renderMemList() {
  const host = $('memList'); host.textContent = '';
  const rows = visibleGrains();
  const forgotten = BROWSE.filter(g => isGone(g) && !isInternal(g))
    .filter(g => !ENTITY || ((g.fields || {}).subject === ENTITY));
  if (!rows.length && !forgotten.length) {
    const e = el('div', 'empty');
    e.textContent = currentGrains().length
      ? 'Nothing matches. Clear the box or pick a different name.'
      : 'No memories yet — open Connect to attach an agent.';
    host.appendChild(e); return;
  }
  const groups = new Map();
  for (const g of rows) {
    const k = subjectOf(g) || '—';
    if (!groups.has(k)) groups.set(k, []);
    groups.get(k).push(g);
  }
  const order = [...groups.keys()].sort((a, b) => groups.get(b).length - groups.get(a).length || a.localeCompare(b));
  for (const k of order) {
    const list = groups.get(k).sort((a, b) => (b.op_seq || 0) - (a.op_seq || 0));
    const head = el('div', 'grp-head');
    head.appendChild(el('h2', null, k === '—' ? 'Everything else' : titleize(k)));
    head.appendChild(el('span', 'meta', list.length + (list.length === 1 ? ' memory' : ' memories')));
    host.appendChild(head);
    for (const g of list) host.appendChild(memRow(g));
  }
  if (forgotten.length) {
    const head = el('div', 'grp-head');
    head.appendChild(el('h2', null, 'Deleted'));
    head.appendChild(el('span', 'meta', forgotten.length + ' removed for good'));
    host.appendChild(head);
    for (const g of forgotten.slice(0, 20)) host.appendChild(memRow(g));
  }
}
function memRow(g) {
  const gone = isGone(g);
  const row = el('div', 'mrow' + (gone ? ' gone' : '') + (SEL === g.hash ? ' sel' : ''));
  const body = el('div', 'body');
  const say = el('div', 'say', gone ? (g.fields ? predicate(g) : 'A memory') : predicate(g));
  body.appendChild(say);
  body.appendChild(el('div', 'prov', gone
    ? 'Deleted at your request — the content is gone for good'
    : provenance(g)));
  const dev = el('div', 'mono dev-only');
  dev.textContent = (g.type || 'grain') + ' · ' + (g.hash || '').slice(0, 12)
    + (g.superseded_by ? ' · superseded ' + g.superseded_by.slice(0, 12) : '');
  body.appendChild(dev);
  row.appendChild(body);
  row.appendChild(el('div', 'when', relTime(hlcMs(g.hlc))));
  row.onclick = () => openPanel(g.hash);
  return row;
}

/* ── ask → answer ── */
function relationFromQuestion(q) {
  const low = ' ' + q.toLowerCase().replace(/[^a-z0-9_ ]/g, ' ') + ' ';
  const rels = [...new Set(currentGrains().map(g => (g.fields || {}).relation).filter(Boolean))];
  let best = null;
  for (const r of rels) {
    for (const w of r.split('_')) {
      if (w.length < 4) continue;
      const stem = w.replace(/s$/, '');
      if (low.includes(' ' + stem)) { best = r; break; }
    }
    if (best) break;
  }
  return best;
}
function entityFromQuestion(q) {
  const low = q.toLowerCase();
  let best = null;
  for (const e of buildEntities(currentGrains())) {
    if (low.includes(e.name.toLowerCase()) && (!best || e.name.length > best.length)) best = e.name;
  }
  return best;
}
/* Free-text recall is a bag of words, so sending the whole question makes
   "what", "does" and "today" compete with the words that matter. */
const STOPWORDS = new Set(['what','whats','who','whos','when','where','why','how','is','are','was',
  'were','do','does','did','has','have','the','a','an','of','for','to','in','on','about','me','my',
  'you','your','i','it','its','tell','show','know','knows','list','find','any','anything',
  'everything','please','can','could','would','there','that','this','and','or']);
const contentWords = q => q.toLowerCase().replace(/[^a-z0-9\s_-]/g, ' ').split(/\s+/)
  .filter(w => w.length > 1 && !STOPWORDS.has(w));
/* Questions about time cannot be answered by recall at all — they are a
   question about the op-log. Answer them from it instead of pretending. */
const TEMPORAL = /\b(today|yesterday|this week|recently|lately|just now|changed|change[sd]?|new|newest|latest|happened|since)\b/i;
function answerFromActivity(q) {
  const since = Date.now() - 24 * 3600 * 1000;
  const ops = LOG.filter(o => hlcMs(o.hlc) >= since)
    .filter(o => { const g = BYHASH[o.hash]; return !(g && isInternal(g)); })
    .sort((a, b) => (b.op_seq || 0) - (a.op_seq || 0));
  const n = k => ops.filter(o => o.op === k).length;
  const text = ops.length
    ? 'In the last 24 hours your agent learned ' + n('add') + ', changed ' + n('supersede')
      + ' and deleted ' + n('forget') + '.'
    : 'Nothing has changed in the last 24 hours.';
  /* A supersede logs two ops for the same grain — show it once. And a
     tombstoned grain has no fields left to make a sentence from, so say
     what happened to it rather than "no readable text". */
  const seen = new Set(), grains = [];
  for (const o of ops) {
    if (grains.length >= 6 || seen.has(o.hash)) continue;
    seen.add(o.hash);
    const g = BYHASH[o.hash];
    const say = o.op === 'forget' || !g || isGone(g) ? 'A memory was deleted'
      : (o.op === 'supersede' ? 'Updated: ' : '') + sentence(g);
    grains.push({ hash: o.hash, hlc: o.hlc, _say: say, fields: (g || {}).fields, type: (g || {}).type });
  }
  return { q, query: null, kind: 'activity', subject: null, relation: null, grains, text, error: null };
}
async function runAsk(q) {
  q = (q || '').trim();
  if (!q) { ANSWER = null; render(); return; }
  const subject = entityFromQuestion(q);
  const relation = relationFromQuestion(q);
  if (!subject && TEMPORAL.test(q)) {
    ANSWER = answerFromActivity(q);
    ENTITY = null;
    if (PAGE !== 'memory') go('memory'); else render();
    return;
  }
  const words = contentWords(q);
  let query;
  if (subject) {
    query = 'RECALL facts WHERE subject = "' + subject.replace(/"/g, '') + '"'
      + (relation ? ' AND relation = "' + relation + '"' : '') + ' LIMIT 50';
  } else {
    query = 'RECALL facts ABOUT "' + (words.join(' ') || q).replace(/"/g, '') + '" LIMIT 20';
  }
  let res = await cal(query);
  if ((!res.ok || !((res.result || {}).grains || []).length) && !subject) {
    const word = words[words.length - 1] || q;
    query = 'RECALL facts LIKE "' + word.replace(/"/g, '') + '" LIMIT 20';
    res = await cal(query);
  }
  const grains = (res.ok && res.result && res.result.type === 'grains') ? (res.result.grains || []) : [];
  ANSWER = { q, query, subject, relation, grains, error: res.ok ? null : (res.error || 'query failed'),
    code: res.code, elapsed: res.elapsed_ms };
  ENTITY = null;
  if (PAGE !== 'memory') go('memory'); else render();
}
/* A CAL result grain and a browse row differ in shape — normalise. */
const rgType = g => g.grain_type || g.type;
const rgFields = g => g.fields || {};
function answerText(a) {
  if (a.error) return null;
  if (a.kind === 'activity') return a.text;
  if (!a.grains.length) return 'Nothing matched that. Ask about one of the names on the left, '
    + 'or try “what changed today?”.';
  const subj = a.subject ? cap(a.subject) : null;
  if (a.relation) {
    /* The same value can be a head in more than one namespace — say it once. */
    const objs = [...new Set(a.grains.filter(g => rgFields(g).relation === a.relation)
      .map(g => rgFields(g).object).filter(o => typeof o === 'string'))];
    if (objs.length) {
      const phrase = (REL_PHRASE[a.relation] || cap(a.relation.replace(/_/g, ' ')) + ' {o}');
      const said = phrase.replace('{o}', objs.slice(0, 3).join(', '));
      return (subj ? subj + ' ' + lowerFirst(said) : said) + '.';
    }
  }
  if (subj) return 'Here is everything your agent knows about ' + subj + ' — '
    + a.grains.length + (a.grains.length === 1 ? ' memory' : ' memories') + '.';
  return 'Found ' + a.grains.length + (a.grains.length === 1 ? ' memory' : ' memories') + ' that match.';
}
function renderAnswer() {
  const host = $('answer');
  host.hidden = !ANSWER; host.textContent = '';
  if (!ANSWER) return;
  const a = ANSWER;
  const top = el('div'); top.style.cssText = 'display:flex;flex-direction:column;gap:10px;padding-bottom:24px';
  top.appendChild(el('span', 'ans-label', a.error ? 'COULD NOT ANSWER' : 'ANSWER'));
  const txt = el('span', 'ans-text', a.error ? a.error : answerText(a));
  if (a.error) txt.style.color = 'var(--danger)';
  top.appendChild(txt);
  if (a.error && a.code) top.appendChild(el('span', 'meta', 'error code ' + a.code));
  host.appendChild(top);

  if (a.grains.length) {
    const box = el('div'); box.style.cssText = 'display:flex;flex-direction:column;border-top:1px solid var(--hair)';
    const lab = el('span', 'meta', 'Based on ' + a.grains.length + (a.grains.length === 1 ? ' memory' : ' memories'));
    lab.style.cssText = 'padding:16px 0 4px'; box.appendChild(lab);
    for (const g of a.grains.slice(0, 6)) {
      const r = el('div', 'srow');
      const dot = el('span'); dot.style.cssText = 'width:6px;height:6px;border-radius:3px;flex-shrink:0;background:var(--ok)';
      r.appendChild(dot);
      r.appendChild(el('span', 't', g._say || sentence({ type: rgType(g), fields: rgFields(g) })));
      r.appendChild(el('span', 'w', relTime(hlcMs(g.hlc)) || ''));
      if (g.hash) r.onclick = () => openPanel(g.hash);
      box.appendChild(r);
    }
    host.appendChild(box);
  }

  if (a.kind === 'activity') {
    const go2 = el('div', 'disclose');
    go2.appendChild(el('span', 'grow', 'Every change, in order'));
    const l = el('span', null, 'Open Activity →');
    l.style.cssText = 'font-size:14px;font-weight:600;color:var(--accent)';
    go2.appendChild(l);
    go2.onclick = () => { ANSWER = null; go('activity'); };
    host.appendChild(go2);
    return;
  }
  const foot = el('div', 'disclose');
  foot.innerHTML = '<svg class="caret" width="15" height="15" viewBox="0 0 24 24" fill="none">'
    + '<path d="M9 5.5l7 6.5-7 6.5" stroke="var(--dim)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>'
    + '<span class="grow">How this answer was found</span>';
  const openq = el('span'); openq.style.cssText = 'font-size:14px;font-weight:600;color:var(--accent)';
  openq.textContent = 'Open in Query';
  openq.onclick = e => { e.stopPropagation(); $('qtext').value = a.query; go('query'); runQuery(); };
  if (a.query) foot.appendChild(openq);
  const copy = el('span'); copy.style.cssText = 'font-size:14px;font-weight:600;color:var(--accent)';
  copy.textContent = 'Copy'; copy.onclick = e => { e.stopPropagation(); copyText(answerText(a) || a.error, 'Answer'); };
  foot.appendChild(copy);
  const detail = el('div');
  detail.style.cssText = 'display:none;flex-direction:column;gap:8px;padding:0 0 20px';
  const pre = el('pre', 'code', a.query); detail.appendChild(pre);
  detail.appendChild(el('span', 'tiny', a.elapsed != null ? 'ran in ' + a.elapsed + ' ms' : ''));
  foot.onclick = () => {
    const open = detail.style.display === 'flex';
    detail.style.display = open ? 'none' : 'flex';
    foot.classList.toggle('open', !open);
  };
  host.appendChild(foot); host.appendChild(detail);
}

/* ══ detail panel ═════════════════════════════════════════════════════ */
function closePanel() { $('panelWrap').hidden = true; SEL = null; renderMemList(); }
async function openPanel(hash) {
  if (!hash) return;
  hash = hash.replace(/^sha256:/, '');
  SEL = hash; renderMemList();
  $('panelWrap').hidden = false;
  const p = $('panel'); p.textContent = '';
  p.appendChild(el('span', 'tiny', 'loading…'));
  const known = BYHASH[hash];
  const g = await api('/api/grain?hash=' + encodeURIComponent(hash));
  p.textContent = '';

  const head = el('div'); head.style.cssText = 'display:flex;align-items:flex-start;gap:12px';
  const ht = el('div'); ht.style.cssText = 'display:flex;flex-direction:column;gap:9px;flex:1';
  ht.appendChild(el('span', 'sec-label', 'MEMORY'));
  const gone = g.ok === false;
  const title = el('span', null, gone
    ? (known ? sentence(known) : 'This memory was deleted')
    : sentence({ type: g.type, fields: g.fields }));
  title.style.cssText = 'font:600 22px/31px var(--sans);color:var(--ink);letter-spacing:-.02em';
  ht.appendChild(title);
  head.appendChild(ht);
  const x = el('button', 'btn ghost sm', '✕');
  x.style.cssText = 'width:34px;padding:0;flex-shrink:0'; x.onclick = closePanel;
  head.appendChild(x);
  p.appendChild(head);

  if (gone) {
    const w = el('div', 'pgroup');
    w.appendChild(el('span', 'sub', 'The content is gone for good — only the record that it was removed remains. '
      + 'That is what "forget" means here: a tombstone, not a hidden row.'));
    const h = el('div', 'mono'); h.textContent = hash; h.style.wordBreak = 'break-all';
    w.appendChild(h); p.appendChild(w); return;
  }

  const f = g.fields || {};
  const when = createdMs(f) || hlcMs(known && known.hlc);
  const prov = el('div', 'pgroup');
  const kv = (k, v, title2) => { const r = el('div'); r.style.cssText = 'display:flex;align-items:baseline;gap:12px';
    const kk = el('span', null, k); kk.style.cssText = 'width:96px;flex-shrink:0;font-size:13.5px;color:var(--dim)';
    const vv = el('span', null, v); vv.style.cssText = 'flex:1;font-size:14.5px;color:var(--ink)';
    if (title2) vv.title = title2;
    r.appendChild(kk); r.appendChild(vv); return r; };
  prov.appendChild(kv('Learned', relTime(when) + (when ? ' · ' + new Date(when).toLocaleDateString() : ''), isoTitle(when)));
  prov.appendChild(kv('Kind', cap(g.type || 'fact') + (g.type === 'observation' ? ' — something it saw, not something it was told' : '')));
  if (f.namespace) prov.appendChild(kv('Namespace', f.namespace));
  if (f.session_id) prov.appendChild(kv('Session', f.session_id));
  const used = TELEMETRY && (TELEMETRY.access || []).find(a => a.hash === hash);
  if (used) prov.appendChild(kv('Used', used.recall_count + ' times · last ' + relTime(used.last_ms)));
  p.appendChild(prov);

  /* version history, in plain language */
  if (g.type === 'fact' && f.subject && f.relation) {
    const hist = await cal('HISTORY WHERE subject = "' + String(f.subject).replace(/"/g, '')
      + '" AND relation = "' + String(f.relation).replace(/"/g, '') + '"');
    const versions = (hist.ok && hist.result && hist.result.versions) || [];
    if (versions.length > 1) {
      const box = el('div', 'pgroup');
      box.appendChild(el('span', 'sec-label', 'HOW THIS CHANGED'));
      versions.forEach((v, i) => {
        const step = el('div', 'step');
        const rail = el('div', 'rail');
        const bul = el('div', 'bul' + (i === 0 ? '' : ' past')); rail.appendChild(bul);
        if (i < versions.length - 1) rail.appendChild(el('div', 'ln'));
        step.appendChild(rail);
        const bd = el('div'); bd.style.cssText = 'display:flex;flex-direction:column;gap:3px;flex:1;padding-bottom:18px';
        const val = el('span', null, typeof v.fields === 'object' && v.fields ? (v.fields.object != null ? String(v.fields.object) : preview(v.fields)) : '');
        val.style.cssText = 'font-size:15.5px;font-weight:500;color:' + (i === 0 ? 'var(--ink)' : 'var(--muted)');
        bd.appendChild(val);
        bd.appendChild(el('span', 'meta', i === 0
          ? 'Added ' + relTime(hlcMs(v.hlc)) + ' · this is what your agent uses now'
          : 'Added ' + relTime(hlcMs(v.hlc)) + ' · replaced, but kept so you can see the change'));
        step.appendChild(bd);
        box.appendChild(step);
      });
      p.appendChild(box);
    }
  }

  /* actions */
  const acts = el('div', 'pgroup');
  const row = el('div'); row.style.cssText = 'display:flex;align-items:center;gap:10px';
  const correct = el('button', 'btn', 'Correct this memory'); correct.style.flex = '1';
  const askAbout = el('button', 'btn ghost', 'Ask about it');
  row.appendChild(lock(correct)); row.appendChild(askAbout);
  acts.appendChild(row);
  const form = el('div'); form.style.cssText = 'display:none;flex-direction:column;gap:9px';
  const inp = document.createElement('input'); inp.type = 'text';
  inp.value = typeof f.object === 'string' ? f.object : '';
  inp.placeholder = 'What should it say instead?';
  const why = document.createElement('input'); why.type = 'text'; why.placeholder = 'Why are you changing it?';
  const save = el('button', 'btn sm', 'Save the correction');
  form.appendChild(el('span', 'meta', 'The old version is kept — corrections are added on top, never written over.'));
  form.appendChild(inp); form.appendChild(why); form.appendChild(save);
  acts.appendChild(form);
  correct.onclick = () => { form.style.display = form.style.display === 'flex' ? 'none' : 'flex'; inp.focus(); };
  askAbout.onclick = () => { closePanel(); $('ask').value = 'what do you know about ' + (f.subject || '') + '?'; runAsk($('ask').value); };
  save.onclick = async () => {
    if (!inp.value.trim()) { toast('Type the new value first'); return; }
    save.disabled = true;
    let q = 'SUPERSEDE sha256:' + hash + ' SET object = "' + inp.value.replace(/"/g, '\\"') + '"';
    if (why.value.trim()) q += ' BECAUSE "' + why.value.replace(/"/g, '\\"') + '"';
    const r = await cal(q);
    save.disabled = false;
    if (r.ok) { toast('Corrected ✓'); closePanel(); await refresh(); }
    else toast('Could not save: ' + (r.error || 'unknown') + (r.code ? ' [' + r.code + ']' : ''));
  };

  const del = el('div'); del.style.cssText = 'display:flex;align-items:center;gap:9px;padding-top:4px';
  del.innerHTML = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" style="flex-shrink:0">'
    + '<path d="M4.5 6.5h15M9.5 6.5V4.8h5v1.7M6.7 6.5l.9 12.2h8.8l.9-12.2" stroke="var(--danger)" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>';
  const forget = el('button', 'btn danger', 'Forget this memory');
  del.appendChild(lock(forget));
  del.appendChild(el('span', 'meta', '— cannot be undone'));
  forget.onclick = async () => {
    if (!confirm('Forget this memory?\n\n"' + sentence({ type: g.type, fields: f })
      + '"\n\nThe content is erased for good. This cannot be undone.')) return;
    const r = await cal('FORGET sha256:' + hash);
    if (r.ok) { toast('Forgotten'); closePanel(); await refresh(); }
    else toast('Could not forget: ' + (r.error || 'unknown'));
  };
  acts.appendChild(del);
  p.appendChild(acts);

  /* developer details */
  const dev = el('div', 'pgroup dev-only dev-flex');
  dev.appendChild(el('span', 'sec-label', 'DEVELOPER DETAILS'));
  const hh = el('div', 'mono'); hh.textContent = g.hash || hash;
  hh.style.cssText = 'word-break:break-all;cursor:pointer'; hh.title = 'click to copy';
  hh.onclick = () => copyText(g.hash || hash, 'Content address');
  dev.appendChild(hh);
  dev.appendChild(el('pre', 'code', JSON.stringify(g.fields, null, 2)));
  const cp = el('button', 'btn ghost sm', 'Copy grain JSON');
  cp.onclick = () => copyText(JSON.stringify(g, null, 2), 'Grain JSON');
  dev.appendChild(cp);
  /* "As the model sees it" (docs/anonymization-proposal.md §8.3): the same
     grain through the egress boundary — pseudonymized fields, whether or
     not a policy is declared yet. The single most persuasive view this
     feature has. */
  const mv = el('button', 'btn ghost sm', 'Model view');
  mv.style.marginLeft = '8px';
  mv.onclick = async () => {
    mv.disabled = true;
    const pv = await api('/api/anon/preview?hash=' + encodeURIComponent(g.hash || hash));
    mv.disabled = false;
    if (!pv || pv.ok === false) { toast('Preview unavailable: ' + ((pv && pv.error) || '')); return; }
    const pre = el('pre', 'code', JSON.stringify(pv.fields, null, 2));
    pre.style.borderLeft = '2px solid var(--warn)';
    dev.appendChild(el('span', 'sec-label', 'AS THE MODEL SEES IT'));
    dev.appendChild(pre);
    mv.remove();
  };
  dev.appendChild(mv);
  p.appendChild(dev);
}

/* ══ activity ═════════════════════════════════════════════════════════ */
const ACT_KINDS = [['all', 'Everything'], ['add', 'Learned'], ['supersede', 'Changed'], ['forget', 'Deleted']];
/* null = the bound session default (the already-loaded global LOG/BYHASH —
   no extra fetch). Anything else fetches that namespace's browse rows once
   (cached) and reads op/hash/fields straight off them instead — a
   namespace-scoped BROWSE row is already everything an op-log row plus a
   BYHASH lookup would have given us. */
let ACT_NS = null;
async function actSetNamespace(ns) {
  ACT_NS = (!ns || ns === boundNamespace()) ? null : ns;
  await renderActivity();
}
async function renderActivity() {
  renderCrumbHeader('actCrumb', [{ label: 'Activity' }], 'Everything your agent learned, changed, or forgot — newest first.');
  const f = $('actFilters'); f.textContent = '';
  for (const [k, label] of ACT_KINDS) {
    const c = el('span', 'chip' + (ACTFILTER === k ? ' on' : ''), label);
    c.onclick = () => { ACTFILTER = k; renderActivity(); };
    f.appendChild(c);
  }
  const nsHost = $('actNsHost'); nsHost.textContent = '';
  nsHost.appendChild(nsCombo('actNs', ACT_NS || boundNamespace(), actSetNamespace));

  const host = $('actList'); host.textContent = '';
  // A namespace-scoped browse row already carries op/hash/hlc *and* the
  // resolved fields in one object — strictly more than /api/log's bare
  // op-log entries, and (unlike /api/log, which spans every namespace with
  // no filter of its own) it only ever contains this namespace's grains, so
  // every row here resolves instead of falling through to a bare hash.
  const rows = await browseForNamespace(ACT_NS || boundNamespace());
  let ops = rows.slice().sort((a, b) => (b.op_seq || 0) - (a.op_seq || 0)).filter(o => !isInternal(o));
  if (ACTFILTER !== 'all') ops = ops.filter(o => o.op === ACTFILTER);
  if (!ops.length) { host.appendChild(el('div', 'empty', 'Nothing here yet.')); return; }
  let day = null;
  for (const o of ops.slice(0, 200)) {
    const ms = hlcMs(o.hlc);
    if (dayKey(ms) !== day) {
      day = dayKey(ms);
      const h = el('span', 'sec-label', dayLabel(ms));
      h.style.cssText = 'display:block;padding:24px 0 12px;font-size:13px;letter-spacing:.06em';
      host.appendChild(h);
    }
    const g = o;
    const ev = el('div', 'ev');
    ev.appendChild(el('span', 'at', clock(ms)));
    const ic = el('span', 'ic');
    ic.innerHTML = o.op === 'add'
      ? '<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M12 5v14M5 12h14" stroke="var(--ok)" stroke-width="2.4" stroke-linecap="round"/></svg>'
      : o.op === 'forget'
      ? '<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M5 12h14" stroke="var(--danger)" stroke-width="2.4" stroke-linecap="round"/></svg>'
      : '<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M4 8h11l-3-3M20 16H9l3 3" stroke="var(--warn)" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"/></svg>';
    ev.appendChild(ic);
    const body = el('div', 'body');
    const verb = o.op === 'add' ? 'Learned that ' : o.op === 'supersede' ? 'Updated: ' : 'Deleted ';
    body.appendChild(el('div', 'say', g && g.fields
      ? verb + lowerFirst(sentence(g))
      : verb.trim() + ' a memory (' + shortHash(o.hash) + ')'));
    /* The time is already in the left column — drop the "Learned …" part. */
    const sub = o.op === 'forget'
      ? 'You asked for this — the content was erased, not just hidden'
      : o.op === 'supersede' ? 'The previous version is kept so you can see the change'
      : (g ? provenanceParts(g).filter(p => !/^Learned /.test(p)).join(' · ') : '');
    if (sub) body.appendChild(el('div', 'prov', sub));
    const dev = el('div', 'mono dev-only');
    dev.textContent = 'op ' + o.op_seq + ' · ' + o.op + ' · ' + (o.hash || '').slice(0, 12);
    body.appendChild(dev);
    ev.appendChild(body);
    /* A wide row has room to say what kind of grain this is and where it
       lives — without that, the extra width past the text is just blank. */
    const tags = el('div', 'ev-tags');
    if (g && g.type) {
      const kind = el('span', 'tag'); kind.style.cssText = 'background:var(--well);color:var(--dim);font-weight:500';
      kind.textContent = g.type;
      tags.appendChild(kind);
    }
    if (g && g.fields && g.fields.namespace) tags.appendChild(el('span', 'tiny mono', g.fields.namespace));
    ev.appendChild(tags);
    ev.style.cursor = 'pointer';
    ev.onclick = () => openPanel(o.hash);
    host.appendChild(ev);
  }
}

/* ══ suggestions ══════════════════════════════════════════════════════ */
/* "loop.contradiction_sweep/1" → "contradiction sweep" */
const analyzerName = id => String(id || '').replace(/^loop\./, '').replace(/\/\d+$/, '').replace(/[._-]/g, ' ');
function analyzerWord(id) {
  const s = analyzerName(id);
  if (/contradict|conflict/.test(s)) return 'a conflict';
  if (/dup/.test(s)) return 'a duplicate';
  if (/stale|decay/.test(s)) return 'something stale';
  if (/gap|missing/.test(s)) return 'a gap';
  return s || 'a finding';
}
function sevStyle(sev) {
  if (sev === 'high') return ['var(--danger)', 'var(--danger-soft)'];
  if (sev === 'medium') return ['var(--warn)', 'var(--warn-soft)'];
  if (sev === 'low') return ['var(--cat-project)', 'var(--accent-soft)'];
  return ['var(--muted)', 'var(--raise)'];
}
function renderSuggestions() {
  renderCrumbHeader('sugCrumb', [{ label: 'Suggestions' }],
    'Ways to make this memory more reliable. Nothing is changed until you approve it, and every change can be undone.');
  const host = $('sugList'); host.textContent = '';
  if (!canWrite()) host.appendChild(readOnlyNote());
  const list = RECS[SUGTAB] || [];
  if (!list.length) {
    host.appendChild(el('div', 'empty', SUGTAB === 'pending'
      ? 'Nothing needs your attention. Run an analysis to look again.'
      : SUGTAB === 'applied' ? 'Nothing has been applied yet.' : 'Nothing dismissed.'));
  }
  for (const r of list) host.appendChild(sugCard(r));
  if (SUGTAB === 'applied') renderOutcomes(host);
}
function sugCard(r) {
  const [fg, bg] = sevStyle(r.severity);
  const card = el('div', 'card sug');
  const head = el('div'); head.style.cssText = 'display:flex;align-items:center;gap:10px';
  const tag = el('span', 'tag', null); tag.style.cssText = 'background:' + bg + ';color:' + fg;
  const d = el('span'); d.style.cssText = 'width:6px;height:6px;border-radius:3px;background:' + fg;
  tag.appendChild(d); tag.appendChild(el('span', null, cap(analyzerWord(r.analyzer).replace(/^an? /, ''))));
  head.appendChild(tag);
  head.appendChild(el('span', 'meta', 'Found by the ' + analyzerName(r.analyzer) + ' check'));
  const sp = el('div'); sp.style.flex = '1'; head.appendChild(sp);
  head.appendChild(el('span', 'meta', r.status || ''));
  card.appendChild(head);

  const body = el('div'); body.style.cssText = 'display:flex;flex-direction:column;gap:8px';
  const t = el('span', null, r.summary || 'A suggestion');
  t.style.cssText = 'font:600 19px/27px var(--sans);color:var(--ink);letter-spacing:-.015em';
  body.appendChild(t);
  if (r.destructive) body.appendChild(el('span', 'sub',
    'This one removes content for good. It cannot be undone once applied.'));
  else body.appendChild(el('span', 'sub',
    'Applying this changes what your agent reads next time. The old version stays in history.'));
  card.appendChild(body);

  const ev = evidenceRows(r.evidence);
  if (ev) card.appendChild(ev);

  const acts = el('div', 'acts');
  const reason = el('div', 'reason'); reason.hidden = true;
  const prompt = el('span', 'meta');
  const line = el('div', 'line');
  const why = document.createElement('input'); why.type = 'text';
  const gate = document.createElement('input'); gate.type = 'text';
  gate.placeholder = 'gate run id (eval-…)'; gate.hidden = true;
  const conf = el('button', 'btn sm', 'Confirm');
  const cancel = el('button', 'btn ghost sm', 'Cancel');
  line.appendChild(why); line.appendChild(gate); line.appendChild(conf); line.appendChild(cancel);
  reason.appendChild(prompt); reason.appendChild(line);

  if (r.status === 'applied') {
    if (r.rollbackable) {
      const undo = el('button', 'btn ghost', 'Undo');
      undo.onclick = () => arm('rollback', 'Why are you undoing this?', 'Undo it');
      acts.appendChild(lock(undo));
    }
    acts.appendChild(el('span', 'note', r.rollbackable ? 'Undoable · the previous state is kept' : 'Not undoable'));
  } else if (r.status === 'rejected') {
    /* Rejected is terminal in the engine's lifecycle — offering a button
       here would only ever produce an error. */
    acts.appendChild(el('span', 'note', 'Dismissed — it will not be applied.'));
  } else if (r.status === 'approved') {
    /* Approved but not yet applied: usually because an apply failed midway.
       Surface it rather than letting it fall between the tabs. */
    const go = el('button', 'btn', 'Finish applying');
    go.onclick = () => arm('apply', 'Why are you applying this?', 'Apply it');
    acts.appendChild(lock(go));
    acts.appendChild(el('span', 'note', 'You approved this, but it has not been applied yet.'));
  } else {
    const ok = el('button', 'btn', r.destructive ? 'Apply — removes content' : 'Apply this fix');
    ok.onclick = () => arm('approve_and_apply', 'Why are you applying this?', 'Apply it');
    const no = el('button', 'btn ghost', 'Dismiss');
    no.onclick = () => arm('reject', 'Why are you dismissing this?', 'Dismiss it');
    acts.appendChild(lock(ok)); acts.appendChild(lock(no));
    acts.appendChild(el('span', 'note', r.destructive
      ? 'Cannot be undone' : r.rollbackable ? 'Undoable · the older memory stays in history' : ''));
  }
  card.appendChild(acts); card.appendChild(reason);

  const dev = el('div', 'mono dev-only');
  dev.textContent = (r.hash || '').slice(0, 16) + ' · ' + (r.analyzer || '') + ' · severity ' + (r.severity || '?')
    + (r.target_ref ? ' · target ' + String(r.target_ref).slice(0, 12) : '');
  card.appendChild(dev);

  let armed = null;
  const gated = !!r.evalset_hash;
  function arm(action, promptText, confirmLabel) {
    armed = action;
    const applying = action === 'apply' || action === 'approve_and_apply';
    prompt.textContent = promptText + ' Your answer is recorded in the audit trail.'
      + (gated && applying
        ? ' This change is gated: paste the run id from `areev eval run --evalset '
          + String(r.evalset_hash).slice(0, 12) + '…`.'
        : '');
    gate.hidden = !(gated && applying);
    conf.textContent = confirmLabel;
    why.placeholder = 'e.g. confirmed with the customer on the call';
    acts.hidden = true; reason.hidden = false;
    why.focus();
  }
  cancel.onclick = () => { armed = null; why.value = ''; gate.value = ''; reason.hidden = true; acts.hidden = false; };
  conf.onclick = async () => {
    if (!why.value.trim()) { toast('A reason is required — it goes in the audit trail'); why.focus(); return; }
    if (!gate.hidden && !gate.value.trim()) {
      toast('This change applies only with a recorded gate run — run the evalset first and paste its run id');
      gate.focus(); return;
    }
    conf.disabled = true; cancel.disabled = true;
    await loopAct(r.hash, armed, why.value.trim(), gate.hidden ? '' : gate.value.trim());
    conf.disabled = false; cancel.disabled = false;
  };
  return card;
}
/* Areev Loop cites evidence as bare content addresses (Vec<String>). A hash is
   not evidence to a human — resolve it to the sentence it stands for, and
   say so plainly when the grain is not in the loaded window. */
const HASH_RE = /^(sha256:)?[0-9a-f]{64}$/i;
/* Areev Loop's own records are Facts too — cite them as what they are rather
   than dumping the serialized recommendation into the card. */
function internalLabel(g) {
  const f = g.fields || {};
  if (f.relation === 'loop_recommendation') {
    let a = null;
    try { a = JSON.parse(f.object).analyzer; } catch (e) { /* not JSON */ }
    return a ? 'An earlier suggestion from the ' + analyzerName(a) + ' check'
             : 'An earlier suggestion from this memory’s review queue';
  }
  if (f.relation === 'loop_audit') return 'An entry in the audit trail';
  return 'An internal Areev record';
}
function describeRef(ref) {
  const hash = String(ref).replace(/^sha256:/, '');
  const g = BYHASH[hash];
  if (!g) return { text: 'A memory outside the loaded window', when: '', hash };
  const text = isInternal(g) ? internalLabel(g) : sentence(g);
  return { text, when: relTime(hlcMs(g.hlc)), hash };
}
function evidenceRows(evidence) {
  if (!evidence) return null;
  let items = [];
  if (Array.isArray(evidence)) items = evidence;
  else if (typeof evidence === 'object') {
    for (const k of ['items', 'grains', 'facts', 'rows']) if (Array.isArray(evidence[k])) { items = evidence[k]; break; }
    if (!items.length) items = Object.entries(evidence).map(([k, v]) => ({ text: k + ': ' + (typeof v === 'object' ? JSON.stringify(v) : v) }));
  }
  if (!items.length) return null;
  const box = el('div', 'evi');
  for (const it of items.slice(0, 6)) {
    const row = el('div', 'evi-row');
    const mark = el('span'); mark.style.cssText = 'width:18px;flex-shrink:0;display:flex;justify-content:center';
    mark.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M6 12h12" stroke="var(--ghost)" stroke-width="2.2" stroke-linecap="round"/></svg>';
    row.appendChild(mark);
    let text, when = '', hash = null;
    if (typeof it === 'string') {
      if (HASH_RE.test(it.trim())) ({ text, when, hash } = describeRef(it.trim()));
      else text = it;
    } else if (it && typeof it === 'object') {
      const h = it.hash || it.grain || it.ref;
      text = it.text || it.summary || it.label;
      if (h) { const d = describeRef(h); hash = d.hash; when = d.when; if (!text) text = d.text; }
      if (!text) text = JSON.stringify(it);
    } else text = String(it);
    row.appendChild(el('span', 't', text));
    if (hash) {
      const h = el('span', 'mono dev-only', hash.slice(0, 12));
      h.style.cssText = 'flex-shrink:0;margin-right:10px';
      row.appendChild(h);
      row.onclick = () => openPanel(hash);
      row.style.cursor = 'pointer';
    }
    row.appendChild(el('span', 'w', when));
    box.appendChild(row);
  }
  /* Never truncate silently — a card citing 10 memories must not look like
     it cites 6. */
  if (items.length > 6) {
    const more = el('div', 'evi-row');
    const pad = el('span'); pad.style.cssText = 'width:18px;flex-shrink:0';
    more.appendChild(pad);
    more.appendChild(el('span', 't', '…and ' + (items.length - 6) + ' more'))
      .style.color = 'var(--dim)';
    box.appendChild(more);
  }
  return box;
}
async function renderOutcomes(parent) {
  const r = await api('/api/loop/outcomes');
  const list = (r && r.ok && r.outcomes) || [];
  if (!list.length) return;
  const host = el('div', 'stack');
  parent.appendChild(host);
  const head = el('div', 'grp-head'); head.appendChild(el('h2', null, 'Did it work?'));
  head.appendChild(el('span', 'meta', 're-measured after each applied change'));
  host.appendChild(head);
  for (const o of list) {
    const row = el('div', 'srow');
    const good = o.verdict !== 'regressed';
    const dot = el('span'); dot.style.cssText = 'width:6px;height:6px;border-radius:3px;flex-shrink:0;background:'
      + (good ? 'var(--ok)' : 'var(--danger)');
    row.appendChild(dot);
    const hz = o.horizon_ms % 86400000 === 0 ? (o.horizon_ms / 86400000) + ' days' : (o.horizon_ms / 3600000) + ' hours';
    row.appendChild(el('span', 't', cap(String(o.metric || '').replace(/_/g, ' '))
      + ' went from ' + o.baseline + ' to ' + o.current + ' after ' + hz));
    const v = el('span', 'w', o.verdict); v.style.color = good ? 'var(--ok)' : 'var(--danger)';
    row.appendChild(v);
    host.appendChild(row);
  }
}
/* A console started without --token-env refuses every write. Say so up front
   rather than letting someone type a reason and hit a wall. */
const canWrite = () => !!(CONFIG && CONFIG.server && CONFIG.server.auth_required);
const READONLY_WHY = 'This console is read-only — restart it with “areev ui --token-env VAR” to make changes.';
function lock(btn) { if (!canWrite()) { btn.disabled = true; btn.title = READONLY_WHY; } return btn; }
function readOnlyNote() {
  const b = el('div', 'banner');
  b.style.cssText = 'background:var(--accent-soft);border-color:var(--accent-line)';
  b.appendChild(el('span', 'grow', 'Read-only. You can look at everything here, but approving, correcting '
    + 'and forgetting need a console started with a token: areev ui --token-env VAR'));
  return b;
}
const errText = res => ((res && res.error) || 'unknown error') + (res && res.code ? ' [' + res.code + ']' : '');
/* The engine's lifecycle is Pending → Approved → Applied, so applying a
   pending recommendation is two calls, not one — going straight to apply
   fails with LOP-E020. One reason covers both: the user made one decision. */
async function loopAct(hash, action, because, gatingRun) {
  const post = (url, body) => api(url, { method: 'POST',
    headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
  const done = async msg => { toast(msg); RECS = {}; await loadRecs(SUGTAB); await refresh(); };
  /* A code or adapter revision applies only with a recorded gate run; the
     server loads the stats from the journaled eval summary, never from us. */
  const applyBody = gatingRun ? { hash, because, gating_run: gatingRun } : { hash, because };
  let res;
  if (action === 'approve_and_apply') {
    res = await post('/api/loop/review', { hash, decision: 'approve', because });
    if (!(res && res.ok)) return done('Could not approve: ' + errText(res));
    res = await post('/api/loop/apply', applyBody);
    return done(res && res.ok ? 'Applied ✓'
      : 'Approved, but applying failed: ' + errText(res) + ' — finish it from Needs review');
  }
  if (action === 'apply') res = await post('/api/loop/apply', applyBody);
  else if (action === 'rollback') res = await post('/api/loop/rollback', { hash, because });
  else res = await post('/api/loop/review', { hash, decision: 'reject', because });
  return done(res && res.ok
    ? (action === 'reject' ? 'Dismissed' : action === 'rollback' ? 'Undone ✓' : 'Applied ✓')
    : 'Could not ' + (action === 'reject' ? 'dismiss' : action) + ': ' + errText(res));
}
async function runAnalysis() {
  const b = $('runLoop'); b.disabled = true; b.textContent = 'Analysing…';
  const res = await api('/api/loop/run', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
  b.disabled = false; b.textContent = 'Run analysis';
  if (res && res.ok) {
    const n = (res.run && res.run.stored) || 0;
    toast(n ? 'Found ' + n + (n === 1 ? ' suggestion' : ' suggestions') : 'Nothing new found');
  } else toast('Could not run: ' + ((res && res.error) || 'the console may be read-only'));
  RECS = {}; SUGTAB = 'pending'; await loadRecs('pending'); render();
}

/* ══ connect ══════════════════════════════════════════════════════════ */
/* null = we could not read the segment list (the /api/segment* surface is
   token-gated even for reads), [] = readable and empty. */
let SEGMENTS = null;
async function loadSegments() {
  const r = await api('/api/segments');
  SEGMENTS = Array.isArray(r) ? r : null;
  render();
}
/* Commands want the path the server actually opened, not the pretty label. */
const DB_NAME = () => DB_PATH || ($('dblabel').textContent || 'memory.db').trim();
function snippetFor(kind) {
  const db = DB_NAME();
  if (kind === 'claude') return 'claude mcp add areev -- areev serve --mcp --db ' + db;
  if (kind === 'python') return 'import areev\ndb = areev.Areev("' + db + '", actor="user:me")\ndb.add_fact("john", "prefers", "green tea")\nprint(db.recall(subject="john"))';
  if (kind === 'node') return 'import { Areev } from "areev";\nconst db = new Areev("' + db + '", "user:me");\ndb.addFact("john", "prefers", "green tea");\nconsole.log(db.recall("john"));';
  return '{\n  "mcpServers": {\n    "areev": {\n      "command": "areev",\n      "args": ["serve", "--mcp", "--db", "' + db + '"]\n    }\n  }\n}';
}
function renderSettingsPage() {
  renderCrumbHeader('setCrumb', [{ label: 'Settings' }],
    'Attach agents to this memory, sync it across the apps your customers reach you through, and configure how this console itself behaves.');
  const host = $('conBody'); host.textContent = '';
  if (CONTAB === 'agent') return renderConnectAgent(host);
  if (CONTAB === 'sync') return renderConnectSync(host);
  return renderConnectGeneral(host);
}
let SNIPTAB = 'claude';
function renderConnectAgent(host) {
  const empty = !currentGrains().length;
  const hero = el('div'); hero.style.cssText = 'display:flex;flex-direction:column;gap:12px;max-width:650px;padding-bottom:8px';
  const h = el('span', null, empty ? 'Your agent’s memory is ready — and empty.' : 'Attach another agent to this memory.');
  h.style.cssText = 'font:700 32px/40px var(--sans);color:var(--ink);letter-spacing:-.03em';
  hero.appendChild(h);
  hero.appendChild(el('span', 'sub', empty
    ? 'Point an agent at this file. Everything it learns lands here as plain sentences you can read, correct, and delete.'
    : 'Anything you connect reads and writes the same memory — they will all know what the others learned.'));
  host.appendChild(hero);

  const card = el('div', 'card');
  const tabs = el('div', 'tabs'); tabs.style.cssText = 'padding:16px 24px 0;gap:24px';
  for (const [k, label] of [['claude', 'Claude Code'], ['python', 'Python'], ['node', 'Node'], ['mcp', 'Any MCP client']]) {
    const b = el('button', SNIPTAB === k ? 'on' : '', label);
    b.onclick = () => { SNIPTAB = k; render(); };
    tabs.appendChild(b);
  }
  card.appendChild(tabs);

  const s1 = el('div'); s1.style.cssText = 'display:flex;flex-direction:column;gap:12px;padding:22px 24px 4px';
  s1.appendChild(el('span', null, '1 · Attach the memory')).style.cssText = 'font-size:14px;font-weight:600;color:var(--ink)';
  const codeRow = el('div');
  codeRow.style.cssText = 'display:flex;align-items:flex-start;gap:16px;background:var(--well);border:1px solid var(--hair);border-radius:10px;padding:15px 14px 15px 18px';
  const pre = el('pre', null, snippetFor(SNIPTAB));
  pre.style.cssText = 'flex:1;font-family:var(--mono);font-size:13.5px;line-height:22px;color:var(--ink);white-space:pre-wrap;word-break:break-word;margin:0';
  const cp = el('button', 'btn ghost sm', 'Copy');
  cp.onclick = () => copyText(snippetFor(SNIPTAB), 'Command');
  codeRow.appendChild(pre); codeRow.appendChild(cp);
  s1.appendChild(codeRow);
  card.appendChild(s1);

  const s2 = el('div'); s2.style.cssText = 'display:flex;flex-direction:column;gap:12px;padding:20px 24px 22px';
  s2.appendChild(el('span', null, '2 · Ask it to remember something')).style.cssText = 'font-size:14px;font-weight:600;color:var(--ink)';
  const quote = el('div');
  quote.style.cssText = 'border:1px dashed var(--line2);border-radius:10px;padding:15px 18px;font-size:15.5px;line-height:24px;color:var(--muted)';
  quote.textContent = '“Remember that John Aldridge prefers green tea and works at Acme Corp.”';
  s2.appendChild(quote);
  card.appendChild(s2);

  const strip = el('div');
  strip.style.cssText = 'display:flex;align-items:center;gap:11px;padding:16px 24px;border-top:1px solid var(--line);'
    + 'background:' + (empty ? 'var(--accent-soft)' : 'var(--ok-soft)');
  const ring = el('span');
  ring.style.cssText = 'width:16px;height:16px;flex-shrink:0;border-radius:8px;display:flex;align-items:center;justify-content:center;background:'
    + (empty ? 'var(--accent-line)' : 'var(--ok-line)');
  const core = el('span'); core.style.cssText = 'width:7px;height:7px;border-radius:4px;background:' + (empty ? 'var(--accent)' : 'var(--ok)');
  ring.appendChild(core); strip.appendChild(ring);
  const st = el('span', null, empty
    ? 'Watching for the first memory — this page fills in on its own.'
    : STATS.grains + ' memories stored. Reload after your agent writes to see new ones.');
  st.style.cssText = 'flex:1;font-size:14px;color:' + (empty ? 'var(--accent)' : 'var(--ok)');
  strip.appendChild(st);
  const rl = el('button', 'btn ghost sm', 'Reload'); rl.onclick = refresh;
  strip.appendChild(rl);
  card.appendChild(strip);
  host.appendChild(card);

  const three = el('div'); three.style.cssText = 'display:flex;gap:44px;padding-top:16px';
  const bit = (t, s) => { const c = el('div'); c.style.cssText = 'display:flex;flex-direction:column;gap:6px;flex:1';
    const tt = el('span', null, t); tt.style.cssText = 'font-size:14.5px;font-weight:600;color:var(--ink)';
    c.appendChild(tt); c.appendChild(el('span', 'meta', s)); return c; };
  three.appendChild(bit('It writes, you read', 'Every fact your agent stores shows up here in plain language — no query needed.'));
  three.appendChild(bit('Nothing is overwritten', 'Corrections are added on top, so you can always see what your agent used to believe.'));
  three.appendChild(bit('It flags its own mistakes', 'Conflicts and duplicates arrive as suggestions you approve — never applied behind your back.'));
  host.appendChild(three);
}
function renderConnectSync(host) {
  const srv = (CONFIG && CONFIG.server) || {};
  const on = !!srv.hub_mode;
  if (!on) {
    const card = el('div', 'card'); card.style.cssText = 'padding:26px 28px;display:flex;flex-direction:column;gap:14px';
    const t = el('span', null, 'Sync is not turned on for this memory.');
    t.style.cssText = 'font:600 19px/27px var(--sans);color:var(--ink);letter-spacing:-.015em';
    card.appendChild(t);
    card.appendChild(el('span', 'sub', 'Right now this console is the only thing reading this file. Start it as a hub and other '
      + 'apps — a voice line, a WhatsApp bot, an email inbox — can push what they learn and pull what the others learned, '
      + 'all against this one memory.'));
    const codeRow = el('div');
    codeRow.style.cssText = 'display:flex;align-items:center;gap:16px;background:var(--well);border:1px solid var(--hair);border-radius:10px;padding:15px 14px 15px 18px';
    const cmd = 'AREEV_HUB_TOKEN=$(openssl rand -hex 16) areev hub --db ' + DB_NAME() + ' --dir ./segments --token-env AREEV_HUB_TOKEN';
    const pre = el('pre', null, cmd);
    pre.style.cssText = 'flex:1;font-family:var(--mono);font-size:13px;line-height:21px;color:var(--ink);white-space:pre-wrap;word-break:break-word;margin:0';
    const cp = el('button', 'btn ghost sm', 'Copy'); cp.onclick = () => copyText(cmd, 'Command');
    codeRow.appendChild(pre); codeRow.appendChild(cp);
    card.appendChild(codeRow);
    card.appendChild(el('span', 'meta', 'Pushing and pulling both need the key. Apps can only ever add — '
      + 'nothing they send can erase what is already here.'));
    host.appendChild(card);
    return;
  }

  if (SEGMENTS === null) {
    const lock = el('div', 'card');
    lock.style.cssText = 'display:flex;align-items:center;gap:14px;padding:18px 20px;margin-bottom:16px';
    const t = el('div'); t.style.cssText = 'display:flex;flex-direction:column;gap:4px;flex:1';
    const t1 = el('span', null, 'Transfers are locked');
    t1.style.cssText = 'font-size:14.5px;font-weight:600;color:var(--ink)';
    t.appendChild(t1);
    t.appendChild(el('span', 'meta', 'Listing what has been pushed and pulled needs the hub key — '
      + 'the same one your apps use to write.'));
    lock.appendChild(t);
    const btn = el('button', 'btn sm', 'Enter the key');
    btn.onclick = async () => {
      const k = window.prompt('Paste the hub key (the value of the --token-env variable):');
      if (!k) return;
      TOKEN = k; sessionStorage.setItem('areev.token', k);
      await loadSegments();
    };
    lock.appendChild(btn);
    host.appendChild(lock);
  }
  const names = Array.isArray(SEGMENTS) ? SEGMENTS : [];
  const apps = new Map();
  for (const n of names) {
    const app = String(n).replace(/\.mgb$/, '').split(/[-_.]/)[0] || 'app';
    if (!apps.has(app)) apps.set(app, 0);
    apps.set(app, apps.get(app) + 1);
  }
  const card = el('div', 'card'); card.style.cssText = 'padding:24px 26px 26px;display:flex;flex-direction:column';
  const row = el('div', 'apps');
  const entries = [...apps.entries()].slice(0, 3);
  if (!entries.length) entries.push(['no apps yet', 0]);
  for (const [name, n] of entries) {
    const a = el('div', 'app');
    const hd = el('div', 'hd');
    const d = el('span', 'dot'); d.style.background = n ? 'var(--ok)' : 'var(--ghost)';
    hd.appendChild(el('b', null, cap(name)));
    hd.appendChild(d);
    a.appendChild(hd);
    a.appendChild(el('span', 'meta', n ? n + (n === 1 ? ' transfer' : ' transfers') : 'nothing received yet'));
    row.appendChild(a);
  }
  card.appendChild(row);
  const conns = el('div', 'conns');
  for (let i = 0; i < entries.length; i++) { const c = el('div'); c.appendChild(el('i')); conns.appendChild(c); }
  conns.style.cssText = 'padding:0';
  const spacer = el('div'); spacer.style.height = '0'; card.appendChild(spacer);
  card.appendChild(conns);
  const bar = el('div', 'hubbar');
  bar.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" style="flex-shrink:0">'
    + '<rect x="7.5" y="2.5" width="14" height="14" rx="4.5" fill="none" stroke="var(--accent-line)" stroke-width="2"/>'
    + '<rect x="2.5" y="7.5" width="14" height="14" rx="4.5" fill="var(--accent)"/></svg>';
  const bt = el('div'); bt.style.cssText = 'display:flex;flex-direction:column;gap:3px;flex:1';
  const b1 = el('span', null, 'One shared memory — ' + DB_NAME());
  b1.style.cssText = 'font-size:15.5px;font-weight:600;color:var(--ink)';
  bt.appendChild(b1);
  bt.appendChild(el('span', null, (STATS.current || 0) + ' memories. Whatever one app learns, the others can answer with.'))
    .style.cssText = 'font-size:13px;color:var(--text)';
  bar.appendChild(bt);
  card.appendChild(bar);
  host.appendChild(card);

  const transfers = el('div', 'stack');
  host.appendChild(transfers);
  const th = el('div', 'grp-head');
  th.appendChild(el('h2', null, 'Recent transfers'));
  th.appendChild(el('span', 'meta', names.length + ' in ' + (srv.segment_dir || 'the segment folder')));
  transfers.appendChild(th);
  if (!names.length) transfers.appendChild(el('div', 'empty', 'Nothing has been pushed or pulled yet.'));
  for (const n of names.slice(-12).reverse()) {
    const r = el('div', 'srow');
    const ic = el('span'); ic.style.cssText = 'width:18px;flex-shrink:0;display:flex;justify-content:center';
    ic.innerHTML = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M12 4.5v14M6 13l6 6 6-6" stroke="var(--ok)" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"/></svg>';
    r.appendChild(ic);
    r.appendChild(el('span', 't', 'Received a bundle from ' + cap(String(n).replace(/\.mgb$/, '').split(/[-_.]/)[0])));
    const w = el('span', 'w', n); w.style.cssText = 'width:auto;font-family:var(--mono);font-size:11.5px;color:var(--hash)';
    r.appendChild(w);
    transfers.appendChild(r);
  }
  const note = el('div', 'card');
  note.style.cssText = 'display:flex;align-items:flex-start;gap:12px;padding:16px 18px';
  note.innerHTML = '<svg width="17" height="17" viewBox="0 0 24 24" fill="none" style="flex-shrink:0">'
    + '<rect x="4.5" y="10.5" width="15" height="9.5" rx="2" stroke="var(--text)" stroke-width="1.7"/>'
    + '<path d="M8 10.5V7.8a4 4 0 018 0v2.7" stroke="var(--text)" stroke-width="1.7"/></svg>';
  const nt = el('div'); nt.style.cssText = 'display:flex;flex-direction:column;gap:5px;flex:1';
  const n1 = el('span', null, srv.auth_required
    ? 'Syncing needs the key. Reading the memory itself does not.'
    : 'This hub accepts writes with no key — anyone who can reach it can add memories.');
  n1.style.cssText = 'font-size:14px;font-weight:600;color:var(--ink)';
  nt.appendChild(n1);
  nt.appendChild(el('span', 'meta', 'Pushing and pulling both require the key; anyone on your network can '
    + 'still read what your agent knows. Apps can only ever add — nothing they send can erase what is already here.'));
  note.appendChild(nt);
  host.appendChild(note);
}
/* One toggle row, shared by Developer mode and Dark mode — same markup the
   rail used to own, now built fresh on every render instead of wired once
   at boot, since it lives inside a page section that redraws per visit. */
function settingsToggle(label, isOn, onToggle) {
  const row = el('div', 'toggle-row');
  row.appendChild(el('span', null, label));
  const btn = el('button', 'sw' + (isOn ? ' on' : ''));
  btn.setAttribute('aria-label', label);
  btn.appendChild(el('i'));
  btn.onclick = () => onToggle(btn);
  row.appendChild(btn);
  return row;
}
function renderConnectGeneral(host) {
  const appearance = el('div', 'card'); appearance.style.cssText = 'padding:8px 22px 18px;margin-bottom:16px';
  appearance.appendChild(el('h2', null, 'This console')).style.padding = '10px 0';
  appearance.appendChild(settingsToggle('Developer mode', document.documentElement.classList.contains('dev'), btn => {
    const on = document.documentElement.classList.toggle('dev');
    localStorage.setItem('areev.dev', on ? '1' : '0');
    btn.classList.toggle('on', on);
    render();
  }));
  appearance.appendChild(settingsToggle('Dark mode',
    (document.documentElement.dataset.theme || (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')) === 'dark',
    btn => {
      const cur = document.documentElement.dataset.theme || (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
      const next = cur === 'dark' ? 'light' : 'dark';
      document.documentElement.dataset.theme = next;
      localStorage.setItem('areev.theme', next);
      btn.classList.toggle('on', next === 'dark');
      Graph.recolor(); WFGraph.recolor(); render();
    }));
  host.appendChild(appearance);

  const c = CONFIG;
  if (!c || c.ok === false) { host.appendChild(el('div', 'empty', 'Configuration unavailable.')); return; }
  const warn = (c.warnings || []);
  if (warn.length) {
    const b = el('div', 'banner'); b.style.marginBottom = '8px';
    b.appendChild(el('span', 'grow', warn.join(' · ')));
    host.appendChild(b);
  }
  const box = el('div', 'card'); box.style.cssText = 'padding:8px 22px 18px';
  const add = (k, v) => { const r = el('div', 'kv');
    r.appendChild(el('span', 'k', k)); r.appendChild(el('span', 'v', v)); box.appendChild(r); };
  add('Memory file', c.db || DB_NAME());
  add('Full-text search', c.file && c.file.text_index ? 'on — your agent can search by words' : 'off');
  add('Vector search', c.recall && c.recall.legs && c.recall.legs.vector
    ? 'on' + (c.file && c.file.embedding ? ' — ' + c.file.embedding.model : '') : 'off — no embedding backend attached');
  add('How recall ranks', 'structural' + (c.recall && c.recall.legs && c.recall.legs.bm25 ? ' + words' : '')
    + (c.recall && c.recall.legs && c.recall.legs.vector ? ' + meaning' : '') + ', fused with RRF');
  add('Namespace', (c.session && c.session.namespace) || 'shared');
  add('Console access', c.server && c.server.auth_required
    ? (c.server.auth_all ? 'protected — every request needs the token' : 'hub mode — writes need the token')
    : 'open — anyone who can reach this port can read and change memory');
  add('Result limit', ((c.executor && c.executor.default_limit) || '?') + ' default, '
    + ((c.executor && c.executor.max_limit) || '?') + ' max');
  host.appendChild(box);

  const ah = el('div', 'grp-head');
  ah.appendChild(el('h2', null, 'What it checks itself for'));
  ah.appendChild(el('span', 'meta', 'analyzers that produce suggestions'));
  host.appendChild(ah);
  const alist = el('div'); host.appendChild(alist);
  api('/api/loop/analyzers').then(r => {
    const list = (r && r.ok && r.analyzers) || [];
    if (!list.length) { alist.appendChild(el('div', 'empty', 'No analyzers reported.')); return; }
    for (const a of list) {
      const row = el('div', 'srow'); row.style.cursor = 'default'; row.style.alignItems = 'flex-start';
      const d = el('span'); d.style.cssText = 'width:6px;height:6px;border-radius:3px;flex-shrink:0;margin-top:8px;background:'
        + (a.enabled ? 'var(--ok)' : 'var(--ghost)');
      row.appendChild(d);
      /* Name over the analyzer's own one-line description: a toggle you cannot
         read is a toggle nobody touches. */
      const body = el('div', 't');
      body.style.cssText = 'display:flex;flex-direction:column;gap:2px;min-width:0';
      body.appendChild(el('span', null, a.title || analyzerName(a.id)));
      if (a.description) {
        const sub = el('span', 'tiny', a.description);
        sub.style.lineHeight = '18px';
        body.appendChild(sub);
      }
      row.appendChild(body);
      const sw = el('button', 'btn ghost sm', a.enabled ? 'On' : 'Off');
      sw.onclick = async () => {
        sw.disabled = true;
        const res = await api('/api/loop/config', { method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ analyzer_id: a.id, enabled: !a.enabled }) });
        sw.disabled = false;
        if (res && res.ok) { toast(a.enabled ? 'Turned off' : 'Turned on'); render(); }
        else toast('Could not change it: ' + ((res && res.error) || 'the console may be read-only'));
      };
      row.appendChild(lock(sw));
      const dev = el('span', 'mono dev-only'); dev.textContent = a.id + ' · ' + (a.tier || '');
      dev.style.cssText = 'margin-left:10px';
      row.appendChild(dev);
      alist.appendChild(row);
    }
  });

  /* Anonymization (docs/anonymization-proposal.md §8.3): declared per-
     namespace policies, the host floor, and a plain-language declare/clear
     form. Modes only — the placeholder→value mappings never reach the
     browser (D5 custody). */
  const anh = el('div', 'grp-head');
  anh.appendChild(el('h2', null, 'Anonymization'));
  anh.appendChild(el('span', 'meta', 'what leaves for the model, pseudonymized'));
  host.appendChild(anh);
  const abox = el('div', 'card'); abox.style.cssText = 'padding:12px 22px 16px';
  const anon = (c.anonymization || { policies: [], floor: false, audit_counts: [] });
  if (anon.floor) {
    const fr = el('div', 'kv');
    fr.appendChild(el('span', 'k', 'Host floor'));
    fr.appendChild(el('span', 'v', 'on — every namespace is pseudonymized on the way out'));
    abox.appendChild(fr);
  }
  if (!anon.policies.length) {
    abox.appendChild(el('div', 'empty', anon.floor
      ? 'No per-namespace policies declared.'
      : 'No policies declared — memories leave for the model as-is.'));
  } else {
    for (const p of anon.policies) {
      const r = el('div', 'kv');
      r.appendChild(el('span', 'k', p.ns));
      r.appendChild(el('span', 'v', p.mode === 'egress'
        ? 'pseudonymized on the way to the model'
        : p.mode === 'audit' ? 'counting what would be hidden (audit)'
        : p.mode));
      abox.appendChild(r);
    }
  }
  const form = el('div');
  form.style.cssText = 'display:flex;gap:8px;align-items:center;margin-top:10px;flex-wrap:wrap';
  const nsIn = el('input'); nsIn.className = 'qin'; nsIn.placeholder = 'namespace';
  nsIn.style.cssText = 'flex:0 1 160px;min-width:120px';
  const modeSel = document.createElement('select'); modeSel.className = 'qin';
  for (const [v, label] of [['egress', 'Pseudonymize for the model'], ['audit', 'Audit only'], ['off', 'Off']]) {
    const o = document.createElement('option'); o.value = v; o.textContent = label; modeSel.appendChild(o);
  }
  const declare = el('button', 'btn sm', 'Declare');
  declare.onclick = async () => {
    const ns = nsIn.value.trim();
    if (!ns) { toast('Name the namespace first'); return; }
    declare.disabled = true;
    const res = await api('/api/anon/config', { method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ns, policy: { mode: modeSel.value } }) });
    declare.disabled = false;
    if (res && res.ok) { toast('Policy declared — it travels with the file'); loadConfig().then(render); }
    else toast('Could not declare it: ' + ((res && res.error) || 'the console may be read-only'));
  };
  const clear = el('button', 'btn ghost sm', 'Clear');
  clear.onclick = async () => {
    const ns = nsIn.value.trim();
    if (!ns) { toast('Name the namespace first'); return; }
    clear.disabled = true;
    const res = await api('/api/anon/config', { method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ns, clear: true }) });
    clear.disabled = false;
    if (res && res.ok) { toast('Policy cleared'); loadConfig().then(render); }
    else toast('Could not clear it: ' + ((res && res.error) || 'the console may be read-only'));
  };
  form.appendChild(nsIn); form.appendChild(styledSelect(modeSel));
  form.appendChild(lock(declare)); form.appendChild(lock(clear));
  abox.appendChild(form);
  const auditRows = anon.audit_counts || [];
  if (auditRows.length) {
    const ad = el('div', 'mono dev-only');
    ad.style.cssText = 'margin-top:8px';
    ad.textContent = 'audit: ' + auditRows.map(r => r.ns + '/' + r.category + '=' + r.count).join(' · ');
    abox.appendChild(ad);
  }
  host.appendChild(abox);
}

/* ══ developer sidebar ════════════════════════════════════════════════ */
function renderDevbar() {
  const s = $('devStats'); s.textContent = '';
  const kv = (k, v) => { const r = el('div'); r.style.cssText = 'display:flex;align-items:baseline;gap:10px';
    const a = el('span', null, k); a.style.cssText = 'flex:1;font-size:13.5px;color:var(--text)';
    const b = el('span', null, v); b.style.cssText = 'font-family:var(--mono);font-size:13px;color:var(--ink)';
    r.appendChild(a); r.appendChild(b); s.appendChild(r); };
  kv('grains / current', (STATS.grains != null ? STATS.grains : '?') + ' / ' + (STATS.current != null ? STATS.current : '?'));
  kv('triples / terms', (STATS.triples != null ? STATS.triples : '?') + ' / ' + (STATS.terms != null ? STATS.terms : '?'));
  const legs = CONFIG && CONFIG.recall && CONFIG.recall.legs;
  kv('recall legs', legs ? ['struct', legs.bm25 && 'bm25', legs.vector && 'vec'].filter(Boolean).join(' · ') : '?');
  kv('ops', STATS.ops != null ? String(STATS.ops) : '?');

  const l = $('devLog'); l.textContent = '';
  for (const o of LOG.slice().sort((a, b) => (b.op_seq || 0) - (a.op_seq || 0)).slice(0, 14)) {
    const r = el('div', 'oprow');
    r.appendChild(el('span', 't', shortWhen(hlcMs(o.hlc))));
    const op = el('span', 'o', o.op);
    op.style.color = o.op === 'add' ? 'var(--ok)' : o.op === 'forget' ? 'var(--danger)' : 'var(--warn)';
    r.appendChild(op);
    /* A hash says an operation happened but not what it did. Resolve it to the
       grain and show what was written; keep the address on hover, and fall back
       to it when the grain is not in the loaded window (or was erased). */
    const g = BYHASH[o.hash];
    /* Bookkeeping the engine writes for itself (__loop_state__ and friends)
       has no sentence worth reading — name the machinery instead. */
    const said = !g ? shortHash(o.hash)
      : isInternal(g) ? 'engine bookkeeping · ' + ((g.fields || {}).relation || rgType(g) || '')
      : (rgType(g) || 'grain') + ' · ' + sentence(g);
    const what = el('span', 'h', said);
    if (!g) what.classList.add('addr');
    else if (isInternal(g)) what.classList.add('sys');
    what.title = (g ? said + '\n' : '') + o.hash;
    r.appendChild(what);
    r.onclick = () => openPanel(o.hash);
    l.appendChild(r);
  }
}
/* ══ graph ════════════════════════════════════════════════════════════ */
const Graph = (() => {
  let cv, ctx, W = 0, H = 0, dpr = 1;
  let nodes = [], links = [], byId = new Map();
  let focus = null, depth = 1, near = new Set();
  let scale = 1, tx = 0, ty = 0, alpha = 0, raf = 0;
  let drag = null, panning = null, hover = null, moved = false;
  let cut = 1;          /* 0..1 over the op-log — the rewind position */
  let colors = {};

  function recolor() {
    colors = { person: cssVar('--cat-person'), org: cssVar('--cat-org'), project: cssVar('--cat-project'),
      thing: cssVar('--cat-thing'), note: cssVar('--cat-note'), line: cssVar('--line2'),
      ink: cssVar('--ink'), dim: cssVar('--dim'), faint: cssVar('--faint'), accent: cssVar('--accent'),
      surface: cssVar('--surface'), well: cssVar('--well') };
  }
  function maxSeq() { return BROWSE.reduce((m, g) => Math.max(m, g.op_seq || 0), 0); }
  function cutSeq() { return Math.round(maxSeq() * cut); }

  function build() {
    const limit = cutSeq();
    const upTo = BROWSE.filter(g => (g.op_seq || 0) <= limit)
      .filter(g => !isGone(g) && !isInternal(g))
      /* a supersede that happened after the cut has not happened yet */
      .filter(g => !g.superseded_by || (BYHASH[g.superseded_by] && (BYHASH[g.superseded_by].op_seq || 0) > limit));
    /* heads are resolved *as of the cut*, so rewinding shows the value that
       was live then, not the one that is live now */
    const heads = headHashes(upTo);
    const grains = upTo.filter(g => (g.type && g.type !== 'fact') || heads.has(g.hash));
    const ents = buildEntities(grains, { tools: false });
    const keep = new Map();
    for (const e of ents) if (e.count || e.deg) keep.set(e.name, e);
    const prev = byId;
    nodes = []; links = []; byId = new Map();
    for (const e of keep.values()) {
      const old = prev.get(e.name);
      const n = { id: e.name, kind: e.kind, count: e.count, deg: e.deg,
        x: old ? old.x : (Math.random() - .5) * 320, y: old ? old.y : (Math.random() - .5) * 320,
        vx: 0, vy: 0, r: 0 };
      n.r = Math.max(13, Math.min(34, 12 + (e.count + e.deg) * 3));
      nodes.push(n); byId.set(n.id, n);
    }
    for (const g of grains) {
      const f = g.fields || {};
      if (g.type === 'fact' && f.subject && typeof f.object === 'string'
          && byId.has(f.subject) && byId.has(f.object)) {
        links.push({ a: f.subject, b: f.object, label: String(f.relation || '').replace(/_/g, ' '), hash: g.hash });
      }
    }
    if (focus && !byId.has(focus)) focus = null;
    if (!focus && nodes.length) focus = nodes.slice().sort((a, b) => (b.count + b.deg) - (a.count + a.deg))[0].id;
    computeNear();
    /* Settle before the first paint so fit() frames a finished layout
       instead of chasing nodes that are still flying apart. */
    alpha = 1;
    for (let i = 0; i < 300; i++) tick();
    alpha = 0.12;
  }
  function computeNear() {
    near = new Set();
    if (!focus) { for (const n of nodes) near.add(n.id); return; }
    near.add(focus);
    let frontier = [focus];
    for (let d = 0; d < depth; d++) {
      const next = [];
      for (const l of links) {
        if (frontier.includes(l.a) && !near.has(l.b)) { near.add(l.b); next.push(l.b); }
        if (frontier.includes(l.b) && !near.has(l.a)) { near.add(l.a); next.push(l.a); }
      }
      frontier = next;
    }
  }
  function tick() {
    if (alpha < 0.005) return;
    const k = alpha;
    for (let i = 0; i < nodes.length; i++) {
      const a = nodes[i];
      for (let j = i + 1; j < nodes.length; j++) {
        const b = nodes[j];
        let dx = b.x - a.x, dy = b.y - a.y;
        let d2 = dx * dx + dy * dy;
        if (d2 < 1) { dx = Math.random() - .5; dy = Math.random() - .5; d2 = 1; }
        if (d2 > 160000) continue;
        const f = (4200 * k) / d2;
        const d = Math.sqrt(d2);
        a.vx -= (dx / d) * f; a.vy -= (dy / d) * f;
        b.vx += (dx / d) * f; b.vy += (dy / d) * f;
      }
    }
    for (const l of links) {
      const a = byId.get(l.a), b = byId.get(l.b);
      if (!a || !b) continue;
      const dx = b.x - a.x, dy = b.y - a.y;
      const d = Math.max(1, Math.hypot(dx, dy));
      const f = (d - 150) * 0.015 * k;
      a.vx += (dx / d) * f; a.vy += (dy / d) * f;
      b.vx -= (dx / d) * f; b.vy -= (dy / d) * f;
    }
    for (const n of nodes) {
      const pull = n.id === focus ? 0.03 : 0.004;
      n.vx += -n.x * pull * k; n.vy += -n.y * pull * k;
      if (drag && drag.id === n.id) { n.vx = 0; n.vy = 0; continue; }
      n.x += (n.vx *= 0.82); n.y += (n.vy *= 0.82);
    }
    alpha *= 0.985;
  }
  function draw() {
    if (!ctx) return;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.clearRect(0, 0, W, H);
    ctx.save();
    ctx.translate(W / 2 + tx, H / 2 + ty);
    ctx.scale(scale, scale);
    /* links */
    for (const l of links) {
      const a = byId.get(l.a), b = byId.get(l.b);
      if (!a || !b) continue;
      const lit = focus && (l.a === focus || l.b === focus);
      const on = near.has(l.a) && near.has(l.b);
      ctx.strokeStyle = lit ? colors.accent : colors.line;
      ctx.globalAlpha = lit ? 0.55 : on ? 0.5 : 0.16;
      ctx.lineWidth = lit ? 2 : 1.4;
      ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
      /* Only label edges with room for it — on a short edge the text lands
         on top of the node names at either end. */
      const len = Math.hypot(b.x - a.x, b.y - a.y);
      if (lit && l.label && scale > 0.55 && len > 130) {
        ctx.globalAlpha = 1;
        const nx = -(b.y - a.y) / len, ny = (b.x - a.x) / len;   /* perpendicular */
        halo(l.label, (a.x + b.x) / 2 + nx * 11, (a.y + b.y) / 2 + ny * 11 + 4,
          '12px ' + cssVar('--sans'), colors.dim);
      }
    }
    /* nodes */
    for (const n of nodes) {
      const on = near.has(n.id);
      const c = colors[n.kind] || colors.thing;
      if (n.id === focus) {
        ctx.globalAlpha = 0.09; ctx.fillStyle = c;
        ctx.beginPath(); ctx.arc(n.x, n.y, n.r + 20, 0, 7); ctx.fill();
        ctx.globalAlpha = 0.35; ctx.strokeStyle = c; ctx.lineWidth = 1.6;
        ctx.beginPath(); ctx.arc(n.x, n.y, n.r + 7, 0, 7); ctx.stroke();
      }
      ctx.globalAlpha = on ? 1 : 0.22;
      ctx.fillStyle = c;
      ctx.beginPath(); ctx.arc(n.x, n.y, n.r, 0, 7); ctx.fill();
      if (hover === n.id) { ctx.globalAlpha = 1; ctx.strokeStyle = colors.ink; ctx.lineWidth = 2;
        ctx.beginPath(); ctx.arc(n.x, n.y, n.r + 3, 0, 7); ctx.stroke(); }
      ctx.globalAlpha = on ? 1 : 0.3;
      if (n.id === focus && n.r > 24) {
        ctx.textAlign = 'center';
        ctx.fillStyle = colors.surface;
        ctx.font = '700 14px ' + cssVar('--sans');
        ctx.fillText(clip(n.id, 12), n.x, n.y + 5);
      } else {
        halo(clip(n.id, 22), n.x, n.y + n.r + 17,
          (on ? '600 ' : '') + '13px ' + cssVar('--sans'), on ? colors.ink : colors.faint);
      }
    }
    ctx.restore();
    ctx.globalAlpha = 1;
  }
  const clip = (s, n) => s.length > n ? s.slice(0, n - 1) + '…' : s;
  /* Labels sit on top of edges; a surface-coloured outline keeps them
     readable wherever the layout puts them. */
  function halo(text, x, y, font, fill) {
    ctx.textAlign = 'center';
    ctx.font = font;
    ctx.lineWidth = 3.5;
    ctx.lineJoin = 'round';
    ctx.strokeStyle = colors.well;
    ctx.strokeText(text, x, y);
    ctx.fillStyle = fill;
    ctx.fillText(text, x, y);
  }
  function loop() {
    /* Only burn frames while the graph is actually on screen. */
    if (PAGE === 'memory' && MVIEW === 'graph') { tick(); draw(); }
    raf = requestAnimationFrame(loop);
  }
  function resize() {
    if (!cv) return;
    dpr = window.devicePixelRatio || 1;
    W = cv.clientWidth; H = cv.clientHeight;
    cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr);
  }
  function toWorld(e) {
    const r = cv.getBoundingClientRect();
    return { x: (e.clientX - r.left - W / 2 - tx) / scale, y: (e.clientY - r.top - H / 2 - ty) / scale };
  }
  function hit(p) {
    for (let i = nodes.length - 1; i >= 0; i--) {
      const n = nodes[i];
      if (Math.hypot(n.x - p.x, n.y - p.y) <= n.r + 4) return n;
    }
    return null;
  }
  function fit() {
    if (!nodes.length) { scale = 1; tx = ty = 0; return; }
    let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
    for (const n of nodes) { x0 = Math.min(x0, n.x - n.r - 40); y0 = Math.min(y0, n.y - n.r - 30);
      x1 = Math.max(x1, n.x + n.r + 40); y1 = Math.max(y1, n.y + n.r + 30); }
    /* Keep the graph clear of the floating inspector and the toolbar. */
    const padR = $('ginspect').hidden ? 24 : 312;
    const padT = 64, padB = 60, padL = 24;
    const availW = Math.max(160, W - padL - padR), availH = Math.max(160, H - padT - padB);
    scale = Math.max(0.25, Math.min(1.4, Math.min(availW / (x1 - x0), availH / (y1 - y0))));
    tx = (padL + availW / 2) - W / 2 - ((x0 + x1) / 2) * scale;
    ty = (padT + availH / 2) - H / 2 - ((y0 + y1) / 2) * scale;
  }
  function inspect() {
    const box = $('ginspect');
    const n = focus && byId.get(focus);
    if (!n) { box.hidden = true; return; }
    box.hidden = false; box.textContent = '';
    const head = el('div'); head.style.cssText = 'display:flex;align-items:center;gap:11px';
    const av = el('span', null, n.id.charAt(0).toUpperCase());
    av.style.cssText = 'display:flex;align-items:center;justify-content:center;width:34px;height:34px;flex-shrink:0;'
      + 'border-radius:17px;color:#fff;font-size:14px;font-weight:600;background:' + (colors[n.kind] || colors.thing);
    head.appendChild(av);
    const ht = el('div'); ht.style.cssText = 'display:flex;flex-direction:column;gap:2px;flex:1;min-width:0';
    const nm = el('span', null, n.id);
    nm.style.cssText = 'font-size:15.5px;font-weight:600;color:var(--ink);overflow:hidden;text-overflow:ellipsis;white-space:nowrap';
    ht.appendChild(nm);
    const kindWord = { person: 'Person', org: 'Company or place', project: 'Project', thing: 'Thing', note: 'Note' }[n.kind] || 'Thing';
    ht.appendChild(el('span', 'meta', kindWord + ' · ' + n.count + (n.count === 1 ? ' memory' : ' memories')
      + ' · ' + links.filter(l => l.a === n.id || l.b === n.id).length + ' links'));
    head.appendChild(ht);
    box.appendChild(head);

    const list = el('div'); list.style.cssText = 'display:flex;flex-direction:column;border-top:1px solid var(--hair)';
    const mine = currentGrains().filter(g => (g.fields || {}).subject === n.id).slice(0, 3);
    for (const g of mine) {
      const r = el('div', null, predicate(g));
      r.style.cssText = 'font-size:13.5px;color:var(--ink);padding:9px 0;border-bottom:1px solid var(--hair);cursor:pointer';
      r.onclick = () => openPanel(g.hash);
      list.appendChild(r);
    }
    if (!mine.length) list.appendChild(el('span', 'meta', 'Mentioned by other memories.')).style.padding = '9px 0';
    box.appendChild(list);

    const acts = el('div'); acts.style.cssText = 'display:flex;align-items:center;gap:8px';
    const all = el('button', 'btn sm', 'See all ' + (n.count || links.filter(l => l.a === n.id || l.b === n.id).length));
    all.style.flex = '1';
    all.onclick = () => { ENTITY = n.id; MVIEW = 'list'; render(); };
    const ex = el('button', 'btn ghost sm', depth === 1 ? 'Expand' : 'Collapse');
    ex.onclick = () => setDepth(depth === 1 ? 2 : 1);
    acts.appendChild(all); acts.appendChild(ex);
    box.appendChild(acts);
  }
  function legend() {
    const host = $('glegend'); host.textContent = '';
    const items = [['person', 'People'], ['org', 'Companies & places'], ['project', 'Projects'],
      ['thing', 'Things they like'], ['note', 'Things it noticed']];
    const present = new Set(nodes.map(n => n.kind));
    for (const [k, label] of items) {
      if (!present.has(k)) continue;
      const s = el('span');
      const d = el('span'); d.style.cssText = 'width:8px;height:8px;border-radius:4px;background:' + (colors[k] || colors.thing);
      s.appendChild(d); s.appendChild(el('span', null, label));
      host.appendChild(s);
    }
    host.hidden = !host.childElementCount;
  }
  function ticks() {
    const host = $('gticks'); host.textContent = '';
    const ops = LOG.slice().sort((a, b) => (a.op_seq || 0) - (b.op_seq || 0));
    if (!ops.length) return;
    const first = hlcMs(ops[0].hlc), last = hlcMs(ops[ops.length - 1].hlc);
    /* Everything from one session? Then dates all read the same — show clocks. */
    const sameDay = (last - first) < 36 * 3600 * 1000;
    const fmt = ms => sameDay ? clock(ms)
      : new Date(ms).toLocaleDateString(undefined, { day: 'numeric', month: 'short' });
    for (let i = 0; i < 4; i++) host.appendChild(el('span', null, fmt(first + (last - first) * (i / 4))));
    const now = el('span', null, cut >= 1 ? 'now' : fmt(first + (last - first) * cut));
    now.style.cssText = 'color:var(--accent);font-weight:600';
    host.appendChild(now);
  }
  function setDepth(d) {
    depth = d;
    $('gdepth').querySelectorAll('button').forEach(b => b.classList.toggle('on', +b.dataset.d === d));
    computeNear(); inspect();
  }
  return {
    recolor,
    wire() {
      cv = $('gcanvas'); ctx = cv.getContext('2d'); recolor();
      window.addEventListener('resize', () => { resize(); fit(); });
      cv.addEventListener('mousedown', e => {
        const p = toWorld(e); const n = hit(p); moved = false;
        if (n) { drag = { id: n.id, dx: n.x - p.x, dy: n.y - p.y }; }
        else { panning = { x: e.clientX - tx, y: e.clientY - ty }; cv.classList.add('grabbing'); }
      });
      window.addEventListener('mousemove', e => {
        if (drag) { const p = toWorld(e); const n = byId.get(drag.id);
          if (n) { n.x = p.x + drag.dx; n.y = p.y + drag.dy; alpha = Math.max(alpha, 0.25); } moved = true; return; }
        if (panning) { tx = e.clientX - panning.x; ty = e.clientY - panning.y; moved = true; return; }
        if (!cv) return;
        const r = cv.getBoundingClientRect();
        if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) { hover = null; return; }
        const n = hit(toWorld(e));
        hover = n ? n.id : null;
        cv.style.cursor = n ? 'pointer' : 'grab';
      });
      window.addEventListener('mouseup', e => {
        if (drag && !moved) { focus = drag.id; computeNear(); inspect(); alpha = Math.max(alpha, .4); }
        drag = null; panning = null; cv.classList.remove('grabbing');
      });
      cv.addEventListener('wheel', e => {
        e.preventDefault();
        const f = e.deltaY < 0 ? 1.12 : 0.89;
        scale = Math.max(0.2, Math.min(3, scale * f));
      }, { passive: false });
      cv.addEventListener('dblclick', () => fit());
      $('gin').onclick = () => { scale = Math.min(3, scale * 1.2); };
      $('gout').onclick = () => { scale = Math.max(0.2, scale / 1.2); };
      $('gfit').onclick = () => fit();
      $('gdepth').querySelectorAll('button').forEach(b => { b.onclick = () => setDepth(+b.dataset.d); });
      $('gjump').addEventListener('input', () => {
        const v = $('gjump').value.trim().toLowerCase();
        if (!v) return;
        const n = nodes.find(x => x.id.toLowerCase().includes(v));
        if (n) { focus = n.id; computeNear(); inspect(); alpha = Math.max(alpha, .5); }
      });
      $('grange').addEventListener('input', () => {
        cut = (+$('grange').value) / 100;
        $('gnow').textContent = cut >= 1 ? 'now' : 'rewound';
        $('gnow').classList.toggle('on', cut >= 1);
        build(); ticks(); inspect(); legend();
      });
    },
    mount() { resize(); build(); fit(); legend(); ticks(); inspect(); if (!raf) loop(); },
    rebuild() { if (!cv || !cv.clientWidth) return; resize(); build(); legend(); ticks(); inspect(); if (!raf) loop(); },
  };
})();

/* ══ workflows: plans as an editable graph ═══════════════════════════
   A Workflow grain is nodes+edges+bindings — content-addressed and
   immutable like every grain here, so "editing" one means authoring a
   new one. SAVE always writes `ADD workflow`, never `SUPERSEDE workflow`:
   the SUPERSEDE form has no surface syntax to carry a `name` forward
   (areev-cal/src/executor.rs builds its fields map from scratch), so a
   supersede would silently drop it. A plan whose edges carry a bounded
   cycle (`max_cycles`) or whose nodes carry a retry count opens
   view-only — `ADD workflow`'s `* N` populates `retries`, not
   `max_cycles`, and has no way to re-emit either on a resave, so editing
   one through the console would silently unbound its loop. */
function workflowGrains() { return wfRows().filter(g => g.type === 'workflow' && isCurrent(g)); }
function toolDefs() { return wfRows().filter(g => g.type === 'tool' && (g.fields || {}).kind === 'definition' && isCurrent(g)); }
function wfLabel(g) {
  const f = g.fields || {};
  if (f.name) return f.name;
  if (Array.isArray(f.nodes) && f.nodes.length) return f.nodes.slice(0, 3).join(' → ') + (f.nodes.length > 3 ? ' …' : '');
  return shortHash(g.hash);
}
function wfIsCalEditable(g) {
  const f = g.fields || {};
  const edges = Array.isArray(f.edges) ? f.edges : [];
  if (edges.some(e => e.max_cycles != null)) return false;
  if (f.retries && Object.keys(f.retries).length) return false;
  return true;
}
function wfNodeExecutor(bindings, nodeId) {
  const raw = bindings ? bindings[nodeId] : null;
  if (!raw) return { kind: 'abstract', tool: null, hash: null };
  const hash = String(raw).replace(/^sha256:/, '');
  const target = wfByHash()[hash];
  if (!target) return { kind: 'host', tool: null, hash };
  if (target.type === 'workflow') return { kind: 'subgraph', tool: target, hash };
  const ek = (target.fields || {}).executor_kind;
  return { kind: ek === 'client' ? 'client' : 'host', tool: target, hash };
}
const WF_KIND_LABEL = { host: 'Host tool', client: 'Human approval', abstract: 'Abstract (LLM step)', subgraph: 'Subgraph (another plan)' };
/* The second line on a node's card — what actually runs, not just what
   kind it is, so reading the graph tells you what each step does without
   opening the inspector for every one. */
function wfNodeSubtitle(ex) {
  if (ex.kind === 'abstract') return 'Abstract (LLM step)';
  const toolName = ex.tool ? ((ex.tool.fields || {}).tool_name || shortHash(ex.hash)) : (ex.hash ? shortHash(ex.hash) : '?');
  const label = ex.kind === 'client' ? 'Human approval' : ex.kind === 'subgraph' ? 'Subgraph' : 'Host tool';
  return label + ' · ' + toolName;
}
const calEsc = s => String(s == null ? '' : s).replace(/\\/g, '\\\\').replace(/"/g, '\\"');

let WF_SEL = null, WF_DRAFT = null, WF_LOCKED = false, WF_PICK = null;
/* null = the bound session default (read straight off the global BROWSE/
   BYHASH, already loaded at boot — no extra fetch). Any other value means
   this page fetched and cached that namespace's rows separately (see
   browseForNamespace); switching pages back to the default is instant and
   never disturbs BROWSE, which the rail/entities/graph still depend on. */
let WF_NS = null, WF_ROWS = null, WF_BYHASH_NS = null;
/* Which run the canvas is tinted by. null = whichever ran most recently;
   '' = the user turned the overlay off and wants structure only. */
let WF_RUN = null;
/* The triggers that start the open plan, and the run overlay, resolved once
   per render rather than per frame — draw() runs on every mouse move. */
let WF_TRG = [], WF_STEPS = null, WF_RUN_ACTIVE = null;

/* Which run the canvas is tinted by, and what each step did in it.
   `WF_RUN === ''` is the user asking for structure only; `null` means "the
   most recent", which is what someone opening a plan cold wants to see. */
function wfSyncRun() {
  WF_STEPS = null; WF_RUN_ACTIVE = null;
  if (!WF_SEL || !RUNIDX || WF_RUN === '') return;
  const runs = RUNIDX.byPlan.get(bareHash(WF_SEL)) || [];
  if (!runs.length) return;
  const pick = WF_RUN ? runs.find(r => r.run_id === WF_RUN) : runs[0];
  if (!pick) return;
  WF_RUN_ACTIVE = pick;
  WF_STEPS = runStepStates(pick.run_id, pick.outcome);
}
function wfTriggerClicked(hash) { WF_PICK = { kind: 'trigger', hash }; renderInspect(); }
const wfRows = () => WF_ROWS || BROWSE;
const wfByHash = () => WF_BYHASH_NS || BYHASH;
async function wfSetNamespace(ns) {
  WF_NS = (!ns || ns === boundNamespace()) ? null : ns;
  if (WF_NS) {
    WF_ROWS = await browseForNamespace(WF_NS);
    WF_BYHASH_NS = {};
    for (const g of WF_ROWS) WF_BYHASH_NS[g.hash] = g;
  } else {
    WF_ROWS = null; WF_BYHASH_NS = null;
  }
  // A namespace switch closes whatever was open — its hash may not even exist
  // here. render() rather than renderWorkflows(): the Tools page shares this
  // picker, and it must not re-render the workflow page it isn't on.
  WF_SEL = null; WF_DRAFT = null; WF_PICK = null; WF_RUN = null;
  render();
}

function wfOpen(hash) {
  const g = wfByHash()[hash];
  if (!g) { toast('No workflow found at ' + shortHash(hash)); return; }
  const f = g.fields || {};
  WF_SEL = hash;
  // A saved workflow always writes to this console's bound namespace (CAL's
  // `ADD workflow` has no `SET namespace = ...` clause to target another
  // one) — so a plan opened while browsing a different namespace is
  // view-only, same as a plan CAL genuinely cannot re-author.
  WF_LOCKED = !wfIsCalEditable(g) || !!WF_NS;
  WF_DRAFT = {
    name: f.name || '',
    nodes: Array.isArray(f.nodes) ? f.nodes.slice() : [],
    edges: (Array.isArray(f.edges) ? f.edges : []).map(e => ({
      src: e.src, dst: e.dst, cond: e.cond || null,
      max_cycles: e.max_cycles != null ? e.max_cycles : null,
    })),
    bindings: Object.assign({}, f.bindings || {}),
  };
  WF_PICK = null;
  WFGraph.resetOverrides();
  renderWorkflows();
}
function wfNew() {
  if (WF_NS) { toast('Switch back to "' + boundNamespace() + '" to create a plan — a save always writes there'); return; }
  WF_SEL = null; WF_LOCKED = false;
  WF_DRAFT = { name: '', nodes: ['start'], edges: [], bindings: {} };
  WF_PICK = { kind: 'node', id: 'start' };
  WFGraph.resetOverrides();
  renderWorkflows();
}
function wfClose() {
  WF_SEL = null; WF_DRAFT = null; WF_PICK = null;
  renderWorkflows();
}
function wfNodeExists(id) { return WF_DRAFT.nodes.includes(id); }
function wfAddNode() {
  if (WF_LOCKED || !WF_DRAFT) return;
  let n = 1, id = 'step_1';
  while (wfNodeExists(id)) { n++; id = 'step_' + n; }
  WF_DRAFT.nodes.push(id);
  WF_PICK = { kind: 'node', id };
  WFGraph.rebuild(); WFGraph.draw(); renderInspect();
}
function wfRenameNode(oldId, nextRaw) {
  const next = String(nextRaw || '').trim();
  if (!WF_DRAFT || !next || next === oldId) return false;
  if (wfNodeExists(next)) { toast('A step named "' + next + '" already exists'); return false; }
  WF_DRAFT.nodes = WF_DRAFT.nodes.map(n => n === oldId ? next : n);
  WF_DRAFT.edges.forEach(e => { if (e.src === oldId) e.src = next; if (e.dst === oldId) e.dst = next; });
  if (WF_DRAFT.bindings[oldId] != null) { WF_DRAFT.bindings[next] = WF_DRAFT.bindings[oldId]; delete WF_DRAFT.bindings[oldId]; }
  if (WF_PICK && WF_PICK.kind === 'node' && WF_PICK.id === oldId) WF_PICK.id = next;
  WFGraph.renameOverride(oldId, next);
  WFGraph.rebuild(); WFGraph.draw();
  return true;
}
function wfDeleteNode(id) {
  if (WF_LOCKED || !WF_DRAFT || WF_DRAFT.nodes.length <= 1) return;
  WF_DRAFT.nodes = WF_DRAFT.nodes.filter(n => n !== id);
  WF_DRAFT.edges = WF_DRAFT.edges.filter(e => e.src !== id && e.dst !== id);
  delete WF_DRAFT.bindings[id];
  WF_PICK = null;
  WFGraph.rebuild(); WFGraph.draw(); renderInspect();
}
function wfBindNode(id, hashOrEmpty) {
  if (!WF_DRAFT) return;
  if (hashOrEmpty) WF_DRAFT.bindings[id] = hashOrEmpty; else delete WF_DRAFT.bindings[id];
  WFGraph.draw(); renderInspect();
}
/* Connecting two steps is a drag gesture (from a node's connector dot to
   another node) rather than a click-click mode toggle — see WFGraph.wire's
   handle drag handling. These three are the plain selection path. */
/* Is there already a path start -> ... -> end through these edges? Used to
   refuse a new edge that would close a cycle: every edge drawn in this
   editor is hardcoded `max_cycles: null` (unbounded), and `ADD workflow`'s
   `* N` syntax populates `retries`, not `max_cycles` — there is no CAL this
   console can author that would re-emit a bound on save. A plan opens
   view-only the moment any of its edges already carries one
   (`wfIsCalEditable`), so every edge reachable from here is unbounded —
   nothing to filter on, just walk them. An unbounded cycle a user can't
   see coming here would only surface later, as `RUN-E002` at run-load time. */
function wfCanReach(edges, start, end) {
  const seen = new Set([start]), stack = [start];
  while (stack.length) {
    const cur = stack.pop();
    if (cur === end) return true;
    for (const e of edges) {
      if (e.src === cur && !seen.has(e.dst)) { seen.add(e.dst); stack.push(e.dst); }
    }
  }
  return false;
}
function wfConnectNodes(fromId, toId) {
  if (!WF_DRAFT || WF_LOCKED || fromId === toId) return;
  const dup = WF_DRAFT.edges.some(e => e.src === fromId && e.dst === toId);
  if (dup) { toast('That edge already exists'); return; }
  if (wfCanReach(WF_DRAFT.edges, toId, fromId)) {
    toast('That would create a cycle this console has no way to bound — it would fail at run time. '
      + 'Undo the loop, or author a bounded repeat outside the console.');
    return;
  }
  WF_DRAFT.edges.push({ src: fromId, dst: toId, cond: null, max_cycles: null });
  WF_PICK = { kind: 'edge', idx: WF_DRAFT.edges.length - 1 };
  WFGraph.rebuild(); WFGraph.draw(); renderInspect();
}
function wfNodeClicked(id) {
  WF_PICK = { kind: 'node', id };
  WFGraph.draw(); renderInspect();
}
function wfEdgeClicked(idx) {
  WF_PICK = { kind: 'edge', idx };
  WFGraph.draw(); renderInspect();
}
function wfCanvasBgClicked() {
  WF_PICK = null;
  WFGraph.draw(); renderInspect();
}
function wfSetEdgeCond(idx, condRaw) {
  const e = WF_DRAFT.edges[idx]; if (!e || e.max_cycles != null) return;
  const cond = String(condRaw || '').trim();
  e.cond = cond || null;
  WFGraph.draw();
}
function wfDeleteEdge(idx) {
  const e = WF_DRAFT.edges[idx]; if (!e || WF_LOCKED || e.max_cycles != null) return;
  WF_DRAFT.edges.splice(idx, 1);
  WF_PICK = null;
  WFGraph.rebuild(); WFGraph.draw(); renderInspect();
}

function renderInspect() {
  const box = $('wfinspect');
  if (!WF_DRAFT || !WF_PICK) { box.hidden = true; WFGraph.setSelection(null); WFGraph.draw(); return; }
  if (WF_PICK.kind === 'node' && !WF_DRAFT.nodes.includes(WF_PICK.id)) { WF_PICK = null; box.hidden = true; return; }
  if (WF_PICK.kind === 'edge' && !WF_DRAFT.edges[WF_PICK.idx]) { WF_PICK = null; box.hidden = true; return; }
  box.hidden = false; box.textContent = '';
  WFGraph.setSelection(WF_PICK);

  if (WF_PICK.kind === 'trigger') {
    const g = triggersFor(WF_SEL).find(t => t.hash === WF_PICK.hash);
    if (!g) { WF_PICK = null; box.hidden = true; WFGraph.setSelection(null); WFGraph.draw(); return; }
    trgInspect(box, g);
    WFGraph.draw();
    return;
  }
  if (WF_PICK.kind === 'node') {
    const id = WF_PICK.id;
    const ex = wfNodeExecutor(WF_DRAFT.bindings, id);
    const badge = el('span', 'wf-badge', WF_KIND_LABEL[ex.kind]);
    badge.style.cssText = 'background:var(--well);color:' + WFGraph.kindColor(ex.kind);
    box.appendChild(badge);

    /* What this step did in the run the canvas is tinted by. Only while an
       overlay is on — with no run selected there is no answer, and "not
       reached" without a run to be un-reached in reads as broken. */
    if (WF_STEPS && WF_RUN_ACTIVE) {
      const st = WF_STEPS.get(id);
      const d = el('div', 'wf-ro');
      d.appendChild(el('span', 'k', 'In ' + WF_RUN_ACTIVE.run_id));
      const v = el('span', 'v', st ? STEP_WORD[st.state] : 'not reached');
      v.style.color = 'var(--' + (st ? STEP_TONE[st.state] : 'faint') + ')';
      d.appendChild(v);
      box.appendChild(d);
      if (st) {
        const open = el('button', 'btn ghost sm', 'See the call ▸');
        open.onclick = () => { TOOLTAB = 'executions'; TOOL_SEL = st.grain.hash; go('tools'); };
        box.appendChild(open);
      }
    }

    const nameField = el('div', 'wf-field');
    nameField.appendChild(el('span', 'tiny', 'Step name'));
    const nameInput = document.createElement('input'); nameInput.type = 'text'; nameInput.value = id;
    nameInput.disabled = WF_LOCKED;
    nameInput.addEventListener('change', () => { if (!wfRenameNode(id, nameInput.value)) { nameInput.value = id; } else { renderInspect(); } });
    nameField.appendChild(nameInput);
    box.appendChild(nameField);

    const bindField = el('div', 'wf-field');
    bindField.appendChild(el('span', 'tiny', 'Runs as'));
    const sel = document.createElement('select'); sel.disabled = WF_LOCKED;
    const opt0 = document.createElement('option'); opt0.value = ''; opt0.textContent = '— unbound (abstract LLM step) —';
    sel.appendChild(opt0);
    /* The option list below is built from Tool definitions only — there is
       no way to author a subgraph binding through this select. Without a
       matching <option>, a node actually bound to a Workflow grain (its
       hash never equals any tool's) fell through to "unbound" here even
       though the badge above correctly says "Subgraph". Represent the
       current binding so the panel doesn't contradict itself; disabled
       because re-selecting it wouldn't rebind to anything new. */
    if (ex.kind === 'subgraph') {
      const optSub = document.createElement('option');
      optSub.value = ex.hash; optSub.disabled = true; optSub.selected = true;
      optSub.textContent = 'Subgraph — ' + (ex.tool ? wfLabel(ex.tool) : shortHash(ex.hash));
      sel.appendChild(optSub);
    }
    for (const t of toolDefs()) {
      const tf = t.fields || {};
      const opt = document.createElement('option');
      opt.value = t.hash;
      opt.textContent = (tf.tool_name || shortHash(t.hash)) + (tf.executor_kind === 'client' ? '  (human approval)' : '');
      if (ex.hash === t.hash) opt.selected = true;
      sel.appendChild(opt);
    }
    sel.addEventListener('change', () => wfBindNode(id, sel.value || null));
    bindField.appendChild(styledSelect(sel));
    if (ex.tool && (ex.tool.fields || {}).tool_description) bindField.appendChild(el('span', 'tiny', ex.tool.fields.tool_description));
    if (ex.kind === 'subgraph') bindField.appendChild(el('span', 'tiny', 'Bound to another plan — runs as a child run.'));
    box.appendChild(bindField);

    const orig = WF_SEL && wfByHash()[WF_SEL] ? (wfByHash()[WF_SEL].fields || {}).retries : null;
    if (orig && orig[id] != null) box.appendChild(el('span', 'tiny', 'Retries on failure: ' + orig[id] + ' (read-only here)'));

    const del = el('button', 'btn ghost sm', 'Delete step');
    del.disabled = WF_LOCKED || WF_DRAFT.nodes.length <= 1;
    del.onclick = () => wfDeleteNode(id);
    box.appendChild(del);
  } else {
    const idx = WF_PICK.idx;
    const e = WF_DRAFT.edges[idx];
    const hd = el('span', null, e.src + ' → ' + e.dst);
    hd.style.cssText = 'font-size:15px;font-weight:600;color:var(--ink)';
    box.appendChild(hd);
    if (e.max_cycles != null) {
      const b = el('span', 'wf-badge', '↻ repeats up to ' + e.max_cycles + '×');
      b.style.cssText = 'background:var(--warn-soft);color:var(--warn)';
      box.appendChild(b);
      box.appendChild(el('span', 'tiny', 'A bounded-cycle edge — not editable through the console yet.'));
    } else {
      const condField = el('div', 'wf-field');
      condField.appendChild(el('span', 'tiny', 'Only when (leave blank for always)'));
      const inp = document.createElement('input'); inp.type = 'text'; inp.value = e.cond || '';
      inp.placeholder = 'e.g. approved == true'; inp.disabled = WF_LOCKED;
      inp.addEventListener('change', () => wfSetEdgeCond(idx, inp.value));
      condField.appendChild(inp);
      box.appendChild(condField);
      const del = el('button', 'btn ghost sm', 'Delete edge');
      del.disabled = WF_LOCKED;
      del.onclick = () => wfDeleteEdge(idx);
      box.appendChild(del);
    }
  }
  WFGraph.draw();
}

/** "3 steps · 2 edges" — what the subtitle slot shows now that it is not an
    invitation to set something inert. */
function wfShape(d) {
  const n = (d.nodes || []).length, e = (d.edges || []).length;
  return n + (n === 1 ? ' step' : ' steps') + ' · ' + e + (e === 1 ? ' edge' : ' edges');
}

function wfCard(g) {
  const f = g.fields || {};
  const nodesN = Array.isArray(f.nodes) ? f.nodes.length : 0;
  const edgesN = Array.isArray(f.edges) ? f.edges.length : 0;
  const b = el('button', 'starter');
  b.appendChild(el('b', '', wfLabel(g)));
  const bits = [nodesN + (nodesN === 1 ? ' step' : ' steps'), edgesN + (edgesN === 1 ? ' edge' : ' edges')];
  if (!wfIsCalEditable(g)) bits.push('view-only');
  if (WF_NS === '*' && f.namespace) bits.push(f.namespace);   // "All namespaces" — say which one each card is
  bits.push(relTime(createdMs(f)));
  b.appendChild(el('span', 'meta', bits.join(' · ')));
  /* What starts it, and how it last went — the two questions the flat trigger
     list and the Runs page used to answer separately. Without these the card
     is a shape with no cause and no history. */
  const trg = triggersFor(g.hash);
  const runs = (RUNIDX && RUNIDX.byPlan.get(g.hash)) || [];
  if (trg.length || runs.length) {
    const foot = el('span', 'meta');
    foot.style.cssText = 'display:flex;align-items:center;gap:12px;flex-wrap:wrap';
    if (trg.length) {
      const live = trg.filter(t => (t.fields || {}).enabled !== false).length;
      const t = el('span');
      t.style.cssText = 'display:flex;align-items:center;gap:6px;color:var(--' + (live ? 'ok' : 'dim') + ')';
      const ring = el('span');
      ring.style.cssText = 'width:7px;height:7px;border-radius:4px;border:1.6px solid currentColor';
      t.appendChild(ring);
      t.appendChild(el('span', null, trg.length === 1 ? trgWhen(trg[0].fields || {})
        : trg.length + ' triggers'));
      foot.appendChild(t);
    }
    if (runs.length) {
      const r = runs[0];
      const rr = el('span');
      rr.style.cssText = 'display:flex;align-items:center;gap:6px;color:var(--' + outcomeTone(r.outcome) + ')';
      const d = el('span');
      d.style.cssText = 'width:7px;height:7px;border-radius:4px;background:currentColor';
      rr.appendChild(d);
      rr.appendChild(el('span', null, 'last run ' + r.outcome));
      foot.appendChild(rr);
    }
    b.appendChild(foot);
  }
  b.onclick = () => wfOpen(g.hash);
  return b;
}
/* One action slot, top right: "New workflow" on the list, "Save as new
   plan" in the editor — never both, never scattered across the page. */
/* Why editing is off, in plain words — covers both reasons a plan can be
   locked: CAL genuinely cannot re-author it (a bounded cycle / retry count),
   or a save from here would land in the wrong namespace. */
/* Plain text — this ends up in a native `title` tooltip, which can't render
   the <code> markup the old inline banner used. */
function wfLockReason() {
  if (WF_NS) return 'Browsing "' + WF_NS + '" — switch back to "' + boundNamespace()
    + '" (this console\'s own namespace) to edit or save. A save always writes there.';
  const g = WF_SEL && wfByHash()[WF_SEL];
  if (g && !wfIsCalEditable(g)) return 'This plan has a bounded-cycle edge or a per-node retry count — '
    + 'CAL can visualize both but has no syntax yet to author them through ADD workflow. Open for viewing '
    + 'only; edit this one via the Rust or Python API.';
  return '';
}
/* Which run the canvas is showing, and the switch to change it. In the header
   rather than floating on the canvas: the tools sit top-left and the inspector
   top-right, so a third float has nowhere to be at a narrow width. */
function wfRunBar() {
  const host = $('wfRunHost'); host.textContent = '';
  const show = !!WF_DRAFT && !!WF_SEL;
  host.hidden = !show;
  if (!show) return;
  const bar = el('div', 'runbar');
  if (!RUNIDX) { bar.appendChild(el('span', 'tally', 'checking runs…')); host.appendChild(bar); return; }
  const runs = RUNIDX.byPlan.get(bareHash(WF_SEL)) || [];
  if (!runs.length) {
    const d = el('span', 'dot'); d.style.background = 'var(--ghost)';
    bar.appendChild(d);
    bar.appendChild(el('span', 'tally', 'Never run'));
    host.appendChild(bar); return;
  }
  const active = WF_RUN_ACTIVE;
  const dot = el('span', 'dot');
  dot.style.background = 'var(--' + (active ? outcomeTone(active.outcome) : 'ghost') + ')';
  bar.appendChild(dot);

  if (active && WF_STEPS) {
    const tally = { done: 0, waiting: 0, failed: 0, stopped: 0 };
    for (const v of WF_STEPS.values()) tally[v.state]++;
    const total = (WF_DRAFT.nodes || []).length;
    const parts = [tally.done + ' of ' + total + ' done'];
    if (tally.waiting) parts.push(tally.waiting + ' waiting');
    if (tally.failed) parts.push(tally.failed + ' failed');
    bar.tallyText = parts.join(' · ');
  }

  const sel = document.createElement('select');
  sel.title = 'Tint the steps by what happened in a run';
  const none = document.createElement('option');
  none.value = '__none__'; none.textContent = 'Structure only';
  sel.appendChild(none);
  for (const r of runs) {
    const o = document.createElement('option');
    o.value = r.run_id; o.textContent = r.run_id + ' · ' + r.outcome;
    if (active && active.run_id === r.run_id) o.selected = true;
    sel.appendChild(o);
  }
  if (!active) none.selected = true;
  bar.appendChild(styledSelect(sel));
  if (bar.tallyText) bar.appendChild(el('span', 'tally', bar.tallyText));
  sel.onchange = () => {
    WF_RUN = sel.value === '__none__' ? '' : sel.value;
    wfSyncRun(); renderWorkflowHeader(); WFGraph.refresh(); renderInspect();
  };

  const jump = el('button', 'go', 'Runs ▸');
  jump.title = 'Open this run on the Runs page';
  jump.onclick = () => go('runs');
  bar.appendChild(jump);
  host.appendChild(bar);
}

function renderWorkflowHeader() {
  const editing = !!WF_DRAFT;
  wfRunBar();
  $('wfNsHost').hidden = editing;
  $('wfNewBtn').hidden = editing;
  $('wfNewBtn').disabled = !!WF_NS;
  $('wfNewBtn').title = WF_NS ? 'Switch back to "' + boundNamespace() + '" to create a plan' : '';
  $('wfSave').hidden = !editing;
  const nsHost = $('wfNsHost'); nsHost.textContent = '';
  nsHost.appendChild(nsCombo('wfNs', WF_NS || boundNamespace(), ns => wfSetNamespace(ns)));
  if (!editing) {
    renderCrumbHeader('wfCrumb', [{ label: 'Workflows' }],
      'Plans <code>areev run</code> executes: nodes are steps, edges are the order they can happen in. '
      + 'Plans are content-addressed and immutable, like every memory here — saving a change writes a new '
      + 'plan; the old one stays recallable by its hash.');
    return;
  }
  const fallbackName = (WF_SEL && wfByHash()[WF_SEL]) ? wfLabel(wfByHash()[WF_SEL]) : 'New workflow';
  renderCrumbHeader('wfCrumb', [{ label: 'Workflows', onClick: wfClose }], null, {
    editTitle: {
      value: WF_DRAFT.name || '', placeholder: fallbackName, disabled: WF_LOCKED,
      onCommit: v => { WF_DRAFT.name = v; renderWorkflowHeader(); },
    },
    // Read-only: a plan is its graph. The editable field here used to write
    // `trigger`, which nothing ever read — so it invited someone to "set a
    // trigger" and then quietly did nothing. Real triggers are their own grains
    // that point at this plan, and they are drawn in the canvas's own lane.
    editDesc: {
      value: wfShape(WF_DRAFT), disabled: true,
    },
    lockHint: WF_LOCKED ? wfLockReason() : null,
  });
  const canSave = !WF_LOCKED && canWrite() && stmtSupported('ADD');
  $('wfSave').disabled = !canSave;
  $('wfSave').title = WF_LOCKED ? (WF_NS ? 'Browsing a different namespace — view only' : 'This plan is view-only in the console')
    : !canWrite() ? READONLY_WHY
    : !stmtSupported('ADD') ? 'This build has no ADD workflow support'
    : 'Write a new plan grain with these steps';
}
/* ---------- Triggers ----------------------------------------------------
   A trigger is a standing rule that starts a workflow. The binding points
   trigger → plan and never the reverse — a plan is content-addressed, so one
   that grew a list of triggers would change address every time a trigger was
   added and orphan its own run history. That direction is why a trigger is
   only fully legible NEXT TO the plan it starts, and why these render on the
   canvas instead of on a page of their own: a flat list of four triggers
   cannot show you that two of them start the same plan.

   Read-only, and not by preference. CAL has no `ADD trigger`, and
   `ADD workflow`'s `ON "..."` clause was removed in 1.3, so a console that
   writes only through /api/cal has no way to author one. Firing is withheld
   for the same reason `run.respond` refuses a shared token: it spends budgets
   and executes effects, and the declaring principal IS the audit record. */
function triggerGrains() {
  return wfRows().filter(g => g.type === 'trigger' && isCurrent(g));
}
const bareHash = h => String(h == null ? '' : h).replace(/^sha256:/, '');
/** The triggers that start one plan, newest first. */
function triggersFor(hash) {
  if (!hash) return [];
  const h = bareHash(hash);
  return triggerGrains()
    .filter(g => bareHash((g.fields || {}).workflow) === h)
    .sort((a, b) => createdMs(b.fields) - createdMs(a.fields));
}

/** Seconds as something a person reads. */
function everyPhrase(n) {
  n = Number(n);
  if (!isFinite(n) || n <= 0) return null;
  if (n % 86400 === 0) return 'every ' + (n / 86400) + 'd';
  if (n % 3600 === 0) return 'every ' + (n / 3600) + 'h';
  if (n % 60 === 0) return 'every ' + (n / 60) + 'm';
  return 'every ' + n + 's';
}

/* A serialized CAL Condition tree, said out loud. `memory` and `composite`
   triggers carry their whole rule in here, so rendering it as JSON would hide
   the one thing the reader came for. Unknown shapes fall back to JSON rather
   than guessing — a wrong sentence is worse than an honest blob. */
const PRED_CMP = { eq: '=', ne: '≠', lt: '<', lte: '≤', gt: '>', gte: '≥',
  contains: 'contains', starts_with: 'starts with', ends_with: 'ends with', in: 'in' };
function predValueText(v) {
  if (v == null) return '?';
  if (typeof v !== 'object') return String(v);
  if (v.kind === 'string') return '"' + v.value + '"';
  if (Array.isArray(v.values)) return '[' + v.values.map(predValueText).join(', ') + ']';
  if ('value' in v) return String(v.value);
  return JSON.stringify(v);
}
function predicateText(p, depth) {
  depth = depth || 0;
  if (p == null) return '';
  if (typeof p !== 'object') return String(p);
  const k = String(p.kind || '');
  if (k === 'and' || k === 'or') {
    const t = predicateText(p.left, depth + 1) + ' ' + k.toUpperCase() + ' ' + predicateText(p.right, depth + 1);
    return depth ? '(' + t + ')' : t;
  }
  if (k === 'not') return 'NOT ' + predicateText(p.inner || p.operand || p.left, depth + 1);
  if (k === 'comparison' || p.field) {
    return (p.field || '?') + ' ' + (PRED_CMP[p.comparator] || p.comparator || '=') + ' ' + predValueText(p.value);
  }
  return JSON.stringify(p);
}

/* What this trigger is actually waiting for, in one line. The kind alone is a
   category ("memory"); this is the rule. */
function trgWhen(f) {
  const kind = String(f.kind || 'interval');
  if (kind === 'interval') return everyPhrase(f.interval_secs) || 'on an interval';
  if (kind === 'polling') {
    const who = (f.connector || 'a connector') + (f.scope ? ' ' + f.scope : '');
    return 'poll ' + who + (everyPhrase(f.interval_secs) ? ' · ' + everyPhrase(f.interval_secs) : '');
  }
  if (kind === 'schedule') return f.cron ? 'cron ' + f.cron : 'on a schedule';
  if (kind === 'once') return f.at_ms ? 'once · ' + dayLabel(Number(f.at_ms)) : 'once';
  if (kind === 'memory') return f.predicate ? 'when ' + predicateText(f.predicate) : 'when memory changes';
  if (kind === 'webhook') return 'on delivery' + (f.scope ? ' · ' + f.scope : '');
  if (kind === 'manual') return 'when fired by hand';
  if (kind === 'composite') return f.predicate ? 'when ' + predicateText(f.predicate) : 'when its members agree';
  return kind;
}
/** The short line drawn under a trigger node on the canvas. */
function trgSubtitle(f) {
  const bits = [String(f.kind || 'interval')];
  if (f.enabled === false) bits.push('disabled');
  return bits.join(' · ');
}

/* The inspector for a trigger node. Every row is read-only text — no inputs,
   no toggles: an input this console cannot honour is a worse lie than an
   absent one. The escape hatch is the exact CLI command, ready to copy. */
function trgInspect(box, g) {
  const f = g.fields || {};
  const live = f.enabled !== false;
  const badge = el('span', 'wf-badge', 'Trigger · ' + String(f.kind || 'interval'));
  badge.style.cssText = 'background:var(--well);color:var(--' + (live ? 'ok' : 'ghost') + ')';
  box.appendChild(badge);

  const row = (k, v, mono) => {
    if (v == null || v === '') return;
    const d = el('div', 'wf-ro');
    d.appendChild(el('span', 'k', k));
    d.appendChild(el('span', 'v' + (mono ? ' mono' : ''), String(v)));
    box.appendChild(d);
  };
  row('Fires', trgWhen(f));
  if (!live) row('State', 'Disabled in the declaration — it will not fire.');
  row('Because', f.because);
  row('Connector', f.connector);
  row('Watches', f.scope);
  if (Array.isArray(f.dedup_key) && f.dedup_key.length) row('Same item when', f.dedup_key.join(' + '), true);
  if (f.correlate) row('Correlated on', f.correlate, true);
  if (f.window_ms) row('Match window', everyPhrase(Number(f.window_ms) / 1000) || (f.window_ms + 'ms'));
  if (f.members && Object.keys(f.members).length) {
    row('Members', Object.keys(f.members).map(a => a + ' → ' + shortHash(bareHash(f.members[a]))).join('\n'), true);
  }
  if (f.concurrency) row('If one is still running', f.concurrency);
  if (f.catchup) row('Missed firings', f.catchup);
  row('Declared', relTime(createdMs(f)));

  /* Whether it has actually fired is per-host state — a `trg:` row in the
     meta table that deliberately does NOT replicate, so a dev memory restored
     from prod cannot inherit prod's cursor. This console genuinely cannot
     know it for another machine; say so rather than drawing an empty column
     that reads as "never fired". */
  const note = el('div', 'wf-ro');
  note.appendChild(el('span', 'k', 'Has it fired?'));
  const nv = el('span', 'v'); nv.style.fontSize = '12.5px'; nv.style.color = 'var(--dim)';
  nv.textContent = 'Per-host state — it does not travel with the memory. Run '
    + '`areev trigger status` on the machine that evaluates it.';
  note.appendChild(nv);
  box.appendChild(note);

  const copy = el('button', 'btn ghost sm', 'Copy `trigger show`');
  copy.onclick = () => copyText('areev trigger show ' + g.hash, 'command');
  box.appendChild(copy);
}

function renderWorkflows() {
  const listHost = $('wfList');
  listHost.hidden = !!WF_DRAFT;
  WF_TRG = WF_SEL ? triggersFor(WF_SEL) : [];
  wfSyncRun();
  /* The list cards and the canvas overlay want the same run index. Fetch it
     once and repaint whichever is on screen — never block first paint on it,
     because a plan must be visible without the runtime answering. */
  if (!RUNIDX && !RUNIDX_INFLIGHT) {
    loadRuns().then(() => {
      if (PAGE !== 'workflows') return;
      if (WF_DRAFT && WF_SEL) { wfSyncRun(); renderWorkflowHeader(); WFGraph.refresh(); renderInspect(); }
      else renderWorkflows();
    });
  }
  if (!WF_DRAFT) {
    const grains = workflowGrains();
    const byLabel = new Map();
    for (const g of grains) {
      const k = wfLabel(g);
      const cur = byLabel.get(k);
      if (!cur || createdMs(g.fields) > createdMs(cur.fields)) byLabel.set(k, g);
    }
    const items = [...byLabel.values()].sort((a, b) => createdMs(b.fields) - createdMs(a.fields));
    listHost.textContent = '';
    if (!items.length) {
      listHost.innerHTML = '<div class="empty">No workflows yet. A plan is what <code>areev run</code> executes — start one with "New workflow" above.</div>';
    } else {
      for (const g of items) listHost.appendChild(wfCard(g));
    }
    renderOrphanTriggers();
  }

  renderWorkflowHeader();
  const wrap = $('wfEditorWrap');
  wrap.hidden = !WF_DRAFT;
  if (!WF_DRAFT) return;

  $('wfAddNode').disabled = WF_LOCKED;
  WFGraph.mount();
  renderInspect();
}

/* A trigger whose plan is not among these rows still fires. It used to be
   visible on the Triggers tab; with that tab gone, an unreferenced trigger
   would simply disappear from the console, which is the one thing a standing
   rule must never do. */
function renderOrphanTriggers() {
  const host = $('wfOrphans');
  if (!host) return;
  const known = new Set(workflowGrains().map(g => g.hash));
  const orphans = triggerGrains().filter(t => !known.has(bareHash((t.fields || {}).workflow)));
  host.textContent = '';
  host.hidden = !orphans.length;
  if (!orphans.length) return;
  const card = el('div', 'card');
  card.style.cssText = 'padding:16px 18px;display:flex;flex-direction:column;gap:10px';
  const hd = el('div');
  hd.style.cssText = 'font-size:13.5px;font-weight:600;color:var(--ink)';
  hd.textContent = orphans.length === 1 ? '1 trigger points somewhere else'
    : orphans.length + ' triggers point somewhere else';
  card.appendChild(hd);
  card.appendChild(el('div', 'tiny', 'Their plan is not in ' + (WF_NS || boundNamespace())
    + ' — superseded, forgotten, or in another namespace. They still fire.'));
  for (const t of orphans) {
    const f = t.fields || {};
    const row = el('div', 'tiny');
    row.style.color = 'var(--text)';
    row.textContent = trgWhen(f) + ' · ' + String(f.kind || '') + ' → plan ' + shortHash(bareHash(f.workflow));
    card.appendChild(row);
  }
  host.appendChild(card);
}

/* A plain sentence describing what changed, so saving rarely means typing
   a reason from scratch — it means glancing at one and hitting Save. */
function wfDiffSummary() {
  const d = WF_DRAFT;
  const name = d.name.trim() || 'this plan';
  if (!WF_SEL) {
    return 'Created "' + name + '" — ' + d.nodes.length + (d.nodes.length === 1 ? ' step' : ' steps')
      + (d.edges.length ? ', ' + d.edges.length + (d.edges.length === 1 ? ' edge' : ' edges') : '') + '.';
  }
  const orig = (wfByHash()[WF_SEL] || {}).fields || {};
  const origNodes = new Set(orig.nodes || []), curNodes = new Set(d.nodes);
  const addedNodes = d.nodes.filter(n => !origNodes.has(n));
  const removedNodes = (orig.nodes || []).filter(n => !curNodes.has(n));
  const key = e => e.src + ' → ' + e.dst;
  const origEdges = new Map((orig.edges || []).map(e => [key(e), e]));
  const curEdges = new Map(d.edges.map(e => [key(e), e]));
  const addedEdges = [...curEdges.keys()].filter(k => !origEdges.has(k));
  const removedEdges = [...origEdges.keys()].filter(k => !curEdges.has(k));
  const changedConds = [...curEdges.keys()].filter(k => origEdges.has(k)
    && (origEdges.get(k).cond || null) !== (curEdges.get(k).cond || null));
  const origB = orig.bindings || {}, curB = d.bindings || {};
  const rebound = [...new Set([...Object.keys(origB), ...Object.keys(curB)])]
    .filter(n => String(origB[n] || '').replace(/^sha256:/, '') !== String(curB[n] || '').replace(/^sha256:/, ''));

  const bits = [];
  if (addedNodes.length) bits.push('added ' + addedNodes.join(', '));
  if (removedNodes.length) bits.push('removed ' + removedNodes.join(', '));
  if (addedEdges.length) bits.push('connected ' + addedEdges.join('; '));
  if (removedEdges.length) bits.push('disconnected ' + removedEdges.join('; '));
  if (changedConds.length) bits.push('updated the condition on ' + changedConds.join('; '));
  if (rebound.length) bits.push('rebound ' + rebound.join(', '));
  if ((orig.name || '') !== d.name.trim()) bits.push('renamed the plan');
  if (!bits.length) return 'Resaved "' + name + '" with no structural change.';
  const s = bits.join('; ') + '.';
  return (s.charAt(0).toUpperCase() + s.slice(1)).slice(0, 240);
}

function wfArmSave() {
  if (!WF_DRAFT || WF_LOCKED) return;
  if (!WF_DRAFT.name.trim()) {
    toast('Name the plan before saving');
    const titleInput = document.querySelector('#wfCrumb input.ctitle');
    if (titleInput) titleInput.focus();
    return;
  }
  if (!WF_DRAFT.nodes.length) { toast('Add at least one step'); return; }
  const reason = wfDiffSummary();
  /* A brand-new plan has nothing to justify yet — write it straight away
     with an auto-generated reason. An edit to something that already
     existed still gets a beat to look before it writes: the reason IS
     that change's audit trail, just pre-filled instead of blank. */
  if (!WF_SEL) { wfSave(reason); return; }

  const box = $('wfReasonBox'); box.textContent = '';
  const composer = el('div', 'reason');
  composer.appendChild(el('span', 'meta', 'Why this change? Filled in from what you edited — adjust it if you like.'));
  const line = el('div', 'line');
  const why = document.createElement('input'); why.type = 'text'; why.value = reason;
  const conf = el('button', 'btn sm', 'Save'); const cancel = el('button', 'btn ghost sm', 'Cancel');
  line.appendChild(why); line.appendChild(conf); line.appendChild(cancel);
  composer.appendChild(line);
  box.appendChild(composer);
  why.focus(); why.select();
  cancel.onclick = () => { box.textContent = ''; };
  conf.onclick = async () => {
    if (!why.value.trim()) { toast('A reason is required — it goes in the audit trail'); why.focus(); return; }
    conf.disabled = true; cancel.disabled = true;
    await wfSave(why.value.trim());
    conf.disabled = false; cancel.disabled = false;
  };
}
async function wfSave(reason) {
  const btn = $('wfSave'), prevLabel = btn.textContent;
  btn.disabled = true; btn.textContent = 'Saving…';
  const d = WF_DRAFT;
  const seen = new Set();
  let body = '';
  for (const e of d.edges) {
    body += '"' + calEsc(e.src) + '" -> "' + calEsc(e.dst) + '"';
    if (e.cond) body += ' WHEN "' + calEsc(e.cond) + '"';
    body += ' ';
    seen.add(e.src); seen.add(e.dst);
  }
  for (const n of d.nodes) if (!seen.has(n)) body += '"' + calEsc(n) + '" ';
  let stmt = 'ADD workflow "' + calEsc(d.name.trim()) + '"';
  stmt += ' ' + body.trim();
  /* Every other interpolated value here (node names, WHEN, trigger, reason,
     the BIND key itself) goes through calEsc() into a quoted string —
     `hash` is the one value emitted bare. A plan opened here can have been
     authored outside this UI (Rust/Python/Node API, or a synced bundle),
     and `wfOpen` copies its `bindings` map verbatim into the draft, so a
     crafted binding value could otherwise append arbitrary CAL clauses
     (rebinding other steps, overriding REASON/ON) to this statement the
     moment someone re-saves that plan. HASH_RE (a full hex sha256, the
     only shape a real binding ever has) is the same check the rest of the
     console already uses to recognize a content address. */
  const skippedBindings = [];
  for (const [node, hash] of Object.entries(d.bindings)) {
    if (!hash) continue;
    if (!HASH_RE.test(String(hash))) { skippedBindings.push(node); continue; }
    stmt += ' BIND "' + calEsc(node) + '" = sha256:' + String(hash).replace(/^sha256:/, '');
  }
  stmt += ' REASON "' + calEsc(reason) + '"';
  const r = await cal(stmt);
  btn.textContent = prevLabel;
  if (!r.ok || !r.result || !r.result.hash) { toast('Could not save: ' + errText(r)); btn.disabled = false; return; }
  toast('Saved as a new plan · ' + shortHash(r.result.hash)
    + (skippedBindings.length ? ' — dropped a malformed binding on ' + skippedBindings.join(', ') : ''));
  $('wfReasonBox').textContent = '';
  await loadBrowse();
  wfOpen(r.result.hash);
}

/* ── the canvas: a deterministic layered layout, not a physics sim — a
   plan reads as "what happens after what", which a left-to-right rank
   order shows and a force-directed blob does not. Forward edges (no
   `max_cycles`) decide rank; a bounded-cycle back-edge draws as a dashed
   arc instead of feeding the ranking, or every node in its cycle would
   collapse to the same rank. */
const WFGraph = (() => {
  let cv, ctx, W = 0, H = 0, dpr = 1;
  let nodes = [], byId = new Map(), edgesGeo = [];
  /* Triggers live in their OWN arrays, never in `nodes`. That is not tidiness:
     `nodes` is the draft the Save button serializes, and a plan grain has no
     field for a trigger (the binding points the other way). Keeping them
     structurally separate makes it impossible for the lane to be saved. */
  let trgNodes = [], trgEdges = [];
  let scale = 1, tx = 0, ty = 0;
  let drag = null, panning = null, moved = false, hoverId = null, trgDown = null;
  let connectFrom = null, connectPt = null, connectTarget = null;   // live drag-to-connect
  let colors = {};
  let posOverride = {};
  let sel = null;

  function recolor() {
    colors = { host: cssVar('--accent'), client: cssVar('--warn'), abstract: cssVar('--cat-project'),
      subgraph: cssVar('--hash'), line: cssVar('--line2'), ink: cssVar('--ink'), dim: cssVar('--dim'),
      faint: cssVar('--faint'), surface: cssVar('--surface'), well: cssVar('--well'),
      /* a trigger is armed, not a step — green reads as "live", and it is the
         one hue the four node kinds do not already use */
      trg: cssVar('--ok'), ok: cssVar('--ok'), warn: cssVar('--warn'),
      danger: cssVar('--danger'), ghost: cssVar('--ghost') };
  }
  const clip = (s, n) => s.length > n ? s.slice(0, n - 1) + '…' : s;
  const COL_W = 240, ROW_H = 96;
  const HANDLE_R = 7, HANDLE_HIT = 11;
  const TRG_W = 196, TRG_H = 52, TRG_GAP = 78, TRG_ROW = 76;

  function layout() {
    const draft = WF_DRAFT;
    const ids = draft ? draft.nodes.slice() : [];
    const forward = draft ? draft.edges.filter(e => e.max_cycles == null) : [];
    const adj = new Map(ids.map(n => [n, []]));
    const indeg = new Map(ids.map(n => [n, 0]));
    for (const e of forward) {
      if (!adj.has(e.src) || !adj.has(e.dst)) continue;
      adj.get(e.src).push(e.dst);
      indeg.set(e.dst, (indeg.get(e.dst) || 0) + 1);
    }
    const rank = new Map(ids.map(n => [n, 0]));
    const queue = ids.filter(n => (indeg.get(n) || 0) === 0);
    /* Snapshot before the topological walk decrements `indeg` out from under
       us — these are the steps a run actually starts at, and so the steps a
       trigger points into. */
    const entryIds = queue.slice();
    const seen = new Set(queue);
    let i = 0, guard = 0;
    while (i < queue.length && guard++ < ids.length * ids.length + 10) {
      const n = queue[i++];
      for (const m of adj.get(n) || []) {
        if (rank.get(m) < rank.get(n) + 1) rank.set(m, rank.get(n) + 1);
        indeg.set(m, (indeg.get(m) || 0) - 1);
        if (indeg.get(m) <= 0 && !seen.has(m)) { seen.add(m); queue.push(m); }
      }
    }
    const maxRank = ids.length ? Math.max(...ids.map(n => rank.get(n) || 0)) : 0;
    for (const n of ids) if (!seen.has(n)) rank.set(n, maxRank + 1);
    const buckets = new Map();
    for (const n of ids) { const r = rank.get(n) || 0; if (!buckets.has(r)) buckets.set(r, []); buckets.get(r).push(n); }
    nodes = [];
    for (const [r, list] of buckets) {
      list.forEach((id, i2) => {
        const defX = r * COL_W, defY = (i2 - (list.length - 1) / 2) * ROW_H;
        const o = posOverride[id];
        nodes.push({ id, x: o ? o.x : defX, y: o ? o.y : defY, w: 150, h: 56 });
      });
    }
    if (ctx) {
      const draftB = draft ? draft.bindings : {};
      for (const n of nodes) {
        const ex = wfNodeExecutor(draftB, n.id);
        ctx.font = '600 13.5px ' + cssVar('--sans');
        const w1 = ctx.measureText(clip(n.id, 24)).width;
        ctx.font = '11.5px ' + cssVar('--sans');
        const w2 = ctx.measureText(clip(wfNodeSubtitle(ex), 30)).width;
        n.w = Math.max(150, Math.max(w1, w2) + 44);
      }
    }
    byId = new Map(nodes.map(n => [n.id, n]));
    edgesGeo = (draft ? draft.edges : []).map((e, idx) => ({ e, idx, a: byId.get(e.src), b: byId.get(e.dst) }));
    layoutTriggers(entryIds);
  }
  /* The lane sits to the LEFT of wherever the entry steps currently are, not
     at a fixed x — nodes are draggable, and a lane pinned to the origin ends
     up behind the plan the moment someone rearranges it. Right-aligned to one
     shared edge so the dashed arrows all span the same gap. */
  function layoutTriggers(entryIds) {
    trgNodes = []; trgEdges = [];
    const list = WF_TRG || [];
    if (!list.length || !nodes.length) return;
    let anchor = (entryIds || []).map(id => byId.get(id)).filter(Boolean);
    if (!anchor.length) anchor = [nodes.reduce((a, b) => (b.x < a.x ? b : a))];
    let left = Infinity, cy = 0;
    for (const n of anchor) { left = Math.min(left, n.x - n.w / 2); cy += n.y; }
    cy /= anchor.length;
    trgNodes = list.map((g, i) => ({
      g, hash: g.hash, w: TRG_W, h: TRG_H,
      x: 0, y: cy + (i - (list.length - 1) / 2) * TRG_ROW,
    }));
    if (ctx) {
      for (const t of trgNodes) {
        const f = t.g.fields || {};
        ctx.font = '600 13px ' + cssVar('--sans');
        const w1 = ctx.measureText(clip(trgWhen(f), 34)).width;
        ctx.font = '11.5px ' + cssVar('--sans');
        const w2 = ctx.measureText(clip(trgSubtitle(f), 28)).width;
        t.w = Math.max(TRG_W, Math.max(w1, w2) + 46);
      }
    }
    const rightEdge = left - TRG_GAP;
    for (const t of trgNodes) {
      t.x = rightEdge - t.w / 2;
      for (const n of anchor) trgEdges.push({ a: t, b: n });
    }
  }
  function hitTrigger(p) {
    for (let i = trgNodes.length - 1; i >= 0; i--) {
      const t = trgNodes[i];
      if (Math.abs(p.x - t.x) <= t.w / 2 + 3 && Math.abs(p.y - t.y) <= t.h / 2 + 3) return t;
    }
    return null;
  }
  function resetOverrides() { posOverride = {}; }
  function renameOverride(oldId, next) { if (posOverride[oldId]) { posOverride[next] = posOverride[oldId]; delete posOverride[oldId]; } }
  function setSelection(s) { sel = s; }
  function kindColor(kind) { return colors[kind] || colors.dim; }
  function handlePt(n) { return { x: n.x + n.w / 2 + 14, y: n.y }; }

  function toWorld(e) {
    const r = cv.getBoundingClientRect();
    return { x: (e.clientX - r.left - W / 2 - tx) / scale, y: (e.clientY - r.top - H / 2 - ty) / scale };
  }
  function hitNode(p) {
    for (let i = nodes.length - 1; i >= 0; i--) {
      const n = nodes[i];
      if (Math.abs(p.x - n.x) <= n.w / 2 + 3 && Math.abs(p.y - n.y) <= n.h / 2 + 3) return n;
    }
    return null;
  }
  function hitHandle(p) {
    for (let i = nodes.length - 1; i >= 0; i--) {
      const n = nodes[i], hp = handlePt(n);
      if (Math.hypot(p.x - hp.x, p.y - hp.y) <= HANDLE_HIT) return n;
    }
    return null;
  }
  /* The curve `draw()` actually strokes, as a single source of truth — its
     endpoints sit on the node borders (offset by half-width, toward
     whichever side the other node is on), not the centers, so an edge
     between two node boxes doesn't visibly cut into either of them. The
     control points still bow off the raw centers (`midx`) — using the
     border x there too would barely change the curve's shape, and this
     keeps the bow symmetric regardless of node width. */
  function edgeCurve(a, b, back) {
    const midx = (a.x + b.x) / 2, bow = back ? -70 - Math.abs(a.x - b.x) * 0.15 : 0;
    return {
      ax: a.x + (b.x >= a.x ? a.w / 2 : -a.w / 2), ay: a.y,
      bx: b.x - (b.x >= a.x ? b.w / 2 : -b.w / 2), by: b.y,
      c1x: midx, c1y: a.y + bow, c2x: midx, c2y: b.y + bow,
    };
  }
  /* Evaluated on that same curve — this used to plug the raw node centers
     in as P0/P3 while `draw()` stroked the border-adjusted curve above, so
     the arrowhead (t≈0.985) landed inside the destination node's box and
     was painted over, and `hitEdge()`'s hit-testing didn't line up with
     what was on screen. */
  function bezierPoint(a, b, back, t) {
    const c = edgeCurve(a, b, back), u = 1 - t;
    return { x: u*u*u*c.ax + 3*u*u*t*c.c1x + 3*u*t*t*c.c2x + t*t*t*c.bx, y: u*u*u*c.ay + 3*u*u*t*c.c1y + 3*u*t*t*c.c2y + t*t*t*c.by };
  }
  function hitEdge(p) {
    let best = -1, bestD = 9;
    for (let i = 0; i < edgesGeo.length; i++) {
      const { a, b, e } = edgesGeo[i];
      if (!a || !b) continue;
      for (let s = 0; s <= 20; s++) {
        const pt = bezierPoint(a, b, e.max_cycles != null, s / 20);
        const d = Math.hypot(pt.x - p.x, pt.y - p.y);
        if (d < bestD) { bestD = d; best = i; }
      }
    }
    return best;
  }
  function roundRect(x, y, w, h, r) {
    ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r);
    ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath();
  }
  function halo(text, x, y, font, fill) {
    ctx.textAlign = 'center'; ctx.font = font; ctx.lineWidth = 3.5; ctx.lineJoin = 'round';
    ctx.strokeStyle = colors.well; ctx.strokeText(text, x, y);
    ctx.fillStyle = fill; ctx.fillText(text, x, y);
  }
  function arrow(x, y, ang, color) {
    ctx.save(); ctx.translate(x, y); ctx.rotate(ang);
    ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(-9, -4.5); ctx.lineTo(-9, 4.5); ctx.closePath();
    ctx.fillStyle = color; ctx.fill(); ctx.restore();
  }
  function draw() {
    if (!ctx) return;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.clearRect(0, 0, W, H);
    ctx.save();
    ctx.translate(W / 2 + tx, H / 2 + ty);
    ctx.scale(scale, scale);
    /* Under the plan's own edges: a trigger arrow is the cause arriving from
       outside, not a step in the graph. Dashed for the same reason — the plan
       does not contain it, and a solid line would read as one more edge you
       could select and delete. */
    for (const te of trgEdges) {
      const live = (te.a.g.fields || {}).enabled !== false;
      const c = edgeCurve(te.a, te.b, false);
      ctx.beginPath();
      ctx.moveTo(c.ax, c.ay);
      ctx.bezierCurveTo(c.c1x, c.c1y, c.c2x, c.c2y, c.bx, c.by);
      ctx.strokeStyle = live ? colors.trg : colors.ghost;
      ctx.lineWidth = 1.6; ctx.setLineDash([6, 5]); ctx.globalAlpha = live ? 0.75 : 0.45;
      ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1;
      const end = bezierPoint(te.a, te.b, false, 0.985), near = bezierPoint(te.a, te.b, false, 0.9);
      ctx.globalAlpha = live ? 0.8 : 0.45;
      arrow(end.x, end.y, Math.atan2(end.y - near.y, end.x - near.x), live ? colors.trg : colors.ghost);
      ctx.globalAlpha = 1;
    }
    for (let i = 0; i < edgesGeo.length; i++) {
      const { a, b, e } = edgesGeo[i];
      if (!a || !b) continue;
      const back = e.max_cycles != null;
      const selected = sel && sel.kind === 'edge' && sel.idx === i;
      const c = edgeCurve(a, b, back);
      ctx.beginPath();
      ctx.moveTo(c.ax, c.ay);
      ctx.bezierCurveTo(c.c1x, c.c1y, c.c2x, c.c2y, c.bx, c.by);
      ctx.strokeStyle = selected ? colors.ink : (back ? colors.faint : colors.line);
      ctx.lineWidth = selected ? 2.4 : 1.8;
      if (back) ctx.setLineDash([5, 4]);
      ctx.globalAlpha = 0.9;
      ctx.stroke();
      ctx.setLineDash([]);
      const end = bezierPoint(a, b, back, 0.985), near = bezierPoint(a, b, back, 0.9);
      arrow(end.x, end.y, Math.atan2(end.y - near.y, end.x - near.x), selected ? colors.ink : (back ? colors.faint : colors.dim));
      const mid = bezierPoint(a, b, back, 0.5);
      let label = e.cond ? clip(e.cond, 26) : '';
      if (back) label = (label ? label + '  ' : '') + '↻ ×' + e.max_cycles;
      if (label && scale > 0.5) halo(label, mid.x, mid.y - 8, '11.5px ' + cssVar('--sans'), back ? colors.faint : colors.dim);
    }
    /* the edge being drawn right now, if any */
    if (connectFrom && connectPt) {
      const a = byId.get(connectFrom);
      if (a) {
        ctx.beginPath();
        ctx.moveTo(a.x + a.w / 2, a.y);
        ctx.lineTo(connectPt.x, connectPt.y);
        ctx.strokeStyle = colors.ink; ctx.lineWidth = 2; ctx.setLineDash([4, 4]); ctx.globalAlpha = 0.7;
        ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1;
      }
    }
    ctx.globalAlpha = 1;
    if (trgNodes.length) {
      const topY = Math.min.apply(null, trgNodes.map(t => t.y - t.h / 2));
      const leftX = Math.min.apply(null, trgNodes.map(t => t.x - t.w / 2));
      if (scale > 0.45) {
        ctx.textAlign = 'left';
        ctx.font = '600 10.5px ' + cssVar('--sans');
        ctx.fillStyle = colors.faint;
        ctx.fillText('STARTED BY', leftX + 2, topY - 12);
      }
      for (const t of trgNodes) {
        const f = t.g.fields || {};
        const live = f.enabled !== false;
        const c = live ? colors.trg : colors.ghost;
        const selected = sel && sel.kind === 'trigger' && sel.hash === t.hash;
        const x0 = t.x - t.w / 2, y0 = t.y - t.h / 2;
        ctx.beginPath(); roundRect(x0, y0, t.w, t.h, 13);
        ctx.fillStyle = colors.surface; ctx.fill();
        ctx.lineWidth = selected ? 2.6 : 1.6;
        ctx.strokeStyle = selected ? colors.ink : c;
        ctx.setLineDash(selected ? [] : [5, 4]);
        ctx.stroke(); ctx.setLineDash([]);
        /* A ring, where a step draws a filled dot — the shape says "not one of
           the steps" before the colour or the dashes do. */
        ctx.beginPath(); ctx.arc(x0 + 15, y0 + 15, 4, 0, 7);
        ctx.lineWidth = 1.8; ctx.strokeStyle = c; ctx.stroke();
        ctx.textAlign = 'left';
        ctx.fillStyle = live ? colors.ink : colors.dim;
        ctx.font = (selected ? '700 ' : '600 ') + '13px ' + cssVar('--sans');
        ctx.fillText(clip(trgWhen(f), 34), x0 + 26, y0 + 20);
        ctx.fillStyle = colors.faint;
        ctx.font = '11.5px ' + cssVar('--sans');
        ctx.fillText(clip(trgSubtitle(f), 28), x0 + 26, y0 + 37);
      }
    }
    for (const n of nodes) {
      const ex = wfNodeExecutor(WF_DRAFT ? WF_DRAFT.bindings : {}, n.id);
      /* The run overlay. A step with no row in this run was never reached, so
         it is dimmed rather than tinted — an absence, not an outcome. */
      const st = WF_STEPS ? (WF_STEPS.get(n.id) || null) : null;
      const unreached = !!WF_STEPS && !st;
      if (unreached) ctx.globalAlpha = 0.5;
      const c = colors[ex.kind] || colors.dim;
      const selected = sel && sel.kind === 'node' && sel.id === n.id;
      const isDropTarget = connectFrom && connectFrom !== n.id && connectTarget === n.id;
      const x0 = n.x - n.w / 2, y0 = n.y - n.h / 2;
      ctx.beginPath(); roundRect(x0, y0, n.w, n.h, 11);
      ctx.fillStyle = colors.surface; ctx.fill();
      ctx.lineWidth = selected || isDropTarget ? 2.6 : 1.6;
      ctx.strokeStyle = isDropTarget ? colors.ink : (selected ? colors.ink : c);
      if (ex.kind === 'abstract') ctx.setLineDash([4, 3]);
      ctx.stroke(); ctx.setLineDash([]);
      if (isDropTarget) {
        ctx.globalAlpha = 0.08; ctx.fillStyle = colors.ink;
        ctx.beginPath(); roundRect(x0, y0, n.w, n.h, 11); ctx.fill(); ctx.globalAlpha = 1;
      }
      if (WF_STEPS) {
        ctx.save();
        ctx.beginPath(); roundRect(x0, y0, n.w, n.h, 11); ctx.clip();
        ctx.fillStyle = st ? colors[STEP_TONE[st.state]] : colors.line;
        ctx.fillRect(x0, y0, 7, n.h);
        ctx.restore();
      }
      ctx.beginPath(); ctx.arc(x0 + 14, y0 + 16, 4, 0, 7); ctx.fillStyle = c; ctx.fill();
      ctx.textAlign = 'left';
      ctx.fillStyle = colors.ink;
      ctx.font = (selected ? '700 ' : '600 ') + '13.5px ' + cssVar('--sans');
      ctx.fillText(clip(n.id, 24), x0 + 25, y0 + 21);
      ctx.fillStyle = colors.dim;
      ctx.font = '11.5px ' + cssVar('--sans');
      ctx.fillText(clip(wfNodeSubtitle(ex), 30), x0 + 25, y0 + 38);
      /* the connector handle — always visible, brighter on hover so it
         reads as grabbable before the user has ever dragged one */
      const hp = handlePt(n);
      const hot = hoverId === n.id || connectFrom === n.id;
      ctx.beginPath(); ctx.arc(hp.x, hp.y, hot ? HANDLE_R + 1.5 : HANDLE_R, 0, 7);
      ctx.fillStyle = colors.surface; ctx.fill();
      ctx.lineWidth = hot ? 2.2 : 1.6; ctx.strokeStyle = hot ? colors.ink : colors.line; ctx.stroke();
      ctx.beginPath(); ctx.arc(hp.x, hp.y, 2.5, 0, 7); ctx.fillStyle = hot ? colors.ink : colors.faint; ctx.fill();
      if (unreached) ctx.globalAlpha = 1;
    }
    ctx.restore();
    ctx.globalAlpha = 1;
  }
  /* A guessed CSS calc() for "fill to the bottom of the window" drifts the
     moment the header above it changes height — measure the canvas's own
     rendered top instead, so it is always exactly right regardless of what
     changed above it. */
  function resize() {
    if (!cv) return;
    const top = cv.getBoundingClientRect().top;
    cv.style.height = Math.max(480, Math.round(window.innerHeight - top - 32)) + 'px';
    dpr = window.devicePixelRatio || 1;
    W = cv.clientWidth; H = cv.clientHeight;
    cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr);
  }
  function fit() {
    if (!nodes.length) { scale = 1; tx = ty = 0; draw(); return; }
    let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
    for (const n of nodes.concat(trgNodes)) {
      x0 = Math.min(x0, n.x - n.w / 2 - 30); y0 = Math.min(y0, n.y - n.h / 2 - 40);
      x1 = Math.max(x1, n.x + n.w / 2 + 40); y1 = Math.max(y1, n.y + n.h / 2 + 40);
    }
    const padR = $('wfinspect').hidden ? 24 : 322, padT = 60, padB = 30, padL = 24;
    const availW = Math.max(160, W - padL - padR), availH = Math.max(160, H - padT - padB);
    scale = Math.max(0.3, Math.min(1.5, Math.min(availW / (x1 - x0), availH / (y1 - y0))));
    tx = (padL + availW / 2) - W / 2 - ((x0 + x1) / 2) * scale;
    ty = (padT + availH / 2) - H / 2 - ((y0 + y1) / 2) * scale;
    draw();
  }
  function legend() {
    const host = $('wflegend'); host.textContent = '';
    const add = (color, label, ring) => {
      const s = el('span');
      const d = el('span');
      d.style.cssText = 'width:8px;height:8px;border-radius:4px;flex-shrink:0;'
        + (ring ? 'border:1.6px solid ' + color : 'background:' + color);
      s.appendChild(d); s.appendChild(el('span', null, label));
      host.appendChild(s);
    };
    for (const [k, label] of [['host', 'Host tool'], ['client', 'Human approval'],
      ['abstract', 'Abstract (LLM)'], ['subgraph', 'Subgraph']]) add(colors[k], label);
    if (trgNodes.length) add(colors.trg, 'Trigger', true);
    /* Only while an overlay is on: a key for colours that aren't on screen is
       just clutter, and this legend has to stay readable at one or two lines. */
    if (WF_STEPS) {
      host.appendChild(el('span', 'legsep', '·'));
      for (const [k, label] of [['ok', 'done'], ['warn', 'waiting'], ['danger', 'failed']]) add(colors[k], label);
    }
  }
  return {
    recolor, resetOverrides, renameOverride, setSelection, kindColor, draw,
    rebuild() { layout(); },
    refresh() { if (!ctx) return; layout(); legend(); draw(); },
    wire() {
      cv = $('wfcanvas'); ctx = cv.getContext('2d'); recolor();
      window.addEventListener('resize', () => { if (!$('wfEditorWrap').hidden) { resize(); fit(); } });
      cv.addEventListener('mousedown', e => {
        const p = toWorld(e); moved = false;
        const h = hitHandle(p);
        if (h && !WF_LOCKED) { connectFrom = h.id; connectPt = p; connectTarget = null; return; }
        const n = hitNode(p);
        if (n) { drag = { id: n.id, dx: n.x - p.x, dy: n.y - p.y }; return; }
        /* Triggers are neither draggable nor connectable: the lane is not the
           user's to arrange, and a plan grain has no field that could record
           where a trigger sits. Panning still arms, so a drag starting on one
           pans exactly like a drag on the background; the click only lands if
           the pointer never moved. */
        const t = hitTrigger(p);
        trgDown = t ? t.hash : null;
        panning = { x: e.clientX - tx, y: e.clientY - ty };
        if (!t) cv.classList.add('grabbing');
      });
      window.addEventListener('mousemove', e => {
        if (connectFrom) {
          const p = toWorld(e); connectPt = p;
          const n = hitNode(p);
          connectTarget = (n && n.id !== connectFrom) ? n.id : null;
          draw(); return;
        }
        if (drag) {
          const p = toWorld(e); const n = byId.get(drag.id);
          if (n) { n.x = p.x + drag.dx; n.y = p.y + drag.dy; posOverride[n.id] = { x: n.x, y: n.y }; }
          moved = true; draw(); return;
        }
        if (panning) { tx = e.clientX - panning.x; ty = e.clientY - panning.y; moved = true; draw(); return; }
        if (!cv) return;
        const r = cv.getBoundingClientRect();
        if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) return;
        const p = toWorld(e);
        const h = hitHandle(p), n = h ? null : hitNode(p);
        const nextHover = h ? h.id : null;
        if (nextHover !== hoverId) { hoverId = nextHover; draw(); }
        cv.style.cursor = h ? 'crosshair' : (n || hitTrigger(p) || hitEdge(p) >= 0) ? 'pointer' : 'grab';
      });
      window.addEventListener('mouseup', e => {
        if (connectFrom) {
          const p = toWorld(e); const n = hitNode(p);
          if (n && n.id !== connectFrom) wfConnectNodes(connectFrom, n.id);
          connectFrom = null; connectPt = null; connectTarget = null; draw();
          return;
        }
        if (drag) { if (!moved) wfNodeClicked(drag.id); drag = null; return; }
        if (panning) {
          if (!moved) {
            if (trgDown) wfTriggerClicked(trgDown);
            else {
              const p = toWorld(e); const ei = hitEdge(p);
              if (ei >= 0) wfEdgeClicked(ei); else wfCanvasBgClicked();
            }
          }
          panning = null; trgDown = null; cv.classList.remove('grabbing');
        }
      });
      cv.addEventListener('mouseleave', () => { if (hoverId) { hoverId = null; draw(); } });
      cv.addEventListener('wheel', e => { e.preventDefault();
        const f = e.deltaY < 0 ? 1.12 : 0.89; scale = Math.max(0.25, Math.min(2.2, scale * f)); draw(); }, { passive: false });
      cv.addEventListener('dblclick', () => fit());
      $('wfin').onclick = () => { scale = Math.min(2.2, scale * 1.2); draw(); };
      $('wfout').onclick = () => { scale = Math.max(0.25, scale / 1.2); draw(); };
      $('wffit').onclick = () => fit();
      document.addEventListener('keydown', e => {
        if (e.key === 'Escape' && connectFrom) { connectFrom = null; connectPt = null; connectTarget = null; draw(); }
      });
    },
    mount() { if (!cv || !cv.clientWidth) { requestAnimationFrame(() => WFGraph.mount()); return; } resize(); layout(); fit(); legend(); draw(); },
  };
})();

/* ══ tools: the catalog, and every call made against it ═══════════════
   Definition and execution are the same grain type split by `kind` — "what
   can run" and "what did run" are two questions about ONE catalog, so they
   are two tabs here rather than two pages. Configuration is not a third tab:
   a tool's schema, locked params and executor ARE the catalog entry, and a
   separate table of the same fields is the kind of duplicate surface that
   drifts out of agreement with the one beside it.

   Everything comes from /api/browse, which is already loaded — no new server
   route, the same way the workflow canvas is built. */
function toolExecs() {
  return wfRows().filter(g => {
    const f = g.fields || {};
    return g.type === 'tool' && f.kind !== 'definition' && isCurrent(g);
  }).sort((a, b) => createdMs(b.fields) - createdMs(a.fields));
}
/** Where a definition is actually wired in: plan → node. */
function toolBoundIn(hash) {
  const out = [];
  for (const g of workflowGrains()) {
    const b = (g.fields || {}).bindings || {};
    for (const node of Object.keys(b)) if (bareHash(b[node]) === hash) out.push({ plan: g, node });
  }
  return out;
}
const toolIsClient = f => (f || {}).executor_kind === 'client';
const toolKindWord = f => toolIsClient(f) ? 'Human approval' : 'Host tool';
const toolKindTone = f => toolIsClient(f) ? 'warn' : 'accent';

function renderTools() {
  const nsHost = $('toolNsHost'); nsHost.textContent = '';
  nsHost.appendChild(nsCombo('toolNs', WF_NS || boundNamespace(), ns => wfSetNamespace(ns)));
  const host = $('toolBody');
  host.textContent = '';
  /* Execution rows resolve their state against the run's outcome, so without
     the index a Pending step in a canceled run would read as "waiting on a
     person" — an approval that can never arrive. Correctness, not a label. */
  if (!RUNIDX && !RUNIDX_INFLIGHT) loadRuns().then(() => { if (PAGE === 'tools') render(); });
  if (TOOLTAB === 'catalog' && TOOL_SEL) { renderToolDetail(host); return; }
  renderCrumbHeader('toolCrumb', [{ label: 'Tools' }],
    'What a step can call. A <b>definition</b> is the catalog entry a plan binds a node to — its schema is '
    + 'the contract the model must fill; an <b>execution</b> is one call that was actually made, journaled '
    + 'as its own immutable grain.');
  if (TOOLTAB === 'catalog') renderToolCatalog(host); else renderToolExecs(host);
}

function renderToolCatalog(host) {
  const defs = toolDefs().slice().sort((a, b) =>
    String((a.fields || {}).tool_name || '').localeCompare(String((b.fields || {}).tool_name || '')));
  if (!defs.length) {
    host.innerHTML = '<div class="empty">No tools defined in this memory. A definition is what a plan node '
      + 'binds to — write one with <code>bind_tool</code>, or <code>ADD tool</code> in CAL.</div>';
    return;
  }
  const grid = el('div', 'toolgrid');
  for (const g of defs) grid.appendChild(toolCard(g));
  host.appendChild(grid);
}

function toolCard(g) {
  const f = g.fields || {};
  const b = el('button', 'toolcard');
  const hd = el('div', 'hd');
  hd.appendChild(el('b', null, f.tool_name || shortHash(g.hash)));
  const badge = el('span', 'wf-badge', toolKindWord(f));
  badge.style.cssText = 'background:var(--well);color:var(--' + toolKindTone(f) + ')';
  hd.appendChild(badge);
  b.appendChild(hd);
  if (f.tool_description) b.appendChild(el('div', 'desc', f.tool_description));

  const ann = f.annotations || {};
  const tags = [];
  if (ann.read_only) tags.push('read-only');
  if (ann.destructive) tags.push('destructive');
  if (ann.idempotent) tags.push('idempotent');
  const bound = toolBoundIn(g.hash);
  const calls = toolExecs().filter(e => (e.fields || {}).tool_name === f.tool_name).length;
  const parts = [];
  if (tags.length) parts.push(tags.join(' · '));
  parts.push(bound.length ? 'bound in ' + bound.map(x => wfLabel(x.plan)).filter((v, i, a) => a.indexOf(v) === i).join(', ')
    : 'not bound in any plan');
  if (calls) parts.push(calls + (calls === 1 ? ' call' : ' calls'));
  b.appendChild(el('div', 'use', parts.join(' — ')));
  b.onclick = () => { TOOL_SEL = f.tool_name || g.hash; render(); };
  return b;
}

function renderToolDetail(host) {
  const g = toolDefs().find(t => ((t.fields || {}).tool_name || t.hash) === TOOL_SEL);
  if (!g) { TOOL_SEL = null; renderTools(); return; }
  const f = g.fields || {};
  renderCrumbHeader('toolCrumb', [
    { label: 'Tools', onClick: () => { TOOL_SEL = null; render(); } },
    { label: f.tool_name || shortHash(g.hash) },
  ], f.tool_description ? esc(f.tool_description) : null);

  const card = el('div', 'card');
  card.style.cssText = 'padding:4px 20px 18px';
  const row = (k, v, mono) => {
    if (v == null || v === '') return;
    const d = el('div', 'kv');
    d.appendChild(el('span', 'k', k));
    const val = el('span', 'v', String(v));
    if (mono) { val.style.fontFamily = 'var(--mono)'; val.style.fontSize = '12.5px'; }
    d.appendChild(val);
    card.appendChild(d);
  };
  row('Runs as', toolKindWord(f) + (toolIsClient(f)
    ? ' — the run pauses here until a person responds'
    : ' — executed by the host through $AREEV_RUN_TOOL_CMD'));
  const ann = f.annotations || {};
  const tags = [ann.read_only && 'read-only', ann.destructive && 'destructive', ann.idempotent && 'idempotent']
    .filter(Boolean);
  if (tags.length) row('Declared effects', tags.join(' · '));
  const bound = toolBoundIn(g.hash);
  if (bound.length) {
    const d = el('div', 'kv');
    d.appendChild(el('span', 'k', 'Bound in'));
    const v = el('span', 'v');
    v.style.cssText = 'display:flex;flex-direction:column;gap:4px;align-items:flex-start';
    for (const x of bound) {
      const link = el('button', 'link');
      link.style.cssText = 'border:0;background:none;color:var(--accent);font:inherit;font-size:13.5px;padding:0;text-align:left';
      link.textContent = wfLabel(x.plan) + ' › ' + x.node;
      link.onclick = () => { location.hash = '#workflows/' + x.plan.hash; };
      v.appendChild(link);
    }
    d.appendChild(v);
    card.appendChild(d);
  } else {
    row('Bound in', 'No plan binds a node to this tool yet.');
  }
  /* An opaque host reference that may carry an endpoint or credentials —
     SR-F5 keeps it out of logs, so keep it out of the default view too. */
  if (f.executor_uri) {
    const d = el('div', 'kv dev-flex');
    d.appendChild(el('span', 'k', 'Executor'));
    const v = el('span', 'v'); v.style.fontFamily = 'var(--mono)'; v.style.fontSize = '12.5px';
    v.textContent = f.executor_uri;
    d.appendChild(v);
    card.appendChild(d);
  }
  if (f.spec_hash) {
    const d = el('div', 'kv dev-flex');
    d.appendChild(el('span', 'k', 'Spec at bind time'));
    const v = el('span', 'v'); v.style.fontFamily = 'var(--mono)'; v.style.fontSize = '12.5px';
    v.textContent = bareHash(f.spec_hash);
    d.appendChild(v);
    card.appendChild(d);
  }
  row('Declared', relTime(createdMs(f)));
  host.appendChild(card);

  section(host, 'What the model may fill in', schemaBlock(f.input_schema)
    || el('div', 'tiny', 'No input schema — this tool takes no arguments.'));
  if (f.output_schema) section(host, 'What it returns', schemaBlock(f.output_schema) || jsonBlock(f.output_schema));
  if (f.locked_params) section(host, 'Locked parameters (the model may not choose these)', jsonBlock(f.locked_params));
  if (Array.isArray(f.examples) && f.examples.length) section(host, 'Examples', jsonBlock(f.examples));

  const mine = toolExecs().filter(e => (e.fields || {}).tool_name === (f.tool_name || ''));
  if (mine.length) {
    const wrap = el('div', 'card execwrap');
    for (const e of mine.slice(0, 12)) wrap.appendChild(execRow(e));
    section(host, 'Recent calls · ' + mine.length, wrap);
  }
}

function section(host, title, body) {
  const h = el('div');
  h.style.cssText = 'display:flex;flex-direction:column;gap:9px;margin-top:12px';
  const t = el('div', 'sec-label', title.toUpperCase());
  h.appendChild(t);
  h.appendChild(body);
  host.appendChild(h);
}

/** A JSON Schema object rendered as a property table, or null if it isn't one. */
function schemaBlock(schema) {
  const props = schema && schema.properties;
  if (!props || typeof props !== 'object') return null;
  const keys = Object.keys(props);
  if (!keys.length) return null;
  const req = new Set(Array.isArray(schema.required) ? schema.required : []);
  const host = el('div', 'card schema');
  host.style.padding = '4px 18px';
  for (const k of keys) {
    const p = props[k] || {};
    const r = el('div', 'r');
    r.appendChild(el('span', 'n', k));
    r.appendChild(el('span', 't', p.type || (p.enum ? 'enum' : 'any')));
    if (req.has(k)) r.appendChild(el('span', 'req', 'required'));
    if (p.description) r.appendChild(el('span', 'd', p.description));
    host.appendChild(r);
  }
  return host;
}

/* Executions, grouped by the run they belong to. A tool call made outside a
   run is a real thing too (an agent calling a tool directly), so it gets its
   own group rather than being filtered out of existence. */
function renderToolExecs(host) {
  const all = toolExecs();
  if (!all.length) {
    host.innerHTML = '<div class="empty">No tool calls recorded yet. Every call a run makes is journaled '
      + 'here as its own grain — start one with <code>areev run start --tool-cmd …</code>.</div>';
    return;
  }
  const groups = new Map();
  for (const g of all) {
    const k = (g.fields || {}).run_id || '';
    if (!groups.has(k)) groups.set(k, []);
    groups.get(k).push(g);
  }
  const order = [...groups.keys()].sort((a, b) => {
    if (!a) return 1;
    if (!b) return -1;
    return createdMs(groups.get(b)[0].fields) - createdMs(groups.get(a)[0].fields);
  });
  for (const key of order) {
    const rows = groups.get(key);
    const grp = el('div', 'rungroup');
    const hd = el('div', 'hd');
    const run = RUNIDX && RUNIDX.byId.get(key);
    hd.appendChild(el('h3', null, key ? key + ' · ' + rows.length : 'Outside a run · ' + rows.length));
    hd.appendChild(el('span', 'tiny', key
      ? (run ? planLabel(run.plan_hash) + ' · ' + run.outcome : 'a governed run')
      : 'called directly by an agent, not journaled against a plan'));
    grp.appendChild(hd);
    const wrap = el('div', 'card execwrap');
    for (const g of rows) wrap.appendChild(execRow(g));
    grp.appendChild(wrap);
    host.appendChild(grp);
  }
}

function execRow(g) {
  const f = g.fields || {};
  const run = RUNIDX && f.run_id ? RUNIDX.byId.get(f.run_id) : null;
  const state = stepState(f, run ? run.outcome : null);
  const wrap = el('div');
  const btn = el('button', 'exec');
  const bar = el('span', 'bar');
  bar.style.background = 'var(--' + STEP_TONE[state] + ')';
  btn.appendChild(bar);
  const nm = el('span', 'nm');
  nm.appendChild(document.createTextNode(f.tool_name || shortHash(g.hash)));
  const sub = [];
  if (f.node && f.node !== f.tool_name) sub.push(f.node);
  sub.push(STEP_WORD[state]);
  if (f.attempt && f.attempt > 1) sub.push('attempt ' + f.attempt);
  if (f.duration_ms != null) sub.push(f.duration_ms + 'ms');
  nm.appendChild(el('span', null, '  ' + sub.join(' · ')));
  btn.appendChild(nm);
  btn.appendChild(el('span', 'when', relTime(createdMs(f))));

  const det = el('div', 'execdet');
  det.hidden = true;
  btn.onclick = () => {
    if (!det.hidden) { det.hidden = true; return; }
    if (!det.childElementCount) buildExecDetail(det, f, g);
    det.hidden = false;
  };
  wrap.appendChild(btn);
  wrap.appendChild(det);
  /* Deep-linked from a canvas node's "See the call" — open it already
     expanded, otherwise the link lands on a closed row and looks inert. */
  if (TOOL_SEL === g.hash) {
    buildExecDetail(det, f, g);
    det.hidden = false;
    requestAnimationFrame(() => btn.scrollIntoView({ block: 'center' }));
  }
  return wrap;
}

function buildExecDetail(det, f, g) {
  const add = (label, body) => {
    det.appendChild(el('div', 'lab', label.toUpperCase()));
    det.appendChild(body);
  };
  if (f.error) {
    const e = el('div', 'tiny'); e.style.color = 'var(--danger)'; e.textContent = f.error;
    add('Error', e);
  }
  if (f.input != null) add('Arguments', jsonBlock(f.input));
  const out = f.tool_content != null ? f.tool_content : f.content;
  if (out != null) {
    let parsed = out;
    try { parsed = typeof out === 'string' ? JSON.parse(out) : out; } catch (err) { parsed = out; }
    add('Result', jsonBlock(parsed));
  }
  const meta = [];
  if (f.author_did) meta.push('by ' + f.author_did);
  if (f.superstep != null) meta.push('superstep ' + f.superstep);
  if (f.usage_usd_micros) meta.push('$' + (f.usage_usd_micros / 1e6).toFixed(4));
  if (f.usage_input_tokens || f.usage_output_tokens) {
    meta.push((f.usage_input_tokens || 0) + ' in / ' + (f.usage_output_tokens || 0) + ' out tokens');
  }
  if (meta.length) det.appendChild(el('div', 'tiny', meta.join(' · ')));
  const dv = el('div', 'tiny dev-only');
  dv.style.fontFamily = 'var(--mono)';
  dv.textContent = 'grain ' + g.hash + (f.tool_call_id ? '  ·  call ' + f.tool_call_id : '');
  det.appendChild(dv);
}

/* ══ query workbench ══════════════════════════════════════════════════
   Everything goes through /api/cal. Saved queries and templates are CAL
   statements (DEFINE / RUN / DESCRIBE / DROP), not console-local state, so
   they live in the .db file and work from the CLI and MCP too. Only the
   history is browser-local — that is personal and ephemeral. */
const READ_ONLY_STMTS = new Set(['RECALL','ASSEMBLE','EXPLAIN','HISTORY','EXISTS','DESCRIBE','COUNT']);
const WRITEY = new Set(['ADD','SUPERSEDE','ACCUMULATE','FORGET','DEFINE','DROP','BATCH','RUN']);
const leadKeyword = q => (String(q || '').trim().split(/[^A-Za-z0-9]/)[0] || '').toUpperCase();
const QUERY_NAME_RE = /^[a-zA-Z][a-zA-Z0-9 _-]{0,63}$/;
const Q = { res: null, view: null, text: '', fmtTab: null };
/* The engine reports what it can actually execute. DEFINE/RUN parse but are
   not in `supported_statements` on this build — the facade has no query or
   template registry — so gate the UI on the engine rather than on the docs. */
let CAPS = null;
const stmtSupported = kw => !CAPS || (CAPS.supported_statements || []).includes(kw);
async function loadCaps() {
  const r = await cal('DESCRIBE CAPABILITIES');
  CAPS = (r.ok && r.result && r.result.info) || null;
}

/* ── history: this browser, this file ── */
const histKey = () => 'areev.hist.' + (String(DB_PATH).split('/').pop() || 'db');
function histLoad() { try { return JSON.parse(localStorage.getItem(histKey()) || '[]'); } catch (e) { return []; } }
function histPush(q, summary) {
  const h = histLoad().filter(x => x.q !== q);
  h.unshift({ q, at: Date.now(), s: summary });
  try { localStorage.setItem(histKey(), JSON.stringify(h.slice(0, 100))); } catch (e) { /* quota */ }
}

/* ── the on-ramp ───────────────────────────────────────────────────────
   A blank editor is a wall for anyone who does not already know CAL. These
   questions write real statements into that same editor, so the first answer
   also teaches the language that produced it. Keep the CAL current — bare `|`
   is deprecated since CAL 1.1 (CAL-W007).

   "john"/"acme-corp" as hardcoded example subjects almost never exist in a
   real memory, so the very first thing a new user tries reliably comes back
   empty. Pull an actual subject (and an actual value) from this file's own
   Facts instead — BROWSE is already loaded at boot, so this costs nothing —
   and fall back to filter-free forms (still true, just less specific) only
   when the file genuinely has no facts yet to draw from. */
function starterFact() {
  for (const g of BROWSE) {
    if (isGone(g) || isInternal(g) || g.type !== 'fact') continue;
    const f = g.fields || {};
    if (typeof f.subject === 'string' && f.subject && f.object != null) return f;
  }
  return null;
}
function buildStarters() {
  const f = starterFact();
  if (!f) return [
    ['What is in this memory right now?', 'RECALL facts LIMIT 20'],
    ['Search the whole memory in plain words', 'RECALL facts ABOUT "notes"'],
    ['How much does it hold, in total?', 'RECALL facts COUNT'],
    ['Build a context brief to paste into a model',
      'ASSEMBLE "brief me on this memory" FROM notes: (RECALL facts LIMIT 20) BUDGET 300 tokens FORMAT markdown'],
  ];
  const q = s => '"' + String(s).replace(/"/g, '\\"') + '"';
  const clip = s => { s = String(s); return s.length > 40 ? s.slice(0, 40) + '…' : s; };
  const subj = f.subject, subjQ = q(subj), aboutQ = q(clip(f.object));
  return [
    ['What do we know about a person or account?', 'RECALL facts WHERE subject = ' + subjQ],
    ['Search the whole memory in plain words', 'RECALL facts ABOUT ' + aboutQ],
    ['How much does it know about one thing?', 'RECALL facts WHERE subject = ' + subjQ + ' COUNT'],
    ['Build a context brief to paste into a model',
      'ASSEMBLE "brief me on ' + subj.replace(/"/g, '\\"') + '" FROM notes: (RECALL facts WHERE subject = '
        + subjQ + ') BUDGET 300 tokens FORMAT markdown'],
  ];
}
function renderStarters() {
  const box = $('qstarters'); box.textContent = '';
  for (const [question, stmt] of buildStarters()) {
    const b = el('button', 'starter');
    b.appendChild(el('b', '', question));
    b.appendChild(el('code', '', stmt));
    b.onclick = () => { setQueryText(stmt); runQuery(stmt); };
    box.appendChild(b);
  }
}
/* Saved queries live in the file; history is this browser. Both were behind ▾
   menus, which is where the two most useful things on the page went to hide. */
async function renderRecents() {
  const box = $('qrecents'); box.textContent = '';
  const savedCol = el('div'), recentCol = el('div');
  savedCol.appendChild(el('div', 'sec-label', 'SAVED'));
  recentCol.appendChild(el('div', 'sec-label', 'RECENT'));
  box.appendChild(savedCol); box.appendChild(recentCol);

  const h = histLoad().slice(0, 5);
  if (!h.length) recentCol.appendChild(el('div', 'rempty', 'Nothing run yet in this browser'));
  for (const it of h) {
    const b = el('button', 'rrow');
    b.appendChild(el('div', 'rq', it.q));
    b.appendChild(el('div', 'rm', relTime(it.at) + (it.s ? ' · ' + it.s : '')));
    b.onclick = () => runQuery(it.q);
    recentCol.appendChild(b);
  }
  const qs = await cal('DESCRIBE QUERIES');
  const list = qs.ok ? pickList((qs.result || {}).info) : [];
  if (!list.length) savedCol.appendChild(el('div', 'rempty',
    stmtSupported('DEFINE') ? 'None saved yet — run something, then Save'
      : 'This build has no registry for saved queries yet'));
  for (const it of list.slice(0, 5)) {
    const name = itemName(it);
    const b = el('button', 'rrow');
    b.appendChild(el('div', 'rn', name));
    b.appendChild(el('div', 'rm', itemDesc(it) || 'RUN "' + name + '"'));
    b.onclick = () => runQuery('RUN "' + name + '"');
    savedCol.appendChild(b);
  }
}
function renderOnramp() { renderStarters(); renderRecents(); }

/* ── the editor ────────────────────────────────────────────────────────
   A textarea cannot hold colour, so the caret stays in a transparent one and
   a mirror underneath carries the highlighting. Keep the two in lockstep:
   same font, same padding, same wrapping, or the colours drift off the text.
   The keyword list is additive on purpose — a word CAL gains before this list
   does simply renders unstyled, which is the harmless failure. */
const CAL_KEYWORDS = new Set(['RECALL', 'ASSEMBLE', 'EXPLAIN', 'HISTORY', 'EXISTS', 'DESCRIBE',
  'COUNT', 'ADD', 'SUPERSEDE', 'ACCUMULATE', 'FORGET', 'DEFINE', 'DROP', 'BATCH', 'RUN', 'LET',
  'WHERE', 'LIMIT', 'ABOUT', 'LIKE', 'FROM', 'BUDGET', 'TOKENS', 'FORMAT', 'PRESET', 'TEMPLATE',
  'ORDER', 'BY', 'ASC', 'DESC', 'AND', 'OR', 'NOT', 'AS', 'SET', 'WITH', 'SINCE', 'UNTIL', 'OF',
  'PRIORITY', 'QUERY', 'QUERIES', 'TEMPLATES', 'CAPABILITIES', 'ELEMENT', 'SECTION', 'PROGRESSIVE',
  'IN', 'TRUE', 'FALSE', 'NULL']);
function highlightCal(src) {
  const s = String(src); let out = '', i = 0;
  while (i < s.length) {
    const ch = s[i];
    if (ch === '"') {
      let j = i + 1;
      while (j < s.length && s[j] !== '"') j += (s[j] === '\\' ? 2 : 1);
      out += '<span class="s">' + esc(s.slice(i, Math.min(j + 1, s.length))) + '</span>';
      i = j + 1; continue;
    }
    if (ch === '-' && s[i + 1] === '-') {
      let j = s.indexOf('\n', i); if (j < 0) j = s.length;
      out += '<span class="c">' + esc(s.slice(i, j)) + '</span>'; i = j; continue;
    }
    if (/[0-9]/.test(ch) && !/[A-Za-z0-9_]/.test(s[i - 1] || '')) {
      let j = i; while (j < s.length && /[0-9._]/.test(s[j])) j++;
      out += '<span class="n">' + esc(s.slice(i, j)) + '</span>'; i = j; continue;
    }
    if (/[A-Za-z_]/.test(ch)) {
      let j = i; while (j < s.length && /[A-Za-z0-9_]/.test(s[j])) j++;
      const w = s.slice(i, j);
      out += CAL_KEYWORDS.has(w.toUpperCase()) ? '<span class="k">' + esc(w) + '</span>' : esc(w);
      i = j; continue;
    }
    out += esc(ch); i++;
  }
  return out;
}
/* Grow with the statement rather than making people drag a corner, but stop
   at max-height so a long ASSEMBLE cannot push the results off the screen. */
function syncEditor() {
  const ta = $('qtext'), hl = $('qhl');
  hl.innerHTML = highlightCal(ta.value) + '\n';   /* spacer: a trailing newline has no box */
  ta.style.height = 'auto';
  ta.style.height = Math.min(ta.scrollHeight, 340) + 'px';
  hl.scrollTop = ta.scrollTop;
}
function setQueryText(s) { $('qtext').value = s; syncEditor(); queryNotice(); }

/* ── result shape helpers ── */
const rType = r => (r && r.type) || 'unknown';
const rGrains = r => (r && r.grains) || [];
function isHomogeneous(gs) {
  if (gs.length < 2) return true;
  const key = g => (rgType(g) || '') + '|' + Object.keys(rgFields(g)).sort().join(',');
  const k0 = key(gs[0]);
  return gs.every(g => key(g) === k0);
}
function defaultQView(r) {
  const t = rType(r);
  if (t === 'explain') return 'plan';
  if (t === 'multi_formatted') { const n = Object.keys(r.formats || {})[0]; return n ? 'fmt:' + n : 'raw'; }
  if (t === 'formatted') return 'format';
  if (t === 'grains' || t === 'assembled') return isHomogeneous(rGrains(r)) ? 'table' : 'cards';
  if (t === 'history') return 'history';
  return 'raw';
}
function viewsFor(r) {
  const t = rType(r), v = [];
  if (t === 'grains' || t === 'assembled') {
    v.push(['cards', 'Cards'], ['table', 'Table']);
    if (rGrains(r).some(g => rgFields(g).subject && typeof rgFields(g).object === 'string')) v.push(['graph', 'Graph']);
  }
  if (t === 'formatted') v.push(['format', r.format || 'Rendered']);
  if (t === 'multi_formatted') for (const n of Object.keys(r.formats || {})) v.push(['fmt:' + n, n]);
  if (t === 'history') v.push(['history', 'Timeline']);
  if (t === 'explain') v.push(['plan', 'Plan']);
  v.push(['raw', 'Raw']);
  return v;
}
function summarise(res) {
  const r = res.result || {}, t = rType(r);
  if (t === 'grains' || t === 'assembled') return rGrains(r).length + ' grains';
  if (t === 'count') return r.count + ' count';
  if (t === 'history') return (r.versions || []).length + ' versions';
  if (t === 'multi_formatted') return Object.keys(r.formats || {}).length + ' formats';
  return t;
}

/* ── running ── */
async function runQuery(text) {
  const t = (text != null ? text : $('qtext').value).trim();
  if (!t) return;
  if (text != null) setQueryText(t);
  Q.text = t;
  $('qerr').hidden = true;
  $('qrun').disabled = true;
  const res = await cal(t);
  $('qrun').disabled = false;
  if (!res.ok) { Q.res = null; showQueryError(t, res); $('qresult').hidden = true; return; }
  Q.res = res; Q.view = defaultQView(res.result); Q.fmtTab = null;
  histPush(t, summarise(res));
  renderQueryResult();
  if (WRITEY.has(leadKeyword(t))) refresh();
}
function showQueryError(q, res) {
  const box = $('qerr');
  let html = '<span class="code">' + esc(res.code || 'CAL') + '</span>' + esc(res.error || 'error');
  if (res.span && res.span.line) {
    const line = q.split('\n')[res.span.line - 1] || '';
    const col = Math.max(1, res.span.col || 1);
    const width = Math.max(1, (res.span.end || 0) - (res.span.start || 0));
    html += '<pre>' + esc(line) + '\n' + ' '.repeat(col - 1)
      + '^'.repeat(Math.min(width, Math.max(1, line.length - col + 1))) + '</pre>';
  }
  if (res.suggestion) html += '<div class="hint">hint: ' + esc(res.suggestion) + '</div>';
  box.innerHTML = html; box.hidden = false;
}
/* Classification is by leading keyword, so a read-only query that opens with
   LET is refused on a token-less console. Say so before they press Run. */
function queryNotice() {
  const kw = leadKeyword($('qtext').value);
  const n = $('qnotice');
  if (!kw || canWrite() || READ_ONLY_STMTS.has(kw)) { n.textContent = ''; return; }
  n.textContent = kw + ' needs a console started with --token-env';
  n.style.color = 'var(--warn)';
}

/* ── the result viewer ── */
const GRAIN_VAR = { fact: '--cat-person', observation: '--cat-note', event: '--cat-thing',
  goal: '--cat-project', tool: '--cat-org', skill: '--cat-project', state: '--cat-thing' };
const FMT_META = { markdown: ['md', 'text/markdown'], table: ['md', 'text/markdown'],
  json: ['json', 'application/json'], yaml: ['yaml', 'text/yaml'], csv: ['csv', 'text/csv'],
  sml: ['sml', 'text/plain'], toon: ['toon', 'text/plain'], text: ['txt', 'text/plain'],
  triples: ['txt', 'text/plain'] };
/* Restate the statement in plain words. Derived from the CAL that was run —
   never guessed from the result — so a non-technical reader can check the
   query asked what they meant before trusting the rows. */
function describeQuery(text) {
  const t = String(text || ''), kw = leadKeyword(t);
  if (kw === 'ASSEMBLE') return 'a context brief, budgeted for a model';
  if (kw === 'EXPLAIN') return 'how the engine would run this — nothing was read';
  if (kw === 'HISTORY') return 'every version of it, newest first';
  const kind = (t.match(/\b(?:RECALL|EXISTS)\s+([a-z_]+)/i) || [])[1];
  const subj = (t.match(/subject\s*=\s*"([^"]+)"/i) || [])[1];
  const about = (t.match(/\bABOUT\s+"([^"]+)"/i) || [])[1];
  const bits = [];
  if (kind && kind.toLowerCase() !== 'facts') bits.push('from ' + kind);
  if (subj) bits.push('about ' + subj);
  if (about) bits.push('matching “' + about + '”');
  bits.push('newest first');
  return bits.join(', ');
}
function renderQuerySummary() {
  const box = $('qsummary'); box.textContent = '';
  const res = Q.res; if (!res) return;
  const r = res.result || {}, t = rType(r), gs = rGrains(r);
  let head;
  if (t === 'count') head = r.count + (r.count === 1 ? ' match' : ' matches');
  else if (t === 'grains' || t === 'assembled') head = gs.length + (gs.length === 1 ? ' memory' : ' memories');
  else if (t === 'history') head = (r.versions || []).length + ' versions';
  else if (t === 'explain') head = 'Query plan';
  /* A FORMAT result counts renderings, not answers — say how many memories
     went in, so "2 formats" cannot be misread as two results. */
  else if (t === 'formatted' || t === 'multi_formatted') {
    const n = r.grain_count;
    head = n != null ? n + (n === 1 ? ' memory' : ' memories') : 'Rendered';
  }
  else head = summarise(res);
  const h = el('div', 'h', head + ' ');
  h.appendChild(el('em', '', describeQuery(Q.text)));
  box.appendChild(h);
  const sup = gs.filter(g => g.superseded_by || rgFields(g).superseded_by).length;
  if (sup) box.appendChild(el('div', 'tiny', sup + (sup === 1 ? ' has' : ' have')
    + ' been superseded since it was written — the older wording is kept so the change stays auditable'));
  else if (res.elapsed_ms != null) box.appendChild(el('div', 'tiny', 'Ran in ' + res.elapsed_ms + ' ms'
    + (r.total_available != null && r.total_available > gs.length
      ? ' · ' + r.total_available + ' match in total' : '')));
}
/* Back to the on-ramp without reloading — the editor keeps its text so the
   last query is still there to edit. */
function resetQuery() {
  Q.res = null; Q.view = null;
  $('qresult').hidden = true; $('qerr').hidden = true;
  $('qonramp').hidden = false; $('qintro').hidden = false; $('qreset').hidden = true;
  renderOnramp(); $('qtext').focus();
}
function renderQueryResult() {
  const res = Q.res;
  $('qresult').hidden = !res;
  $('qonramp').hidden = !!res;
  $('qintro').hidden = !!res;
  $('qreset').hidden = !res;
  if (!res) return;
  renderQuerySummary();
  const r = res.result || {}, t = rType(r);
  /* The view can survive a re-render (page switch) into a result that has no
     such view — fall back rather than render an empty pane. */
  const available = viewsFor(r).map(v => v[0]);
  if (!available.includes(Q.view)) Q.view = defaultQView(r);
  const bar = $('qbar'); bar.textContent = '';
  const gs = rGrains(r);
  const total = r.total_available;
  const seg = el('div', 'seg sm');
  for (const [v, name] of viewsFor(r)) {
    const b = el('button', Q.view === v ? 'on' : '', name);
    b.onclick = () => { Q.view = v; renderQueryResult(); };
    seg.appendChild(b);
  }
  bar.appendChild(seg);
  const sp = el('div'); sp.style.flex = '1'; bar.appendChild(sp);
  bar.appendChild(resultMenu('Copy', m => {
    /* Ordered by where results actually go: a doc or ticket, a spreadsheet,
       then code. `text` only exists on a FORMAT result — offer it first when
       it does, because that is the thing the person asked to be rendered. */
    if (r.text) mi(m, 'Copy as shown', 'the rendered ' + (r.format || 'output'),
      () => copyText(r.text, 'Result'));
    if (t === 'grains' || t === 'assembled') {
      mi(m, 'Copy as Markdown', 'a table you can paste into a doc',
        () => copyText(grainsMarkdown(gs), 'Markdown table'));
      mi(m, 'Copy as CSV', 'for a spreadsheet', () => copyText(grainsCsv(gs), 'CSV'));
    }
    mi(m, 'Copy as JSON', 'the raw result', () => copyText(JSON.stringify(r, null, 2), 'Result JSON'));
  }));
  bar.appendChild(resultMenu('Download', m => {
    mi(m, 'JSON', 'areev-result.json', () => download('areev-result.json', JSON.stringify(r, null, 2)));
    if (t === 'grains' || t === 'assembled') {
      mi(m, 'CSV', 'areev-result.csv', () => download('areev-result.csv', grainsCsv(gs), 'text/csv'));
    }
  }));

  const body = $('qbody'); body.textContent = '';
  if (t === 'assembled') body.appendChild(assembledSources(r));
  if (Q.view === 'cards') body.appendChild(qCards(gs));
  else if (Q.view === 'table') body.appendChild(qTable(gs));
  else if (Q.view === 'graph') body.appendChild(qGraphNote(gs));
  else if (Q.view === 'format' || String(Q.view).startsWith('fmt:')) body.appendChild(qFormats(r));
  else if (Q.view === 'history') body.appendChild(qHistory(r));
  else if (Q.view === 'plan') body.appendChild(qPlan(r));
  else body.appendChild(jsonBlock(r));
  /* Lay out immediately (reading scrollHeight forces the reflow we need),
     then once more on the next frame in case web fonts shift the metrics. */
  if (Q.view === 'cards') { layoutMasonry(); requestAnimationFrame(layoutMasonry); }

  /* Honest paging: the engine tells us the true total, so never imply the
     page is the whole answer. Re-runs with a larger LIMIT (CAL is bounded,
     there is no stream to scroll). */
  const more = $('qmore'); more.textContent = ''; more.hidden = true;
  if ((t === 'grains' || t === 'assembled') && total != null && total > gs.length) {
    more.hidden = false;
    const b = el('button', 'btn ghost', 'Load 20 more (' + (total - gs.length) + ' not shown)');
    b.onclick = () => runQuery(growLimit(Q.text, 20));
    more.appendChild(b);
  }
}
function growLimit(text, by) {
  const m = /\bLIMIT\s+(\d+)/i.exec(text);
  if (m) return text.replace(/\bLIMIT\s+\d+/i, 'LIMIT ' + (parseInt(m[1], 10) + by));
  /* FORMAT closes the statement, so a LIMIT appended after it would not
     parse — insert before the clause instead of at the end. */
  const f = /\sFORMAT\s/i.exec(text);
  if (f) return text.slice(0, f.index) + ' LIMIT ' + (20 + by) + text.slice(f.index);
  return text.trim() + ' LIMIT ' + (20 + by);
}
/* A dropdown built where the bar is rebuilt each render. It carries the same
   classes as the static menus, so the document-level click handler closes it. */
function resultMenu(label, build) {
  const wrap = el('div', 'menuwrap');
  const btn = el('button', 'btn ghost sm hasmenu', label);
  const menu = el('div', 'menu'); menu.hidden = true;
  btn.onclick = () => {
    const wasOpen = !menu.hidden;
    for (const x of document.querySelectorAll('.menu')) x.hidden = true;
    if (wasOpen) return;
    menu.textContent = ''; build(menu); menu.hidden = false;
  };
  wrap.appendChild(btn); wrap.appendChild(menu);
  return wrap;
}
/* Markdown, because a result usually ends up in a ticket or a doc. Pipes in a
   value would break the table, so escape them rather than dropping them. */
function grainsMarkdown(gs) {
  const keys = new Set(); for (const g of gs) for (const k of Object.keys(rgFields(g))) keys.add(k);
  const cols = ['kind', ...keys];
  const cell = v => (v == null ? '' : (typeof v === 'object' ? JSON.stringify(v) : String(v)))
    .replace(/\|/g, '\\|').replace(/\n/g, ' ');
  return ['| ' + cols.join(' | ') + ' |', '| ' + cols.map(() => '---').join(' | ') + ' |']
    .concat(gs.map(g => '| ' + cols.map(c =>
      cell(c === 'kind' ? rgType(g) : rgFields(g)[c])).join(' | ') + ' |')).join('\n');
}
/* Colour JSON the same way values are coloured elsewhere in the console. The
   regex runs before quote-escaping — escaping `"` first would hide the very
   delimiter it matches on — so only &, < and > are escaped up front. */
function highlightJson(text) {
  const safe = String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  return safe.replace(
    /("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false)\b|\b(null)\b|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g,
    (m, str, colon, bool, nul, num) => {
      if (str) return '<span class="' + (colon ? 'jk' : 'js') + '">' + str + '</span>' + (colon || '');
      if (bool) return '<span class="jb">' + bool + '</span>';
      if (nul) return '<span class="jz">' + nul + '</span>';
      if (num) return '<span class="jn">' + num + '</span>';
      return m;
    });
}
function jsonBlock(value) {
  const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
  const pre = el('pre', 'code jsonv');
  pre.innerHTML = highlightJson(text);
  return pre;
}
function grainsCsv(gs) {
  const keys = new Set(); for (const g of gs) for (const k of Object.keys(rgFields(g))) keys.add(k);
  const cols = ['hash', ...keys];
  const cell = v => { const s = v == null ? '' : (typeof v === 'object' ? JSON.stringify(v) : String(v));
    return /[",\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; };
  return [cols.join(',')].concat(gs.map(g => cols.map(c =>
    cell(c === 'hash' ? g.hash : rgFields(g)[c])).join(','))).join('\n');
}
const CARD_SKIP = new Set(['subject','relation','object','type','content','tool_content','description']);
/* Stored values are machine-shaped — epoch millis and raw JSON. Render them
   the way a person reads them, but never lie about the value. */
function fmtValue(key, val) {
  if (val == null) return '';
  if (typeof val === 'number' && /(^|_)(at|ms)$/.test(key) && val > 1e11) {
    return new Date(val).toLocaleString();
  }
  if (typeof val === 'number' && !Number.isInteger(val)) return String(Math.round(val * 1e4) / 1e4);
  if (typeof val === 'object') return clampText(JSON.stringify(val));
  return clampText(String(val));
}
/* Classify a value so colour can mean something. Hashes are teal wherever they
   appear in this console; a failing flag is the one thing worth flagging. */
function valueClass(key, val) {
  const k = String(key).toLowerCase();
  if (typeof val === 'boolean') return val ? (/error|fail|stale|gone/.test(k) ? 'v-no' : 'v-yes') : 'v-time';
  if (typeof val === 'number') return /(^|_)(at|ms)$/.test(k) && val > 1e11 ? 'v-time' : 'v-num';
  const s = String(val);
  if (/hash|^id$|_by$|derived_from|^svt$/.test(k) && /^[0-9a-f]{12,}$/i.test(s)) return 'v-hash';
  if (/^[0-9a-f]{40,}$/i.test(s)) return 'v-hash';
  return '';
}
/* Nothing matched is a result, not a failure. Restate the question, then hand
   over the two moves that usually find it: search the words instead of the
   key, or drop the filter. */
function qNoResults() {
  const box = el('div', 'nores');
  box.appendChild(el('div', 't', 'Nothing matched'));
  box.appendChild(el('div', 'd', 'The query ran without error — this memory simply holds nothing '
    + (describeQuery(Q.text) || 'matching it') + '. Memories are only ever added, so an empty '
    + 'answer means it was never written, not that it was removed.'));
  const acts = el('div', 'acts');
  const about = (Q.text.match(/subject\s*=\s*"([^"]+)"/i) || [])[1];
  if (about) {
    const b = el('button', 'btn ghost sm', 'Search the words instead');
    b.onclick = () => { const s = 'RECALL facts ABOUT "' + about + '"'; setQueryText(s); runQuery(s); };
    acts.appendChild(b);
  }
  if (/\bWHERE\b/i.test(Q.text)) {
    const b = el('button', 'btn ghost sm', 'Drop the filter');
    b.onclick = () => { const s = Q.text.replace(/\s+WHERE\b[\s\S]*?(?=\s+(?:LIMIT|ORDER|FORMAT|COUNT)\b|$)/i, '');
      setQueryText(s.trim()); runQuery(s.trim()); };
    acts.appendChild(b);
  }
  const b = el('button', 'btn ghost sm', 'Start over');
  b.onclick = resetQuery; acts.appendChild(b);
  box.appendChild(acts);
  return box;
}
/* EXPLAIN answers "how would you run this", so render the plan rather than
   dropping the reader into raw JSON. The engine ignores FORMAT here — it has
   no rows to render — which is worth saying out loud, because asking for
   `EXPLAIN … FORMAT markdown` and getting no markdown tab looks like a bug. */
const PLAN_LABEL = { query_routing: 'routing', index_usage: 'index', estimated_cost: 'cost',
  grain_type: 'reads', statement_type: 'statement', pipeline: 'pipeline', filters: 'filters' };
function qPlan(r) {
  const plan = r.plan || {};
  const wrap = el('div', 'planv');
  const order = ['statement_type', 'query_routing', 'index_usage', 'estimated_cost',
    'filters', 'pipeline', 'grain_type'];
  const keys = order.filter(k => k in plan).concat(Object.keys(plan).filter(k => !order.includes(k)));
  for (const k of keys) {
    const v = plan[k];
    const row = el('div', 'prow');
    row.appendChild(el('b', null, PLAN_LABEL[k] || k.replace(/_/g, ' ')));
    row.appendChild(el('span', null, Array.isArray(v) ? v.join(' · ') : String(v)));
    wrap.appendChild(row);
  }
  if (/\bFORMAT\b/i.test(Q.text)) {
    const n = el('div', 'pnote', 'FORMAT is ignored by EXPLAIN — a plan has no rows to render, '
      + 'so no rendered tab appears. Run the same query without EXPLAIN to see it formatted.');
    wrap.appendChild(n);
  }
  return wrap;
}
function qCards(gs) {
  const host = el('div'); host.id = 'qcards';
  if (!gs.length) return qNoResults();
  for (const g of gs) {
    const f = rgFields(g), t = rgType(g);
    const c = el('div', 'qcard');
    const hd = el('div', 'hd');
    const k = el('span', 'kind', t || 'grain');
    k.style.color = 'var(' + (GRAIN_VAR[t] || '--cat-thing') + ')';
    hd.appendChild(k);
    const sp = el('div'); sp.style.flex = '1'; hd.appendChild(sp);
    if (g.hlc) hd.appendChild(el('span', 'tiny', relTime(hlcMs(g.hlc))));
    c.appendChild(hd);
    c.appendChild(el('div', 'say', sentence({ type: t, fields: f })));
    for (const [key, val] of Object.entries(f)) {
      if (CARD_SKIP.has(key)) continue;
      const row = el('div', 'kv');
      row.appendChild(el('b', null, key.replace(/_/g, ' ')));
      row.appendChild(el('span', valueClass(key, val), fmtValue(key, val)));
      c.appendChild(row);
    }
    if (g.hash) {
      const h = el('div', 'mono dev-only', g.hash.slice(0, 20));
      c.appendChild(h);
      c.style.cursor = 'pointer';
      c.onclick = () => openPanel(g.hash);
    }
    host.appendChild(c);
  }
  return host;
}
/* Measure the *content*, not the box. Once a card is placed it is already
   constrained to its grid rows, so reading the rendered height feeds the
   previous answer back in — collapse to one row first, then measure
   scrollHeight (overflow is hidden, so that is the natural height). */
function layoutMasonry() {
  const grid = $('qcards'); if (!grid) return;
  const rowH = 8, gutter = 16;
  for (const c of grid.children) c.style.gridRowEnd = 'span 1';
  void grid.offsetHeight;
  for (const c of grid.children) {
    c.style.gridRowEnd = 'span ' + Math.ceil((c.scrollHeight + gutter) / rowH);
  }
}
function qTable(gs) {
  if (!gs.length) return qNoResults();
  const freq = new Map();
  for (const g of gs) for (const k of Object.keys(rgFields(g))) freq.set(k, (freq.get(k) || 0) + 1);
  /* A memory reads subject → relation → object; sorting columns by how often
     a field appears put object before subject and inverted the sentence. Pin
     the triple in reading order, then the rest by frequency. */
  const LEAD = ['subject', 'relation', 'object'];
  const rest = [...freq.entries()].sort((a, b) => b[1] - a[1]).map(e => e[0])
    .filter(k => k !== 'type' && !LEAD.includes(k));
  const cols = LEAD.filter(k => freq.has(k)).concat(rest).slice(0, 8);
  const wrap = el('div'); wrap.style.overflowX = 'auto';
  const tb = document.createElement('table'); tb.id = 'qtable';
  const thead = document.createElement('thead'); const hr = document.createElement('tr');
  hr.appendChild(el('th', null, 'kind'));
  for (const c of cols) hr.appendChild(el('th', null, c.replace(/_/g, ' ')));
  thead.appendChild(hr); tb.appendChild(thead);
  const tbody = document.createElement('tbody');
  for (const g of gs) {
    const tr = document.createElement('tr');
    tr.style.cursor = g.hash ? 'pointer' : 'default';
    if (g.hash) tr.onclick = () => openPanel(g.hash);
    const kd = el('td', null, rgType(g) || '');
    kd.style.color = 'var(' + (GRAIN_VAR[rgType(g)] || '--cat-thing') + ')';
    tr.appendChild(kd);
    for (const c of cols) {
      const v = rgFields(g)[c];
      tr.appendChild(el('td', valueClass(c, v), fmtValue(c, v)));
    }
    tbody.appendChild(tr);
  }
  tb.appendChild(tbody); wrap.appendChild(tb);
  return wrap;
}
function qFormats(r) {
  const map = rType(r) === 'multi_formatted' ? (r.formats || {}) : { [r.format || 'text']: r.text || '' };
  const names = Object.keys(map);
  const wrap = el('div'); wrap.style.cssText = 'display:flex;flex-direction:column;gap:12px;padding-top:14px';
  /* Which format to show now lives in Q.view. Test for the key, not the text:
     a renderer that produced "" is still a format you asked for, and treating
     it as missing made an empty tab impossible to select. */
  const want = String(Q.view).startsWith('fmt:') ? String(Q.view).slice(4) : null;
  Q.fmtTab = (want != null && want in map) ? want : names[0];
  const text = map[Q.fmtTab] != null ? map[Q.fmtTab] : '';
  if (!text) wrap.appendChild(el('div', 'pnote', 'The ' + Q.fmtTab + ' renderer returned nothing — '
    + 'there were no grains to render. The query ran fine; it simply matched nothing.'));
  else wrap.appendChild(Q.fmtTab === 'json' ? jsonBlock(text) : el('pre', 'code', text));
  const row = el('div'); row.style.cssText = 'display:flex;gap:9px';
  const cp = el('button', 'btn ghost sm', 'Copy');
  cp.onclick = () => copyText(text, Q.fmtTab);
  const meta = FMT_META[Q.fmtTab] || ['txt', 'text/plain'];
  const dl = el('button', 'btn ghost sm', 'Download .' + meta[0]);
  dl.onclick = () => download('areev-result.' + meta[0], text, meta[1]);
  row.appendChild(cp); row.appendChild(dl);
  wrap.appendChild(row);
  return wrap;
}
function qHistory(r) {
  const wrap = el('div'); wrap.style.paddingTop = '10px';
  for (const v of (r.versions || [])) {
    const row = el('div', 'srow');
    const f = v.fields || {};
    row.appendChild(el('span', 't', typeof f.object === 'string' ? f.object : preview(f)));
    row.appendChild(el('span', 'w', relTime(hlcMs(v.hlc))));
    if (v.hash) { row.style.cursor = 'pointer'; row.onclick = () => openPanel(v.hash); }
    wrap.appendChild(row);
  }
  return wrap;
}
function qGraphNote(gs) {
  const wrap = el('div'); wrap.style.paddingTop = '14px';
  wrap.appendChild(el('div', 'meta', 'Showing these ' + gs.length + ' results as a graph — '
    + 'scroll to zoom, drag the background to pan, drag a node to move it, click one to explore it.'));
  const stage = el('div'); stage.id = 'qstage'; stage.style.marginTop = '10px';
  const cv = document.createElement('canvas');
  cv.id = 'qcanvas';
  stage.appendChild(cv);
  const zoom = el('div', 'float'); zoom.id = 'qzoom';
  const btn = (txt, title, cls) => { const b = el('button', cls, txt); b.title = title; return b; };
  const bOut = btn('−', 'zoom out'), bIn = btn('+', 'zoom in'), bFit = btn('Fit', 'fit to view', 'lbl');
  zoom.append(bOut, bIn, bFit);
  stage.appendChild(zoom);
  wrap.appendChild(stage);
  /* The canvas has no layout size until it is in the document. */
  requestAnimationFrame(() => drawResultGraph(cv, gs, { zin: bIn, zout: bOut, fit: bFit }));
  return wrap;
}
/* Assembly is Areev's differentiator — show where the budget went. */
function assembledSources(r) {
  const wrap = el('div'); wrap.style.cssText = 'display:flex;flex-direction:column;gap:8px;padding:14px 0';
  const cap = r.budget_limit || r.total_tokens || 1;
  wrap.appendChild(el('span', 'sec-label', 'ASSEMBLY BUDGET · ' + (r.total_tokens || 0)
    + (r.budget_limit ? ' of ' + r.budget_limit : '') + ' tokens'));
  for (const s of (r.sources || [])) {
    const row = el('div'); row.style.cssText = 'display:flex;align-items:center;gap:12px';
    const n = el('span', null, s.name || s.label || 'source');
    n.style.cssText = 'width:150px;flex-shrink:0;font-size:13.5px;color:var(--ink)';
    row.appendChild(n);
    const track = el('div'); track.style.cssText = 'flex:1;height:8px;border-radius:4px;background:var(--raise)';
    const fill = el('div');
    const pct = Math.max(2, Math.round(100 * (s.tokens || 0) / cap));
    fill.style.cssText = 'height:8px;border-radius:4px;background:var(--accent);width:' + pct + '%';
    track.appendChild(fill); row.appendChild(track);
    row.appendChild(el('span', 'tiny', (s.tokens || 0) + ' tok · ' + (s.grain_count != null ? s.grain_count + ' grains' : '')));
    wrap.appendChild(row);
  }
  return wrap;
}

/* A compact, self-contained layout for result graphs. Deliberately separate
   from the memory graph: that one owns rewind, depth and focus state, and
   entangling the two would make both harder to reason about. */
function drawResultGraph(cv, gs, ctrls) {
  const ctx = cv.getContext('2d');
  const nodes = new Map(), links = [];
  const add = n => { if (!nodes.has(n)) nodes.set(n, { id: n, x: (Math.random() - .5) * 260,
    y: (Math.random() - .5) * 260, vx: 0, vy: 0, deg: 0 }); return nodes.get(n); };
  for (const g of gs) {
    const f = rgFields(g);
    if (!f.subject || typeof f.object !== 'string' || !f.object) continue;
    const a = add(f.subject), b = add(f.object);
    a.deg++; b.deg++;
    links.push({ a: f.subject, b: f.object, label: String(f.relation || '').replace(/_/g, ' ') });
  }
  const list = [...nodes.values()];
  if (!list.length) { ctx.clearRect(0, 0, cv.width, cv.height); return; }
  /* Settle once, up front: the layout is the answer's shape, and a graph that
     keeps drifting under the cursor is harder to read than one that holds
     still. Everything after this is view state — the node positions only move
     when a person drags them. */
  for (let step = 0; step < 320; step++) {
    const k = Math.max(0.05, 1 - step / 320);
    for (let i = 0; i < list.length; i++) for (let j = i + 1; j < list.length; j++) {
      const a = list[i], b = list[j];
      let dx = b.x - a.x, dy = b.y - a.y, d2 = dx * dx + dy * dy;
      if (d2 < 1) { dx = Math.random(); dy = Math.random(); d2 = 1; }
      if (d2 > 160000) continue;
      const d = Math.sqrt(d2), f = (4200 * k) / d2;
      a.vx -= dx / d * f; a.vy -= dy / d * f; b.vx += dx / d * f; b.vy += dy / d * f;
    }
    for (const l of links) {
      const a = nodes.get(l.a), b = nodes.get(l.b);
      const dx = b.x - a.x, dy = b.y - a.y, d = Math.max(1, Math.hypot(dx, dy));
      const f = (d - 150) * 0.015 * k;
      a.vx += dx / d * f; a.vy += dy / d * f; b.vx -= dx / d * f; b.vy -= dy / d * f;
    }
    for (const n of list) { n.vx += -n.x * 0.005 * k; n.vy += -n.y * 0.005 * k;
      n.x += (n.vx *= 0.82); n.y += (n.vy *= 0.82); }
  }
  /* ── view state: one pan/zoom transform over settled world coordinates ── */
  let scale = 1, tx = 0, ty = 0, W = 0, H = 0, hover = null, touched = false;
  const radius = n => 12 + Math.min(16, n.deg * 3);
  const MIN_SCALE = 0.2, MAX_SCALE = 4;
  function fit() {
    let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
    for (const n of list) { const r = radius(n);
      x0 = Math.min(x0, n.x - r - 50); x1 = Math.max(x1, n.x + r + 50);
      y0 = Math.min(y0, n.y - r - 26); y1 = Math.max(y1, n.y + r + 26); }
    scale = Math.max(0.25, Math.min(1.3, Math.min(W / (x1 - x0), H / (y1 - y0))));
    tx = W / 2 - (x0 + x1) / 2 * scale;
    ty = H / 2 - (y0 + y1) / 2 * scale;
  }
  const toWorld = e => { const r = cv.getBoundingClientRect();
    return { x: (e.clientX - r.left - tx) / scale, y: (e.clientY - r.top - ty) / scale }; };
  /* Topmost first, so the node you see on top is the one you grab. */
  const hit = p => { for (let i = list.length - 1; i >= 0; i--) { const n = list[i];
    if (Math.hypot(n.x - p.x, n.y - p.y) <= radius(n) + 4) return n; } return null; };
  function resize() {
    W = cv.clientWidth; H = cv.clientHeight;
    const dpr = window.devicePixelRatio || 1;
    cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr);
  }
  /* Coalesce to one paint per frame — a trackpad emits wheel events far faster
     than the display refreshes. */
  let queued = false;
  const redraw = () => { if (queued) return; queued = true;
    requestAnimationFrame(() => { queued = false; draw(); }); };
  /* Zoom about a point in canvas space, so the thing under the cursor (or the
     middle, for the buttons) stays put. */
  function zoomAt(px, py, factor) {
    const next = Math.max(MIN_SCALE, Math.min(MAX_SCALE, scale * factor));
    if (next === scale) return;
    tx = px - (px - tx) * (next / scale);
    ty = py - (py - ty) * (next / scale);
    scale = next; touched = true; redraw();
  }

  function draw() {
    const dpr = window.devicePixelRatio || 1;
    const ink = cssVar('--ink'), line = cssVar('--line2'), accent = cssVar('--accent'),
          well = cssVar('--well'), dim = cssVar('--dim');
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.clearRect(0, 0, W, H);
    ctx.save();
    ctx.translate(tx, ty); ctx.scale(scale, scale);
    ctx.strokeStyle = line; ctx.lineWidth = 1.5;
    for (const l of links) { const a = nodes.get(l.a), b = nodes.get(l.b);
      ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke(); }
    const halo = (t, x, y, font, fill) => { ctx.font = font; ctx.textAlign = 'center';
      ctx.lineWidth = 3.5; ctx.lineJoin = 'round'; ctx.strokeStyle = well; ctx.strokeText(t, x, y);
      ctx.fillStyle = fill; ctx.fillText(t, x, y); };
    if (scale > 0.5) for (const l of links) {
      const a = nodes.get(l.a), b = nodes.get(l.b);
      const len = Math.hypot(b.x - a.x, b.y - a.y);
      if (!l.label || len < 130) continue;
      const nx = -(b.y - a.y) / len, ny = (b.x - a.x) / len;
      halo(l.label, (a.x + b.x) / 2 + nx * 11, (a.y + b.y) / 2 + ny * 11 + 4, '12px ' + cssVar('--sans'), dim);
    }
    for (const n of list) {
      const r = radius(n);
      if (n.id === hover) { ctx.strokeStyle = accent; ctx.lineWidth = 2 / scale;
        ctx.beginPath(); ctx.arc(n.x, n.y, r + 4, 0, 7); ctx.stroke(); }
      ctx.fillStyle = accent; ctx.globalAlpha = 0.9;
      ctx.beginPath(); ctx.arc(n.x, n.y, r, 0, 7); ctx.fill();
      ctx.globalAlpha = 1;
      halo(n.id.length > 22 ? n.id.slice(0, 21) + '…' : n.id, n.x, n.y + r + 16,
        '600 13px ' + cssVar('--sans'), ink);
    }
    ctx.restore();
  }

  /* ── interaction ──
     Drag listeners live on the window only while a gesture is running, so a
     result graph that gets replaced (every re-render builds a new canvas)
     leaves nothing behind. */
  cv.addEventListener('mousedown', e => {
    e.preventDefault();
    const p = toWorld(e), n = hit(p);
    let moved = false;
    const drag = n ? { id: n.id, dx: n.x - p.x, dy: n.y - p.y } : null;
    const pan = n ? null : { x: e.clientX - tx, y: e.clientY - ty };
    if (pan) cv.classList.add('grabbing');
    const move = ev => {
      moved = moved || Math.abs(ev.clientX - e.clientX) + Math.abs(ev.clientY - e.clientY) > 3;
      if (drag) { const q = toWorld(ev); const t = nodes.get(drag.id);
        if (t) { t.x = q.x + drag.dx; t.y = q.y + drag.dy; } }
      else { tx = ev.clientX - pan.x; ty = ev.clientY - pan.y; }
      touched = true; redraw();
    };
    const up = () => {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseup', up);
      cv.classList.remove('grabbing');
      /* A click that never moved is a click, not a gesture. */
      if (n && !moved) runQuery('RECALL facts WHERE subject = "' + n.id.replace(/"/g, '') + '" LIMIT 50');
    };
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseup', up);
  });
  cv.addEventListener('mousemove', e => {
    const n = hit(toWorld(e));
    const id = n ? n.id : null;
    cv.style.cursor = n ? 'pointer' : 'grab';
    if (id !== hover) { hover = id; redraw(); }
  });
  cv.addEventListener('mouseleave', () => { if (hover) { hover = null; redraw(); } });
  cv.addEventListener('wheel', e => {
    e.preventDefault();
    const r = cv.getBoundingClientRect();
    /* macOS trackpad pinch arrives as ctrl+wheel — finer steps, or it snaps. */
    const f = e.ctrlKey ? Math.exp(-e.deltaY * 0.01) : (e.deltaY < 0 ? 1.12 : 0.89);
    zoomAt(e.clientX - r.left, e.clientY - r.top, f);
  }, { passive: false });
  cv.addEventListener('dblclick', () => { touched = false; fit(); redraw(); });
  if (ctrls) {
    ctrls.zin.onclick = () => zoomAt(W / 2, H / 2, 1.2);
    ctrls.zout.onclick = () => zoomAt(W / 2, H / 2, 1 / 1.2);
    ctrls.fit.onclick = () => { touched = false; fit(); redraw(); };
  }
  /* Re-fit on resize only while the view is untouched: once someone has zoomed
     somewhere deliberately, yanking them back to the whole graph is worse. */
  const ro = new ResizeObserver(() => {
    if (!cv.isConnected) { ro.disconnect(); return; }
    if (!cv.clientWidth) return;
    resize(); if (!touched) fit(); redraw();
  });
  ro.observe(cv);

  resize(); fit(); draw();
}

/* ── menus: saved queries, templates, history, formats ── */
function openMenu(id, build) {
  const m = $(id);
  const wasOpen = !m.hidden;
  for (const x of document.querySelectorAll('.menu')) x.hidden = true;
  if (wasOpen) return;
  m.textContent = '';
  build(m);
  m.hidden = false;
}
document.addEventListener('click', e => {
  if (!e.target.closest('.menuwrap')) for (const x of document.querySelectorAll('.menu')) x.hidden = true;
});
function mi(parent, label, sub, fn) {
  const d = el('div', 'mi');
  d.appendChild(document.createTextNode(label));
  if (sub) d.appendChild(el('small', null, sub));
  d.onclick = fn;
  parent.appendChild(d);
  return d;
}
const FORMATS = ['sml', 'toon', 'markdown', 'json', 'yaml', 'csv', 'table', 'triples'];
function setFormat(spec) {
  let t = $('qtext').value.trim().replace(/\s+FORMAT\s+(\[[^\]]*\]|preset\s+"[^"]*"|template\s+"[^"]*"|\w+)\s*$/i, '');
  $('qtext').value = t + ' FORMAT ' + spec;
  runQuery();
}
function buildFormatMenu(m) {
  m.appendChild(el('div', 'sep', 'RENDER AS'));
  for (const f of FORMATS) mi(m, f, null, () => setFormat(f));
  m.appendChild(el('div', 'sep', 'SEVERAL AT ONCE'));
  mi(m, 'json + markdown', 'FORMAT [json AS data, markdown AS readable]',
    () => setFormat('[json AS data, markdown AS readable]'));
  mi(m, 'sml + markdown', 'FORMAT [sml AS compact, markdown AS readable]',
    () => setFormat('[sml AS compact, markdown AS readable]'));
}
function buildHistoryMenu(m) {
  const h = histLoad();
  if (!h.length) { m.appendChild(el('div', 'sep', 'NOTHING YET')); return; }
  m.appendChild(el('div', 'sep', 'THIS BROWSER ONLY · ' + h.length));
  for (const it of h.slice(0, 40)) {
    mi(m, (it.s || 'ran') + ' · ' + relTime(it.at), it.q, () => runQuery(it.q));
  }
  const c = mi(m, 'Clear history', null, () => {
    localStorage.removeItem(histKey()); toast('History cleared'); openMenu('histMenu', buildHistoryMenu);
  });
  c.style.color = 'var(--danger)';
}
/* DESCRIBE returns a free-form `info` blob; find the list wherever it is. */
function pickList(info) {
  if (Array.isArray(info)) return info;
  if (info && typeof info === 'object') {
    for (const k of ['queries', 'templates', 'items', 'names', 'list']) if (Array.isArray(info[k])) return info[k];
    for (const v of Object.values(info)) if (Array.isArray(v)) return v;
  }
  return [];
}
const itemName = it => typeof it === 'string' ? it : (it.name || it.id || JSON.stringify(it).slice(0, 40));
const itemDesc = it => typeof it === 'string' ? '' : (it.description || it.desc || '');
async function buildSavedMenu(m) {
  if (!stmtSupported('DEFINE')) {
    const n = el('div', 'mi', 'This build cannot save queries or templates — the memory file '
      + 'has no registry for them yet. DESCRIBE QUERIES still lists any that exist.');
    n.style.cssText = 'color:var(--warn);white-space:normal;cursor:default';
    m.appendChild(n);
  }
  m.appendChild(el('div', 'sep', 'SAVED QUERIES'));
  const loading = el('div', 'mi', 'loading…'); m.appendChild(loading);
  const [qs, ts] = await Promise.all([cal('DESCRIBE QUERIES'), cal('DESCRIBE TEMPLATES')]);
  loading.remove();
  const qlist = qs.ok ? pickList((qs.result || {}).info) : [];
  if (!qlist.length) m.appendChild(el('div', 'mi', qs.ok ? 'none saved yet' : 'could not list'));
  for (const it of qlist) {
    const n = itemName(it);
    mi(m, n, itemDesc(it) || 'RUN "' + n + '"', () => runQuery('RUN "' + n + '"'));
  }
  m.appendChild(el('div', 'sep', 'TEMPLATES'));
  const tlist = ts.ok ? pickList((ts.result || {}).info) : [];
  if (!tlist.length) m.appendChild(el('div', 'mi', ts.ok ? 'none defined yet' : 'could not list'));
  for (const it of tlist) {
    const n = itemName(it);
    mi(m, n, 'FORMAT preset "' + n + '"', () => setFormat('preset "' + n + '"'));
  }
}
async function saveCurrentQuery() {
  const body = $('qtext').value.trim();
  if (!body) { toast('Nothing to save'); return; }
  if (!stmtSupported('DEFINE')) {
    toast('This build cannot save queries — DEFINE is not in the engine’s supported statements');
    return;
  }
  if (!canWrite()) { toast('Saving needs a console started with --token-env'); return; }
  const name = window.prompt('Name this query (letters, numbers, spaces, _ and -):');
  if (!name) return;
  if (!QUERY_NAME_RE.test(name)) { toast('That name will not be accepted — start with a letter, max 64 chars'); return; }
  const desc = window.prompt('Describe it (optional):') || '';
  const stmt = 'DEFINE QUERY "' + name + '"'
    + (desc ? ' DESCRIPTION "' + desc.replace(/"/g, "'") + '"' : '')
    + ' AS { ' + body + ' }';
  const res = await cal(stmt);
  if (res.ok) toast('Saved — it lives in the memory file, not this browser');
  else toast('Could not save: ' + (res.error || 'unknown') + (res.code ? ' [' + res.code + ']' : ''));
}

boot();
</script>