semlith 0.17.1

A fast local vector store for AI agents — index files once, keep it current as you save, and answer questions across all of it in milliseconds without leaving the machine.
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
/* semlith portal
 *
 * Plain DOM, no framework, no build step. The whole file is served from the
 * binary, so there is nothing to bundle and nothing to fetch: what you read
 * here is what runs.
 *
 * Every view is a function that returns an element, and the router swaps one
 * for another inside <main>. The shell around it — topbar, rail, drawer — is
 * built once and then mutated in place. That split matters: rebuilding the
 * shell to open a menu used to re-run the current view, which re-hit the API
 * and threw away whatever the user had typed into it.
 */

"use strict";

// ---------------------------------------------------------------- helpers

/** Build an element. Attributes in `props`, children as the rest. */
function el(tag, props, ...kids) {
  const node = document.createElement(tag);
  for (const [key, value] of Object.entries(props || {})) {
    if (value === null || value === undefined || value === false) continue;
    if (key === "class") node.className = value;
    else if (key === "text") node.textContent = value;
    else if (key.startsWith("on")) node.addEventListener(key.slice(2), value);
    else node.setAttribute(key, value === true ? "" : String(value));
  }
  for (const kid of kids.flat()) {
    if (kid === null || kid === undefined || kid === false) continue;
    node.append(kid.nodeType ? kid : document.createTextNode(String(kid)));
  }
  return node;
}

/** Replace an element's children. */
function fill(node, ...kids) {
  node.replaceChildren();
  for (const kid of kids.flat()) {
    if (kid === null || kid === undefined || kid === false) continue;
    node.append(kid.nodeType ? kid : document.createTextNode(String(kid)));
  }
  return node;
}

/* The session token.
 *
 * It arrives once, in the query of the URL the daemon printed, and from then on
 * it lives in this page and in sessionStorage — never in a cookie. A cookie
 * would be attached to a request any page on any other 127.0.0.1 port made,
 * because every port on localhost is the same site; a header is attached only
 * by this page.
 *
 * The token is taken out of the address bar as soon as it is read, so it is not
 * in the history, not in a bookmark, and not in what someone screenshots. The
 * reload path is why sessionStorage is here at all: refreshing the page sends a
 * request this script did not make, so the URL it reloads must not need to
 * carry the token.
 */
const TOKEN_HEADER = "Semlith-Token";

const session = (() => {
  const KEY = "semlith.token";
  let token = "";
  try {
    const fromUrl = new URLSearchParams(location.search).get("token");
    if (fromUrl) {
      token = fromUrl;
      sessionStorage.setItem(KEY, token);
      const clean = location.pathname + location.hash;
      history.replaceState(null, "", clean || "/");
    } else {
      token = sessionStorage.getItem(KEY) || "";
    }
  } catch (_) {
    /* A browser with storage disabled still works for as long as this document
     * lives; only the reload stops surviving. */
  }
  return {
    get: () => token,
    set(fresh) {
      token = fresh;
      try {
        sessionStorage.setItem(KEY, fresh);
      } catch (_) {
        /* as above */
      }
    },
  };
})();

/** The headers every request to this daemon carries. */
function authed(extra) {
  return { ...(extra || {}), [TOKEN_HEADER]: session.get() };
}

/* An image the store indexed, fetched rather than linked.
 *
 * A browser attaches no header to an `<img src>`, and since 0.14.0 the token is
 * a header, so the bytes are read through `fetch` and handed to the element
 * directly.
 *
 * A `data:` URL rather than an object URL, which is what this used until
 * 0.16.0 and why no preview ever appeared: the policy the server sends is
 * `img-src 'self' data:`, and a `blob:` URL is neither, so every one of them
 * was refused before it decoded. `data:` costs the base64 third and has no
 * handle to revoke — acceptable because the body panel holds one picture at a
 * time. Widening the policy to `blob:` would have been the other fix, and the
 * policy is the thing this product is checkable on. */
function imagePreview(path) {
  const img = el("img", { class: "preview", alt: "" });
  const failed = () =>
    img.replaceWith(el("pre", { class: "muted", text: `${path} could not be read` }));
  fetch(`/api/image?path=${encodeURIComponent(path)}`, {
    credentials: "omit",
    headers: authed(),
  })
    .then((response) => (response.ok ? response.blob() : Promise.reject(response.statusText)))
    .then((blob) => {
      const reader = new FileReader();
      reader.onload = () => {
        img.src = String(reader.result);
      };
      reader.onerror = failed;
      reader.readAsDataURL(blob);
    })
    .catch(failed);
  return img;
}

async function api(path, options) {
  const options_ = options || {};
  const response = await fetch(path, {
    // No cookie is sent because there is none to send, and saying so keeps a
    // future one from being attached by accident.
    credentials: "omit",
    ...options_,
    headers: authed(options_.headers),
  });
  if (!response.ok) {
    let detail = response.statusText;
    try {
      const body = await response.json();
      if (body && body.error) detail = body.error;
    } catch (_) {
      /* an empty body is what 401 sends on purpose */
    }
    throw new Error(detail || "request failed");
  }
  return response.json();
}

function post(path, body) {
  return api(path, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });
}

const NUM = new Intl.NumberFormat();
const n = (value) => NUM.format(value || 0);

function bytes(value) {
  const units = ["B", "KB", "MB", "GB", "TB"];
  let size = Number(value) || 0;
  let unit = 0;
  while (size >= 1024 && unit < units.length - 1) {
    size /= 1024;
    unit += 1;
  }
  return `${unit === 0 ? size : size.toFixed(1)} ${units[unit]}`;
}

function when(unix) {
  if (!unix) return "never";
  const seconds = Math.max(0, Math.floor(Date.now() / 1000) - unix);
  if (seconds < 60) return `${seconds}s ago`;
  if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
  if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
  return `${Math.floor(seconds / 86400)}d ago`;
}

function clock(unix) {
  return new Date(unix * 1000).toTimeString().slice(0, 8);
}

const SVG_NS = "http://www.w3.org/2000/svg";

/** An inline icon. Decorative: the control around it carries the name. */
function icon(d, size, solid) {
  const svg = document.createElementNS(SVG_NS, "svg");
  svg.setAttribute("viewBox", "0 0 24 24");
  svg.setAttribute("width", String(size || 16));
  svg.setAttribute("height", String(size || 16));
  // A shape that is a shape rather than a stroke — the three dots of a menu
  // control. Drawn as strokes they are zero-length segments whose whole size
  // is the line width, which is as faint as a mark can be.
  svg.setAttribute("fill", solid ? "currentColor" : "none");
  svg.setAttribute("stroke", solid ? "none" : "currentColor");
  svg.setAttribute("stroke-width", "1.7");
  svg.setAttribute("stroke-linecap", "round");
  svg.setAttribute("stroke-linejoin", "round");
  svg.setAttribute("aria-hidden", "true");
  for (const segment of String(d).split("|")) {
    const path = document.createElementNS(SVG_NS, "path");
    path.setAttribute("d", segment);
    svg.append(path);
  }
  return svg;
}

const ICONS = {
  menu: "M4 7h16|M4 12h16|M4 17h16",
  search: "M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14z|M20 20l-3.5-3.5",
  plus: "M12 5v14|M5 12h14",
  sun: "M12 3v2|M12 19v2|M3 12h2|M19 12h2|M5.6 5.6 7 7|M17 17l1.4 1.4|M18.4 5.6 17 7|M7 17l-1.4 1.4|M12 7.8a4.2 4.2 0 1 0 0 8.4 4.2 4.2 0 0 0 0-8.4z",
  folder: "M3 7.5A1.5 1.5 0 0 1 4.5 6h4l2 2.5h7A1.5 1.5 0 0 1 19 10v7a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 3 17z",
  file: "M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z|M14 3v5h5",
  up: "M5 12h14|M11 6l-6 6 6 6",
  alert: "M12 9v4|M12 17h.01|M12 4 3 19h18z",
  moon: "M20 14.5A8.5 8.5 0 0 1 9.5 4a8.5 8.5 0 1 0 10.5 10.5z",
  copy: "M9 9h9a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1v-9a1 1 0 0 1 1-1z|M6 15H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h9a1 1 0 0 1 1 1v1",
  // Three filled dots, as circles rather than as dotted strokes.
  more:
    "M12 4.1a2 2 0 1 0 0 4 2 2 0 0 0 0-4z|M12 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4z|"
    + "M12 15.9a2 2 0 1 0 0 4 2 2 0 0 0 0-4z",
};

/* The nav marks, from the design. `|` separates subpaths so one mark can be
 * more than a single stroke. */
const NAV_ICONS = {
  stores: "M12 4l8 4-8 4-8-4 8-4|M4 12l8 4 8-4|M4 16.5l8 4 8-4",
  files: "M6 3h7l5 5v13H6z|M13 3v5h5",
  index: "M4 6h16|M4 12h10|M4 18h13",
  search: "M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14z|M16.2 16.2 20 20",
  graph: "M5 6h4v4H5z|M15 14h4v4h-4z|M9 8h4v8h2",
  ledger: "M5 4h11l3 3v13H5z|M9 9h6|M9 13h6|M9 17h4",
  agents: "M9 3h6v5H9z|M12 8v3|M5 11h14v9H5z|M9 15h.01|M15 15h.01",
  privacy: "M12 3l7 3v6c0 4.3-3 7.3-7 9-4-1.7-7-4.7-7-9V6z",
  about: "M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16z|M12 11v5|M12 8h.01",
};

/** A button that copies text and says so for a moment.
 *
 * Invisible until the pointer enters the block it belongs to — see `.copy` in
 * the stylesheet — so a page never shows a column of copy buttons competing
 * with the content they copy. */
function copyButton(getText, label, word) {
  const was = label || "Copy";
  // A field wide enough to hold a command has room for the word; the icon is
  // for a code block, where the control sits over the text it copies.
  const face = () => (word ? was : icon(ICONS.copy, 14));
  const button = el("button", {
    class: "button secondary small copy",
    type: "button",
    "aria-label": was,
    title: was,
    onclick: async () => {
      const text = typeof getText === "function" ? getText() : getText;
      try {
        await navigator.clipboard.writeText(text);
      } catch (_) {
        // No clipboard permission, or an insecure context. Selecting the text
        // is still a way to copy it, and silently doing nothing is not.
        const area = el("textarea", { class: "offscreen" });
        area.value = text;
        document.body.append(area);
        area.select();
        try {
          document.execCommand("copy");
        } catch (__) {
          /* nothing else to try */
        }
        area.remove();
      }
      button.classList.add("done");
      fill(button, "Copied");
      setTimeout(() => {
        button.classList.remove("done");
        fill(button, face());
      }, 1400);
    },
  });
  fill(button, face());
  return button;
}

function copyField(command, word) {
  return el(
    "div",
    { class: word ? "copyfield worded" : "copyfield" },
    el("code", { class: "text", text: command }),
    copyButton(command, "Copy", word),
  );
}

/** A code block with its copy control over the top-right corner. */
function codeBlock(text, label) {
  return el(
    "div",
    { class: "code-block" },
    el("pre", { class: "code", text }),
    copyButton(text, label || "Copy"),
  );
}

/* A command, a path or an identifier set inside a sentence.
 *
 * This is what makes the capitalisation rule read as a rule rather than as a
 * typo: the product is "Semlith" in prose and `semlith` is a command, and the
 * only thing that tells a reader which one they are looking at is that one of
 * them is set in mono. */
function mono(text) {
  return el("code", { class: "mono", text });
}

/** A paragraph of prose, where any part may be a mono command. */
function says(...parts) {
  return el("p", { class: "subtitle" }, parts);
}

/** A failure. Coloured like a problem, because it is one. */
function error(message) {
  return el(
    "div",
    { class: "error", role: "alert" },
    icon(ICONS.alert, 17),
    el("span", { class: "what", text: message }),
  );
}

/** An absence. Nothing went wrong; there is simply nothing here. */
function empty(message) {
  return el("div", { class: "empty" }, message);
}

/* ------------------------------------------------------------------- tips */

/* One tooltip for the whole portal.
 *
 * The element lives at the end of <body> and is positioned against the
 * viewport, which is the whole point: the previous implementation was a
 * `::after` on the element being described, and `.table-wrap` carries
 * `overflow: auto`, so a scroll container clipped it. The Files page's path
 * tip — the reason the feature exists — was the one that could not be read.
 *
 * `show` takes content and the rectangle to hang it off. It prefers to sit
 * above and left-aligned, and flips or clamps when that would leave the
 * viewport. The Graph canvas uses the same element for its richer card, so
 * there is one implementation rather than two. */
const tip = {
  node: null,
  owner: null,

  ensure() {
    if (!this.node) {
      this.node = el("div", { class: "tip", role: "tooltip", "aria-hidden": "true" });
      document.body.append(this.node);
    }
    return this.node;
  },

  /** `content` is a string or an element; `rect` is a viewport rectangle. */
  show(content, rect, owner) {
    const node = this.ensure();
    this.owner = owner || null;
    fill(node, content);
    node.setAttribute("aria-hidden", "false");
    // Measured after filling and before positioning: the size depends on the
    // text, and a stale measurement puts the flip decision on the wrong side.
    node.dataset.open = "true";
    const box = node.getBoundingClientRect();
    const margin = 8;
    let left = rect.left;
    if (left + box.width > window.innerWidth - margin) {
      left = Math.max(margin, window.innerWidth - margin - box.width);
    }
    let top = rect.top - box.height - 6;
    // Above by default, below when there is no room — the flip the criterion
    // asks for, and the reason this is measured against the viewport.
    if (top < margin) top = rect.bottom + 6;
    node.style.left = `${Math.max(margin, Math.round(left))}px`;
    node.style.top = `${Math.round(top)}px`;
  },

  /** Hang a tip off an element. */
  at(target, content) {
    this.show(content || target.getAttribute("data-tip"), target.getBoundingClientRect(), target);
  },

  /** Hang a tip off a point, for the canvas, which has no elements to hang on. */
  atPoint(x, y, content, owner) {
    this.show(content, { left: x + 12, top: y - 8, bottom: y + 18 }, owner);
  },

  hide(owner) {
    if (!this.node) return;
    if (owner && this.owner !== owner) return;
    this.node.dataset.open = "false";
    this.node.setAttribute("aria-hidden", "true");
    this.owner = null;
  },
};

/* Delegated, so a tip costs nothing per row: every table in the portal renders
 * its rows fresh, and binding two listeners to each of a thousand cells is how
 * a scroll starts to stutter. */
function wireTips() {
  const find = (node) => (node && node.closest ? node.closest("[data-tip]") : null);

  document.addEventListener("pointerover", (e) => {
    const target = find(e.target);
    if (target) tip.at(target);
    else if (tip.owner && tip.owner.nodeType) tip.hide();
  });
  document.addEventListener("pointerout", (e) => {
    const target = find(e.target);
    if (target) tip.hide(target);
  });
  // Keyboard parity: focus shows the same label a hover does.
  document.addEventListener("focusin", (e) => {
    const target = find(e.target);
    if (target) tip.at(target);
  });
  document.addEventListener("focusout", (e) => {
    const target = find(e.target);
    if (target) tip.hide(target);
  });
  // A fixed tip does not travel with the row it describes, so it leaves when
  // the row does. Capture, because the scroll happens inside a card.
  window.addEventListener("scroll", () => tip.hide(), true);
  window.addEventListener("resize", () => tip.hide());
}

/* ----------------------------------------------------------------- table */

/* One table for the whole portal: Stores, Files, Languages, the About model
 * list and the Agents client list all render through this. Five hand-written
 * tables is how one page gains sorting and the other four do not.
 *
 * Columns are `{ key, label, className, sortable, value, render }`. `value`
 * pulls the sort key out of a row; `render` returns the cell's content. A
 * table is client-side by default — its rows are already in hand — and
 * `server: true` hands sorting and paging back to the caller instead, which is
 * what the Files table needs: sorting has to order the whole store rather than
 * the page of it that happens to be loaded.
 */
const PER_PAGE = [5, 10, 25, 50];

function dataTable(spec) {
  const columns = spec.columns;
  const view = {
    page: 1,
    perPage: spec.perPage || 10,
    sort: spec.sort || null,
    dir: spec.dir || "asc",
  };
  let rows = spec.rows || [];
  let total = spec.total === undefined ? rows.length : spec.total;

  const headRow = el("tr", {});
  const body = el("tbody", {});
  const foot = el("div", { class: "table-foot" });
  const table = el(
    "table",
    { class: spec.className || null },
    el("thead", {}, headRow),
    body,
  );
  // `grow: false` for a table that shares a page with other blocks: stretching
  // a three-row table down a 900px page to fill it is empty space pretending
  // to be a table.
  const node = el(
    "div",
    { class: spec.grow ? "card table-card grow" : "card table-card" },
    el("div", { class: "table-wrap" }, table),
    foot,
  );

  function pages() {
    return Math.max(1, Math.ceil(total / view.perPage));
  }

  function sorted() {
    if (!view.sort) return rows;
    const column = columns.find((c) => c.key === view.sort);
    if (!column || !column.value) return rows;
    const sign = view.dir === "desc" ? -1 : 1;
    // A copy: sorting the caller's array in place would reorder the data
    // behind whatever else is reading it.
    return [...rows].sort((a, b) => {
      const x = column.value(a);
      const y = column.value(b);
      if (typeof x === "number" && typeof y === "number") return (x - y) * sign;
      return String(x).localeCompare(String(y), undefined, { numeric: true }) * sign;
    });
  }

  function shown() {
    if (spec.server) return rows;
    const from = (view.page - 1) * view.perPage;
    return sorted().slice(from, from + view.perPage);
  }

  function changed() {
    if (spec.server && spec.onChange) spec.onChange({ ...view });
    else paint();
  }

  function sortBy(key) {
    if (view.sort === key) view.dir = view.dir === "asc" ? "desc" : "asc";
    else {
      view.sort = key;
      view.dir = "asc";
    }
    view.page = 1;
    changed();
  }

  function paintHead() {
    fill(
      headRow,
      columns.map((column) => {
        const on = view.sort === column.key;
        if (column.head) {
          // A header that is a control rather than a label — the select-all
          // box above a column of checkboxes.
          return el("th", { class: column.className || null }, column.head());
        }
        if (column.sortable === false) {
          return el("th", { class: column.className || null, text: column.label });
        }
        return el(
          "th",
          {
            class: column.className || null,
            "aria-sort": on ? (view.dir === "asc" ? "ascending" : "descending") : "none",
          },
          el(
            "button",
            { class: "sort", type: "button", onclick: () => sortBy(column.key) },
            column.label,
            el("span", { class: "arrow", text: on ? (view.dir === "asc" ? "↑" : "↓") : "" }),
          ),
        );
      }),
    );
  }

  function paintBody() {
    const page = shown();
    fill(
      body,
      page.map((row, i) =>
        el(
          "tr",
          {},
          columns.map((column) =>
            el(
              "td",
              { class: column.className || null },
              column.render ? column.render(row, i) : String(column.value ? column.value(row) : ""),
            ),
          ),
        ),
      ),
    );
  }

  function paintFoot() {
    const from = total === 0 ? 0 : (view.page - 1) * view.perPage + 1;
    const to = Math.min(total, view.page * view.perPage);
    fill(
      foot,
      el("span", { class: "meta", text: `${n(from)}–${n(to)} of ${n(total)}` }),
      el("span", { class: "divider-v" }),
      el("span", { class: "eyebrow", text: "per page" }),
      el(
        "span",
        { class: "chips" },
        PER_PAGE.map((size) =>
          el("button", {
            class: "chip",
            type: "button",
            "aria-pressed": String(size === view.perPage),
            text: String(size),
            onclick: () => {
              view.perPage = size;
              view.page = 1;
              changed();
            },
          }),
        ),
      ),
      el("span", { class: "spacer" }),
      el("button", {
        class: "button ghost small",
        type: "button",
        text: "Prev",
        disabled: view.page <= 1,
        onclick: () => {
          view.page -= 1;
          changed();
        },
      }),
      el("span", { class: "meta", text: `Page ${n(view.page)} / ${n(pages())}` }),
      el("button", {
        class: "button ghost small",
        type: "button",
        text: "Next",
        disabled: view.page >= pages(),
        onclick: () => {
          view.page += 1;
          changed();
        },
      }),
    );
  }

  function paint() {
    paintHead();
    paintBody();
    paintFoot();
  }

  paint();

  return {
    node,
    /** Replace the rows. `count` is the whole-store total in server mode. */
    update(next, count) {
      rows = next || [];
      total = count === undefined ? rows.length : count;
      if (view.page > pages()) view.page = pages();
      paint();
    },
    /** What the server should sort and page by. */
    query: () => ({ ...view }),
  };
}

/* The server-side folder picker.
 *
 * One component, used by the Index page to choose what to index and by the
 * Stores page to choose a directory to adopt. It browses the daemon's
 * filesystem rather than the browser's, because the daemon is what has to open
 * the path — a `<input type=file webkitdirectory>` hands over a list of file
 * objects and not the one thing needed, which is the path itself.
 */
function folderPicker(options) {
  const { onChoose, choose, onError } = options || {};
  const card = el("div", { class: "card picker", hidden: true });

  async function open(path) {
    let data;
    try {
      data = await api(`/api/dirs?path=${encodeURIComponent(path || "")}`);
    } catch (e) {
      if (onError) onError(e.message);
      return false;
    }
    card.hidden = false;
    fill(
      card,
      el(
        "div",
        { class: "crumbs" },
        el(
          "button",
          {
            class: "button secondary small",
            type: "button",
            disabled: !data.parent,
            onclick: () => open(data.parent),
          },
          icon(ICONS.up, 15),
          "Up",
        ),
        el("span", { class: "where", text: data.path }),
        el("span", { class: "spacer" }),
        el("button", {
          class: "button small",
          type: "button",
          text: choose || "Use this folder",
          onclick: () => {
            card.hidden = true;
            if (onChoose) onChoose(data.path);
          },
        }),
        el("button", {
          class: "button ghost small",
          type: "button",
          text: "Close",
          onclick: () => {
            card.hidden = true;
          },
        }),
      ),
      el(
        "div",
        { class: "entries" },
        data.entries.length
          ? data.entries.map((entry) =>
              el(
                "button",
                {
                  class: "entry",
                  type: "button",
                  onclick: () => {
                    if (entry.dir) open(entry.path);
                    else {
                      card.hidden = true;
                      if (onChoose) onChoose(entry.path);
                    }
                  },
                },
                icon(entry.dir ? ICONS.folder : ICONS.file),
                el("span", { class: "name", text: entry.name }),
              ),
            )
          : el("div", { class: "card pad" }, empty("Nothing here that Semlith can index.")),
      ),
    );
    return true;
  }

  return {
    node: card,
    open,
    close: () => {
      card.hidden = true;
    },
    isOpen: () => !card.hidden,
  };
}

/** A path on one line, truncated at the start, whole on hover.
 *
 * The end is the part that identifies a file: every row on the Files page
 * begins with the same `/Users/...` and differs in its last segment, so cutting
 * the end throws away the only part worth reading. */
function pathCell(value, className) {
  return el(
    "span",
    { class: className ? `one-line tail ${className}` : "one-line tail", "data-tip": value },
    el("bdi", { text: value }),
  );
}

/** A value on one line, truncated at the end, whole on hover. */
function lineCell(value, className) {
  return el("span", {
    class: className ? `one-line ${className}` : "one-line",
    "data-tip": value,
    text: value,
  });
}

/** An input with a real label. A placeholder is not one: it leaves on typing. */
function labelled(id, text, input) {
  input.id = id;
  return [el("label", { class: "sr-only", for: id, text }), input];
}

/* One page header for the whole portal.
 *
 * The title, its status pill immediately beside it, and any page actions at
 * the end of that row; the subtitle on a row of its own at the page's full
 * width. Every page uses it, so a pill is never floated to the far side of a
 * header away from the title it describes, and a subtitle is never squeezed
 * into a narrow column by a button sitting opposite it. */
function pageHead(title, subtitle, extra) {
  const { pill, actions } = extra || {};
  return el(
    "div",
    { class: "page-head" },
    el(
      "div",
      { class: "line" },
      el("h1", { text: title }),
      pill || null,
      actions ? el("span", { class: "spacer" }) : null,
      actions ? el("div", { class: "actions" }, actions) : null,
    ),
    subtitle ? el("p", { class: "subtitle", text: subtitle }) : null,
  );
}

/* A row's actions, behind one control.
 *
 * A column of buttons per row is a column of noise, and the destructive one
 * sits a mis-aimed click away from the ordinary one. The menu is a single
 * host appended to the body for the same reason the tooltip is: a popup
 * inside a cell is clipped by the table's own `overflow: auto`. */
const menu = {
  node: null,
  owner: null,

  ensure() {
    if (this.node) return this.node;
    this.node = el("div", { class: "menu", role: "menu", hidden: true });
    document.body.append(this.node);
    // One listener each, not one per menu: the host outlives every row that
    // opens it.
    document.addEventListener("pointerdown", (e) => {
      if (this.node.hidden) return;
      if (this.node.contains(e.target) || (this.owner && this.owner.contains(e.target))) return;
      this.close();
    });
    document.addEventListener("keydown", (e) => {
      if (e.key === "Escape") this.close();
    });
    window.addEventListener("resize", () => this.close());
    // A menu anchored to a row in a scrolling table has to go when the row
    // moves, rather than hang over the wrong one.
    window.addEventListener("scroll", () => this.close(), true);
    return this.node;
  },

  /** `items` are `{ label, tone, onclick }`; `at` is the control it hangs off. */
  open(at, items) {
    const node = this.ensure();
    if (this.owner === at && !node.hidden) return this.close();
    this.owner = at;
    at.setAttribute("aria-expanded", "true");
    fill(
      node,
      items.map((item) =>
        el("button", {
          class: item.tone ? `menu-item ${item.tone}` : "menu-item",
          type: "button",
          role: "menuitem",
          text: item.label,
          onclick: () => {
            this.close();
            item.onclick();
          },
        }),
      ),
    );
    node.hidden = false;
    const box = node.getBoundingClientRect();
    const rect = at.getBoundingClientRect();
    const margin = 8;
    let left = rect.right - box.width;
    left = Math.min(Math.max(margin, left), window.innerWidth - margin - box.width);
    let top = rect.bottom + 6;
    if (top + box.height > window.innerHeight - margin) top = rect.top - box.height - 6;
    node.style.left = `${Math.round(left)}px`;
    node.style.top = `${Math.round(Math.max(margin, top))}px`;
    node.querySelector(".menu-item")?.focus();
  },

  close() {
    if (!this.node) return;
    this.node.hidden = true;
    if (this.owner) this.owner.setAttribute("aria-expanded", "false");
    this.owner = null;
  },
};

/** The control that opens one, for the end of a table row. */
function rowMenu(items) {
  const button = el("button", {
    class: "button secondary small icon",
    type: "button",
    "aria-haspopup": "menu",
    "aria-expanded": "false",
    "aria-label": "Actions",
    title: "Actions",
    onclick: () => menu.open(button, items()),
  });
  fill(button, icon(ICONS.more, 18, true));
  return button;
}

/** A status pill. One shape, and a dot only where it reports a state. */
function pill(text, tone, props) {
  return el(
    "span",
    { class: tone ? `pill ${tone}` : "pill", ...(props || {}) },
    tone ? el("i", {}) : null,
    text,
  );
}

// ---------------------------------------------------------------- state

const NARROW = "(max-width: 899px)";

const state = {
  stores: [],
  theme: "light",
  navOpen: !window.matchMedia(NARROW).matches,
  /** Carried from the welcome screen into the Index view's path field. */
  pendingPath: "",
  /** Carried from a search hit into the Graph page, or into Search. */
  pendingSymbol: "",
  pendingQuery: "",
  /** The last search, kept so leaving the page and coming back does not throw
   * the question away along with its answers. */
  search: { query: "", stores: [] },
  /** How many clients are talking to the daemon, for the sidebar card. */
  agents: null,
};

/* Pages, in the design's grouping. The ones the roadmap puts in a later
 * release — Inside the index, Reports, License — are deliberately absent
 * rather than stubbed: a nav item that leads nowhere is worse than one that
 * does not exist yet. Everything listed here is free on every tier. */
const VIEWS = [
  { group: "Workspace", id: "stores", label: "Stores", title: "Stores" },
  { group: "Workspace", id: "files", label: "Files", title: "Files" },
  { group: "Workspace", id: "index", label: "Index", title: "Index" },
  { group: "Explore", id: "search", label: "Search", title: "Search" },
  { group: "Explore", id: "graph", label: "Graph", title: "Graph" },
  { group: "Operate", id: "agents", label: "Agents", title: "Agents" },
  { group: "Operate", id: "ledger", label: "Ledger", title: "Retrieval ledger" },
  { group: "Operate", id: "privacy", label: "Privacy", title: "Privacy" },
  { group: "About", id: "about", label: "About", title: "About" },
];

/** The sidebar's count, kept with the data it describes rather than with the
 * render that happened to be running when it changed. */
function paintStoreCount() {
  const node = document.getElementById("daemon-stores");
  if (!node) return;
  const many = state.stores.length;
  const parts = [`${many} store${many === 1 ? "" : "s"}`];
  // Only once the answer is known: "0 agents" while the route is still in
  // flight reads as a fact rather than as a question nobody has asked yet.
  if (state.agents !== null) {
    parts.push(`${state.agents} agent${state.agents === 1 ? "" : "s"}`);
  }
  node.textContent = parts.join(" · ");
}

/** How many clients are connected, from whichever page last asked. */
function noteAgents(data) {
  state.agents = (data.connections || []).length;
  paintStoreCount();
}


// ---------------------------------------------------------------- graph

/* The colours the canvas draws with, read from the stylesheet rather than
 * repeated here: the page is themed by CSS custom properties, and a canvas
 * cannot inherit one. Re-read on every paint so a theme switch is picked up. */
function graphInk() {
  const style = getComputedStyle(document.documentElement);
  const read = (name, fallback) => (style.getPropertyValue(name) || fallback).trim();
  return {
    edge: read("--line", "#dce3e8"),
    hot: read("--blue", "#4c7088"),
    node: read("--panel", "#ffffff"),
    nodeLine: read("--line", "#dce3e8"),
    text: read("--ink-2", "#3a4d5e"),
    nearFill: read("--blue-soft", "#e3ecf2"),
    nearLine: read("--blue", "#4c7088"),
    nearText: read("--ink", "#1e2a35"),
    // The tone an ambiguous edge is drawn in: the same amber the badge uses,
    // so the canvas and the rail say one thing.
    warn: read("--amber-ink", "#7a4e0a"),
    sel: read("--accent", "#f0a43c"),
    selLine: read("--accent-edge", "#c97f14"),
    selText: read("--accent-ink", "#1e2a35"),
    muted: read("--muted", "#64778a"),
  };
}

/** The last two segments of a path: enough to recognise, short enough to read. */
function shortPath(path) {
  const parts = String(path).split("/").filter(Boolean);
  return parts.slice(-2).join("/") || path;
}

/** True when the viewer has asked for less movement. */
function stillness() {
  return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}

/* A force-directed canvas of labelled boxes.
 *
 * Positions are kept in 0..1 and multiplied by the canvas size on every frame,
 * so a resize moves the graph rather than rebuilding it, and the constants
 * below mean the same thing at any window width. They are the design bundle's:
 * repulsion 5200 over distance squared, a spring at rest 138px, damping 0.86,
 * and a weak pull to the centre.
 *
 * ponytail: O(n²) repulsion over every pair each frame. The node budget is 180,
 * so that is ~16k pairs — fine at 60fps. Past a few hundred this wants a
 * quadtree, not a faster loop.
 */
function graphCanvas(options) {
  const { onPick, onHover } = options || {};
  const canvas = el("canvas", { class: "graph-canvas" });
  const wrap = el("div", { class: "graph-stage" }, canvas);
  let nodes = [];
  let edges = [];
  let drawn = [];
  let selected = null;
  let near = new Set();
  let hovered = null;
  let dragging = null;
  let down = null;
  let frame = null;
  let running = true;
  let settled = false;
  /* Whether this canvas has ever been in the document. See `tick`. */
  let attached = false;
  /* How much of the force is still applied. The layout cools, but never to
   * nothing: it bottoms out at `ALPHA_FLOOR`, so the springs keep holding the
   * shape while the drift below moves it. Anything that changes the layout —
   * a drag, a new scope, an edge-kind filter — re-heats it. */
  let alpha = 1;
  /* Springs are shared out by how many edges a node carries. A hub with forty
   * edges feels forty pulls where a leaf feels one, and at this node count that
   * is what turns the simulation into a two-frame bounce: every node overshoots
   * its rest position, and the next step overshoots back. Dividing by the
   * square root of the degree is what keeps a dense neighbourhood stable. */
  let load = [];

  function size() {
    const ratio = window.devicePixelRatio || 1;
    const box = wrap.getBoundingClientRect();
    const w = Math.max(box.width, 240);
    const h = Math.max(box.height, 240);
    canvas.width = Math.round(w * ratio);
    canvas.height = Math.round(h * ratio);
    const ctx = canvas.getContext("2d");
    ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
    return { w, h, ctx };
  }

  /* The furthest a node may move in one step, in fractions of the canvas.
   * Without it a single large force sends a node across the frame and the
   * spring drags it back, which is the bounce this cap exists to stop. */
  const MAX_STEP = 0.012;

  /* The layout never freezes. Cooling to a standstill was what stopped the
   * two-frame bounce, but a still picture is not what this view is for, so the
   * heat bottoms out here and every node carries a slow wander on top of it.
   *
   * The wander is a sine of the clock and the node's own phase, not a random
   * nudge: a random walk accumulates, drags nodes off their springs and is
   * indistinguishable from the jitter this replaced. A smooth curve at this
   * amplitude settles at under a pixel a frame, which reads as a drift. */
  const ALPHA_FLOOR = 0;
  const DRIFT = 0.00003;

  function step(w, h) {
    const clock = performance.now() * 0.00028;
    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) * w;
        let dy = (b.y - a.y) * h;
        let d2 = dx * dx + dy * dy;
        if (d2 < 1) {
          // Exactly coincident nodes have no direction to separate along.
          d2 = 1;
          dx = 0.6;
          dy = 0.4;
        }
        const d = Math.sqrt(d2);
        const force = (5200 / d2) * alpha;
        a.vx -= ((dx / d) * force) / w;
        a.vy -= ((dy / d) * force) / h;
        b.vx += ((dx / d) * force) / w;
        b.vy += ((dy / d) * force) / h;
      }
    }
    for (const edge of drawn) {
      const a = nodes[edge.from];
      const b = nodes[edge.to];
      if (!a || !b) continue;
      const dx = (b.x - a.x) * w;
      const dy = (b.y - a.y) * h;
      const d = Math.max(1, Math.sqrt(dx * dx + dy * dy));
      const pull = (d - 138) * 0.0025 * alpha;
      // Shared out by degree at each end, so a hub is not dragged about by
      // every edge it happens to carry.
      const ax = Math.sqrt(load[edge.from] || 1);
      const bx = Math.sqrt(load[edge.to] || 1);
      a.vx += ((((dx / d) * pull * d) / w) * 0.02) / ax;
      a.vy += ((((dy / d) * pull * d) / h) * 0.02) / ax;
      b.vx -= ((((dx / d) * pull * d) / w) * 0.02) / bx;
      b.vy -= ((((dy / d) * pull * d) / h) * 0.02) / bx;
    }
    let moved = 0;
    for (const node of nodes) {
      node.vx += (0.5 - node.x) * 0.006 * alpha;
      node.vy += (0.5 - node.y) * 0.008 * alpha;
      node.vx += Math.cos(clock + node.phase) * DRIFT;
      node.vy += Math.sin(clock * 0.9 + node.phase * 1.7) * DRIFT;
      if (node === dragging) {
        node.vx = 0;
        node.vy = 0;
        continue;
      }
      node.vx *= 0.86;
      node.vy *= 0.86;
      // One step can only take a node so far. A force large enough to throw it
      // across the frame is a force the spring will undo next step, which is
      // the two-frame bounce rather than a layout.
      node.vx = Math.max(-MAX_STEP, Math.min(MAX_STEP, node.vx));
      node.vy = Math.max(-MAX_STEP, Math.min(MAX_STEP, node.vy));
      moved += Math.abs(node.vx) + Math.abs(node.vy);
      // Kept inside the frame: a node that drifts off-canvas is a node nobody
      // can click.
      node.x = Math.min(0.94, Math.max(0.06, node.x + node.vx));
      node.y = Math.min(0.92, Math.max(0.08, node.y + node.vy));
    }
    alpha = Math.max(ALPHA_FLOOR, alpha * 0.985);
    return moved;
  }

  /** Put the heat back in, for anything that changes the layout. */
  function reheat(to) {
    alpha = Math.max(alpha, to === undefined ? 0.35 : to);
  }

  /** A rounded rectangle, the shape every symbol is drawn as. */
  function box(ctx, x, y, w, h, r) {
    ctx.beginPath();
    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 paint() {
    const { w, h, ctx } = size();
    const ink = graphInk();
    ctx.clearRect(0, 0, w, h);

    // Measured first: an edge stops at the box it points into, which means
    // every box's size has to be known before the first edge is drawn.
    ctx.font = '500 11px "IBM Plex Mono", ui-monospace, monospace';
    for (const node of nodes) {
      const ease = stillness() ? (node === hovered ? 1 : 0) : node.hover || 0;
      node.hover = ease;
      const text = ctx.measureText(node.label).width;
      node.w = (text + 22) * (1 + 0.05 * ease);
      node.h = 28 * (1 + 0.05 * ease);
    }

    for (const edge of drawn) {
      const a = nodes[edge.from];
      const b = nodes[edge.to];
      if (!a || !b) continue;
      const ax = a.x * w;
      const ay = a.y * h;
      const bx = b.x * w;
      const by = b.y * h;
      const hot = edge.from === selected || edge.to === selected;
      const angle = Math.atan2(by - ay, bx - ax);
      // To the edge of the box rather than to its centre, so the arrowhead
      // lands where the reader sees the symbol begin.
      const inset = Math.min(b.w / 2 + 6, Math.abs(b.h / 2 / Math.sin(angle) || b.w));
      const ex = bx - Math.cos(angle) * Math.min(inset, b.w / 2 + 6);
      const ey = by - Math.sin(angle) * (b.h / 2 + 3);
      ctx.save();
      ctx.strokeStyle = hot ? ink.hot : ink.edge;
      ctx.fillStyle = hot ? ink.hot : ink.edge;
      ctx.lineWidth = hot ? 1.7 : 1.1;
      // Drawn with the same four values the rail shows. An edge the source
      // settled is solid; one matched by bare name is dotted; one that could
      // mean several different definitions is dashed and drawn in the warning
      // tone, because it is not a claim about this code at all.
      const settled = edge.confidence === "extracted" || edge.confidence === "resolved";
      if (edge.confidence === "ambiguous") {
        ctx.strokeStyle = hot ? ink.hot : ink.warn;
        ctx.fillStyle = hot ? ink.hot : ink.warn;
        ctx.setLineDash([6, 4]);
      } else {
        ctx.setLineDash(settled ? [] : [2, 3]);
      }
      ctx.beginPath();
      ctx.moveTo(ax, ay);
      ctx.lineTo(ex, ey);
      ctx.stroke();
      ctx.setLineDash([]);
      ctx.beginPath();
      ctx.moveTo(ex, ey);
      ctx.lineTo(ex - Math.cos(angle - 0.4) * 7, ey - Math.sin(angle - 0.4) * 7);
      ctx.lineTo(ex - Math.cos(angle + 0.4) * 7, ey - Math.sin(angle + 0.4) * 7);
      ctx.closePath();
      ctx.fill();
      ctx.restore();
    }

    nodes.forEach((node, i) => {
      const on = i === selected;
      const beside = near.has(i);
      const x = node.x * w - node.w / 2;
      const y = node.y * h - node.h / 2;
      box(ctx, x, y, node.w, node.h, 8);
      ctx.fillStyle = on ? ink.sel : beside ? ink.nearFill : ink.node;
      ctx.save();
      if (node.hover) {
        ctx.shadowColor = ink.nearLine;
        ctx.shadowBlur = 14 * node.hover;
      }
      ctx.fill();
      ctx.restore();
      ctx.lineWidth = (on ? 1.6 : 1) + 0.8 * node.hover;
      ctx.strokeStyle = on ? ink.selLine : beside ? ink.nearLine : ink.nodeLine;
      ctx.stroke();
      ctx.fillStyle = on ? ink.selText : beside ? ink.nearText : ink.text;
      ctx.fillText(node.label, x + 11, y + node.h / 2 + 4);
    });
  }

  function tick() {
    // A view that has been navigated away from is not worth animating. The
    // canvas is built before it is inserted, so the first frames legitimately
    // run detached — only a canvas that *was* in the page and is not any more
    // has been thrown away.
    if (wrap.isConnected) attached = true;
    else if (attached) {
      frame = null;
      running = false;
      observer.disconnect();
      return;
    }
    const box = wrap.getBoundingClientRect();
    if (running || dragging) step(Math.max(box.width, 240), Math.max(box.height, 240));
    // Hover is eased rather than switched, so a fast pointer sweep across a
    // crowded graph does not strobe.
    for (const node of nodes) {
      node.hover = (node.hover || 0) + ((node === hovered ? 1 : 0) - (node.hover || 0)) * 0.16;
      if (node.hover < 0.002) node.hover = 0;
    }
    paint();
    frame = requestAnimationFrame(tick);
  }

  function at(event) {
    const box = canvas.getBoundingClientRect();
    return { x: event.clientX - box.left, y: event.clientY - box.top, w: box.width, h: box.height };
  }

  function hit(point) {
    for (let i = nodes.length - 1; i >= 0; i--) {
      const node = nodes[i];
      const cx = node.x * point.w;
      const cy = node.y * point.h;
      if (
        Math.abs(point.x - cx) < (node.w || 80) / 2 &&
        Math.abs(point.y - cy) < (node.h || 28) / 2
      ) {
        return i;
      }
    }
    return null;
  }

  function selectAt(index) {
    selected = index;
    near = new Set();
    for (const edge of drawn) {
      if (edge.from === index) near.add(edge.to);
      if (edge.to === index) near.add(edge.from);
    }
  }

  canvas.addEventListener("pointerdown", (event) => {
    const index = hit(at(event));
    if (index === null) return;
    canvas.setPointerCapture(event.pointerId);
    dragging = nodes[index];
    reheat();
    down = { x: event.clientX, y: event.clientY, index };
    canvas.classList.add("dragging");
    event.preventDefault();
  });

  canvas.addEventListener("pointermove", (event) => {
    const point = at(event);
    if (dragging) {
      dragging.x = Math.min(0.94, Math.max(0.06, point.x / point.w));
      dragging.y = Math.min(0.92, Math.max(0.08, point.y / point.h));
      if (!frame) paint();
      return;
    }
    const index = hit(point);
    const node = index === null ? null : nodes[index];
    canvas.classList.toggle("over-node", Boolean(node));
    if (node !== hovered) {
      hovered = node;
      if (!frame) paint();
    }
    if (onHover) onHover(node, event.clientX, event.clientY);
  });

  const release = (event) => {
    if (down) {
      // A drag that went nowhere is a click. Four pixels is the slack a
      // pointer has on the way down.
      const moved = Math.abs(event.clientX - down.x) + Math.abs(event.clientY - down.y);
      if (moved < 4) {
        selectAt(down.index);
        if (onPick) onPick(nodes[down.index]);
      }
    }
    dragging = null;
    down = null;
    canvas.classList.remove("dragging");
    if (!frame) paint();
  };
  canvas.addEventListener("pointerup", release);
  canvas.addEventListener("pointercancel", release);
  canvas.addEventListener("pointerleave", () => {
    hovered = null;
    dragging = null;
    down = null;
    canvas.classList.remove("dragging", "over-node");
    if (onHover) onHover(null);
    if (!frame) paint();
  });

  // A canvas has no layout of its own to react to a resize with, and the
  // stylesheet cannot repaint it.
  const observer = new ResizeObserver(() => {
    if (!frame) paint();
  });
  observer.observe(wrap);

  return {
    node: wrap,
    draw(data, kinds) {
      nodes = (data.nodes || []).map((row, i) => {
        const angle = (i / Math.max((data.nodes || []).length, 1)) * Math.PI * 2;
        return {
          ...row,
          // Truncated for the canvas only. Test names run past sixty
          // characters, and a box that wide covers its neighbours and pushes
          // the layout off the frame; the whole name is in the hover card and
          // in the rail the moment the node is picked.
          label: row.name.length > 26 ? `${row.name.slice(0, 25)}…` : row.name,
          x: 0.5 + Math.cos(angle) * 0.28,
          y: 0.5 + Math.sin(angle) * 0.28,
          vx: 0,
          vy: 0,
          // Where this node is in its own wander, so forty nodes drift apart
          // rather than sliding as one block.
          phase: Math.random() * Math.PI * 2,
          hover: 0,
          callers: 0,
          callees: 0,
        };
      });
      edges = data.edges || [];
      load = nodes.map(() => 1);
      for (const edge of edges) {
        if (nodes[edge.from]) nodes[edge.from].callees += 1;
        if (nodes[edge.to]) nodes[edge.to].callers += 1;
        if (load[edge.from] !== undefined) load[edge.from] += 1;
        if (load[edge.to] !== undefined) load[edge.to] += 1;
      }
      selected = null;
      near = new Set();
      hovered = null;
      this.filter(kinds);
      // Settled before the first painted frame, rather than exploding outward
      // while the reader watches.
      alpha = 1;
      const box = wrap.getBoundingClientRect();
      for (let i = 0; i < 220; i++) {
        step(Math.max(box.width, 240), Math.max(box.height, 240));
      }
      settled = true;
      paint();
    },
    /** Draw only the edge kinds asked for. Returns how many are drawn. */
    filter(kinds) {
      drawn = !kinds || !kinds.size ? edges : edges.filter((e) => kinds.has(e.kind));
      if (selected !== null) selectAt(selected);
      // Fewer edges is a different layout, so the springs get another go at it.
      reheat(0.25);
      if (settled) paint();
      return drawn.length;
    },
    /** Select a node by name, as though it had been clicked. */
    pick(name) {
      const index = nodes.findIndex((node) => node.name === name);
      if (index < 0) return false;
      selectAt(index);
      paint();
      if (onPick) onPick(nodes[index]);
      return true;
    },
    counts: () => ({ nodes: nodes.length, edges: drawn.length }),
    running: () => running,
    toggle() {
      running = !running;
      if (running) reheat(0.2);
      return running;
    },
    start() {
      // Under reduced motion the graph is solved once and then still: there is
      // no loop to pause, and nothing moves unless the reader moves it.
      if (stillness()) {
        running = false;
        paint();
        return;
      }
      if (!frame) tick();
    },
    stop() {
      running = false;
      if (frame) cancelAnimationFrame(frame);
      frame = null;
      observer.disconnect();
    },
    repaint: paint,
  };
}

const EDGE_KINDS = ["calls", "imports", "defines", "references"];

async function graphView() {
  await refreshStores();

  const kinds = new Set(EDGE_KINDS);
  const chosen = new Set();
  const meta = el("span", { class: "graph-count" });
  const rail = el("div", { class: "graph-rail" });

  const canvas = graphCanvas({
    onPick: (node) => select(node),
    onHover: (node, x, y) => {
      if (!node) return tip.hide("graph");
      tip.atPoint(
        x,
        y,
        [
          el(
            "div",
            { class: "tip-head" },
            el("i", {}),
            node.name,
          ),
          row("kind", node.kind),
          row("file", `${shortPath(node.path)}:${node.start_line}-${node.end_line}`),
          row("store", node.store || (state.stores[0] && state.stores[0].name) || "—"),
          row("calls", `${node.callers} in · ${node.callees} out`),
        ],
        "graph",
      );
    },
  });

  function row(key, value) {
    return el(
      "div",
      { class: "tip-row" },
      el("span", { class: "k", text: key }),
      el("span", { class: "v", text: String(value) }),
    );
  }

  const pause = el("button", {
    class: "button secondary small",
    type: "button",
    text: "Pause",
    onclick: (e) => {
      const on = canvas.toggle();
      e.currentTarget.textContent = on ? "Pause" : "Resume";
    },
  });

  /* The label has to come from what the canvas is actually doing, not from a
   * second reading of the media query: under reduced motion `start` never
   * begins a loop, and a button reading "Pause" beside a still picture is a
   * lie about which of the two is in charge. */
  function paintPause() {
    pause.textContent = canvas.running() ? "Pause" : "Settled";
  }

  function counts() {
    const { nodes, edges } = canvas.counts();
    meta.textContent = `${n(nodes)} symbols · ${n(edges)} edges`;
  }

  function blank(message) {
    return fill(
      rail,
      el("div", { class: "graph-selected" }, el("div", { class: "rail-hint", text: message })),
    );
  }

  function ends(title, list, absent, extra) {
    return el(
      "div",
      { class: "rail-group" },
      el("h3", { text: title }),
      list.length
        ? el(
            "ul",
            { class: "rail-list" },
            list.map((end) => endRow(end)),
          )
        : el("div", { class: "rail-hint", text: absent }),
      extra || null,
    );
  }

  /* One neighbour. An ambiguous row stands for several definitions and must
   * not name one of them: a reader who follows it would open one of four files
   * the call could have meant. It says how many instead, and opens on ask. */
  function endRow(end) {
    if (end.confidence === "ambiguous") {
      const li = el("li", { class: "ambiguous-row" });
      let open = false;
      const toggle = el("button", {
        class: "link-button",
        type: "button",
        text: `${end.name} · ${end.definitions} definitions`,
        "aria-expanded": "false",
        onclick: async () => {
          open = !open;
          toggle.setAttribute("aria-expanded", String(open));
          if (!open) return fill(nested);
          fill(nested, el("div", { class: "rail-hint", text: "Loading…" }));
          let all;
          try {
            all = await api(
              `/api/neighbors?name=${encodeURIComponent(state.graphSelected)}&all=1`,
            );
          } catch (e) {
            return fill(nested, error(e.message));
          }
          const each = all.callees.filter((c) => c.name === end.name);
          fill(
            nested,
            el(
              "ul",
              { class: "rail-list nested" },
              each.map((one) =>
                el(
                  "li",
                  {},
                  el("a", {
                    href: `#graph?name=${encodeURIComponent(one.name)}`,
                    text: `${shortPath(one.path)}:${one.start_line}`,
                    onclick: (e) => {
                      e.preventDefault();
                      focus(one.name);
                    },
                  }),
                ),
              ),
            ),
          );
        },
      });
      const nested = el("div", { class: "nested-wrap" });
      return fill(li, toggle, confidenceBadge(end.confidence), el("span", { class: "via", text: end.kind }), nested);
    }
    return el(
      "li",
      {},
      el("a", {
        href: `#graph?name=${encodeURIComponent(end.name)}`,
        text: end.name,
        onclick: (e) => {
          e.preventDefault();
          focus(end.name);
        },
      }),
      confidenceBadge(end.confidence),
      el("span", { class: "via", text: end.kind }),
    );
  }

  /* What the four values mean, once, under the rail. A badge whose meaning a
   * reader has to guess is a badge that gets read as decoration. */
  function confidenceLegend() {
    return el(
      "div",
      { class: "conf-legend" },
      Object.entries(CONFIDENCE).map(([value, [label, why]]) =>
        el(
          "span",
          { class: "legend-chip" },
          el("span", { class: `conf ${value}`, text: label }),
          el("span", { class: "why", text: why }),
        ),
      ),
    );
  }

  async function select(node) {
    fill(rail, el("div", { class: "rail-hint", text: "Loading…" }));
    let data;
    try {
      data = await api(`/api/neighbors?name=${encodeURIComponent(node.name)}`);
    } catch (e) {
      return fill(rail, error(e.message));
    }
    state.graphSelected = node.name;
    const edge = (e) => ({
      name: e.name,
      kind: e.kind,
      confidence: e.confidence,
      definitions: e.definitions,
      path: e.path,
      start_line: e.start_line,
    });

    fill(
      rail,
      el(
        "div",
        { class: "graph-selected" },
        el("span", { class: "eyebrow", text: "Selected symbol" }),
        el("h2", { class: "sym", text: node.name }),
        el("div", {
          class: "loc",
          "data-tip": node.path,
          text: `${shortPath(node.path)}:${node.start_line}-${node.end_line}`,
        }),
        el(
          "div",
          { class: "chips" },
          el("span", { class: "chip static blue", text: node.kind }),
          node.store ? el("span", { class: "chip static", text: node.store }) : null,
          el("span", {
            class: "chip static",
            text: `${Math.max(node.end_line - node.start_line + 1, 1)} lines`,
          }),
        ),
      ),
      ends("Callers", data.callers.map(edge), "Nothing in the graph calls this."),
      ends(
        "Callees",
        data.callees.map(edge),
        "A leaf, as far as the extracted edges go.",
        // Targets the store holds no definition for. Left out by default,
        // because a list of names this corpus knows nothing about is noise —
        // and counted, because "no callees" and "every callee is outside the
        // index" are different facts.
        data.hidden
          ? el("button", {
              class: "link-button quiet",
              type: "button",
              text: `Show ${data.hidden} unresolved`,
              onclick: async (e) => {
                const button = e.currentTarget;
                button.textContent = "Loading…";
                let all;
                try {
                  all = await api(`/api/neighbors?name=${encodeURIComponent(node.name)}&all=1`);
                } catch (err) {
                  button.replaceWith(error(err.message));
                  return;
                }
                button.replaceWith(
                  el(
                    "ul",
                    { class: "rail-list nested" },
                    all.unresolved.map((one) =>
                      el(
                        "li",
                        {},
                        el("span", { text: one.name }),
                        el("span", { class: "via", text: one.kind }),
                      ),
                    ),
                  ),
                );
              },
            })
          : null,
      ),
      confidenceLegend(),
      el(
        "div",
        { class: "rail-actions" },
        el("a", {
          class: "button secondary small",
          href: "#search",
          text: "Chunks it lives in",
          onclick: (e) => {
            e.preventDefault();
            state.pendingQuery = node.name;
            go("search");
          },
        }),
      ),
    );
  }

  async function load(params) {
    meta.textContent = "loading…";
    const query = new URLSearchParams(params || {});
    for (const store of chosen) query.append("store", store);
    let data;
    try {
      data = await api(`/api/graph?${query}`);
    } catch (e) {
      meta.textContent = "";
      return fill(rail, error(e.message));
    }
    if (!data.nodes.length) {
      meta.textContent = "0 symbols";
      canvas.draw({ nodes: [], edges: [] }, kinds);
      return blank(
        data.total === 0
          ? "This store has no symbols yet. The graph is built as files are indexed — run Index once, or leave the daemon watching."
          : "Nothing in this scope. Clear the filters, or pick a store.",
      );
    }
    canvas.draw(data, kinds);
    counts();
    // A focused view arrives with its centre chosen, so the rail says something
    // before the first click rather than asking for one.
    const centre = params && params.name;
    if (centre && canvas.pick(centre)) return;
    blank("Pick a node to see what calls it and what it calls.");
  }

  function focus(name) {
    load({ name, limit: "45" });
  }

  const scopeInput = el("input", {
    type: "search",
    placeholder: "Scope to a path, or find a symbol",
    onkeydown: (e) => {
      if (e.key !== "Enter") return;
      const value = e.currentTarget.value.trim();
      if (!value) return load({});
      // A path fragment scopes; anything else is read as a symbol to centre on.
      load(value.includes("/") || value.includes(".") ? { path: value } : { name: value });
    },
  });

  const kindChips = EDGE_KINDS.map((kind) =>
    el("button", {
      class: "chip",
      type: "button",
      "aria-pressed": "true",
      text: kind,
      onclick: (e) => {
        const on = e.currentTarget.getAttribute("aria-pressed") !== "true";
        e.currentTarget.setAttribute("aria-pressed", String(on));
        if (on) kinds.add(kind);
        else kinds.delete(kind);
        canvas.filter(kinds);
        counts();
      },
    }),
  );

  const storeChips = state.stores.map((store) =>
    el("button", {
      class: "chip",
      type: "button",
      "aria-pressed": "false",
      text: store.name,
      onclick: (e) => {
        const on = e.currentTarget.getAttribute("aria-pressed") !== "true";
        e.currentTarget.setAttribute("aria-pressed", String(on));
        if (on) chosen.add(store.name);
        else chosen.delete(store.name);
        load({});
      },
    }),
  );

  const page = el(
    "div",
    { class: "graph-page" },
    el(
      "div",
      { class: "graph-band" },
      pageHead(
        "Graph",
        "Edges are re-extracted on the same pass that re-embeds a file. Never a stale build artifact.",
        { actions: [el("div", { class: "filters" }, kindChips), pause] },
      ),
      el(
        "div",
        { class: "graph-controls" },
        el(
          "div",
          { class: "graph-scope" },
          icon(ICONS.search, 16),
          labelled("graph-scope", "Scope the graph", scopeInput),
        ),
        storeChips.length > 1 ? el("div", { class: "filters" }, storeChips) : null,
      ),
    ),
    el(
      "div",
      { class: "graph-body" },
      el(
        "div",
        { class: "graph-frame" },
        canvas.node,
        el(
          "div",
          { class: "graph-legend" },
          el("span", { class: "key extracted" }, el("i", {}), "extracted"),
          el("span", { class: "key resolved" }, el("i", {}), "resolved"),
          el("span", { class: "key inferred" }, el("i", {}), "inferred"),
          el("span", { class: "key ambiguous" }, el("i", {}), "ambiguous"),
          el("span", { class: "key selected" }, el("i", {}), "selected"),
        ),
        meta,
      ),
      rail,
    ),
  );

  blank("Pick a node to see what calls it and what it calls.");
  // The canvas has no size until it is in the document.
  setTimeout(async () => {
    canvas.start();
    paintPause();
    const pending = state.pendingSymbol;
    state.pendingSymbol = "";
    if (pending) return load({ name: pending, limit: "45" });
    // Land on the busiest symbol's neighbourhood rather than on everything at
    // once. The whole store drawn at once is honest and unreadable, and a
    // reader arriving at a knot learns nothing.
    try {
      const overview = await api("/api/graph?limit=1");
      const busiest = (overview.nodes || [])[0];
      if (busiest) return focus(busiest.name);
    } catch (_) {
      /* fall through to the overview */
    }
    load({});
  }, 0);
  return page;
}

/** One figure with its label, as the design draws them. */
/* Ring one card in the accent, for the single figure a page exists to show.
 *
 * A wrapper rather than an argument on `stat`, because emphasis is a property
 * of the page's argument and not of the number: the same statistic is ringed on
 * one page and plain on another. */
function ringed(node) {
  node.classList.add("ringed");
  return node;
}

function stat(label, value, note) {
  return el(
    "div",
    { class: "stat" },
    el("span", { class: "eyebrow", text: label }),
    el("span", { class: "value", text: value }),
    note ? el("span", { class: "sub", text: note }) : null,
  );
}

// --------------------------------------------------------------- ledger

async function ledgerView() {
  let data;
  try {
    data = await api("/api/ledger");
  } catch (e) {
    return el("div", { class: "view" }, pageHead("Retrieval ledger"), error(e.message));
  }

  const on = data.recording;
  return el(
    "div",
    { class: "view" },
    pageHead(
      "Retrieval ledger",
      "Every query an agent ran, recorded locally. The honest token number, a debugging trail, and an audit record that never left the machine.",
      {
        pill: on
          ? pill("recording", "on", {
              title:
                "On by default. Rows live in the store beside the chunks and never leave this machine.",
            })
          : pill("not recording", null),
      },
    ),
    // Six across, then two wide, then who asked — the order the design puts
    // them in, and the order they are read in: what was asked, what it cost,
    // what it saved, and how much of the ledger that figure covers.
    el(
      "div",
      { class: "strip" },
      stat(
        "Queries recorded",
        n(data.queries),
        `${n(data.clients)} client${data.clients === 1 ? "" : "s"}`,
      ),
      stat("Excerpt tokens", n(data.excerpt_tokens), "what agents were actually sent"),
      stat(
        "Whole-file tokens",
        n(data.whole_file_tokens),
        "what reading those files whole would have cost, counted with the store's tokenizer",
      ),
      // A ratio never stands alone. Coverage says how much of the ledger it is
      // computed over, and the tier says whether the tokens were counted or
      // estimated — without both, a number like 18.3x is a marketing claim.
      // Ringed rather than merely present: it is the figure a reader came for,
      // and the ring is what carries its two qualifiers with it.
      ringed(
        stat(
          "Measured ratio",
          data.ratio ? `${data.ratio.toFixed(1)}×` : "—",
          data.ratio ? `coverage ${data.coverage}% · ${data.tier}` : "needs a recorded query",
        ),
      ),
      stat(
        "Coverage",
        `${data.coverage || 0}%`,
        `${n(data.credited || 0)} of ${n(data.queries)} retrievals credited`,
      ),
      stat(
        "Net tokens",
        n(data.net_tokens || 0),
        "whole-file less excerpt, over rows that found something",
      ),
    ),
    el(
      "div",
      { class: "strip" },
      stat(
        "Zero-hit",
        `${data.queries ? Math.round(((data.queries - (data.credited || 0)) * 100) / data.queries) : 0}%`,
        "queries the corpus could not answer — recorded, and credited nothing",
      ),
      stat("Tier", data.tier || "modelled", "modelled · measured — measured when the store's own tokenizer counted it"),
    ),
    clientBreakdown(data.by_client),
    el(
      "div",
      { class: "scroller" },
      el(
        "div",
        { class: "grid three" },
        el(
          "div",
          { class: "card pad dense" },
          copyField("semlith ledger --last 20"),
          el("p", {
            class: "subtitle",
            text: "Prints the ledger on the command line. Nothing here needs a key.",
          }),
        ),
        el(
          "div",
          { class: "card pad dense" },
          copyField("semlith ledger --verify"),
          el("p", {
            class: "subtitle",
            text: "Re-walks the hash chain and names the first row that does not verify.",
          }),
          el("p", {
            class: "subtitle",
            text: data.intact
              ? "The chain is intact."
              : "The chain does not verify. Some rows have been edited or removed.",
          }),
        ),
        el(
          "div",
          { class: "card pad dense" },
          copyField("semlith start --no-ledger"),
          el("p", {
            class: "subtitle",
            text: "Run the daemon without recording, for this session only. SEMLITH_LEDGER=0 does the same for a machine.",
          }),
        ),
      ),
      on
        ? null
        : el(
            "div",
            { class: "notice" },
            el("div", { class: "what", text: "Recording is off" }),
            el(
              "div",
              {},
              "The daemon was started with ",
              mono("--no-ledger"),
              ". Start it without that flag to record what your agents retrieve. Nothing is sent anywhere; the rows live in the store beside the chunks.",
            ),
          ),
      says(
        "Stored in ",
        mono("~/.semlith/stores/<name>/store.db"),
        ", table ",
        mono("retrievals"),
        ". On by default; ",
        mono("--no-ledger"),
        " or ",
        mono("SEMLITH_LEDGER=0"),
        " turns it off, and deleting the rows is one ",
        mono("DELETE"),
        ".",
      ),
    ),
  );
}

/* Who the ledger recorded, and how often.
 *
 * The row that says the ledger works. Before 0.15.0 it could only ever read
 * `portal 31`, because the portal's own search box was the only thing that
 * wrote to it; a line with `claude-code` on it is the whole point of the
 * release. */
function clientBreakdown(byClient) {
  const entries = Object.entries(byClient || {}).sort((a, b) => b[1] - a[1]);
  if (!entries.length) return null;
  return el(
    "div",
    { class: "client-breakdown" },
    // Labelled, because a bare run of names and numbers under eight stat cards
    // reads as a caption for the cards rather than as its own fact. The line
    // after it is the fact: these are the client's own names, from the MCP
    // handshake, not a guess made here.
    el("span", { class: "eyebrow", text: "by client" }),
    entries.map(([client, count], i) =>
      el(
        "span",
        { class: "client" },
        i ? el("span", { class: "sep", text: "·" }) : null,
        el("span", { class: "who", text: client }),
        el("span", { class: "count", text: n(count) }),
      ),
    ),
    el("span", {
      class: "client-note",
      text: "— MCP, HTTP and CLI, under the client's own name",
    }),
  );
}

/** Read the store list into `state`, so every view agrees on how many exist. */
async function refreshStores() {
  try {
    const data = await api("/api/stores");
    state.stores = data.stores || [];
    paintStoreCount();
  } catch (_) {
    // A failed refresh must not empty the list: `state.stores.length` decides
    // whether the app or the first-run screen is shown, and a dropped request
    // is not the same as having no stores.
  }
  return state.stores;
}

// ---------------------------------------------------------------- stores

/* "Agents connected", on the Stores page.
 *
 * The same list the Agents page draws, read from the same route, because two
 * readings of "which agents are talking to this daemon" is how one page says
 * two and the other says none. */
function agentsCard() {
  const card = el("div", { class: "card pad dense" });
  const body = el("div", { class: "rows" });
  fill(
    card,
    el("span", { class: "card-title", text: "Agents connected" }),
    body,
    el("span", { class: "spacer" }),
    el("button", {
      class: "button ghost small",
      type: "button",
      text: "Copy config for another client",
      onclick: () => go("agents"),
    }),
  );
  fill(body, el("div", { class: "rail-hint", text: "Asking the daemon…" }));

  api("/api/agents")
    .then((data) => {
      noteAgents(data);
      const live = data.connections || [];
      if (!live.length) {
        fill(
          body,
          el("div", {
            class: "rail-hint",
            text: "No client is talking to this daemon right now.",
          }),
        );
        return;
      }
      fill(
        body,
        live.map((client) =>
          el(
            "div",
            { class: "kv" },
            el("span", { text: client.name }),
            el("span", { class: "spacer" }),
            el("span", {
              class: "meta",
              text: `${client.transport} · ${n(client.queries)} quer${
                client.queries === 1 ? "y" : "ies"
              }`,
            }),
          ),
        ),
      );
    })
    .catch((e) => fill(body, error(e.message)));

  return card;
}

/* A question that has to be answered before anything else happens.
 *
 * A native `<dialog>` rather than a div: the focus trap, the Escape key, the
 * inert background and the backdrop are the platform's, and every one of them
 * is a thing a hand-rolled overlay gets wrong. `run` returns a promise; while
 * it is pending the dialog says so, and an error is shown inside it rather
 * than behind it. */
function ask({ title, body, confirm, tone, run }) {
  const dialog = el("dialog", { class: "modal" });
  const problem = el("div", { class: "note" });
  const go = el("button", {
    class: tone === "bad" ? "button danger" : "button",
    type: "button",
    text: confirm,
    onclick: async () => {
      go.disabled = true;
      const was = go.textContent;
      go.textContent = "Working…";
      problem.className = "note";
      problem.textContent = "";
      try {
        await run();
        dialog.close();
      } catch (e) {
        problem.className = "note bad";
        problem.textContent = e.message;
        go.disabled = false;
        go.textContent = was;
      }
    },
  });
  fill(
    dialog,
    el("h2", { class: "card-title", text: title }),
    el("p", { class: "subtitle", text: body }),
    problem,
    el(
      "div",
      { class: "actions" },
      el("span", { class: "spacer" }),
      el("button", {
        class: "button secondary",
        type: "button",
        text: "Cancel",
        onclick: () => dialog.close(),
      }),
      go,
    ),
  );
  // Removed on close, however it was closed — the button, Escape, or the
  // backdrop — so the page never accumulates dialogs nobody can see.
  dialog.addEventListener("close", () => dialog.remove());
  dialog.addEventListener("click", (e) => {
    if (e.target === dialog) dialog.close();
  });
  document.body.append(dialog);
  dialog.showModal();
  return dialog;
}

/** Ask before deleting a store.
 *
 * A store is minutes of embedding, so the question says what goes and what
 * does not, and the button that answers it is the red one. */
function confirmDelete(name) {
  ask({
    title: `Delete ${name}?`,
    body: "Its vectors, chunks, graph and ledger are deleted, and the registry stops listing it. The files it indexed are untouched.",
    confirm: `Delete ${name}`,
    tone: "bad",
    run: async () => {
      const done = await post("/api/store/delete", { store: name });
      await refreshStores();
      // After the re-render, not before: the render replaces the element the
      // message would have been written into.
      await render();
      note(done.message);
    },
  });
}

/** A line under the page head, for something that just happened to the page. */
function note(text, bad) {
  const holder = document.querySelector(".view > .note.page-note");
  if (!holder) return;
  holder.className = bad ? "note page-note bad" : "note page-note";
  holder.textContent = text;
}

async function storesView() {
  const stores = await refreshStores();

  const rootNote = el("div", { class: "note" });
  /* A root the registry lists and the disk no longer has. The picker is the
   * same one the page already uses, and re-pointing is a registry edit: no
   * re-embedding, nothing rewritten. */
  const rootPicker = folderPicker({
    choose: "Point the store here",
    onError: (message) => {
      rootNote.className = "note bad";
      rootNote.textContent = message;
    },
    onChoose: async (path) => {
      rootNote.className = "note";
      rootNote.textContent = "Re-pointing…";
      try {
        const done = await post("/api/root", { store: rootPicker.store, root: path });
        rootNote.textContent = done.message;
        await refreshStores();
      } catch (e) {
        rootNote.className = "note bad";
        rootNote.textContent = e.message;
      }
    },
  });

  function repoint(store, missing) {
    rootPicker.store = store;
    rootNote.className = "note";
    rootNote.textContent = `Choose where ${missing.split("/").pop() || missing} lives now.`;
    rootPicker.open("");
  }

  const adoptNote = el("div", { class: "note" });
  const picker = folderPicker({
    choose: "Adopt this directory",
    onError: (message) => {
      adoptNote.className = "note bad";
      adoptNote.textContent = message;
    },
    onChoose: async (path) => {
      adoptNote.className = "note";
      adoptNote.textContent = "Adopting…";
      try {
        const done = await post("/api/adopt", { path });
        adoptNote.textContent =
          done.message || `${path} is registered. It joins on the next daemon start.`;
        await refreshStores();
      } catch (e) {
        adoptNote.className = "note bad";
        adoptNote.textContent = e.message;
      }
    },
  });

  const head = pageHead("Stores", "Everything indexed on this machine. Nothing leaves it.", {
    actions: [
      el(
        "button",
        { class: "button secondary", type: "button", onclick: () => picker.open("") },
        icon(ICONS.folder),
        "Adopt existing .semlith",
      ),
      el(
        "button",
        { class: "button", type: "button", onclick: () => go("index") },
        icon(ICONS.plus),
        "Index a folder",
      ),
    ],
  });

  if (!stores.length) {
    return el(
      "div",
      { class: "view" },
      head,
      picker.node,
      adoptNote,
      empty("No store is open. Index a folder and it appears here."),
    );
  }

  const totals = stores.reduce(
    (sum, s) => ({
      files: sum.files + s.files,
      chunks: sum.chunks + s.chunks,
      bytes: sum.bytes + s.bytes,
      lines: sum.lines + (s.lines || 0),
      watching: sum.watching + (s.watching ? 1 : 0),
      formats: Math.max(sum.formats, s.formats || 0),
      readers: Math.max(sum.readers, s.readers || 0),
    }),
    { files: 0, chunks: 0, bytes: 0, lines: 0, watching: 0, formats: 0, readers: 0 },
  );
  const dim = stores.find((s) => s.dim)?.dim;

  const table = dataTable({
    className: "w-stores",
    sort: "name",
    perPage: 10,
    rows: stores,
    columns: [
      {
        key: "name",
        label: "Store",
        value: (s) => s.name,
        render: (s) =>
          el(
            "div",
            { class: "rows tight" },
            lineCell(s.name, "name"),
            pathCell(s.dir, "meta"),
            // The model per store, which the About page states only once for
            // the machine. Two stores can have been built with two models and
            // their vectors are not comparable, so it belongs beside the row.
            lineCell(`${s.model} · ${s.dim} dims`, "meta"),
            // Two things worth saying about a store rather than about its
            // contents: whether this machine has agreed to open it without
            // being told to, and whether anybody else on the machine can read
            // what it holds.
            s.trusted === false
              ? el(
                  "div",
                  { class: "chips" },
                  pill("not trusted", "warn"),
                  el("button", {
                    class: "button secondary small",
                    type: "button",
                    text: "Trust this store",
                    onclick: async (e) => {
                      const button = e.currentTarget;
                      button.disabled = true;
                      adoptNote.className = "note";
                      adoptNote.textContent = "Trusting…";
                      try {
                        await post("/api/trust", { path: s.dir });
                        adoptNote.textContent = `${s.dir} is trusted. semlith opens it from its own directory now, without --store.`;
                        await refreshStores();
                      } catch (err) {
                        adoptNote.className = "note bad";
                        adoptNote.textContent = err.message;
                        button.disabled = false;
                      }
                    },
                  }),
                )
              : null,
            s.loose_mode
              ? el(
                  "div",
                  { class: "chips" },
                  pill(`mode ${s.loose_mode}`, "warn"),
                  el("span", {
                    class: "meta",
                    text: "other users on this machine can read what this store indexed; the next open narrows it to 700",
                  }),
                )
              : null,
          ),
      },
      {
        key: "roots",
        label: "Roots",
        className: "meta narrow-drop",
        sortable: false,
        render: (s) =>
          (s.roots || []).length
            ? s.roots.map((r) =>
                r.present
                  ? pathCell(r.path)
                  : el(
                      "div",
                      { class: "gone-row" },
                      pathCell(r.path, "gone"),
                      // A root the registry still lists and the disk no longer
                      // has. Re-pointing it is one click rather than a command
                      // with two paths in it.
                      el("button", {
                        class: "button danger small",
                        type: "button",
                        text: "Re-point",
                        onclick: () => repoint(s.name, r.path),
                      }),
                    ),
              )
            : "—",
      },
      { key: "files", label: "Files", className: "num", value: (s) => s.files, render: (s) => n(s.files) },
      {
        key: "chunks",
        label: "Chunks",
        className: "num narrow-drop",
        value: (s) => s.chunks,
        render: (s) => n(s.chunks),
      },
      {
        key: "last_write",
        label: "Last write",
        value: (s) => s.last_write || 0,
        // Green means a write landed. A store that is watched and has never
        // been written to is neither good news nor a warning, so it carries a
        // plain pill with no dot at all.
        render: (s) => {
          if (!s.watching) return pill("not watching", "warn");
          return s.last_write ? pill(when(s.last_write), "good") : pill("never");
        },
      },
      {
        key: "open",
        label: "",
        className: "row-end",
        sortable: false,
        // One control rather than a button per action: the destructive one
        // does not belong a mis-aimed click away from the ordinary one.
        render: (s) =>
          rowMenu(() => [
            { label: "Open in Files", onclick: () => go("files") },
            {
              label: "Delete store…",
              tone: "bad",
              onclick: () => confirmDelete(s.name),
            },
          ]),
      },
    ],
  });

  const feed = stores
    .flatMap((s) => (s.events || []).map((e) => ({ at: e.at, text: e.text })))
    .sort((a, b) => b.at - a.at)
    .slice(0, 40);

  return el(
    "div",
    { class: "view" },
    head,
    picker.node,
    adoptNote,
    rootPicker.node,
    rootNote,
    el("div", { class: "note page-note" }),
    el(
      "div",
      { class: "strip" },
      stat("Stores", n(stores.length), `${totals.watching} being watched`),
      stat("Files", n(totals.files), `${n(totals.formats)} formats`),
      stat("Chunks", n(totals.chunks), dim ? `${dim}-dimension vectors` : "embedded and searchable"),
      stat("Lines", n(totals.lines), `${n(totals.readers)} readers in use`),
      stat("On disk", bytes(totals.bytes), "int8 quantised"),
    ),
    el(
      "div",
      { class: "scroller" },
      table.node,
      el(
        "div",
        { class: "grid fill" },
        el(
          "div",
          { class: "card pad dense" },
          el(
            "div",
            { class: "head" },
            el("span", { class: "card-title", text: "Watcher" }),
            el("span", { class: "meta", text: "live" }),
          ),
          feed.length
            ? el(
                "div",
                { class: "feed" },
                // One line per event, with the whole of it on the tooltip. A
                // line that wraps is three lines when it names a path, and
                // forty of those grew the card until it pushed the table it
                // sits under off the page.
                feed.map((e) =>
                  el(
                    "div",
                    { class: "row" },
                    el("span", { class: "at", text: clock(e.at) }),
                    lineCell(e.text, "what"),
                  ),
                ),
              )
            : empty("Nothing has changed on disk since the daemon started."),
        ),
        agentsCard(),
      ),
    ),
  );
}

// ----------------------------------------------------------------- files

async function filesView() {
  const chosenExt = new Set();
  const summary = el("span", { class: "pill" });
  const holder = el("div", {});

  const pathInput = el("input", {
    type: "text",
    placeholder: "path glob, e.g. src/**",
    oninput: () => {
      clearTimeout(load.timer);
      load.timer = setTimeout(() => load(true), 200);
    },
  });

  /** Which request is current, so a slow one cannot overwrite a fast one. */
  let generation = 0;

  async function forget(path, row, store) {
    try {
      // Named, always. The row knows which store holds the file, and a daemon
      // serving two stores cannot guess — it refuses a write that names none,
      // which is what the page used to send.
      await post("/api/forget", { path, store });
      // The row goes, and the page is reloaded behind it: with the server
      // paging, the row that moves up into the gap is on the server.
      row.remove();
      picked.delete(path);
      paintBulk();
      load();
    } catch (e) {
      // In the note, not over the table: an error that replaces the rows
      // takes away the thing the reader was working with. Rethrown so a
      // dialog waiting on this stays open and shows it too.
      bulkNote.className = "note bad";
      bulkNote.textContent = e.message;
      throw e;
    }
  }

  /* The rows ticked for a bulk forget, by path.
   *
   * Kept out here rather than in the table, because the table re-renders on
   * every sort, page and filter and a selection that vanished when you sorted
   * would be a selection nobody could trust. */
  const picked = new Map();
  const bulkNote = el("div", { class: "note" });
  const bulkBar = el("div", { class: "bulk", hidden: true });

  function paintBulk() {
    bulkBar.hidden = picked.size === 0;
    if (!picked.size) return;
    const many = picked.size;
    fill(
      bulkBar,
      el("span", {
        class: "meta",
        text: `${n(many)} file${many === 1 ? "" : "s"} selected`,
      }),
      el("span", { class: "spacer" }),
      el("button", {
        class: "button ghost small",
        type: "button",
        text: "Clear",
        onclick: () => {
          picked.clear();
          for (const box of table.node.querySelectorAll("input.pick")) box.checked = false;
          paintBulk();
        },
      }),
      el("button", {
        class: "button danger small",
        type: "button",
        text: `Forget ${n(many)} file${many === 1 ? "" : "s"}`,
        onclick: (e) => {
          const button = e.currentTarget;
          const stores = [...new Set(picked.values())];
          ask({
            title: `Forget ${n(many)} file${many === 1 ? "" : "s"}?`,
            body: `Their chunks and vectors are dropped from ${stores.join(
              " and ",
            )}. The files on disk are untouched, and indexing the folder again brings them back.`,
            confirm: `Forget ${n(many)} file${many === 1 ? "" : "s"}`,
            tone: "bad",
            run: () => forgetPicked(button),
          });
        },
      }),
    );
  }

  async function forgetPicked(button) {
    button.disabled = true;
    button.textContent = "Forgetting…";
    bulkNote.className = "note";
    bulkNote.textContent = "";
    // One call per store: a write names the store it is for, and a selection
    // made across two of them is two writes, not an ambiguous one.
    const byStore = new Map();
    for (const [path, store] of picked) {
      if (!byStore.has(store)) byStore.set(store, []);
      byStore.get(store).push(path);
    }
    try {
      let files = 0;
      let forgot = 0;
      let absent = 0;
      for (const [store, paths] of byStore) {
        const done = await post("/api/forget", { paths, store });
        // One path in a store answers in the single-file shape.
        files += done.files === undefined ? 1 : done.files;
        forgot += done.forgot || 0;
        absent += (done.not_indexed || []).length;
      }
      picked.clear();
      paintBulk();
      bulkNote.textContent = absent
        ? `${n(files)} file${files === 1 ? "" : "s"} forgotten, ${n(forgot)} chunk${
            forgot === 1 ? "" : "s"
          } removed. ${n(absent)} were not indexed and were left alone.`
        : `${n(files)} file${files === 1 ? "" : "s"} forgotten, ${n(forgot)} chunk${
            forgot === 1 ? "" : "s"
          } removed.`;
      load();
    } catch (e) {
      bulkNote.className = "note bad";
      bulkNote.textContent = e.message;
      button.disabled = false;
      paintBulk();
      // Rethrown so the dialog that asked stays open and shows it too.
      throw e;
    }
  }

  const table = dataTable({
    className: "w-files",
    server: true,
    sort: "path",
    columns: [
      {
        key: "pick",
        label: "",
        className: "pick",
        sortable: false,
        // Selects every row on the page rather than every row in the store: a
        // filter of ten thousand files behind one tick is a mistake nobody
        // meant to make.
        head: () => {
          const all = el("input", {
            type: "checkbox",
            class: "pick all",
            "aria-label": "Select every file on this page",
            onchange: () => {
              for (const box of table.node.querySelectorAll("tbody input.pick")) {
                if (box.checked !== all.checked) box.click();
              }
            },
          });
          return all;
        },
        render: (f) => {
          const box = el("input", {
            type: "checkbox",
            class: "pick",
            "aria-label": `Select ${f.path}`,
            onchange: () => {
              if (box.checked) picked.set(f.path, f.store);
              else picked.delete(f.path);
              paintBulk();
            },
          });
          box.checked = picked.has(f.path);
          return box;
        },
      },
      {
        key: "path",
        label: "Path",
        className: "path",
        // One line, with the whole path on the shared tooltip: a wrapped path
        // makes every row a different height and the column unreadable.
        render: (f) => pathCell(f.path),
      },
      {
        key: "store",
        label: "Store",
        className: "meta narrow-drop",
        sortable: false,
        render: (f) => f.store,
      },
      {
        key: "reader",
        label: "Read as",
        className: "narrow-drop",
        sortable: false,
        render: (f) => el("span", { class: "tag", text: f.reader }),
      },
      {
        key: "lang",
        label: "Language",
        className: "meta narrow-drop",
        sortable: false,
        render: (f) => f.lang || "—",
      },
      {
        key: "lines",
        label: "Lines",
        className: "num",
        // An image has no lines. Its pixel size goes here rather than a zero,
        // which would read as a file that failed to parse.
        render: (f) => (f.reader === "image" ? "—" : n(f.lines)),
      },
      { key: "chunks", label: "Chunks", className: "num narrow-drop", render: (f) => n(f.chunks) },
      {
        key: "indexed",
        label: "Indexed",
        className: "meta",
        render: (f) => when(f.indexed_at),
      },
      {
        key: "forget",
        label: "",
        sortable: false,
        render: (f) => {
          const button = el("button", {
            class: "forget",
            type: "button",
            text: "Forget",
            onclick: () => {
              const row = button.closest("tr");
              ask({
                title: "Forget this file?",
                body: `${f.path} — its chunks and vectors are dropped from ${f.store}. The file on disk is untouched, and indexing the folder again brings it back.`,
                confirm: "Forget it",
                tone: "bad",
                run: async () => {
                  button.disabled = true;
                  button.textContent = "Forgetting…";
                  await forget(f.path, row, f.store);
                },
              });
            },
          });
          return button;
        },
      },
    ],
    rows: [],
    total: 0,
    onChange: () => load(),
  });

  async function load(reset) {
    const mine = ++generation;
    const view = table.query();
    if (reset) view.page = 1;
    const params = new URLSearchParams();
    if (pathInput.value.trim()) params.set("path", pathInput.value.trim());
    for (const ext of chosenExt) params.append("ext", ext);
    params.set("sort", view.sort || "path");
    params.set("dir", view.dir);
    params.set("limit", String(view.perPage));
    params.set("offset", String((view.page - 1) * view.perPage));

    let data;
    try {
      data = await api(`/api/files?${params}`);
    } catch (e) {
      if (mine !== generation) return;
      fill(holder, el("div", { class: "card pad" }, error(e.message)));
      summary.textContent = "";
      return;
    }
    if (mine !== generation) return;

    summary.textContent = `${n(data.total)} files · ${n(data.formats)} format${
      data.formats === 1 ? "" : "s"
    } · ${n(data.stores)} store${data.stores === 1 ? "" : "s"}`;

    if (!data.total) {
      fill(
        holder,
        el(
          "div",
          { class: "card pad" },
          empty("Nothing indexed matches that. The filter, not the corpus — clear it and look again."),
        ),
      );
      return;
    }
    table.update(data.files, data.total);
    if (!holder.contains(table.node)) fill(holder, table.node);
  }

  // The formats this release added are on the list, so they are one click away
  // rather than something you have to know to type.
  const EXTENSIONS = ["rs", "md", "py", "ts", "js", "go", "pdf", "docx", "epub", "png", "jpg"];
  const extChips = EXTENSIONS.map((ext) =>
    el("button", {
      class: "chip",
      type: "button",
      "aria-pressed": "false",
      text: `.${ext}`,
      onclick: (e) => {
        const on = e.currentTarget.getAttribute("aria-pressed") !== "true";
        e.currentTarget.setAttribute("aria-pressed", String(on));
        if (on) chosenExt.add(ext);
        else chosenExt.delete(ext);
        clearTimeout(load.timer);
        load(true);
      },
    }),
  );

  load();

  return el(
    "div",
    { class: "view" },
    pageHead(
      "Files",
      "What is indexed, and which reader parsed it — so “not indexed” and “not discussed” stop looking the same.",
      { pill: summary },
    ),
    el(
      "div",
      { class: "filters" },
      el(
        "div",
        { class: "field wide" },
        icon(ICONS.search, 15),
        labelled("files-filter", "Filter files by path glob", pathInput),
      ),
      extChips,
    ),
    bulkBar,
    bulkNote,
    holder,
    el("p", {
      class: "subtitle",
      text: "Forget drops the file's chunks and vectors. The file on disk is untouched.",
    }),
  );
}

// ------------------------------------------------------- read and pattern

/* Which store a question is asked of. One choice rather than a row of
 * independent toggles: "All stores" is a state a reader can name, where three
 * chips half-lit is a filter they have to reconstruct from the lighting. */
function storePicker(initial, onChange) {
  let picked = initial || "";
  const row = el("div", { class: "store-chips" });
  const paint = () => {
    for (const chip of row.children) {
      chip.setAttribute("aria-pressed", String(chip.getAttribute("data-store") === picked));
    }
  };
  const add = (name, label) =>
    row.append(
      el("button", {
        class: "chip",
        type: "button",
        "data-store": name,
        text: label,
        onclick: () => {
          picked = name;
          paint();
          onChange();
        },
      }),
    );
  add("", "All stores");
  for (const store of state.stores) add(store.name, store.name);
  paint();
  return { node: row, stores: () => (picked ? [picked] : []) };
}

/* Whether the file still looks the way it did when it was indexed — the dot
 * and the word together. The dot alone was a colour with the meaning in a
 * tooltip, which is no meaning at all on a phone or in a screenshot. */
function freshMark(fresh) {
  const ok = fresh !== false;
  return el(
    "span",
    {
      class: "fresh",
      title: ok ? "indexed from the bytes on disk" : "file changed since it was indexed",
    },
    el("span", { class: `fresh-dot ${ok ? "is-fresh" : "is-stale"}` }),
    el("span", { class: "word", text: ok ? "fresh" : "stale" }),
  );
}

/* Code with a line-number gutter, numbered from the span's own first line —
 * the same coordinates `semlith read` and every error message print, so a
 * number read here can be typed back in without arithmetic. */
function codeGutter(text, startLine) {
  const from = Number(startLine) || 1;
  return el(
    "div",
    { class: "gutter-code" },
    String(text == null ? "" : text)
      .split("\n")
      .map((line, i) =>
        el(
          "div",
          { class: "code-line" },
          el("span", { class: "ln", text: String(from + i) }),
          el("span", { class: "lt", text: line }),
        ),
      ),
  );
}

/** One span, as `/api/read` returns it. */
function spanCard(span) {
  const named = span.symbol ? `${span.symbol_kind || ""} ${span.symbol}`.trim() : "";
  return el(
    "div",
    { class: "span-card" },
    el(
      "div",
      { class: "span-head" },
      el("span", { class: "path", text: span.path }),
      el("span", { class: "lines", text: `${span.start_line}-${span.end_line}` }),
      span.store ? el("span", { class: "from", text: span.store }) : null,
      el("span", { class: "spacer" }),
      freshMark(span.fresh),
    ),
    named ? el("div", { class: "sig", text: named }) : null,
    codeGutter(span.text, span.start_line),
  );
}
// ---------------------------------------------------------------- search

/* Which of the ranked lists found a hit. The word rather than an initial: a
 * hit the graph alone reached is a neighbour of a match rather than a match,
 * and `g` said that only to a reader who hovered it. */
const LIST_LABELS = {
  vector: "vector — the embedding matched",
  keyword: "full text — the terms matched",
  graph: "graph — reached from a neighbouring symbol",
  image: "image — the picture matched the words",
};

function fusionBadges(lists) {
  if (!lists || !lists.length) return null;
  return el(
    "span",
    { class: "badges" },
    lists.map((list) =>
      el("span", { class: `badge ${list}`, title: LIST_LABELS[list] || list, text: list }),
    ),
  );
}

/* The four confidence values an edge or a graph-found hit can carry, and what
 * each one actually claims. Never rendered without one: a hop with no badge is
 * a hop a reader will assume was verified. */
const CONFIDENCE = {
  extracted: ["extracted", "the import names the target"],
  resolved: ["resolved", "name and module hint agree on one definition"],
  inferred: ["inferred", "matched by bare name"],
  ambiguous: ["ambiguous", "several definitions, none chosen"],
};

function confidenceBadge(value) {
  if (!value) return null;
  const [label, why] = CONFIDENCE[value] || [value, ""];
  return el("span", { class: `conf ${value}`, title: why, text: label });
}

/* What a graph-reached hit's provenance means, as a sentence rather than as a
 * badge nobody can expand. A reader who does not know what `inferred` claims
 * reads every row as verified. */
const PROVENANCE_NOTE = {
  extracted: "Found through the graph: the source names the target, so nothing had to be ranked.",
  resolved: "Found through the graph: the name and its module hint agree on one definition.",
  inferred: "Found through the graph by bare name. Corroborate before you rely on it.",
  ambiguous:
    "Found through the graph, but several definitions carry this name and none was chosen.",
};

/* The one line of a chunk worth showing in a locator row: the line with most
 * of the query's words in it, or the first line with anything on it. */
function bestLine(text, query) {
  const terms = (query || "")
    .split(/[^A-Za-z0-9_]+/)
    .filter((t) => t.length > 2)
    .map((t) => t.toLowerCase());
  let best = null;
  let bestScore = -1;
  for (const raw of (text || "").split("\n")) {
    const line = raw.trim();
    if (!line) continue;
    const lowered = line.toLowerCase();
    const score = terms.filter((t) => lowered.includes(t)).length;
    if (score > bestScore) {
      bestScore = score;
      best = line;
    }
  }
  if (!best) return "";
  // Capped as the tool caps it, rather than left to the stylesheet's ellipsis:
  // a row is one line of context, and a minified file would otherwise put a
  // whole line of it into the page for the browser to hide.
  return best.length > 120 ? `${best.slice(0, 120)}…` : best;
}

/* What one locator row costs, counted the way `mcp::locate` counts it: the
 * text the row actually renders, at four characters to a token. */
function rowCost(hit, query) {
  const named = hit.symbol ? `${hit.symbol_kind || ""} ${hit.symbol}`.trim() : "";
  const marks = (hit.lists || []).join("+") + (hit.fresh === false ? " stale" : "");
  const row = `  ${hit.start_line}-${hit.end_line} ${named} ${marks}\n    ${bestLine(
    hit.text,
    query,
  )}\n`;
  return Math.ceil(row.length / 4);
}

/** The likeliest symbol name in a hit, for the link into the graph. */
function symbolIn(hit) {
  const match = hit.text.match(
    /(?:fn|function|def|func|class|struct|interface|type)\s+([A-Za-z_][A-Za-z0-9_]*)/,
  );
  return match ? match[1] : "";
}

async function searchView() {
  await refreshStores();

  const results = el("div", { class: "results locate-list" });
  const bodyCard = el("div", { class: "span-card" });
  const aroundName = el("span", { class: "sym" });
  const footer = el("div", { class: "locate-footer" });
  const meta = el("span", { class: "search-meta" });
  /* The shape the ranker read and what it did about it, from the answer's own
   * fields. Re-deriving the rule here would be a second classifier, and only
   * one of the two ranked the hits underneath it. */
  const shapeHint = el("div", { class: "shape-hint", hidden: true });

  /* The second ring, drawn rather than linked. One canvas for the whole visit
   * to the page: a fresh one per opened hit would be a fresh animation loop
   * per click. */
  const ego = graphCanvas({
    /* The same two handlers the Graph page passes, so the panel behaves like
     * the page it is a window onto rather than like a picture of it: a node
     * lifts on hover with a card naming it, and a click selects it and its
     * neighbours. Without these the hint underneath — "drag a node · click to
     * select" — described something that did not happen. */
    onHover: (node, x, y) => {
      if (!node) return tip.hide("ego");
      tip.atPoint(
        x,
        y,
        [
          el("div", { class: "tip-head" }, el("i", {}), node.name),
          node.kind ? egoRow("kind", node.kind) : null,
          node.path
            ? egoRow("file", `${shortPath(node.path)}:${node.start_line}-${node.end_line}`)
            : null,
        ].filter(Boolean),
        "ego",
      );
    },
    onPick: (node) => {
      aroundName.textContent = node ? node.name : "—";
    },
  });
  const stage = el(
    "div",
    { class: "ego-panel", hidden: true },
    ego.node,
    el("span", { class: "ego-hint", text: "drag a node · click to select" }),
  );
  /* Both hidden until a row is open. The panel is tall enough to be a graph
   * rather than a thumbnail, which makes it a large empty box on a page nobody
   * has searched yet — and "Around" with nothing after it is a heading for
   * something that is not there. */
  const aroundHead = el(
    "div",
    { class: "around-head", hidden: true },
    el("span", { class: "title" }, "Around ", aroundName),
    el("span", { class: "meta", text: "graph expansion" }),
  );
  const showRing = (on) => {
    stage.hidden = !on;
    aroundHead.hidden = !on;
  };

  // The dials, in the design's order. Each is the same control an agent sets
  // on the tool, shown here so a person can see what the agent is holding.
  let k = 8;
  const kValue = el("span", { class: "dial-value", text: "k = 8" });
  const bump = (delta) => {
    const next = Math.min(50, Math.max(1, k + delta));
    if (next === k) return;
    k = next;
    kValue.textContent = `k = ${k}`;
    run();
  };
  const kDial = el(
    "div",
    { class: "dial" },
    kValue,
    el("button", { class: "step", type: "button", "aria-label": "fewer hits", title: "fewer hits", text: "–", onclick: () => bump(-1) }),
    el("button", { class: "step", type: "button", "aria-label": "more hits", title: "more hits", text: "+", onclick: () => bump(1) }),
  );

  /* Which side of the corpus to lean towards. Live from 0.16.0: the query text
   * says how a question was written, and this says what the asker is after,
   * which the text cannot. */
  let prefer = "any";
  const preferPills = ["code", "docs", "any"].map((name) =>
    el("button", {
      class: "seg",
      type: "button",
      "aria-pressed": String(name === prefer),
      text: name,
      onclick: () => {
        if (prefer === name) return;
        prefer = name;
        for (const pill of preferPills) {
          pill.setAttribute("aria-pressed", String(pill.textContent === prefer));
        }
        run();
      },
    }),
  );
  const preferDial = el(
    "div",
    { class: "dial" },
    el("span", { class: "dial-label", text: "Prefer" }),
    el("span", { class: "segs" }, preferPills),
  );

  const langField = el("input", { class: "bare", size: "8", placeholder: "any", onchange: () => run() });
  const pathField = el("input", { class: "bare", size: "8", placeholder: "any", onchange: () => run() });
  const langDial = el(
    "div",
    { class: "dial" },
    el("span", { class: "dial-prefix", text: "lang:" }),
    labelled("search-lang", "Only this language", langField),
  );
  const pathDial = el(
    "div",
    { class: "dial" },
    el("span", { class: "dial-prefix", text: "path:" }),
    labelled("search-path", "Only paths matching this glob", pathField),
  );

  const budgetField = el("input", { class: "bare", size: "5", value: "1500", inputmode: "numeric", onchange: () => run() });
  const budgetDial = el(
    "div",
    { class: "dial" },
    el("span", { class: "dial-label", text: "Budget" }),
    labelled("search-budget", "Budget in tokens", budgetField),
    el("span", { class: "unit", text: "tok" }),
  );
  const budget = () => Math.max(200, Number(String(budgetField.value).replace(/[^0-9]/g, "")) || 1500);

  // Restored rather than reset: the question and the store filter survive a
  // trip to another page, because coming back to an empty box means typing it
  // again.
  const picker = storePicker(state.search.stores[0] || "", () => run());
  let generation = 0;

  const input = el("input", {
    type: "search",
    placeholder: "Ask it something",
    oninput: () => {
      // The hint is about the query in the box. An empty box has no shape.
      if (!input.value.trim()) shapeHint.hidden = true;
    },
    onkeydown: (e) => {
      if (e.key === "Enter") run();
    },
  });

  const nothing = () =>
    empty("Type a phrase or an identifier. Both halves of the search run either way.");

  async function run() {
    const query = input.value.trim();
    state.search = { query, stores: picker.stores() };
    if (!query) {
      shapeHint.hidden = true;
      fill(results, nothing());
      showBody(null, "");
      fill(footer);
      meta.textContent = "";
      return;
    }

    const mine = ++generation;
    const params = new URLSearchParams({ query, k: String(k), prefer });
    for (const store of picker.stores()) params.append("store", store);
    const lang = langField.value.trim();
    const path = pathField.value.trim();
    if (lang) params.append("lang", lang);
    if (path) params.append("path", path);

    meta.textContent = "searching…";
    let data;
    try {
      data = await api(`/api/search?${params}`);
    } catch (e) {
      if (mine !== generation) return;
      fill(results, error(e.message));
      showBody(null, "");
      fill(footer);
      meta.textContent = "";
      return;
    }
    if (mine !== generation) return;

    if (data.shape_label) {
      fill(
        shapeHint,
        el("span", { class: "dot" }),
        el("span", { text: `${data.shape_label} · ${data.weighting}` }),
      );
      shapeHint.hidden = false;
    }

    // Hits and how long, which is what the question was. The corpus size is a
    // fact about the store, and the Stores page is where it is asked.
    meta.textContent = data.hits.length
      ? `${data.hits.length} hit${data.hits.length === 1 ? "" : "s"} · ${(data.micros / 1000).toFixed(1)} ms`
      : "";

    if (!data.hits.length) {
      showBody(null, "");
      fill(footer);
      fill(
        results,
        empty(
          "No chunk in the selected stores matches that. If a store chip is on it is the filter, not the corpus — clear it and ask again.",
        ),
      );
      return;
    }

    // Grouped by file, in the order the ranking put the files in: eight hits
    // in one file are one file to open, and the best hit's file is the first
    // thing read.
    const groups = [];
    for (const hit of data.hits) {
      const found = groups.find((g) => g.path === hit.path && g.store === hit.store);
      if (found) found.hits.push(hit);
      else groups.push({ path: hit.path, store: hit.store, hits: [hit] });
    }

    // Cut to the budget, lowest-ranked first, exactly as the tool does — and
    // the footer says so. A footer that reported a budget nothing enforced
    // would be a number for decoration; a list that silently dropped rows
    // would be worse.
    const cap = budget();
    let spent = 0;
    const shown = [];
    for (const group of groups) {
      // What the *rows* cost, not what the chunks behind them cost. A locate
      // row is one line of a chunk however long the chunk is, which is the
      // whole point of the format — measuring the chunk here would make the
      // page cut at a tenth of the budget the tool cuts at, for the same
      // number in the same box.
      const cost = group.hits.reduce((total, hit) => total + rowCost(hit, query), 4);
      // The first group always shows, whatever it costs: a budget that
      // returned nothing would turn a search into a silent failure.
      if (shown.length && spent + cost > cap) break;
      spent += cost;
      shown.push(group);
    }
    const kept = shown.reduce((total, group) => total + group.hits.length, 0);

    fill(
      results,
      shown.map((group) => {
        const spans = group.hits.map((hit) => `${hit.start_line}-${hit.end_line}`);
        return el(
          "div",
          { class: "locate-group" },
          el(
            "div",
            { class: "locate-file" },
            el("span", { class: "file", "data-tip": group.path, text: shortPath(group.path) }),
            group.store ? el("span", { class: "from", text: group.store }) : null,
            el("span", { class: "spacer" }),
            el("span", {
              class: "span-summary",
              text: spans.length > 1 ? `${spans.length} spans · ${spans.join(", ")}` : spans[0],
            }),
          ),
          group.hits.map((hit) => locateRow(hit, query)),
        );
      }),
    );
    fill(
      footer,
      el("span", {
        text: `${kept} of ${data.hits.length} shown · ${n(spent)} tokens · budget ${n(cap)}`,
      }),
      kept < data.hits.length
        ? el("span", {
            class: "truncated",
            text: `truncated: ${kept} of ${data.hits.length}`,
          })
        : null,
    );
    // The body panel starts on the best hit rather than empty: the first
    // question anyone has about a result list is what the top one says.
    const first = results.querySelector(".locate-row");
    if (first) first.setAttribute("aria-pressed", "true");
    showBody(shown[0].hits[0], query);
  }

  /* One locator line: where it is, what it is called, how it was found,
   * whether the file has moved under it, and one line of it. Both lines sit
   * inside the one control, so the excerpt is part of the target rather than
   * a strip of dead pixels under it. */
  function locateRow(hit, query) {
    const line = bestLine(hit.text, query);
    const row = el(
      "button",
      {
        class: "locate-row",
        type: "button",
        "aria-pressed": "false",
        onclick: () => {
          for (const other of results.querySelectorAll(".locate-row")) {
            other.setAttribute("aria-pressed", "false");
          }
          row.setAttribute("aria-pressed", "true");
          showBody(hit, query);
        },
      },
      el(
        "span",
        { class: "row-top" },
        el("span", {
          class: "lines",
          text: hit.image
            ? `${hit.image.width}×${hit.image.height} px`
            : `${hit.start_line}-${hit.end_line}`,
        }),
        // A hit with no symbol is prose, said rather than left as a gap the
        // reader has to interpret. An image is neither, and its badge and its
        // pixel dimensions have already said so.
        hit.image
          ? null
          : el("span", {
              class: "sym",
              text: hit.symbol ? `${hit.symbol_kind || ""} ${hit.symbol}`.trim() : "prose",
            }),
        fusionBadges(hit.lists),
        el("span", { class: "spacer" }),
        freshMark(hit.fresh),
        // Only for a hit the graph reached: a vector match has no provenance
        // to state beyond the badge it already carries.
        confidenceBadge(hit.provenance),
      ),
      line ? el("span", { class: "locate-excerpt", text: line }) : null,
    );
    return row;
  }

  /* The second stage: the span itself, once a row has been chosen.
   *
   * What the row already carries is painted at once; the signature, the
   * symbol's whole span and the neighbourhood arrive from `/api/read` and
   * `/api/symbol` after it, because none of them is worth a spinner over the
   * text the reader clicked for.
   */
  let openHit = null;
  let openQuery = "";
  let wholeSpan = null;
  let signature = "";
  let whole = false;
  /* How many definitions the second read found. `many` is not a failure — it
   * is the store saying it cannot tell which one this is, and the button says
   * that rather than pretending there is nothing more to open. */
  let definitions = 0;
  let bodyGeneration = 0;

  function showBody(hit, query) {
    openHit = hit;
    openQuery = query;
    wholeSpan = null;
    signature = "";
    whole = false;
    definitions = 0;
    const mine = ++bodyGeneration;
    paintBody();
    if (!hit) {
      ego.draw({ nodes: [], edges: [] }, null);
      aroundName.textContent = "—";
      return;
    }

    const target = hit.symbol || `${hit.path}:${hit.start_line}`;
    const params = new URLSearchParams({ target });
    if (hit.store) params.append("store", hit.store);
    api(`/api/read?${params}`)
      .then((data) => {
        if (mine !== bodyGeneration) return;
        if (!data.span) {
          definitions = (data.definitions || []).length;
          if (definitions) paintBody();
          return;
        }
        wholeSpan = data.span;
        // The signature is the first line of the definition, which is where
        // every language this indexes puts it.
        if (hit.symbol) {
          signature = (data.span.text || "")
            .split("\n")
            .map((l) => l.trim())
            .find((l) => l.length > 0) || "";
        }
        paintBody();
      })
      .catch(() => {
        /* The row's own text is already on screen; a failed second read is
         * not worth replacing it with an error. */
      });

    drawAround(hit, mine);
  }

  function paintBody() {
    const hit = openHit;
    if (!hit) {
      fill(
        bodyCard,
        empty("Pick a row. The span opens here, with what it is called and how it was found."),
      );
      showRing(false);
      return;
    }
    const showing = whole && wholeSpan ? wholeSpan : hit;
    const lines = `${showing.start_line}-${showing.end_line}`;
    // Nothing wider to open: a button that redraws the same lines is a button
    // that makes a reader doubt they clicked it.
    const wider =
      wholeSpan &&
      (wholeSpan.start_line < hit.start_line || wholeSpan.end_line > hit.end_line);

    fill(
      bodyCard,
      el(
        "div",
        { class: "span-head" },
        el("span", { class: "path", "data-tip": hit.path, text: shortPath(hit.path) }),
        el("span", { class: "lines", text: lines }),
        el("span", { class: "spacer" }),
        freshMark(hit.fresh),
        confidenceBadge(hit.provenance),
      ),
      hit.provenance && PROVENANCE_NOTE[hit.provenance]
        ? el("p", { class: "prov-note", text: PROVENANCE_NOTE[hit.provenance] })
        : null,
      hit.fresh === false
        ? el("p", {
            class: "note",
            text: "This file has changed since it was indexed. The lines below are what was read then.",
          })
        : null,
      signature ? el("div", { class: "sig", text: signature }) : null,
      hit.image ? imagePreview(hit.path) : codeGutter(showing.text, showing.start_line),
      el(
        "div",
        { class: "span-foot" },
        el("button", {
          class: "button secondary small",
          type: "button",
          disabled: !wider,
          title: wider
            ? null
            : definitions
              ? `${definitions} definitions carry this name, and which one this is was not settled. The Read page lists them.`
              : "this span is already the whole of it",
          text: whole
            ? "Collapse to the matched span"
            : hit.symbol
              ? "Read whole symbol"
              : "Read the whole section",
          onclick: () => {
            whole = !whole;
            paintBody();
          },
        }),
        el("span", {
          class: "body-meta",
          "data-tip": hit.path,
          text: `semlith_read · ${shortPath(hit.path)}:${lines} · second stage`,
        }),
        el("span", { class: "spacer" }),
        el("a", {
          href: "#graph",
          class: "quiet",
          text: "Open in graph",
          onclick: (e) => {
            e.preventDefault();
            state.pendingSymbol = hit.symbol || symbolIn(hit);
            go("graph");
          },
        }),
      ),
    );
  }

  /* The neighbourhood of the open hit, one ring out and then one more, from
   * the evidence block `/api/symbol` already returns. Drawn here rather than
   * linked to, because leaving the page to see what calls this loses the span
   * that raised the question. */
  async function drawAround(hit, mine) {
    const name = hit.symbol || symbolIn(hit);
    aroundName.textContent = name || "—";
    // A hit in prose sits inside no definition, so there is no ring to draw
    // and no heading worth showing over an empty canvas.
    if (!name) {
      showRing(false);
      return ego.draw({ nodes: [], edges: [] }, null);
    }
    showRing(true);
    const params = new URLSearchParams({ name });
    if (hit.store) params.append("store", hit.store);
    let data;
    try {
      data = await api(`/api/symbol?${params}`);
    } catch (_) {
      return;
    }
    if (mine !== bodyGeneration) return;
    ego.draw(egoGraph(name, data), null);
    /* Select the symbol the panel is about, so it arrives drawn in the accent
     * with its neighbours lifted — the state the Graph page puts a focused node
     * in. Before this the centre was one grey box among twenty. */
    ego.pick(name);
  }

  fill(results, nothing());
  paintBody();
  setTimeout(() => {
    ego.start();
    if (state.pendingQuery) {
      input.value = state.pendingQuery;
      state.pendingQuery = "";
      run();
    } else if (state.search.query) {
      input.value = state.search.query;
      run();
    }
    input.focus();
  }, 0);

  return el(
    "div",
    { class: "search-page" },
    el(
      "div",
      { class: "search-band" },
      el("h1", { class: "sr-only", text: "Search" }),
      el(
        "div",
        { class: "search-field" },
        icon(ICONS.search, 18),
        labelled("search-query", "Search the index", input),
        meta,
      ),
      shapeHint,
      el(
        "div",
        { class: "filters" },
        picker.node,
        el("span", { class: "rule" }),
        kDial,
        preferDial,
        langDial,
        pathDial,
        budgetDial,
        el("span", { class: "dial-note", text: "what one answer may cost an agent" }),
      ),
    ),
    el(
      "div",
      { class: "two-stage" },
      el("div", { class: "locate-col" }, results, footer),
      el(
        "div",
        { class: "body-col" },
        bodyCard,
        aroundHead,
        stage,
      ),
    ),
  );
}

/* The evidence block, as a graph the canvas can draw: the symbol at the
 * centre, its callers and callees around it, and the second ring hung off the
 * first-ring name it was reached through — `via` is the whole of what makes
 * it a second ring rather than another neighbour.
 *
 * A caller or callee row is an `EdgeEnd`, which flattens the symbol it
 * reached into itself: the name is on the row, not under a `symbol` key, and
 * `kind` is the edge's kind rather than the symbol's. */
/** One `key  value` line in the ego panel's hover card. */
function egoRow(key, value) {
  return el(
    "div",
    { class: "tip-row" },
    el("span", { class: "k", text: key }),
    el("span", { class: "v", text: String(value) }),
  );
}

function egoGraph(name, data) {
  const centre = (data.symbols || [])[0] || {};
  const nodes = [
    {
      name,
      kind: centre.kind || "symbol",
      path: centre.path,
      start_line: centre.start_line,
      end_line: centre.end_line,
    },
  ];
  const index = new Map([[name, 0]]);
  const edges = [];
  /* `where` is the symbol row an edge resolved to, when there was one. The
   * hover card says which file a neighbour lives in, which is most of what
   * anyone wants from it. */
  const add = (label, kind, where) => {
    if (!index.has(label)) {
      index.set(label, nodes.length);
      nodes.push({
        name: label,
        kind,
        path: where && where.path,
        start_line: where && where.start_line,
        end_line: where && where.end_line,
      });
    }
    return index.get(label);
  };
  const link = (from, to, kind, confidence) => {
    if (from !== to) edges.push({ from, to, kind, confidence });
  };
  for (const end of data.callers || []) {
    link(add(end.name, end.kind, end), 0, end.kind, end.confidence);
  }
  for (const end of data.callees || []) {
    link(0, add(end.name, end.kind, end), end.kind, end.confidence);
  }
  for (const hop of data.ego || []) {
    const via = index.get(hop.via);
    if (via === undefined) continue;
    const it = add(hop.name, hop.kind);
    if (hop.direction === "caller") link(it, via, hop.kind, hop.confidence);
    else link(via, it, hop.kind, hop.confidence);
  }
  return { nodes, edges };
}

// ----------------------------------------------------------------- index

async function indexView() {
  await refreshStores();

  // Hidden until there is something to say. An empty terminal-coloured slab
  // under an idle page is a block of nothing pretending to be output.
  const log = el("div", { class: "log", "aria-live": "polite", hidden: true });
  const bar = el("span", {});
  // Set through CSSOM rather than a style attribute: the CSP blocks the
  // attribute, and this is the one value that genuinely has to be dynamic.
  bar.style.width = "0%";
  const pct = el("span", { class: "pct", text: "0%" });
  const status = el("span", { class: "meta", text: "idle" });
  const picker = folderPicker({
    onChoose: (path) => {
      field.value = path;
    },
    onError: (message) => complain(message),
  });
  const note = el("div", { class: "note" });
  const urlCard = el("div", { class: "card pad", hidden: true });
  const urlNote = el("div", { class: "note" });

  const folderButton = el(
    "button",
    {
      class: "button secondary",
      type: "button",
      "aria-pressed": "false",
      onclick: () => reveal("picker"),
    },
    icon(ICONS.folder),
    "Choose folder…",
  );
  const urlButton = el(
    "button",
    {
      class: "button secondary",
      type: "button",
      "aria-pressed": "false",
      onclick: () => reveal("url"),
    },
    icon(ICONS.file),
    "Add from a URL",
  );

  /* The two ways to start a queue are mutually exclusive: showing a folder
   * picker and a URL field at once offers two answers to one question. Both
   * start closed, so the page opens on the path field and its actions, and the
   * button that opened one stays lit while it is open. */
  function reveal(which) {
    const wantPicker = which === "picker" && !picker.isOpen();
    const wantUrl = which === "url" && urlCard.hidden;
    if (!wantPicker) picker.close();
    urlCard.hidden = !wantUrl;
    if (wantPicker) picker.open("");
    if (wantUrl) urlField.focus();
    folderButton.setAttribute("aria-pressed", String(wantPicker));
    urlButton.setAttribute("aria-pressed", String(wantUrl));
  }

  const field = el("input", {
    type: "text",
    placeholder: "~/work/api",
    value: state.pendingPath || "",
  });
  state.pendingPath = "";
  const urlField = el("input", { type: "text", placeholder: "link to a page, a PDF or a file" });

  const start = el("button", { class: "button", type: "button", text: "Start indexing" });
  /* While a run is on, Start becomes Pause and Stop appears beside it. A run
   * holds the writer, so these are the only two things a reader can do about
   * one that is taking longer than they expected. */
  const stopButton = el("button", {
    class: "button secondary",
    type: "button",
    text: "Stop",
    hidden: true,
  });
  let running = false;
  let paused = false;

  /** Send pause, resume or stop to the store the run is writing to. */
  async function control(action) {
    return post("/api/index/control", {
      action,
      store: storeSelect.value || undefined,
    });
  }

  function showRunning(on) {
    running = on;
    paused = false;
    stopButton.hidden = !on;
    stopButton.disabled = false;
    stopButton.textContent = "Stop";
    start.textContent = on ? "Pause" : "Start indexing";
    start.disabled = false;
    addButton.disabled = on;
  }
  const addButton = el("button", { class: "button secondary", type: "button", text: "Fetch and index" });

  const storeSelect = el(
    "select",
    { class: "field", "aria-label": "Store to write to" },
    state.stores.map((store) => el("option", { value: store.name, text: store.name })),
  );

  function say(text, key, outcome) {
    log.hidden = false;
    log.append(
      el(
        "div",
        // The outcome colours the line, so a wall of "unchanged" reads as
        // background and the files actually being embedded stand out of it.
        { class: outcome ? `line ${outcome}` : "line" },
        key ? el("span", { class: "key", text: key }) : null,
        outcome ? el("span", { class: "outcome", text: outcome }) : null,
        el("span", { class: "what", text }),
      ),
    );
    // Only while the reader is already at the end: scrolling back through a
    // long run should not be yanked away by the next line.
    const atEnd = log.scrollHeight - log.scrollTop - log.clientHeight < 40;
    if (atEnd) log.scrollTop = log.scrollHeight;
  }

  function complain(message, focus) {
    note.className = "note bad";
    note.textContent = message;
    if (focus) focus.focus();
  }

  /* One reader for both buttons. /api/add fetches the URL and then hands what
   * landed to the same write queue a folder goes through, so it answers with
   * the same event stream and there is no second progress mechanism. */
  async function run(route, body) {
    showRunning(true);
    note.className = "note";
    note.textContent = "";
    log.replaceChildren();
    say(`POST ${route} · newline-delimited JSON, chunked`, "→");
    bar.style.width = "0%";
    pct.textContent = "0%";
    status.textContent = "working";

    try {
      const response = await fetch(route, {
        method: "POST",
        credentials: "omit",
        headers: authed({ "Content-Type": "application/json" }),
        body: JSON.stringify({ ...body, store: storeSelect.value || undefined }),
      });
      if (!response.ok) {
        // The body is the same `{"error": ...}` shape every other route
        // answers with, and showing the JSON rather than the sentence inside
        // it is how a clear message arrives looking like a fault.
        const body = await response.text();
        let detail = body;
        try {
          detail = JSON.parse(body).error || body;
        } catch (_) {
          /* a plain-text body is fine too */
        }
        throw new Error(detail || response.statusText);
      }

      // The response is chunked and arrives while the writer works, so it is
      // read as it comes rather than awaited whole — the point of streaming it.
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let buffer = "";
      for (;;) {
        const { value, done } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true });
        let cut;
        while ((cut = buffer.indexOf("\n")) >= 0) {
          const line = buffer.slice(0, cut).trim();
          buffer = buffer.slice(cut + 1);
          if (!line) continue;
          const event = JSON.parse(line);
          if (event.event === "queued") {
            // The writer is one thread. Saying so is the difference between a
            // page that looks stuck and a page that is waiting its turn.
            status.textContent = event.ahead
              ? `queued — ${n(event.ahead)} ahead of it`
              : "queued for the writer";
            say(
              event.ahead
                ? `waiting for ${event.store}'s writer — ${n(event.ahead)} job${
                    event.ahead === 1 ? "" : "s"
                  } ahead of this one`
                : `waiting for ${event.store}'s writer; it finishes what the watcher is doing first`,
              "queued",
            );
          } else if (event.event === "started") {
            status.textContent = "walking the tree";
            say("walking the tree and hashing what it finds", "start");
          } else if (event.event === "file") {
            const share = event.total ? (event.scanned / event.total) * 100 : 0;
            const shown = Math.min(100, share);
            bar.style.width = `${shown.toFixed(1)}%`;
            pct.textContent = `${Math.round(shown)}%`;
            // The same three facts the terminal prints: which file, what is
            // happening to it, and the run's totals so far. Every file says
            // something, so a re-index of an unchanged corpus is a list of
            // "unchanged" rather than a bar that sits at nothing and then
            // jumps to done.
            const rate = event.elapsed_ms
              ? Math.round((event.chunks / event.elapsed_ms) * 1000)
              : 0;
            status.textContent = `${event.scanned}/${event.total} files · ${n(
              event.chunks,
            )} chunks${rate ? ` · ${n(rate)} chunks/s` : ""}`;
            say(event.path, `${event.scanned}/${event.total}`, event.outcome);
          } else if (event.event === "done") {
            /* Named, one line each, with the rule that refused them. An agent
             * or a person who asked for a file and got silence cannot tell that
             * from a file that was not there. */
            for (const refusal of event.refused || []) {
              say(`${refusal.path} — ${refusal.why}`, "refused", "refused");
            }
            if (event.stopped) {
              // Not 100%: nothing was kept, and a full bar would say the
              // opposite of what happened.
              bar.style.width = "0%";
              pct.textContent = "0%";
              status.textContent = "stopped";
              say(
                "stopped — everything this run embedded was undone, so the store is as it was before it started",
                "stopped",
              );
              await refreshStores();
              continue;
            }
            bar.style.width = "100%";
            pct.textContent = "100%";
            status.textContent = "done";
            say(
              `${event.indexed} indexed, ${event.unchanged} unchanged, ${event.skipped} skipped, ${event.removed} removed, ${event.chunks} chunks`,
              "done",
            );

            // The store list has changed. Without this, a first index left
            // `state.stores` empty and the next visit to Stores bounced the
            // user to the first-run screen with their work apparently gone.
            await refreshStores();
          } else if (event.event === "slice") {
            // The writer handed itself back to the watcher and took the rest
            // of this run back onto the queue. One run, one stream: there is
            // nothing for the reader to do.
            status.textContent = `${n(event.remaining)} left — yielding to the watcher`;
            say(
              `${n(event.remaining)} paths left; the writer is giving the watcher a turn and will carry on`,
              "slice",
            );
          } else if (event.event === "paused") {
            status.textContent = "paused";
            say("held between files — the writer is still this run's", "paused");
          } else if (event.event === "resumed") {
            status.textContent = "working";
            say("carrying on", "resumed");
          } else if (event.event === "error") {
            status.textContent = "failed";
            say(event.error, "error");
          } else if (event.event === "started") {
            say(event.paths.join(", "), "indexing");
          }
        }
      }
    } catch (e) {
      status.textContent = "failed";
      say(e.message, "error");
      return e.message;
    } finally {
      showRunning(false);
    }
    return null;
  }

  stopButton.addEventListener("click", () => {
    ask({
      title: "Stop this index run?",
      body: "Everything it has embedded so far is undone, so the store is left exactly as it was before the run started. Indexing the same folder again begins at 0%.",
      confirm: "Stop and undo",
      tone: "bad",
      run: async () => {
        stopButton.disabled = true;
        stopButton.textContent = "Stopping…";
        status.textContent = "stopping — undoing what it embedded";
        await control("stop");
      },
    });
  });

  start.addEventListener("click", async () => {
    if (running) {
      // Pause and resume are the same button: the run is the thing being
      // toggled, and two buttons for one state is two things to read.
      const want = paused ? "resume" : "pause";
      start.disabled = true;
      try {
        await control(want);
        paused = !paused;
        start.textContent = paused ? "Resume" : "Pause";
        status.textContent = paused ? "paused" : "working";
      } catch (e) {
        complain(e.message);
      } finally {
        start.disabled = false;
      }
      return;
    }
    const path = field.value.trim();
    if (!path) {
      complain("Give a path to index, or choose a folder.", field);
      return;
    }
    run("/api/index", { path });
  });

  addButton.addEventListener("click", async () => {
    const url = urlField.value.trim();
    if (!url) {
      urlNote.className = "note bad";
      urlNote.textContent = "Give an https URL to fetch.";
      urlField.focus();
      return;
    }
    urlNote.className = "note";
    urlNote.textContent = "";
    const failed = await run("/api/add", { url });
    // A failed fetch leaves the card open with what went wrong on it. Closing
    // it would take the message away with it and leave the page looking as
    // though nothing had been asked for.
    if (failed) {
      urlNote.className = "note bad";
      urlNote.textContent = failed;
      urlCard.hidden = false;
    }
  });

  return el(
    "div",
    { class: "view" },
    pageHead("Index"),
    says(
      "The daemon is the writer, so this queues behind the watcher rather than fighting it — the same path ",
      mono("semlith_index"),
      " takes.",
    ),
    // The path field has the row to itself, above the actions: sharing a row
    // with four buttons is what held it to 420px on a 1440px page.
    el(
      "div",
      { class: "field tall full" },
      el("span", { class: "prefix", text: "path" }),
      labelled("index-path", "Path to index", field),
    ),
    el(
      "div",
      { class: "filters" },
      folderButton,
      urlButton,
      state.stores.length > 1 ? storeSelect : null,
      start,
      stopButton,
      el("span", { class: "spacer" }),
      // What the queue actually holds, from /api/stores. The line it replaces
      // said "writer: daemon", which named a process rather than telling
      // anyone anything about their work.
      el("span", {
        class: "meta",
        text: `queue depth ${state.stores.reduce((sum, store) => sum + (store.queue || 0), 0)}`,
      }),
    ),
    note,
    el(
      "div",
      { class: "scroller" },
    picker.node,
    fill(
      urlCard,
      el("span", { class: "eyebrow", text: "Add from a URL" }),
      el("p", {
        class: "subtitle",
        text: "One https request, for exactly this URL — a page, a PDF, or a file on GitHub. Nothing is crawled and no credential is ever sent. The file is saved inside this store's downloads folder, never in your working tree.",
      }),
      el(
        "div",
        { class: "field tall full" },
        el("span", { class: "prefix", text: "url" }),
        labelled("index-url", "URL to fetch and index", urlField),
      ),
      el("div", { class: "actions" }, addButton),
      urlNote,
    ),
    el(
      "div",
      { class: "card pad" },
      el(
        "div",
        { class: "head" },
        el("span", { class: "card-title", text: "Progress" }),
        status,
        el("span", { class: "spacer" }),
        pct,
      ),
      el("div", { class: "bar" }, bar),
    ),
    log,
    ),
  );
}

// -------------------------------------------------------- install panel

/* What this machine has set up, and the one thing the page can fix itself.
 *
 * The install commands that used to head this card belonged on a machine that
 * does not have semlith yet — which is not the machine reading this page. What
 * is useful here is the state of each step and a way to act on the one that is
 * not done.
 */
function installPanel() {
  const card = el("div", { class: "card pad install-panel" });
  const title = () => el("span", { class: "card-title", text: "This machine" });
  fill(card, title(), el("p", { class: "subtitle", text: "Checking…" }));

  const stateWord = {
    done: "done",
    "already-done": "already done",
    skipped: "not done",
    failed: "failed",
  };
  const tone = (state) =>
    state === "done" || state === "already-done" ? "good" : state === "failed" ? "bad" : "warn";

  function paint(setup) {
    const note = el("div", { class: "note" });

    const fixPath = el("button", {
      class: "button small",
      type: "button",
      text: "Add it to PATH",
      onclick: async () => {
        fixPath.disabled = true;
        note.className = "note";
        note.textContent = "Editing your shell profile…";
        try {
          const done = await post("/api/setup", { step: "path" });
          note.textContent = `${done.step.detail} — open a new terminal for it to take effect.`;
          paint(done.status);
        } catch (e) {
          note.className = "note bad";
          note.textContent = e.message;
          fixPath.disabled = false;
        }
      },
    });

    const install = el("button", {
      class: "button small",
      type: "button",
      text: "Install it",
      disabled: true,
      onclick: async () => {
        install.disabled = true;
        check.disabled = true;
        note.className = "note";
        note.textContent = "Downloading and verifying…";
        try {
          const done = await post("/api/upgrade", { action: "apply" });
          note.textContent = done.restart;
        } catch (e) {
          note.className = "note bad";
          note.textContent = e.message;
        } finally {
          check.disabled = false;
        }
      },
    });

    const check = el("button", {
      class: "button secondary small",
      type: "button",
      text: "Check for updates",
      onclick: async () => {
        check.disabled = true;
        note.className = "note";
        note.textContent = "Asking GitHub…";
        try {
          const found = await post("/api/upgrade", { action: "check" });
          note.textContent = found.available
            ? `${found.latest} is available; you are on ${found.installed}.`
            : `Already on the newest build, ${found.installed}.`;
          if (found.blocked) note.textContent += ` ${found.blocked}`;
          install.disabled = !found.available || Boolean(found.blocked);
        } catch (e) {
          note.className = "note bad";
          note.textContent = e.message;
        } finally {
          check.disabled = false;
        }
      },
    });

    fill(
      card,
      title(),
      el(
        "div",
        { class: "rows" },
        (setup.steps || []).map((step) =>
          el(
            "div",
            { class: "kv step" },
            pill(stateWord[step.state] || step.state, tone(step.state)),
            el("span", { class: "card-title", text: step.name }),
            lineCell(step.detail, "meta"),
            // The one step this page can perform, and only while there is
            // something to do: the step's own state is the answer, not the
            // live PATH, which a daemon started before the edit never sees.
            // The others are an install and a model download, which belong to
            // the command that owns them.
            step.name === "path" && step.state !== "already-done" && step.state !== "done"
              ? el("span", { class: "spacer" })
              : null,
            step.name === "path" && step.state !== "already-done" && step.state !== "done"
              ? fixPath
              : null,
          ),
        ),
      ),
      note,
      el("hr", { class: "rule" }),
      el("span", { class: "eyebrow", text: `Installed version ${setup.version}` }),
      el("div", { class: "actions" }, check, install),
    );
  }

  api("/api/setup")
    .then(paint)
    .catch((e) => fill(card, title(), error(e.message)));

  return card;
}

// ---------------------------------------------------------------- agents

async function agentsView() {
  let data;
  try {
    data = await api("/api/agents");
  } catch (e) {
    return el("div", { class: "view" }, pageHead("Agents"), error(e.message));
  }

  noteAgents(data);
  const clients = data.clients || [];
  const tools = data.tools || [];
  const live = data.connections || [];
  const endpoint = data.endpoint || { url: "", open: false };

  // ---- the endpoint, in the page header
  const address = el("code", { class: "text", text: endpoint.url });
  const endpointNote = el("div", { class: "note" });
  const toggle = el("button", {
    class: "button secondary small",
    type: "button",
    text: endpoint.open ? "Stop" : "Start",
    onclick: async () => {
      toggle.disabled = true;
      endpointNote.className = "note";
      endpointNote.textContent = endpoint.open ? "Closing…" : "Opening…";
      try {
        const done = await post("/api/endpoint", { open: !endpoint.open });
        endpoint.open = done.open;
        toggle.textContent = done.open ? "Stop" : "Start";
        endpointNote.textContent = done.open
          ? "The endpoint is answering. A configured client reconnects on its next call."
          : "The endpoint is closed. The daemon, the watcher and the portal are unaffected.";
        fill(statePill, el("i", {}), done.open ? "answering" : "closed");
        statePill.className = done.open ? "pill good" : "pill warn";
      } catch (e) {
        endpointNote.className = "note bad";
        endpointNote.textContent = e.message;
      } finally {
        toggle.disabled = false;
      }
    },
  });
  const statePill = pill(endpoint.open ? "answering" : "closed", endpoint.open ? "good" : "warn");

  // ---- rotation
  const keyNote = el("div", { class: "note" });
  const rotate = el("button", {
    class: "button secondary small",
    type: "button",
    text: "Rotate key",
    onclick: async () => {
      rotate.disabled = true;
      keyNote.className = "note";
      keyNote.textContent = "Rotating…";
      try {
        const done = await post("/api/key", {});
        // Only if the page was already showing the real one; otherwise the
        // stanza still names the variable, which is now correct for the new
        // key without anybody touching it.
        if (stanzas.revealed) stanzas.key = done.key;
        showClient(chosen);
        const carried = done.updated || [];
        // Said plainly, because the two halves have different consequences:
        // what was rewritten needs nothing done to it, and what was not needs
        // the stanza above pasted in before the old key stops working.
        const rewrote = carried.length
          ? `Carried the new key into ${carried.length} configuration file${
              carried.length === 1 ? "" : "s"
            }: ${carried.join(", ")}.`
          : "No configuration file on this machine carried the old key.";
        keyNote.textContent = done.previous_valid
          ? `New key. ${rewrote} The previous one keeps working until this daemon exits, so a session already open finishes — any client configured elsewhere needs the new stanza before then.`
          : `New key. ${rewrote} The previous one is refused now; any client configured elsewhere needs the new stanza.`;
      } catch (e) {
        keyNote.className = "note bad";
        keyNote.textContent = e.message;
      } finally {
        rotate.disabled = false;
      }
    },
  });

  // ---- the key itself, only when asked for
  /* Masked until asked for. The route does not send a preview either: a
   * preview of an agent key still begins `sml_`, and the point is that nothing
   * about the credential arrives unasked. */
  const MASKED = data.key_set ? "sml_" + "•".repeat(24) : "no key yet";
  const keyBox = el("code", { class: "text", text: MASKED });
  const reveal = el("button", {
    class: "button secondary small",
    type: "button",
    text: "Reveal",
    onclick: async () => {
      if (stanzas.revealed) {
        // Pressed again: put it away. A page left open on a screen should not
        // keep showing a live credential because somebody looked at it once.
        stanzas.revealed = false;
        stanzas.key = "${" + KEY_ENV + "}";
        keyBox.textContent = MASKED;
        reveal.textContent = "Reveal";
        showClient(chosen);
        return;
      }
      reveal.disabled = true;
      try {
        const shown = await post("/api/agents/reveal", {});
        stanzas.revealed = true;
        stanzas.key = String(shown.key);
        keyBox.textContent = stanzas.key;
        reveal.textContent = "Hide";
        showClient(chosen);
      } catch (e) {
        keyNote.className = "note bad";
        keyNote.textContent = e.message;
      } finally {
        reveal.disabled = false;
      }
    },
  });

  // ---- connected clients
  const connected = dataTable({
    className: "w-agents",
    sort: "name",
    grow: false,
    perPage: 10,
    rows: live,
    columns: [
      {
        key: "name",
        label: "Connected",
        value: (c) => c.name,
        render: (c) => el("div", { class: "who" }, el("span", { class: "dot good" }), c.name),
      },
      { key: "transport", label: "Transport", className: "meta", value: (c) => c.transport },
      { key: "revision", label: "Revision", className: "meta narrow-drop", value: (c) => c.revision },
      {
        key: "queries",
        label: "Queries",
        className: "num",
        value: (c) => c.queries,
        render: (c) => n(c.queries),
      },
    ],
  });

  // ---- stanzas, grouped
  const GROUPS = [
    ["terminal", "Terminal"],
    ["editor", "Editors"],
    ["desktop", "Desktop"],
  ];
  /* What a stanza carries.
   *
   * The variable form by default: a configuration file that names
   * `${SEMLITH_AGENT_KEY}` keeps working across every rotation, and a file that
   * carries the key itself goes stale the moment somebody presses Rotate. The
   * real key is fetched only when Reveal is pressed — `/api/agents` no longer
   * returns it, so a page that is merely open never receives the credential
   * that opens the MCP endpoint. */
  const KEY_ENV = data.key_env || "SEMLITH_AGENT_KEY";
  const stanzas = { key: "${" + KEY_ENV + "}", revealed: false };
  let group = GROUPS.find(([id]) => clients.some((c) => c.group === id))[0];
  let chosen = clients.findIndex((c) => c.group === group);
  const tabs = el("div", { class: "tabs" });
  const chips = el("div", { class: "filters" });
  const body = el("div", { class: "stanza" });

  /** The HTTP form, built here from the key the route just handed back. */
  /** The placeholder the README prints where a real key goes. */
  const KEY_SLOT = "${SEMLITH_AGENT_KEY}";

  /** Whether a stanza configures the endpoint rather than a subprocess. */
  const overHttp = (text) => text.includes("/mcp") || text.includes("--transport http");

  function httpStanza() {
    return `{\n  "mcpServers": {\n    "semlith": {\n      "url": "${endpoint.url}",\n      "headers": { "Authorization": "Bearer ${stanzas.key}" }\n    }\n  }\n}`;
  }

  function showGroup(id) {
    group = id;
    const first = clients.findIndex((c) => c.group === id);
    showClient(first < 0 ? chosen : first);
  }

  function showClient(index) {
    chosen = index;
    const client = clients[index];
    fill(
      tabs,
      GROUPS.map(([id, label]) => {
        const count = clients.filter((c) => c.group === id).length;
        return el(
          "button",
          {
            class: "tab",
            type: "button",
            "aria-pressed": String(id === group),
            onclick: () => showGroup(id),
          },
          label,
          el("span", { class: "count", text: String(count) }),
        );
      }),
    );
    fill(
      chips,
      clients.map((c, i) =>
        c.group === group
          ? el("button", {
              class: "chip",
              type: "button",
              "aria-pressed": String(i === chosen),
              text: c.name,
              onclick: () => showClient(i),
            })
          : null,
      ),
    );
    if (!client) {
      fill(body, empty("No client stanza is compiled into this build."));
      return;
    }
    // The documented stanzas. They name ${SEMLITH_AGENT_KEY}, which is what a
    // client should carry: it survives a rotation, and the key stays in one
    // file with one set of permissions. Pressing Reveal substitutes the literal
    // value for a reader who wants to paste it somewhere that cannot read an
    // environment variable.
    const own = (client.stanzas || []).map((s) => ({
      format: s.format,
      text: s.text.trimEnd().replaceAll(KEY_SLOT, stanzas.key),
    }));
    // A one-line command belongs in a field with a Copy beside it, not in a
    // slab of dark code: it is a thing you paste into a shell, not a file you
    // are going to read.
    // Shell one-liners, labelled by what they register rather than mixed in
    // with the block above: several clients configure the endpoint in a file
    // but can only add a subprocess from their CLI, and an unlabelled command
    // under an HTTP stanza reads as a second way to do the same thing.
    const shells = own.filter((s) => s.format === "sh");
    const wired = shells.filter((s) => overHttp(s.text));
    const spawned = shells.filter((s) => !overHttp(s.text));
    const blocks = own.filter((s) => s.format !== "sh");
    const http = blocks.filter((s) => overHttp(s.text));
    const stdio = blocks.filter((s) => !overHttp(s.text));
    const config = http.length ? http : stdio;
    fill(
      body,
      el(
        "div",
        { class: "head" },
        el("span", { class: "card-title", text: client.name }),
        el("span", { class: "meta", text: client.note }),
      ),
      // A client with no HTTP stanza of its own gets the generic one, which is
      // the shape most schemas take. A client with one gets its own: `httpUrl`
      // for Gemini, `serverUrl` for Windsurf, TOML for Codex — a generic block
      // beside those is a second, wrong answer.
      // One configuration block, not two. A client that can reach the
      // endpoint is shown the endpoint; one that cannot — Zed, Claude Desktop,
      // Amazon Q, which have nowhere to put a header — is shown the subprocess
      // it can run. Printing both left a reader choosing between two answers
      // with nothing to choose on.
      el("span", {
        class: "eyebrow",
        text: config.length && config === http
          ? "Over HTTP — one endpoint, one key, no subprocess"
          : "As a subprocess — no key needed",
      }),
      (config.length ? config.map((s) => s.text) : [httpStanza()]).map((text) =>
        codeBlock(text, "Copy stanza"),
      ),
      wired.length ? el("span", { class: "eyebrow", text: "Or from a terminal" }) : null,
      wired.map((s) => copyField(s.text, true)),
      spawned.length
        ? el("span", { class: "eyebrow", text: "Or add the subprocess from a terminal" })
        : null,
      spawned.map((s) => copyField(s.text, true)),
    );
  }
  showClient(chosen);

  return el(
    "div",
    { class: "view" },
    pageHead("Agents", "One endpoint, every client, no per-client process.", {
      pill: statePill,
      actions: [
        el("div", { class: "copyfield worded" }, address, copyButton(endpoint.url, "Copy", true)),
        toggle,
        rotate,
      ],
    }),
    endpointNote,
    el(
      "div",
      { class: "card pad dense" },
      el("span", { class: "card-title", text: "Agent key" }),
      el("div", { class: "copyfield" }, keyBox, el("div", { class: "actions" }, reveal)),
      says(
        "Shown truncated, and fetched in full only when you press Reveal — the page does not receive it just for being open. Every stanza below names ",
        mono("${" + KEY_ENV + "}"),
        " instead of the key, so the client reads it from the environment at start and a rotation needs no file rewritten. It is exported by the block ",
        mono("semlith setup"),
        " wrote in your shell startup file, from ",
        mono(data.key_path || "~/.semlith/agent.key"),
        ".",
      ),
    ),
    keyNote,
    el(
      "div",
      { class: "grid scroller" },
      el(
        "div",
        { class: "rows" },
        live.length
          ? connected.node
          : el(
              "div",
              { class: "card pad dense" },
              el("span", { class: "card-title", text: "Connected" }),
              empty("No client is talking to this daemon right now."),
            ),
        el(
          "div",
          { class: "card pad dense tools" },
          el(
            "div",
            { class: "head" },
            el("span", { class: "card-title", text: "Tools exposed" }),
            el("span", {
              class: "meta",
              text: `${tools.length} tool${tools.length === 1 ? "" : "s"}`,
            }),
          ),
          // The schema is the first thing every agent reads and the last thing
          // anyone thinks to measure: it is paid once per session, before a
          // single question is asked. Measured from what this daemon is
          // serving right now rather than quoted from a release, so the number
          // cannot go stale on the page.
          el(
            "div",
            { class: "cost" },
            el("span", { class: "card-title", text: "What the tool list costs" }),
            el("span", {
              class: "cost-line",
              text: `${tools.length} tools · ${n(data.tool_list_bytes || 0)} bytes · about ${n(
                Math.ceil((data.tool_list_bytes || 0) / 4),
              )} tokens per session`,
            }),
            el("span", {
              class: "cost-note",
              text: "read once, before the agent asks anything",
            }),
          ),
          el(
            "div",
            { class: "tool-grid" },
            // The name and what it is for, both read from the tool's own
            // definition: a second copy is how a tool ends up served with one
            // description and documented with another.
            tools.flatMap((tool) => [
              el("span", { class: "tool-name", text: tool.name }),
              el("span", { class: "tool-about", text: tool.about }),
            ]),
          ),
        ),
        installPanel(),
      ),
      el("div", { class: "card pad stanzas" }, tabs, chips, body),
    ),
  );
}

// --------------------------------------------------------------- privacy

async function privacyView() {
  let data;
  try {
    data = await api("/api/privacy");
  } catch (e) {
    return el("div", { class: "view" }, pageHead("Privacy"), error(e.message));
  }

  const tokenBox = el("code", { class: "text", text: data.token_preview || "—" });
  const rotateNote = el("div", { class: "note" });
  const rotate = el("button", {
    class: "button secondary small",
    type: "button",
    text: "Rotate",
    onclick: async () => {
      rotate.disabled = true;
      rotateNote.className = "note";
      rotateNote.textContent = "Rotating…";
      try {
        const fresh = await post("/api/rotate", {});
        // The rotate response is the one place the whole token appears after
        // the printed URL, and this page has to take the new one before its
        // next request: nothing else will tell it. What is shown is still the
        // preview — a page that prints a live credential in full is a page
        // someone screenshots.
        session.set(String(fresh.token));
        tokenBox.textContent = `${String(fresh.token).slice(0, 16)}…`;
        rotateNote.textContent =
          "Rotated. The old token stopped working immediately. This is the portal's own session token, not the agent key: no client stanza carries it, so nothing needs reconfiguring. The agent key is rotated on the Agents page.";
      } catch (e) {
        rotateNote.className = "note bad";
        rotateNote.textContent = e.message;
      } finally {
        rotate.disabled = false;
      }
    },
  });

  const fact = (key, value, why) =>
    el(
      "div",
      { class: "stat fact" },
      el("span", { class: "eyebrow", text: key }),
      el("span", { class: "fact-value", text: value }),
      el("span", { class: "sub", text: why }),
    );

  /* The four steps, numbered, each with its own copy button. A packet capture
   * is the only one of them that proves anything on its own; the others are
   * what make the first one quick to believe. */
  const step = (number, what, command) =>
    el(
      "div",
      { class: "step-row" },
      el("span", { class: "n", text: number }),
      el(
        "div",
        { class: "what" },
        el("div", { class: "say", text: what }),
        copyField(command),
      ),
    );

  return el(
    "div",
    { class: "view" },
    pageHead(
      "Privacy",
      "The claim is “nothing leaves this machine”. This page is how you check it yourself, in about a minute.",
      { pill: pill(data.airgap ? "airgap mode armed" : "airgap off", data.airgap ? "good" : null) },
    ),
    el(
      "div",
      { class: "strip" },
      fact("Bind address", data.bind, "loopback only, with no flag to change it"),
      fact("CORS", "none", "no origin may read this server's responses"),
      fact("Host check", "localhost only", "a foreign Host header gets 400 before anything runs"),
      fact("Assets", "include_bytes!", "the page you are reading is inside the binary"),
      fact("Telemetry", "none", "no analytics, and no update check Semlith makes on its own"),
      // Said on this page, not only on the Ledger page. Somebody checking the
      // privacy claim should find the one thing semlith writes down about
      // them here, with how to stop it, rather than discovering it elsewhere.
      fact(
        "Retrieval ledger",
        "records locally",
        "the daemon prints this on every start; --no-ledger stops it for a session, SEMLITH_LEDGER=0 for a machine, and the rows never leave the store",
      ),
      fact("Model cache", data.model_cached ? "cached" : "not downloaded", data.model_cache),
    ),
    el(
      "div",
      { class: "grid scroller" },
      el(
        "div",
        { class: "card pad" },
        el("span", { class: "card-title", text: "Verify it yourself" }),
        el(
          "div",
          { class: "steps-list" },
          step(
            "1",
            "Ask the operating system what this process has open. Only loopback should appear.",
            "lsof -nP -p $(pgrep -f 'semlith start') -i",
          ),
          step(
            "2",
            "Watch every interface but loopback while you search. Nothing should appear.",
            "sudo tcpdump -i any -n 'not host 127.0.0.1 and not host ::1'",
          ),
          step(
            "3",
            "Arm the refusal. Anything that would reach the network exits instead, naming what it refused.",
            "semlith start --airgap",
          ),
          step("4", "Or pull the cable: the portal loads and searches with no network at all.", "ifconfig en0 down"),
        ),
      ),
      el(
        "div",
        { class: "rows" },
        /* The rules this release added, each with what the daemon found when it
         * looked. A page that states a policy is a page; a page that states a
         * policy and the reading behind it is something a reader can disagree
         * with, which is the only version worth putting on a Privacy page. */
        el(
          "div",
          { class: "card pad" },
          el(
            "div",
            { class: "head" },
            el("span", { class: "card-title", text: "Rules" }),
            el("span", { class: "spacer" }),
            pill(
              (data.rules || []).every((r) => r.ok) ? "all holding" : "check the rows",
              (data.rules || []).every((r) => r.ok) ? "good" : "warn",
            ),
          ),
          el("p", {
            class: "subtitle",
            text: "What semlith refuses, and what this daemon found when it checked. Every row is a rule the binary enforces and a test that fails if it stops.",
          }),
          el(
            "div",
            { class: "rules" },
            (data.rules || []).map((rule) =>
              el(
                "div",
                { class: rule.ok ? "rule-row" : "rule-row bad" },
                el(
                  "div",
                  { class: "rule-head" },
                  el("span", { class: "dot " + (rule.ok ? "good" : "warn") }),
                  el("span", { class: "rule-id", text: rule.id }),
                ),
                el("p", { class: "rule-text", text: rule.rule }),
                // The reading, under the rule rather than beside it: it is a
                // path or a count often enough that a column would spend the
                // whole card's width on one of them and wrap the rest.
                el(
                  "div",
                  { class: "rule-found" },
                  el("span", { class: "eyebrow", text: "found" }),
                  el("code", { class: "rule-check", text: rule.check }),
                ),
              ),
            ),
          ),
        ),
        el(
          "div",
          { class: "card pad" },
          el("span", { class: "card-title", text: "The one outbound connection that exists" }),
          says(
            "The embedding model is downloaded once, on first index, and cached. ",
            mono("semlith upgrade"),
            " and ",
            mono("semlith add"),
            " reach the network only in the second you ask them to. ",
            mono("--airgap"),
            " refuses all three and exits naming what it refused.",
          ),
          copyField("SEMLITH_MODEL_CACHE=/media/usb/models semlith index ."),
          el(
            "div",
            { class: "chips" },
            pill(data.model_cached ? "model cached" : "model not downloaded", data.model_cached ? "good" : "warn"),
            el("span", {
              class: "meta",
              text: "granite-embedding-small-english-r2 · int8 · Apache-2.0",
            }),
          ),
        ),
        el(
          "div",
          { class: "card pad" },
          el("span", { class: "card-title", text: "Session token" }),
          el("div", { class: "copyfield" }, tokenBox, el("div", { class: "actions" }, rotate)),
          rotateNote,
          says(
            "Generated at start, handed to this page once by the printed URL, and sent back as a ",
            mono(data.token_header),
            " header on every ",
            mono("/api"),
            " route. It is in no cookie: every port on localhost is the same site, so a cookie would travel to a page served by anything else on this machine, and a header will not. Shown truncated — no response carries it in full except the one that rotates it.",
          ),
          el("hr", { class: "rule" }),
          el("span", { class: "card-title", text: "Content-Security-Policy" }),
          codeBlock(data.csp),
          el("p", {
            class: "subtitle",
            text: `Host headers answered: ${(data.host_allowed || []).join(", ")}. Everything else gets 400.`,
          }),
        ),
      ),
    ),
  );
}

// ----------------------------------------------------------------- about

/* Every name `--lang` accepts, with a tick on the ones the graph is extracted
 * from. It lives here rather than on a page of its own because it is a fact
 * about the binary, and a page that held one table was a click between the
 * reader and a list they wanted to scan. */
function langCard(languages, withEdges) {
  const edges = new Set(withEdges);
  return el(
    "div",
    { class: "card pad lang-card" },
    el(
      "div",
      { class: "rows tight" },
      el("span", { class: "card-title", text: `${languages.length} languages` }),
      el("span", {
        class: "subtitle",
        text:
          edges.size === languages.length
            ? `Search filters and the code graph read the same table, so the two cannot disagree. Every one carries graph edges.`
            : `Search filters and the code graph read the same table, so the two cannot disagree. ${edges.size} of ${languages.length} carry graph edges.`,
      }),
    ),
    el(
      "div",
      { class: "lang-grid" },
      languages.map((lang) => {
        const has = edges.has(lang.name);
        const names = (lang.extensions || [])
          .map((e) => `.${e}`)
          .concat(lang.filenames || []);
        return el(
          "div",
          { class: "lang-row" },
          // Every row is ticked, because every row is true of the thing the
          // tick says: the language is indexed and `--lang` selects it. A
          // language that also carries graph edges says so beside its name.
          // Since 0.17.0 that is all of them, and the mark stays rather than
          // being dropped as redundant: if a grammar is ever refused — a
          // copyleft licence is the case that would do it — the gap has to be
          // visible here rather than inferred from its absence.
          el("span", {
            class: "tick on",
            title: "indexed, and --lang selects it",
            text: "✓",
          }),
          el("span", { class: "name", text: lang.name }),
          has ? el("span", { class: "graph-mark", text: "graph" }) : null,
          el("span", { class: "spacer" }),
          el("span", { class: "exts", text: names.join(" ") }),
        );
      }),
    ),
    says(
      `All ${languages.length} are indexed and selectable with `,
      mono("--lang"),
      edges.size === languages.length
        ? ", and every one marked "
        : `. The ${edges.size} marked `,
      mono("graph"),
      edges.size === languages.length
        ? " carries symbols and edges as well, from a tree-sitter grammar. "
        : " carry symbols and edges as well, from a tree-sitter grammar; the rest are searched as text. ",
      mono("semlith languages"),
      " prints the same table. Extension and filename decide the language — file contents are never read to guess it, because a store is searched far more often than it is built.",
    ),
    says(
      "Forty of these grammars arrived in 0.17.0 and they are not free: the binary went from 47.0 MiB to 111.3 MiB, ",
      mono("+64.3 MiB"),
      ", measured on the build machine against a 0.16.0 build made with the same toolchain. That is parser tables rather than debug information — both binaries are already symbol-light — and OCaml alone is 12.6 MiB of it. The number is stated rather than budgeted for: no language was dropped to hit a size.",
    ),
  );
}

async function aboutView() {
  let about;
  let models;
  let languages;
  try {
    [about, models, languages] = await Promise.all([
      api("/api/about"),
      api("/api/models"),
      api("/api/languages"),
    ]);
  } catch (e) {
    return el("div", { class: "view" }, pageHead("About"), error(e.message));
  }

  const row = (key, value) =>
    el(
      "div",
      { class: "kv pair" },
      el("span", { class: "k", text: key }),
      el("span", { class: "v", text: value }),
    );

  const list = (models && models.models) || [];
  const table = dataTable({
    className: "w-models",
    sort: "name",
    perPage: 10,
    rows: list,
    columns: [
      {
        key: "name",
        label: "Model",
        className: "path",
        value: (m) => m.name,
        // One line with the name on the tooltip: wrapped across two lines a
        // model name reads as two models.
        render: (m) => el("span", { class: "one-line", "data-tip": m.name, text: m.name }),
      },
      { key: "dim", label: "Dims", className: "num", value: (m) => m.dim, render: (m) => String(m.dim) },
      {
        key: "bytes",
        label: "Size",
        className: "num",
        value: (m) => m.bytes || 0,
        // Blank rather than guessed: a model this machine has never fetched has
        // no size here to measure, and fastembed's catalogue does not carry one.
        render: (m) => (m.bytes ? bytes(m.bytes) : "—"),
      },
      { key: "description", label: "Note", className: "meta", value: (m) => m.description },
    ],
  });

  return el(
    "div",
    { class: "view" },
    pageHead("About", "One Rust binary. The portal you are reading is compiled into it."),
    el(
      "div",
      // Sized to its content rather than to the height left over, so the page
      // scrolls as one. With `grow` the two columns were capped at the
      // viewport and the language card — 46 rows — pushed the rest of the left
      // column out of sight with nothing to scroll it back.
      { class: "grid two" },
      el(
        "div",
        { class: "rows" },
        el(
          "div",
          { class: "card pad" },
          row("Version", `${about.version} · store format ${about.format_version}`),
          row("Binary", `${about.binary} · ${bytes(about.binary_bytes)} · ${about.target}`),
          row("Bound to", about.bind),
          row("Store home", about.store_home),
          row("Model cache", about.model_cache),
          row("MCP revisions", (about.revisions || []).join(" · ")),
          row("Uptime", `${Math.floor(about.uptime / 60)}m · pid ${about.pid}`),
        ),
        langCard(languages.languages || [], about.graph_languages || []),
      ),
      list.length ? table.node : el("div", { class: "card pad" }, empty("No model is listed.")),
    ),
    el("p", {
      class: "subtitle",
      text: "The model is fixed when a store is created — vectors from two models are not comparable. To switch, delete the store and index again.",
    }),
  );
}

// --------------------------------------------------------------- welcome

function welcomeView() {
  const note = el("div", { class: "note" });
  const field = el("input", { type: "text", placeholder: "~/Documents/work" });

  const step = (num, title, what) =>
    el(
      "div",
      { class: "step" },
      el("span", { class: "eyebrow", text: num }),
      el("span", { class: "card-title", text: title }),
      el("span", { class: "what", text: what }),
    );

  return el(
    "div",
    { class: "welcome" },
    el("div", { class: "lockup" }, logoImage(38), el("span", { class: "name", text: "Semlith" })),
    el(
      "div",
      { class: "hero" },
      el(
        "div",
        { class: "titles" },
        el("h1", { class: "hero-title", text: "No stores yet" }),
        el("p", {
          class: "subtitle",
          text: "The daemon is running and holds nothing. Point it at a folder and it indexes everything a person could read in there — code, Markdown, PDFs, Office files, notebooks, books and mail.",
        }),
      ),
      el(
        "div",
        { class: "field tall" },
        el("span", { class: "prefix", text: "path" }),
        labelled("welcome-path", "Folder to index", field),
      ),
      note,
      el(
        "div",
        { class: "actions" },
        el("button", {
          class: "button",
          type: "button",
          text: "Index this folder",
          onclick: () => {
            const path = field.value.trim();
            if (!path) {
              note.className = "note bad";
              note.textContent = "Give a path first, or open the picker instead.";
              field.focus();
              return;
            }
            // Carried across rather than dropped: this button used to validate
            // a path and then open the Index view with an empty field.
            state.pendingPath = path;
            go("index");
          },
        }),
        el("button", {
          class: "button secondary",
          type: "button",
          text: "Open the folder picker",
          onclick: () => go("index"),
        }),
        el("button", {
          class: "button ghost",
          type: "button",
          text: "Skip for now",
          onclick: () => go("about"),
        }),
      ),
      el("hr", { class: "rule" }),
      el("span", { class: "eyebrow", text: "Or from a terminal" }),
      copyField("semlith index ~/Documents/work"),
      says(
        "No ",
        mono("--store"),
        " flag. It lands in ",
        mono("~/.semlith/stores/work"),
        " and is registered against that root.",
      ),
    ),
    el(
      "div",
      { class: "steps" },
      step("01", "Index", "One pass over the folder. Only what changed is re-embedded on the next."),
      step("02", "Stays current", "The daemon watches the roots and re-embeds on save."),
      step("03", "Ask", "From here, the CLI, or any agent over MCP — the same fused search."),
    ),
    el("div", { class: "foot", text: "127.0.0.1 · loopback only · no external asset" }),
  );
}

// ---------------------------------------------------------------- router

const RENDER = {
  stores: storesView,
  files: filesView,
  index: indexView,
  search: searchView,
  agents: agentsView,
  privacy: privacyView,
  about: aboutView,
  graph: graphView,
  ledger: ledgerView,
};

function go(id) {
  // On a phone the drawer covers the page it is navigating to, so it closes on
  // the way out. Done here rather than on each nav item because every route
  // into a page goes through this — the rail, the drawer, the brand, the search
  // launcher, the "Index a folder" button and the `/` shortcut.
  if (shell.main && window.matchMedia(NARROW).matches && state.navOpen) {
    setNav(false);
  }
  // Re-render even when the hash is already this page: clicking the nav item
  // for the page you are on should still do something, and no hashchange
  // fires for an unchanged hash.
  if ((location.hash || "").slice(1) === id) render();
  else location.hash = `#${id}`;
}

/** Whether dark is showing, whether by choice or by the OS. */
function isDark() {
  const chosen = document.documentElement.getAttribute("data-theme");
  if (chosen) return chosen === "dark";
  return window.matchMedia("(prefers-color-scheme: dark)").matches;
}

/** The mark, in whichever theme is showing. */
function logoImage(size) {
  return el("img", {
    class: "logo",
    src: isDark() ? "logo-dark.svg" : "logo.svg",
    alt: "",
    width: size,
    height: size,
  });
}

function theme(next) {
  document.documentElement.setAttribute("data-theme", next);
  state.theme = next;
  try {
    localStorage.setItem("semlith-theme", next);
  } catch (_) {
    /* a private window refuses storage; the toggle still works for this run */
  }
  for (const img of document.querySelectorAll("img.logo")) {
    img.src = next === "dark" ? "logo-dark.svg" : "logo.svg";
  }
  paintThemeButton();
}

/** The toggle shows where it goes, not where you are. */
function paintThemeButton() {
  const button = shell.themeButton;
  if (!button) return;
  const toDark = !isDark();
  fill(button, icon(toDark ? ICONS.moon : ICONS.sun));
  button.setAttribute("aria-label", toDark ? "Switch to dark" : "Switch to light");
  button.setAttribute("title", toDark ? "Switch to dark" : "Switch to light");
}

// ----------------------------------------------------------------- shell

const shell = {};

function buildShell() {
  const hamburger = el(
    "button",
    {
      class: "hamburger",
      type: "button",
      "aria-label": "Toggle navigation",
      "aria-expanded": String(state.navOpen),
      onclick: () => setNav(!state.navOpen, true),
    },
    icon(ICONS.menu, 17),
  );

  const pageTitle = el("span", { class: "page-title" });

  const themeButton = el("button", {
    class: "icon-button",
    type: "button",
    onclick: () => theme(isDark() ? "light" : "dark"),
  });
  shell.themeButton = themeButton;
  paintThemeButton();

  const topbar = el(
    "div",
    { class: "topbar" },
    hamburger,
    el(
      "button",
      {
        class: "brand",
        type: "button",
        "aria-label": "Semlith — go to Stores",
        onclick: () => go("stores"),
      },
      logoImage(26),
      el("span", { class: "wordmark", text: "Semlith" }),
    ),
    el("span", { class: "divider-v" }),
    pageTitle,
    el("span", { class: "spacer" }),
    el(
      "button",
      {
        class: "search-launcher",
        type: "button",
        "aria-label": "Search the index",
        onclick: () => go("search"),
      },
      icon(ICONS.search, 15),
      el("span", { class: "what", text: "Ask the index a question" }),
      el("span", { class: "key-hint", text: "/" }),
    ),
    themeButton,
  );

  const groups = [];
  for (const view of VIEWS) {
    const last = groups[groups.length - 1];
    if (last && last.label === view.group) last.items.push(view);
    else groups.push({ label: view.group, items: [view] });
  }

  const rail = el(
    "nav",
    { class: "rail", "aria-label": "Sections" },
    groups.map((group, i) =>
      el(
        "div",
        { class: "rail-group" },
        group.items.map((view) =>
          el(
            "button",
            {
              class: "rail-item",
              type: "button",
              "data-view": view.id,
              "aria-label": view.label,
              title: view.label,
              onclick: () => go(view.id),
            },
            icon(NAV_ICONS[view.id], 17),
          ),
        ),
        i < groups.length - 1 ? el("div", { class: "rail-rule" }) : null,
      ),
    ),
    el("span", { class: "spacer" }),
    el("span", { class: "live-dot", title: "semlith start" }),
  );

  const sidebar = el(
    "nav",
    { class: "sidebar", "aria-label": "Sections" },
    groups.map((group) =>
      el(
        "div",
        { class: "nav-group" },
        el("div", { class: "nav-group-label", text: group.label }),
        group.items.map((view) =>
          el(
            "button",
            {
              class: "nav-item",
              type: "button",
              "data-view": view.id,
              onclick: () => go(view.id),
            },
            icon(NAV_ICONS[view.id], 16),
            el("span", { text: view.label }),
          ),
        ),
      ),
    ),
    el("span", { class: "spacer" }),
    el(
      "div",
      { class: "daemon-card" },
      el("div", { class: "who" }, el("span", { class: "live-dot" }), mono("semlith start")),
      // The address with its port: "127.0.0.1" alone does not tell you which
      // of two daemons this tab is looking at.
      el("div", { class: "fact", text: `${location.host} · sole writer` }),
      el("div", { class: "fact", id: "daemon-stores", text: "" }),
    ),
  );

  const scrim = el("button", {
    class: "scrim",
    type: "button",
    "aria-label": "Close navigation",
    hidden: true,
    onclick: () => setNav(false, true),
  });

  const main = el("main", {});
  const body = el("div", { class: "body" }, rail, sidebar, scrim, main);

  Object.assign(shell, { topbar, pageTitle, rail, sidebar, scrim, main, hamburger });
  return el("div", { id: "app" }, topbar, body);
}

/** Open or close the navigation without re-rendering the view inside it. */
function setNav(open, fromUser) {
  const was = state.navOpen;
  state.navOpen = open;
  const narrow = window.matchMedia(NARROW).matches;
  shell.hamburger.setAttribute("aria-expanded", String(open));
  shell.sidebar.hidden = !open;
  // The rail is the wide-screen stand-in for the closed drawer. On a narrow
  // screen CSS hides it outright, so it is only ever a wide-screen concern.
  shell.rail.hidden = open || narrow;
  shell.scrim.hidden = !(open && narrow);

  // Over a page, the drawer is a cover — so the keyboard goes into it when it
  // opens and comes back to the button that opened it when it closes. Only for
  // a deliberate toggle: stealing focus on load or on a resize would be rude.
  if (!fromUser || !narrow || open === was) return;
  if (open) {
    const first = shell.sidebar.querySelector(".nav-item");
    if (first) first.focus();
  } else {
    shell.hamburger.focus();
  }
}

function markCurrent(current) {
  for (const node of document.querySelectorAll("[data-view]")) {
    if (node.getAttribute("data-view") === current) node.setAttribute("aria-current", "page");
    else node.removeAttribute("aria-current");
  }
}

let renderGeneration = 0;

async function render() {
  const current = (location.hash || "#stores").slice(1);
  const root = document.getElementById("root");

  // With no store there is nothing for the navigation to navigate, so the
  // first-run screen is the whole page rather than a view inside the shell.
  if (!state.stores.length && current !== "index" && current !== "about") {
    fill(root, welcomeView());
    shell.main = null;
    return;
  }

  if (!shell.main || !root.contains(shell.main)) {
    fill(root, buildShell());
    setNav(state.navOpen);
  }

  const view = VIEWS.find((v) => v.id === current) || VIEWS[0];
  shell.pageTitle.textContent = view.title;
  document.title = `Semlith · ${view.title}`;
  markCurrent(view.id);

  paintStoreCount();

  const mine = ++renderGeneration;
  fill(shell.main, el("div", { class: "view" }, el("p", { class: "subtitle", text: "Loading…" })));
  try {
    const node = await (RENDER[view.id] || RENDER.stores)();
    if (mine !== renderGeneration) return;
    fill(shell.main, node);
  } catch (e) {
    if (mine !== renderGeneration) return;
    fill(shell.main, el("div", { class: "view" }, error(e.message)));
  }
}

async function boot() {
  let saved = null;
  try {
    saved = localStorage.getItem("semlith-theme");
  } catch (_) {
    /* private window */
  }
  // Only an explicit choice stamps the attribute. Without one the stylesheet's
  // prefers-color-scheme block decides, so a machine set to dark is not shown
  // a white page and asked to go and find the toggle.
  if (saved === "dark" || saved === "light") {
    theme(saved);
  } else {
    state.theme = isDark() ? "dark" : "light";
  }

  wireTips();

  await refreshStores();
  // Not awaited: the sidebar's agent count is a detail, and `claude mcp list`
  // behind this route is slow on some machines. It fills itself in.
  api("/api/agents").then(noteAgents).catch(() => {});
  await render();

  window.addEventListener("hashchange", render);

  // A width change moves the drawer between overlay and column. Without this
  // the scrim stayed over the content after a resize until the next navigation.
  window.matchMedia(NARROW).addEventListener("change", (e) => {
    if (shell.main) setNav(!e.matches);
  });

  window.addEventListener("keydown", (e) => {
    if (e.key === "Escape" && state.navOpen && window.matchMedia(NARROW).matches && shell.main) {
      setNav(false, true);
      return;
    }
    if (e.key !== "/" || e.target.matches("input, textarea, select")) return;
    e.preventDefault();
    if ((location.hash || "").slice(1) === "search") {
      const box = document.querySelector(".search-field input");
      if (box) box.focus();
      return;
    }
    go("search");
  });
}

boot();