eclipse-core 0.13.3

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

use crate::error::{Error, Result};
use crate::message::{Message, Role};
use rusqlite::{params, Connection, OptionalExtension, TransactionBehavior};
use serde::{Deserialize, Serialize};
use std::io::{Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Record {
    /// Unix milliseconds.
    pub ts: u64,
    pub message: Message,
}

/// What the last turn on a session cost, kept in the store so a row can be honest about a
/// session nothing is running any more (#344).
///
/// The numbers are a **snapshot of one turn**, not a dimension of the session, which is why they
/// live in one JSON column rather than a column per counter: the counter set moves (a cache-write
/// field, reasoning tokens), and a `sessions.db` should not grow a migration every time the usage
/// struct does. A blob that will not parse reads as absent — the same thing the dashboard shows
/// for a session that never ran — so a corrupt record can never be mistaken for a measurement.
///
/// `ctx` is the server's own string (`eclipse_core::contextbar`), rendered when the turn
/// finished. Storing the string rather than its inputs is the point: the dashboard paints what
/// the terminal prints, and neither surface recomputes a denominator (#264).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct TurnCost {
    /// Unix milliseconds, when the turn's accounting was written.
    pub at_ms: u64,
    /// `ctx 121K/262K ██████░░░░│░ 46%`, from the reader the CLI uses.
    pub ctx: String,
    #[serde(default)]
    pub prompt_tokens: Option<u64>,
    #[serde(default)]
    pub completion_tokens: Option<u64>,
    #[serde(default)]
    pub cached_tokens: Option<u64>,
    #[serde(default)]
    pub ttft_ms: Option<u64>,
    #[serde(default)]
    pub latency_ms: Option<u64>,
    /// Absent when the model counted nothing or the clock did not move.
    #[serde(default)]
    pub tokens_per_sec: Option<f64>,
    /// The denominator that was in force for that turn — a fact about that model, not about the
    /// one selected now.
    #[serde(default)]
    pub window_tokens: Option<u64>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct SessionInfo {
    pub id: String,
    pub messages: usize,
    /// Unix milliseconds of the last record (0 if empty/unknown).
    pub updated_ms: u64,
    /// First user message, truncated.
    pub preview: String,
    /// Name set with `rename`, if any.
    pub title: Option<String>,
    /// Where the session came from: `native`, `jsonl` (imported) or `subagent:<parent>:<route>`.
    pub origin: String,
    /// Set with `pin`: the session sorts first in every listing and no retention policy
    /// deletes it.
    pub pinned: bool,
    /// Set with `archive`: out of every listing, still in the search, and out of a prune's
    /// reach unless the prune asks for it (`#240`).
    pub archived: bool,
    /// The last turn's numbers, so a row can show what a session cost without a run in flight
    /// (#344). `None` for a session that has never finished a turn.
    pub cost: Option<TurnCost>,
}

/// What a subagent session says about itself: the session whose run started it and the route
/// it ran on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SubagentOrigin<'a> {
    pub parent: &'a str,
    pub route: &'a str,
}

/// One flare run's ledger row (`#171`) — what `flares list` prints and what a cancel addresses.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlareRunRow {
    pub id: String,
    pub task: String,
    /// `running`, `done`, `cancelled` or `failed`.
    pub state: String,
    /// The routes the run's jobs named, deduplicated, in the order they were asked for.
    pub routes: Vec<String>,
    pub jobs: usize,
    pub parent: Option<String>,
    pub started_ms: u64,
    pub finished_ms: Option<u64>,
    pub prompt_tokens: Option<u64>,
    pub completion_tokens: Option<u64>,
    pub iterations: usize,
}

impl FlareRunRow {
    pub fn finished(&self) -> bool {
        self.finished_ms.is_some()
    }
}

/// One child of a run, as the ledger keeps it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlareJobRow {
    pub run_id: String,
    pub n: usize,
    pub route: String,
    pub session_id: Option<String>,
    /// `running`, `done`, `failed` or `dropped`.
    pub state: String,
    pub prompt_tokens: Option<u64>,
    pub completion_tokens: Option<u64>,
    pub iterations: usize,
    /// Why a failed or dropped child ended that way, in one line.
    pub why: Option<String>,
}

/// One bot's conversations, as the Bots tab reads them (`#509`).
///
/// The tab lists identities, not sessions: a bot answering on a lane opens one conversation and
/// keeps it, so the row is "this bot, last heard from then, this much said". `sessions` counts
/// every conversation the bot has had — a cleared one is archived, not deleted, and the count is
/// what says it happened.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BotSessions {
    pub name: String,
    pub sessions: usize,
    /// Messages in the newest conversation, which is the one the row's label describes.
    pub messages: usize,
    /// The newest conversation: what the row opens.
    pub last_session: String,
    pub last_activity_ms: u64,
    /// Every conversation this bot has is archived: it was cleared, and nothing has been said
    /// since. The row still lists it — an identity does not stop existing because its transcript
    /// was filed away.
    pub archived: bool,
}

/// The prefix of a subagent session's `origin`. Ids contain no `:`, so the parent ends at the
/// first one after it; a route name may contain anything and is last.
const SUBAGENT_ORIGIN: &str = "subagent:";

/// The prefix of a bot's session `origin` (`#509`): `bot:<name>`, one name and no parent. The
/// same shape as `subagent:` on purpose — the store, compaction, search and the cost ledger read
/// a session by its `origin`, so a bot adds a prefix and a parser, not a table.
const BOT_ORIGIN: &str = "bot:";

/// The prefix of a flare's session `origin` (`#171`): `flare:<run>:<n>`, the run's id and the
/// flare's position in it. A run id contains no `:`, so the position is last and parses as a
/// number — a row whose tail is not one is not a flare this build wrote.
const FLARE_ORIGIN: &str = "flare:";

/// What a flare session says about itself: the run that started it and its position in that run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FlareOrigin<'a> {
    pub run: &'a str,
    /// 1-based, the order the lead asked for them in — which is how a reader talks about them.
    pub n: usize,
}

impl SessionInfo {
    /// Set when the session is a child that a `delegate` call ran, not a conversation.
    pub fn subagent(&self) -> Option<SubagentOrigin<'_>> {
        let rest = self.origin.strip_prefix(SUBAGENT_ORIGIN)?;
        let (parent, route) = rest.split_once(':')?;
        Some(SubagentOrigin { parent, route })
    }

    /// The bot whose conversation this is, when it is one (`#509`).
    ///
    /// A name with a `:` in it never parses: the name is checked at load for exactly that reason,
    /// and a row written by something else is not allowed to look like two names.
    pub fn bot(&self) -> Option<&str> {
        self.origin
            .strip_prefix(BOT_ORIGIN)
            .filter(|name| !name.is_empty() && !name.contains(':'))
    }

    /// Whether this session belongs to a bot rather than to the person at the keyboard.
    pub fn is_bot(&self) -> bool {
        self.bot().is_some()
    }

    /// The flare run and position this session belongs to, when it is a flare (`#171`).
    ///
    /// The tail must parse as a number: `flare:run:two` is not a flare this build wrote, and
    /// reading it as one would put a row in a run listing under a position nothing can address.
    pub fn flare(&self) -> Option<FlareOrigin<'_>> {
        let rest = self.origin.strip_prefix(FLARE_ORIGIN)?;
        let (run, n) = rest.rsplit_once(':')?;
        let n: usize = n.parse().ok()?;
        (!run.is_empty() && n > 0).then_some(FlareOrigin { run, n })
    }

    /// Whether this session is one worker of a flare run rather than a conversation.
    pub fn is_flare(&self) -> bool {
        self.flare().is_some()
    }

    /// [`label`](Self::label), with `[subagent · route]` in front of a child's, `[bot · name]` in
    /// front of a bot's and `[flare · run/n]` in front of a flare's — the places that list
    /// sessions beside conversations and have no room for the parent's id.
    pub fn tagged_label(&self) -> String {
        if let Some(o) = self.subagent() {
            return format!("[subagent \u{b7} {}] {}", o.route, self.label());
        }
        if let Some(name) = self.bot() {
            return format!("[bot \u{b7} {name}] {}", self.label());
        }
        if let Some(f) = self.flare() {
            return format!("[flare \u{b7} {}/{}] {}", f.run, f.n, self.label());
        }
        self.label().to_string()
    }

    /// What to call the session in listings: its title, else the preview, else the id.
    pub fn label(&self) -> &str {
        match (&self.title, self.preview.is_empty()) {
            (Some(t), _) => t,
            (None, false) => &self.preview,
            (None, true) => &self.id,
        }
    }
}

/// Who wrote a session's title. The order is the precedence: a name a person typed is never
/// replaced, a name a model wrote is replaced only by a person, and the derived name is a
/// placeholder that either of the other two may take over.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum TitleSource {
    /// [`crate::naming::derive`]: the opening message's first line, written before any call.
    Derived,
    /// The one small-model call, when its answer survived `naming::clean_reply`.
    Llm,
    /// Typed by a person with `rename` (or the dashboard's ⋮ → rename).
    User,
}

impl TitleSource {
    pub fn as_str(self) -> &'static str {
        match self {
            TitleSource::Derived => "derived",
            TitleSource::Llm => "llm",
            TitleSource::User => "user",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExportFormat {
    Json,
    Markdown,
}

const MAX_TITLE_CHARS: usize = 200;

/// Pruning more sessions than this at once needs an explicit `--force` (manual prune) and
/// is refused outright by [`SessionStore::auto_prune`].
pub const PRUNE_CONFIRM_ABOVE: usize = 10;

/// Result of [`SessionStore::auto_prune`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AutoPrune {
    /// Both retention limits are 0: nothing to apply, nothing deleted.
    NoLimits,
    /// The policy selects no session.
    Nothing,
    /// Deleted `removed` sessions; `failed` could not be deleted. `pinned_kept` matched the
    /// policy and was left alone because it is pinned.
    Pruned {
        removed: usize,
        failed: usize,
        pinned_kept: usize,
    },
    /// The policy would remove `would_remove` sessions, more than
    /// [`PRUNE_CONFIRM_ABOVE`]: nothing was deleted.
    Skipped { would_remove: usize },
}

/// What a retention policy would delete, and what it refuses to touch.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PrunePlan {
    /// Ids the policy selects, newest first. Nothing is deleted by computing this.
    pub candidates: Vec<String>,
    /// How many sessions matched the policy and were kept anyway because they are pinned.
    pub pinned_kept: usize,
    /// How many matched and were kept because they are archived, and this prune did not ask for
    /// them (`--archived`). Counted apart from `pinned_kept` so the sentence that says why each
    /// one survived can name the flag that would have changed the answer.
    pub archived_kept: usize,
}

/// Title sidecar of a legacy `<id>.jsonl` session: read once, at import.
#[derive(Serialize, Deserialize)]
struct Meta {
    title: String,
}

const MAX_MEMORY_FILE_BYTES: u64 = 64 * 1024;

/// Schema of the stored memory. `1` was the model-written summary alone and, having no
/// `version` field, is what a file without one means; `2` adds the compiled handoff
/// ([`Handoff`]), which is what lets a long session reuse one instead of recompiling it on
/// every request.
pub const MEMORY_VERSION: u32 = 3;

/// The deterministic handoff compiled from the dropped middle, stored beside the summary so the
/// work is done once per covered range rather than once per request.
///
/// It carries the renderer's own version: a handoff written by a build that shaped the text
/// differently is not reused, because reusing it would put two shapes of the same document in one
/// session's history.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Handoff {
    pub text: String,
    /// [`crate::compact::VERSION`] when it was compiled.
    pub version: String,
    /// Middle turns this document stands in for.
    pub covered_turns: usize,
    /// Middle messages this document stands in for.
    pub covered_messages: usize,
    /// The `seq` of the first and last message the document stands in for, when the caller knew
    /// them. The counts describe a *size*, not a window: [`crate::context::Trimmed`] is relative
    /// to `head_end`, and `head_end` flips between `0` and `first_end` when the budget, the
    /// model or `protect_last_n` changes while the tail shifts to compensate — so "1 turn, 2
    /// messages" names several different windows, and a document reused for the wrong one
    /// describes messages that are still verbatim in the same request.
    #[serde(default)]
    pub covered_from: Option<u64>,
    #[serde(default)]
    pub covered_to: Option<u64>,
    pub generated_at_ms: u64,
    /// The bounded judgement pass's answer, when one survived the validator and went into
    /// [`Handoff::text`]. Kept beside it so the readout and the harness can say what the model
    /// contributed and on whose authority, without parsing the document.
    #[serde(default)]
    pub judgement: Option<Judgement>,
}

/// One accepted judgement pass: what the model said about *why*, and which model said it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Judgement {
    pub text: String,
    /// The auxiliary route that answered, as this process named it.
    pub model: String,
    pub generated_at_ms: u64,
}

impl Handoff {
    /// Usable as-is for `turns`/`messages` only when it was compiled for exactly that range and
    /// by this shape of compiler. A handoff for a *larger* range is not an extension of a
    /// smaller one — the sections are re-rendered, not appended — so a wider document would
    /// describe messages that are still present verbatim.
    ///
    /// The counts alone are not the range: the same pair of numbers names a different window
    /// whenever `head_end` moves. `from`/`to` are the `seq` of the first and last covered
    /// message, and a stored document that does not carry them is not reused — a recompile costs
    /// milliseconds, and a wrong document costs the model's trust in its own history.
    pub fn covers(
        &self,
        turns: usize,
        messages: usize,
        from: Option<u64>,
        to: Option<u64>,
    ) -> bool {
        self.version == crate::compact::VERSION
            && self.covered_turns == turns
            && self.covered_messages == messages
            && match (self.covered_from, self.covered_to, from, to) {
                (Some(a), Some(b), Some(c), Some(d)) => a == c && b == d,
                _ => false,
            }
    }
}

/// Per-session memory, stored beside the transcript: the compiled handoff that stands in for the
/// dropped middle of the conversation, and what range of the transcript it covers. It never
/// replaces the transcript.
///
/// There is no model-written summary here, and no second shape to choose between: a file written
/// by an older build (v1 or v2) still loads, its summary is ignored, and the next handoff write
/// replaces the record. The only model input compaction has is the judgement pass's bullets,
/// which live inside [`Handoff::judgement`] where they can be attributed and discarded together
/// with the document they belong to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Memory {
    /// [`MEMORY_VERSION`] as written, or `0` for a file written before the field existed.
    #[serde(default)]
    pub version: u32,
    /// The compiled handoff, absent when none has been stored yet.
    #[serde(default)]
    pub handoff: Option<Handoff>,
}

impl Memory {
    /// The schema this file was written with; a file from before the field existed is v1.
    pub fn schema(&self) -> u32 {
        self.version.max(1)
    }

    /// Why this memory must not be used, if so: a schema this build cannot read, a handoff in a
    /// file that predates handoffs, an empty or untrimmed document, or counts that make no sense.
    pub fn validate(&self) -> std::result::Result<(), String> {
        let schema = self.schema();
        if schema > MEMORY_VERSION {
            return Err(format!(
                "memory schema {schema} is newer than this build understands ({MEMORY_VERSION})"
            ));
        }
        if self.handoff.is_some() && schema < 2 {
            return Err("a handoff in a v1 memory file".into());
        }
        if self.handoff.is_none() {
            return Err("nothing remembered".into());
        }
        if let Some(h) = &self.handoff {
            if h.text.trim().is_empty() {
                return Err("empty handoff".into());
            }
            if h.text.trim() != h.text {
                return Err("handoff is not trimmed".into());
            }
            if h.covered_turns == 0 || h.covered_messages < h.covered_turns {
                return Err("inconsistent handoff counts".into());
            }
            if let Some(j) = &h.judgement {
                if j.text.trim().is_empty() || j.text.trim() != j.text {
                    return Err("empty or untrimmed judgement".into());
                }
            }
        }
        Ok(())
    }

    /// The compiled handoff, if this build can read it and it is structurally sound. Whether it
    /// still covers what is being dropped is [`Handoff::covers`]'s question, not this one's.
    pub fn usable_handoff(&self) -> Option<&Handoff> {
        self.validate().ok()?;
        self.handoff.as_ref()
    }
}

#[derive(Clone)]
pub struct SessionStore {
    dir: PathBuf,
    /// Opened on first use and kept for the life of the store. `None` until then, so
    /// constructing a store cannot fail.
    db: Arc<Mutex<Option<Db>>>,
}

impl std::fmt::Debug for SessionStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // The connection is not printable and carries nothing a caller needs to see.
        f.debug_struct("SessionStore")
            .field("dir", &self.dir)
            .finish()
    }
}

/// How long a run waits for another *process* to release a session before giving up.
pub const LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(30);

/// How often the wait re-tries the lock.
const LOCK_POLL: std::time::Duration = std::time::Duration::from_millis(50);

/// A held session lock. Dropping it releases the lock (the OS does the same if the
/// process dies, so a crash cannot leave a session permanently locked).
#[derive(Debug)]
pub struct SessionLock {
    id: String,
    /// The locked file: closing it drops the `flock`.
    _file: std::fs::File,
}

impl SessionLock {
    pub fn id(&self) -> &str {
        &self.id
    }
}

/// A stored `state` word back into the enum. An unknown word reads as `Stopped`: a goal this
/// build cannot name is not one it should keep working on.
fn goal_state(word: String) -> crate::goals::State {
    use crate::goals::State;
    match word.as_str() {
        "active" => State::Active,
        "paused" => State::Paused,
        "done" => State::Done,
        "blocked" => State::Blocked,
        _ => State::Stopped,
    }
}

fn open_lock_file(path: &Path) -> Result<std::fs::File> {
    let mut opts = std::fs::OpenOptions::new();
    opts.create(true).read(true).write(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        opts.mode(0o600);
    }
    opts.open(path).map_err(|e| Error::io(path, e))
}

/// Record who holds the lock, so a refusal elsewhere can name them. Best effort: a failed
/// write must not fail the lock.
fn write_lock_holder(file: &mut std::fs::File) {
    let text = format!("pid {}\n", std::process::id());
    let _ = file.set_len(0);
    let _ = file.seek(SeekFrom::Start(0));
    let _ = file.write_all(text.as_bytes());
    let _ = file.flush();
}

#[cfg(unix)]
fn try_lock_exclusive(file: &std::fs::File) -> std::io::Result<bool> {
    use std::os::unix::io::AsRawFd;
    // SAFETY: `file` owns a valid descriptor for the duration of the call.
    let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
    if rc == 0 {
        return Ok(true);
    }
    let err = std::io::Error::last_os_error();
    match err.raw_os_error() {
        // Another process holds it; anywhere else would be a real error.
        Some(libc::EWOULDBLOCK) => Ok(false),
        _ => Err(err),
    }
}

#[cfg(not(unix))]
fn try_lock_exclusive(_file: &std::fs::File) -> std::io::Result<bool> {
    // No portable advisory lock without extra dependencies; the per-process mutex in the
    // runtime is all there is here (see the docs' limitations).
    Ok(true)
}

/// A session some process is running right now, as seen by [`held_locks`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeldLock {
    pub id: String,
    /// What the holder wrote into the lock file (`pid N`), or `another process`.
    pub holder: String,
}

/// Which sessions in `dir` are locked by a live run.
///
/// A lock file left behind by a finished run is not a lock — the OS drops the `flock` with the
/// process — so each file is probed with a non-blocking *shared* lock: it fails only while an
/// exclusive holder exists, and it never creates a file or waits. A directory that does not
/// exist holds nothing. On non-Unix targets there is no cross-process lock to ask about, and
/// the answer is always empty.
pub fn held_locks(dir: &Path) -> Vec<HeldLock> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    let mut held = Vec::new();
    for entry in entries.flatten() {
        let path = entry.path();
        let Some(id) = path
            .file_name()
            .and_then(|n| n.to_str())
            .and_then(|n| n.strip_suffix(".lock"))
        else {
            continue;
        };
        if validate_id(id).is_err() {
            continue;
        }
        let Ok(file) = std::fs::File::open(&path) else {
            continue;
        };
        if is_locked_by_another(&file) {
            let holder = std::fs::read_to_string(&path)
                .ok()
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .unwrap_or_else(|| "another process".to_string());
            held.push(HeldLock {
                id: id.to_string(),
                holder,
            });
        }
    }
    held.sort_by(|a, b| a.id.cmp(&b.id));
    held
}

#[cfg(unix)]
/// A lock file nobody is holding: its holder is gone, so the kernel released the lock and the
/// file is left behind. `eclipse doctor --fix` removes these.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StaleLock {
    pub path: PathBuf,
    /// The session the lock belongs to, taken from the file name — what `doctor` compares with the
    /// store to tell a leftover from a lock whose session is gone (`#497`).
    pub id: String,
    /// What the file says held it, for the message: `pid 1234`, or `another process`.
    pub holder: String,
}

/// The `<id>.lock` files in `dir` that are *not* held by a live process.
///
/// The counterpart of [`held_locks`]: that one answers "which sessions are in use", this one
/// answers "which leftovers can be cleaned up". A file whose `flock` is free is a file whose
/// holder died, because the kernel releases the lock then and nothing removes the file.
pub fn stale_locks(dir: &Path) -> Vec<StaleLock> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    let mut stale = Vec::new();
    for entry in entries.flatten() {
        let path = entry.path();
        let Some(id) = path
            .file_name()
            .and_then(|n| n.to_str())
            .and_then(|n| n.strip_suffix(".lock"))
        else {
            continue;
        };
        if validate_id(id).is_err() {
            continue;
        }
        let Ok(file) = std::fs::File::open(&path) else {
            continue;
        };
        if is_locked_by_another(&file) {
            continue;
        }
        let holder = std::fs::read_to_string(&path)
            .ok()
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| "another process".to_string());
        let id = id.to_string();
        stale.push(StaleLock { path, id, holder });
    }
    stale.sort_by(|a, b| a.path.cmp(&b.path));
    stale
}

fn is_locked_by_another(file: &std::fs::File) -> bool {
    use std::os::unix::io::AsRawFd;
    // SAFETY: `file` owns a valid descriptor for the duration of the call.
    let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) };
    if rc == 0 {
        // Closing the descriptor drops the probe; nothing to undo.
        return false;
    }
    std::io::Error::last_os_error().raw_os_error() == Some(libc::EWOULDBLOCK)
}

#[cfg(not(unix))]
fn is_locked_by_another(_file: &std::fs::File) -> bool {
    false
}

static COUNTER: AtomicU64 = AtomicU64::new(0);

pub fn now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

/// How long ago a stored timestamp is, in the words a person would use. `0` says nothing
/// rather than claiming 1970: a session imported with no readable record has no time.
pub fn ago_words(at_ms: u64) -> String {
    if at_ms == 0 {
        return String::new();
    }
    let secs = now_ms().saturating_sub(at_ms) / 1000;
    match secs {
        0..=59 => "just now".to_string(),
        60..=3_599 => format!("{}m ago", secs / 60),
        3_600..=86_399 => format!("{}h ago", secs / 3_600),
        _ => format!("{}d ago", secs / 86_400),
    }
}

/// Ids become file names, so only a conservative character set is accepted.
pub fn validate_id(id: &str) -> Result<()> {
    let ok = !id.is_empty()
        && id.len() <= 64
        && id
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
    if ok {
        Ok(())
    } else {
        Err(Error::Session(format!("invalid session id {id:?}")))
    }
}

impl SessionStore {
    pub fn new(dir: impl Into<PathBuf>) -> Self {
        Self {
            dir: dir.into(),
            db: std::sync::Arc::new(std::sync::Mutex::new(None)),
        }
    }

    pub fn dir(&self) -> &Path {
        &self.dir
    }

    /// Sortable, unique-enough id: `<unix-ms>-<pid>-<counter>`.
    pub fn new_id(&self) -> String {
        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
        format!("{}-{}-{}", now_ms(), std::process::id(), n)
    }

    fn lock_path(&self, id: &str) -> Result<PathBuf> {
        validate_id(id)?;
        Ok(self.dir.join(format!("{id}.lock")))
    }

    /// Run `f` against the database, opening (and migrating, and importing any legacy
    /// `.jsonl` files) on first use.
    ///
    /// Opening lazily keeps [`SessionStore::new`] infallible — the CLI constructs a store
    /// before it knows whether the state directory is usable — and puts the error where it
    /// can be reported: on the call that needed the data.
    /// `pub(crate)` so the runtime's tests can inject a failure (a rejecting trigger) and
    /// check that a failed memory save is reported instead of breaking the run.
    pub(crate) fn with_db<T>(&self, f: impl FnOnce(&mut Db) -> Result<T>) -> Result<T> {
        let mut guard = self
            .db
            .lock()
            .map_err(|_| Error::Session("session store is poisoned".into()))?;
        if guard.is_none() {
            *guard = Some(Db::open(&self.dir)?);
        }
        f(guard.as_mut().expect("just opened"))
    }

    /// Take an exclusive lock on one session so two *processes* (the CLI and the
    /// dashboard, or two shells) cannot interleave their messages into the same
    /// transcript. Waits up to `wait` for a holder to finish. Dropping the guard releases
    /// it, and the OS releases it if the process dies, so a crashed run leaves nothing
    /// stuck.
    ///
    /// On non-Unix targets no cross-process lock is taken (the guard is inert); within one
    /// process the runtime's own per-session mutex still applies.
    pub async fn lock(&self, id: &str, wait: std::time::Duration) -> Result<SessionLock> {
        let path = self.lock_path(id)?;
        std::fs::create_dir_all(&self.dir).map_err(|e| Error::io(&self.dir, e))?;
        let mut file = open_lock_file(&path)?;
        let started = std::time::Instant::now();
        loop {
            match try_lock_exclusive(&file) {
                Ok(true) => {
                    write_lock_holder(&mut file);
                    return Ok(SessionLock {
                        id: id.to_string(),
                        _file: file,
                    });
                }
                Ok(false) => {
                    if started.elapsed() >= wait {
                        let holder = std::fs::read_to_string(&path)
                            .ok()
                            .map(|s| s.trim().to_string())
                            .filter(|s| !s.is_empty())
                            .unwrap_or_else(|| "another process".to_string());
                        return Err(Error::Session(format!(
                            "session {id} is in use by {holder}; waited {}s",
                            wait.as_secs()
                        )));
                    }
                    tokio::time::sleep(LOCK_POLL).await;
                }
                Err(e) => return Err(Error::io(&path, e)),
            }
        }
    }

    /// One non-blocking attempt at the same lock [`lock`](Self::lock) takes, for a caller that
    /// has no future to await it in — a UI thread asking "is a run in flight?" before it fires a
    /// `/loop` tick (`#173`). `Ok(Some)` means the caller now holds it and must drop it.
    ///
    /// It is the same primitive, not a second opinion: the lock is `flock`, and a session's lock
    /// file is a session's lock file whether the take is polled or instantaneous.
    pub fn try_lock(&self, id: &str) -> Result<Option<SessionLock>> {
        let path = self.lock_path(id)?;
        std::fs::create_dir_all(&self.dir).map_err(|e| Error::io(&self.dir, e))?;
        let mut file = open_lock_file(&path)?;
        match try_lock_exclusive(&file) {
            Ok(true) => {
                write_lock_holder(&mut file);
                Ok(Some(SessionLock {
                    id: id.to_string(),
                    _file: file,
                }))
            }
            Ok(false) => Ok(None),
            Err(e) => Err(Error::io(&path, e)),
        }
    }

    /// `#172`: write a session's goal, replacing whatever was there.
    ///
    /// One goal per session, so this is an upsert rather than an append: `/goal <text>` on a
    /// session that already has one replaces it, which is what "one standing goal" means.
    pub fn set_goal(&self, goal: &crate::goals::Goal) -> Result<()> {
        validate_id(&goal.session)?;
        self.with_db(|db| {
            // The session row exists so the goal has something to belong to. Written alone, a goal
            // insert that then failed left the row behind — an empty session nobody asked for,
            // listed as if they had opened one (`#565`).
            let tx = db
                .conn
                .transaction_with_behavior(TransactionBehavior::Immediate)?;
            tx.execute(
                "INSERT INTO sessions (id, created_ms, updated_ms, messages, origin)
                 VALUES (?1, ?2, ?2, 0, 'native')
                 ON CONFLICT(id) DO NOTHING",
                params![goal.session, goal.created_ms],
            )
            .map_err(|e| Error::Session(format!("could not ensure the session row: {e}")))?;
            tx.execute(
                "INSERT INTO goals
                     (session_id, text, gate, budget, turns, state, note, garbage,
                      created_ms, updated_ms)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
                 ON CONFLICT(session_id) DO UPDATE SET
                     text = excluded.text, gate = excluded.gate, budget = excluded.budget,
                     turns = excluded.turns, state = excluded.state, note = excluded.note,
                     garbage = excluded.garbage, updated_ms = excluded.updated_ms",
                params![
                    goal.session,
                    goal.text,
                    goal.gate,
                    goal.budget as i64,
                    goal.turns as i64,
                    goal.state.as_str(),
                    goal.note,
                    goal.garbage as i64,
                    goal.created_ms,
                    goal.updated_ms,
                ],
            )
            .map_err(|e| Error::Session(format!("could not save the goal: {e}")))?;
            tx.commit()?;
            Ok(())
        })
    }

    /// `#172`: a session's goal, if it has one.
    pub fn goal(&self, id: &str) -> Result<Option<crate::goals::Goal>> {
        validate_id(id)?;
        self.with_db(|db| {
            let found = db
                .conn
                .query_row(
                    "SELECT text, gate, budget, turns, state, note, garbage, created_ms, updated_ms
                       FROM goals WHERE session_id = ?1",
                    params![id],
                    |r| {
                        Ok(crate::goals::Goal {
                            session: id.to_string(),
                            text: r.get(0)?,
                            gate: r.get(1)?,
                            budget: r.get::<_, i64>(2)? as u32,
                            turns: r.get::<_, i64>(3)? as u32,
                            state: goal_state(r.get::<_, String>(4)?),
                            note: r.get(5)?,
                            garbage: r.get::<_, i64>(6)? != 0,
                            created_ms: r.get(7)?,
                            updated_ms: r.get(8)?,
                        })
                    },
                )
                .optional()?;
            Ok(found)
        })
    }

    /// Remove a session's goal and its judgements (`/goal clear`).
    pub fn clear_goal(&self, id: &str) -> Result<()> {
        validate_id(id)?;
        self.with_db(|db| {
            // One act, two tables. Both deletes apart, a crash in between left the judgements of
            // the goal that was just cleared, and the next goal on this session inherited them —
            // its first turn was judged against somebody else's work (`#565`).
            let tx = db
                .conn
                .transaction_with_behavior(TransactionBehavior::Immediate)?;
            tx.execute("DELETE FROM goals WHERE session_id = ?1", params![id])
                .map_err(|e| Error::Session(format!("could not clear the goal: {e}")))?;
            tx.execute("DELETE FROM goal_turns WHERE session_id = ?1", params![id])
                .map_err(|e| Error::Session(format!("could not clear the judgements: {e}")))?;
            tx.commit()?;
            Ok(())
        })
    }

    /// Record one judgement, keyed by the turn number it judged.
    pub fn record_goal_turn(&self, id: &str, judgement: &crate::goals::Judgement) -> Result<()> {
        validate_id(id)?;
        self.with_db(|db| {
            db.conn
                .execute(
                    "INSERT INTO goal_turns (session_id, turn, verdict, why, at_ms)
                     VALUES (?1, ?2, ?3, ?4, ?5)
                     ON CONFLICT(session_id, turn) DO UPDATE SET
                         verdict = excluded.verdict, why = excluded.why, at_ms = excluded.at_ms",
                    params![
                        id,
                        judgement.turn as i64,
                        judgement.verdict,
                        judgement.why,
                        judgement.at_ms,
                    ],
                )
                .map_err(|e| Error::Session(format!("could not record the judgement: {e}")))?;
            Ok(())
        })
    }

    /// Every judgement about a session's goal, oldest first.
    pub fn goal_turns(&self, id: &str) -> Result<Vec<crate::goals::Judgement>> {
        validate_id(id)?;
        self.with_db(|db| {
            let mut stmt = db
                .conn
                .prepare(
                    "SELECT turn, verdict, why, at_ms FROM goal_turns
                      WHERE session_id = ?1 ORDER BY turn",
                )
                .map_err(|e| Error::Session(format!("could not read the judgements: {e}")))?;
            let rows = stmt
                .query_map(params![id], |r| {
                    Ok(crate::goals::Judgement {
                        turn: r.get::<_, i64>(0)? as u32,
                        verdict: r.get(1)?,
                        why: r.get(2)?,
                        at_ms: r.get(3)?,
                    })
                })
                .map_err(|e| Error::Session(format!("could not read the judgements: {e}")))?;
            Ok(rows.flatten().collect())
        })
    }

    /// Every goal a process could still work on — `Active` or `Paused`, newest first.
    ///
    /// The dashboard's sweeper asks this each pass: a goal is due when its last turn said
    /// "continue", which is a fact on the row, not a timer in a task.
    pub fn live_goals(&self) -> Result<Vec<crate::goals::Goal>> {
        self.with_db(|db| {
            let mut stmt = db
                .conn
                .prepare(
                    "SELECT session_id, text, gate, budget, turns, state, note, garbage,
                            created_ms, updated_ms
                       FROM goals WHERE state IN ('active', 'paused') ORDER BY updated_ms DESC",
                )
                .map_err(|e| Error::Session(format!("could not list goals: {e}")))?;
            let rows = stmt
                .query_map([], |r| {
                    Ok(crate::goals::Goal {
                        session: r.get(0)?,
                        text: r.get(1)?,
                        gate: r.get(2)?,
                        budget: r.get::<_, i64>(3)? as u32,
                        turns: r.get::<_, i64>(4)? as u32,
                        state: goal_state(r.get::<_, String>(5)?),
                        note: r.get(6)?,
                        garbage: r.get::<_, i64>(7)? != 0,
                        created_ms: r.get(8)?,
                        updated_ms: r.get(9)?,
                    })
                })
                .map_err(|e| Error::Session(format!("could not list goals: {e}")))?;
            Ok(rows.flatten().collect())
        })
    }

    /// Whether some process is running this session right now — the busy test `/loop` uses.
    ///
    /// A probe, not a reservation: it takes the lock and releases it, so a run that starts in the
    /// same instant is not blocked by the question. What it answers is "was it free a moment
    /// ago", which is what a tick landing on a busy session needs to know.
    pub fn is_busy(&self, id: &str) -> bool {
        match self.try_lock(id) {
            Ok(Some(lock)) => {
                drop(lock);
                false
            }
            Ok(None) => true,
            // A lock file that cannot be opened is not evidence of a run in flight; the run
            // itself will say what went wrong and that is the better place to report it.
            Err(_) => false,
        }
    }

    pub fn exists(&self, id: &str) -> bool {
        if validate_id(id).is_err() {
            return false;
        }
        self.with_db(|db| {
            let found: Option<i64> = db
                .conn
                .query_row("SELECT 1 FROM sessions WHERE id = ?1", params![id], |r| {
                    r.get(0)
                })
                .optional()?;
            Ok(found.is_some())
        })
        .unwrap_or(false)
    }

    /// Record the calls of one assistant message as waiting for an answer.
    ///
    /// A row that already exists keeps its decision: the same call recorded twice has the same
    /// answer or none, and the second recording can arrive while the run that asked is already
    /// stopping, which is exactly when overwriting a decision would lose it.
    pub fn record_pending(
        &self,
        id: &str,
        seq: i64,
        calls: &[crate::approvals::Pending],
    ) -> Result<()> {
        self.record_pending_at(id, seq, 0, calls)
    }

    /// The same, with the position `calls[0]` holds in its assistant message.
    ///
    /// `ord` is half of the row's key, so a caller that records one call at a time has to pass the
    /// position that call actually holds: every call written at 0 collides with the first one, and
    /// `ON CONFLICT DO NOTHING` then drops the rest of the turn silently (#547).
    pub fn record_pending_at(
        &self,
        id: &str,
        seq: i64,
        ord: usize,
        calls: &[crate::approvals::Pending],
    ) -> Result<()> {
        validate_id(id)?;
        self.with_db(|db| {
            let tx = db.conn.transaction()?;
            for (offset, call) in calls.iter().enumerate() {
                tx.execute(
                    "INSERT INTO approvals
                         (session_id, seq, ord, call_id, tool, summary, args, decision, decided_ms)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, NULL, NULL)
                     ON CONFLICT(session_id, seq, ord) DO NOTHING",
                    params![
                        id,
                        seq,
                        (ord + offset) as i64,
                        call.call_id,
                        call.tool,
                        call.summary,
                        call.args
                    ],
                )?;
            }
            tx.commit()?;
            Ok(())
        })
    }

    /// Every recorded call for a session, oldest message first and in the order the model made
    /// them — the order `eclipse approve --index N` counts in.
    pub fn pending_calls(&self, id: &str) -> Result<Vec<crate::approvals::PendingCall>> {
        validate_id(id)?;
        self.with_db(|db| {
            let mut stmt = db.conn.prepare(
                "SELECT seq, ord, call_id, tool, summary, args, decision, decided_ms, by
                   FROM approvals WHERE session_id = ?1 ORDER BY seq, ord",
            )?;
            let rows = stmt
                .query_map(params![id], |r| {
                    let stored: Option<String> = r.get(6)?;
                    Ok(crate::approvals::PendingCall {
                        seq: r.get(0)?,
                        ord: r.get::<_, i64>(1)? as usize,
                        call: crate::approvals::Pending::new(
                            r.get::<_, String>(2)?,
                            r.get::<_, String>(3)?,
                            r.get::<_, String>(4)?,
                            r.get::<_, String>(5)?,
                        ),
                        decision: stored.as_deref().map(crate::approvals::Decision::parse),
                        decided_ms: r.get(7)?,
                        by: r.get(8)?,
                    })
                })?
                .collect::<std::result::Result<Vec<_>, _>>()?;
            Ok(rows)
        })
    }

    /// Write the answer for one recorded call. Refused if the call is not recorded: an approval
    /// for a call that does not exist would resolve nothing, and silently accepting it would
    /// tell the user their answer counted.
    pub fn decide_pending(
        &self,
        id: &str,
        seq: i64,
        ord: usize,
        decision: &crate::approvals::Decision,
        by: &str,
    ) -> Result<()> {
        validate_id(id)?;
        // `Defer` has no stored value, and writing one would make "still waiting" look like an
        // answer: the row keeps its `NULL` and nothing goes in the log.
        let Some(stored) = decision.store() else {
            return Ok(());
        };
        let now = now_ms() as i64;
        let changed = self.with_db(|db| {
            // One write, two tables, and the issue's point: the log row is only meaningful
            // *because* the ruling landed, and someone reading the log while the `approvals` row
            // is cleared must never see the answer without the entry that says who gave it.
            // `Immediate` takes the write lock at BEGIN rather than at the first statement, so two
            // processes settle who writes before either has half-written (`#565`).
            let tx = db
                .conn
                .transaction_with_behavior(TransactionBehavior::Immediate)?;
            let changed = tx.execute(
                "UPDATE approvals SET decision = ?4, decided_ms = ?5, by = ?6
                  WHERE session_id = ?1 AND seq = ?2 AND ord = ?3",
                params![&id, seq, ord as i64, &stored, now, by],
            )?;
            // The row is deleted once the answer is in the transcript, so the log is what makes
            // "who let this through" answerable afterwards.
            if changed > 0 {
                tx.execute(
                    "INSERT INTO approval_log
                         (session_id, at_ms, call_id, tool, summary, decision, by)
                     SELECT session_id, ?4, call_id, tool, summary, ?5, ?6 FROM approvals
                      WHERE session_id = ?1 AND seq = ?2 AND ord = ?3",
                    params![&id, seq, ord as i64, now, &stored, by],
                )?;
            }
            tx.commit()?;
            Ok(changed)
        })?;
        if changed == 0 {
            return Err(Error::Session(format!(
                "{id}: no tool call recorded at message {seq}, position {ord}"
            )));
        }
        Ok(())
    }

    /// Note a ruling that had no waiting row: a judge's allow or deny (`#340`).
    ///
    /// Those calls never become pending — nothing is waiting on them — so there is no row to hang
    /// the decider on, and the log is the only place the decision can live. Written best-effort by
    /// the caller: a bookkeeping failure must never turn an approval into a refusal.
    pub fn log_decision(
        &self,
        id: &str,
        call: &crate::approvals::Pending,
        decision: &crate::approvals::Decision,
        by: &str,
    ) -> Result<()> {
        validate_id(id)?;
        let Some(stored) = decision.store() else {
            return Ok(());
        };
        let now = now_ms() as i64;
        self.with_db(|db| {
            Ok(db.conn.execute(
                "INSERT INTO approval_log (session_id, at_ms, call_id, tool, summary, decision, by)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                params![
                    id,
                    now,
                    &call.call_id,
                    &call.tool,
                    &call.summary,
                    &stored,
                    by
                ],
            )?)
        })?;
        Ok(())
    }

    /// Every ruling recorded for a session, oldest first (`#340`).
    ///
    /// The pending rows are transient by design, so this is the only place "who let this through"
    /// survives. One row per answered call: the decision as stored (`allow`, `deny:<why>`) and who
    /// answered it.
    pub fn approval_log(&self, id: &str) -> Result<Vec<crate::approvals::Ruling>> {
        validate_id(id)?;
        self.with_db(|db| {
            let mut stmt = db.conn.prepare(
                "SELECT at_ms, call_id, tool, summary, decision, by FROM approval_log
                  WHERE session_id = ?1 ORDER BY at_ms, rowid",
            )?;
            let rows = stmt
                .query_map(params![id], |r| {
                    Ok(crate::approvals::Ruling {
                        at_ms: r.get(0)?,
                        call_id: r.get(1)?,
                        tool: r.get(2)?,
                        summary: r.get(3)?,
                        decision: crate::approvals::Decision::parse(&r.get::<_, String>(4)?),
                        by: r.get(5)?,
                    })
                })?
                .collect::<std::result::Result<Vec<_>, _>>()?;
            Ok(rows)
        })
    }

    /// Forget the recorded calls of a session — the run that asked has answered them in the
    /// transcript, or the session is gone. Returns how many rows went.
    pub fn clear_pending(&self, id: &str) -> Result<usize> {
        validate_id(id)?;
        self.with_db(|db| {
            Ok(db
                .conn
                .execute("DELETE FROM approvals WHERE session_id = ?1", params![id])?)
        })
    }

    /// Forget one recorded call — its answer has been written into the transcript as the tool
    /// result, which is the durable record a reader actually reads.
    pub fn clear_call(&self, id: &str, call_id: &str) -> Result<usize> {
        validate_id(id)?;
        self.with_db(|db| {
            Ok(db.conn.execute(
                "DELETE FROM approvals WHERE session_id = ?1 AND call_id = ?2",
                params![id, call_id],
            )?)
        })
    }

    /// The `seq` a session's transcript ends at, or -1 for an empty one.
    pub fn last_seq(&self, id: &str) -> Result<i64> {
        validate_id(id)?;
        self.with_db(|db| {
            Ok(db.conn.query_row(
                "SELECT COALESCE(MAX(seq), -1) FROM messages WHERE session_id = ?1",
                params![id],
                |r| r.get(0),
            )?)
        })
    }

    /// Append one message to the session, creating it on first use.
    /// How one tool call ended, for the marks a replayed session draws (`#447`).
    ///
    /// The verdict belongs beside the message, not inside it: a `tool` message is the model's wire
    /// shape, and a field there would either be sent to the model or skipped and never stored. The
    /// call id is what a replayed row joins on, so it is the key.
    pub fn set_tool_outcome(&self, id: &str, call_id: &str, is_error: bool) -> Result<()> {
        validate_id(id)?;
        let session = id.to_string();
        let call = call_id.to_string();
        self.with_db(|db| {
            db.conn
                .execute(
                    "INSERT INTO tool_outcomes (session_id, call_id, is_error) VALUES (?1, ?2, ?3)
                     ON CONFLICT (session_id, call_id) DO UPDATE SET is_error = excluded.is_error",
                    rusqlite::params![session, call, is_error as i64],
                )
                .map_err(|e| Error::Session(e.to_string()))?;
            Ok(())
        })
    }

    /// Every recorded verdict for a session, by call id. An empty map is a session recorded before
    /// this table existed, and the reader falls back to reading the text.
    pub fn tool_outcomes(&self, id: &str) -> Result<std::collections::HashMap<String, bool>> {
        validate_id(id)?;
        let session = id.to_string();
        self.with_db(|db| {
            let mut stmt = db
                .conn
                .prepare("SELECT call_id, is_error FROM tool_outcomes WHERE session_id = ?1")
                .map_err(|e| Error::Session(e.to_string()))?;
            let rows = stmt
                .query_map(rusqlite::params![session], |row| {
                    Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)? != 0))
                })
                .map_err(|e| Error::Session(e.to_string()))?;
            let mut out = std::collections::HashMap::new();
            for row in rows {
                let (call, is_error) = row.map_err(|e| Error::Session(e.to_string()))?;
                out.insert(call, is_error);
            }
            Ok(out)
        })
    }

    pub fn append(&self, id: &str, message: &Message) -> Result<()> {
        self.append_seq(id, message).map(|_| ())
    }

    /// [`append`](Self::append), returning the `seq` the message was stored under. A pending
    /// approval is keyed by the message that carried the call, so the loop needs the number it
    /// cannot compute itself: the store owns sequence allocation.
    pub fn append_seq(&self, id: &str, message: &Message) -> Result<i64> {
        validate_id(id)?;
        let now = now_ms() as i64;
        let body = serde_json::to_string(message).map_err(|e| Error::Session(e.to_string()))?;
        let role = role_name(message.role);
        // The preview is the first thing the user said; it is captured once, when that
        // message arrives, so listing never has to walk the transcript.
        let preview = (message.role == Role::User)
            .then(|| {
                message
                    .content
                    .as_deref()
                    .map(|t| t.split_whitespace().collect::<Vec<_>>().join(" "))
                    .map(|t| t.chars().take(60).collect::<String>())
            })
            .flatten()
            // An empty string is not a preview. `COALESCE(preview, ?3)` fills only a NULL, so a
            // user row that said nothing (a picture and no text) used to freeze the listing at
            // "untitled" for the rest of the session, even after a real message arrived.
            .filter(|p| !p.trim().is_empty());

        self.with_db(|db| {
            let tx = db.conn.transaction()?;
            // The session row first: the foreign key on `messages` is immediate, and a
            // message cannot be inserted before the thing it belongs to exists.
            tx.execute(
                "INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
                 VALUES (?1, ?2, ?2, NULL, NULL, 0, 'native')
                 ON CONFLICT(id) DO NOTHING",
                params![id, now],
            )?;
            let seq: i64 = tx.query_row(
                "SELECT COALESCE(MAX(seq), -1) + 1 FROM messages WHERE session_id = ?1",
                params![id],
                |r| r.get(0),
            )?;
            tx.execute(
                "INSERT INTO messages (session_id, seq, at_ms, role, body)
                 VALUES (?1, ?2, ?3, ?4, ?5)",
                params![id, seq, now, role, body],
            )?;
            tx.execute(
                "UPDATE sessions
                    SET updated_ms = ?2,
                        messages   = messages + 1,
                        preview    = COALESCE(preview, ?3)
                  WHERE id = ?1",
                params![id, now, preview],
            )?;
            if db.fts {
                tx.execute(
                    "INSERT INTO messages_fts (session_id, seq, content) VALUES (?1, ?2, ?3)",
                    params![id, seq, searchable(message)],
                )?;
            }
            tx.commit()?;
            Ok(seq)
        })
    }

    /// Create the session row for a subagent, marked with where it came from, before it has a
    /// message. The origin is what `sessions list` shows and what `--continue` skips; the
    /// transcript of the parent never mentions the child. A row that already exists is left
    /// as it is.
    pub fn begin_subagent(&self, id: &str, parent: &str, route: &str) -> Result<()> {
        validate_id(parent)?;
        self.begin_row(id, &format!("{SUBAGENT_ORIGIN}{parent}:{route}"))
    }

    /// Create the row for one flare of a run (`#171`), before it has a message.
    ///
    /// A flare is a child like a subagent's, and the run id is not a session id — it names the
    /// ledger row, not a conversation — so it is only checked for shape here.
    pub fn begin_flare(&self, id: &str, run: &str, n: usize) -> Result<()> {
        if run.is_empty() || run.contains(':') {
            return Err(Error::Config(format!(
                "a flare run id is one word without a colon, not {run:?}"
            )));
        }
        self.begin_row(id, &format!("{FLARE_ORIGIN}{run}:{n}"))
    }

    /// Open the run's ledger row (`#171`), before the first child starts.
    pub fn begin_flare_run(
        &self,
        id: &str,
        task: &str,
        routes: &[String],
        jobs: usize,
        parent: &str,
    ) -> Result<()> {
        let task: String = task.chars().take(500).collect();
        self.with_db(|db| {
            db.conn.execute(
                "INSERT INTO flare_runs (id, task, state, routes, jobs, parent, started_ms)
                 VALUES (?1, ?2, 'running', ?3, ?4, ?5, ?6)",
                params![
                    id,
                    task,
                    routes.join(","),
                    jobs as i64,
                    parent,
                    now_ms() as i64
                ],
            )?;
            Ok(())
        })
    }

    /// A child has its session and is about to call the model.
    pub fn flare_job_running(&self, run: &str, n: usize, route: &str, session: &str) -> Result<()> {
        self.with_db(|db| {
            db.conn.execute(
                "INSERT INTO flare_jobs (run_id, n, route, session_id, state)
                 VALUES (?1, ?2, ?3, ?4, 'running')
                 ON CONFLICT(run_id, n) DO UPDATE SET
                   route = excluded.route, session_id = excluded.session_id,
                   state = 'running'",
                params![run, n as i64, route, session],
            )?;
            Ok(())
        })
    }

    /// How that child ended, and what it cost. `state` is one word: done, failed or dropped.
    #[allow(clippy::too_many_arguments)]
    pub fn flare_job_done(&self, done: &FlareJobRow) -> Result<()> {
        self.with_db(|db| {
            db.conn.execute(
                "INSERT INTO flare_jobs (run_id, n, route, session_id, state, prompt_tokens,
                                         completion_tokens, iterations, why)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
                 ON CONFLICT(run_id, n) DO UPDATE SET
                   route = excluded.route, session_id = excluded.session_id,
                   state = excluded.state, prompt_tokens = excluded.prompt_tokens,
                   completion_tokens = excluded.completion_tokens,
                   iterations = excluded.iterations, why = excluded.why",
                params![
                    done.run_id,
                    done.n as i64,
                    done.route,
                    done.session_id,
                    done.state,
                    done.prompt_tokens.map(|v| v as i64),
                    done.completion_tokens.map(|v| v as i64),
                    done.iterations as i64,
                    done.why,
                ],
            )?;
            Ok(())
        })
    }

    /// Close the run: its state and what all its children cost together.
    #[allow(clippy::too_many_arguments)]
    pub fn finish_flare_run(
        &self,
        id: &str,
        state: &str,
        prompt: Option<u64>,
        completion: Option<u64>,
        iterations: usize,
    ) -> Result<()> {
        self.with_db(|db| {
            db.conn.execute(
                "UPDATE flare_runs SET state = ?2, finished_ms = ?3, prompt_tokens = ?4,
                        completion_tokens = ?5, iterations = ?6
                  WHERE id = ?1",
                params![
                    id,
                    state,
                    now_ms() as i64,
                    prompt.map(|v| v as i64),
                    completion.map(|v| v as i64),
                    iterations as i64
                ],
            )?;
            Ok(())
        })
    }

    /// Ask a run to stop, from any process. The run checks between children, so a queued flare
    /// is dropped before it starts rather than after it has paid for its first turn.
    pub fn cancel_flare_run(&self, id: &str) -> Result<bool> {
        self.with_db(|db| {
            let n = db.conn.execute(
                "UPDATE flare_runs SET cancel_requested = 1 WHERE id = ?1",
                params![id],
            )?;
            Ok(n > 0)
        })
    }

    /// Whether anyone has asked this run to stop.
    pub fn flare_cancel_requested(&self, id: &str) -> Result<bool> {
        self.with_db(|db| {
            let mut stmt = db
                .conn
                .prepare("SELECT cancel_requested FROM flare_runs WHERE id = ?1")?;
            let mut rows = stmt.query(params![id])?;
            match rows.next()? {
                Some(r) => Ok(r.get::<_, i64>(0)? != 0),
                None => Ok(false),
            }
        })
    }

    /// The runs, newest first — what `flares list` and the dashboard read.
    pub fn flare_runs(&self, limit: usize) -> Result<Vec<FlareRunRow>> {
        let limit = limit.clamp(1, 200) as i64;
        self.with_db(|db| {
            let mut stmt = db.conn.prepare(
                "SELECT id, task, state, routes, jobs, parent, started_ms, finished_ms,
                        prompt_tokens, completion_tokens, iterations
                   FROM flare_runs ORDER BY started_ms DESC LIMIT ?1",
            )?;
            let rows = stmt.query_map(params![limit], run_row)?;
            Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
        })
    }

    /// One run and its children, in the lead's order.
    pub fn flare_run(&self, id: &str) -> Result<Option<(FlareRunRow, Vec<FlareJobRow>)>> {
        self.with_db(|db| {
            let mut stmt = db.conn.prepare(
                "SELECT id, task, state, routes, jobs, parent, started_ms, finished_ms,
                        prompt_tokens, completion_tokens, iterations
                   FROM flare_runs WHERE id = ?1",
            )?;
            let mut rows = stmt.query(params![id])?;
            let Some(row) = rows.next()? else {
                return Ok(None);
            };
            let run = run_row(row)?;
            let mut stmt = db.conn.prepare(
                "SELECT n, route, session_id, state, prompt_tokens, completion_tokens,
                        iterations, why
                   FROM flare_jobs WHERE run_id = ?1 ORDER BY n",
            )?;
            let jobs = stmt
                .query_map(params![id], |r| {
                    Ok(FlareJobRow {
                        run_id: id.to_string(),
                        n: r.get::<_, i64>(0)? as usize,
                        route: r.get(1)?,
                        session_id: r.get(2)?,
                        state: r.get(3)?,
                        prompt_tokens: r.get::<_, Option<i64>>(4)?.map(|v| v as u64),
                        completion_tokens: r.get::<_, Option<i64>>(5)?.map(|v| v as u64),
                        iterations: r.get::<_, Option<i64>>(6)?.unwrap_or(0).max(0) as usize,
                        why: r.get(7)?,
                    })
                })?
                .collect::<std::result::Result<Vec<_>, _>>()?;
            Ok(Some((run, jobs)))
        })
    }

    /// The flares a run started, in the order the lead asked for them.
    ///
    /// A run that was cancelled part-way has fewer rows than jobs, and that is the honest answer:
    /// a flare that never started has no transcript to open.
    pub fn flares_of(&self, run: &str) -> Result<Vec<SessionInfo>> {
        let prefix = format!("{FLARE_ORIGIN}{run}:");
        let mut out: Vec<SessionInfo> = self
            .list_rows(true, true)?
            .into_iter()
            .filter(|s| s.origin.starts_with(&prefix))
            .collect();
        out.sort_by_key(|s| s.flare().map_or(0, |f| f.n));
        Ok(out)
    }

    /// The origin `POST /v1/chat/completions` writes: a headless call is a run, not a
    /// conversation, and it must not look like one in a listing or in `--continue`.
    pub const API_ORIGIN: &str = "api";

    /// Create the row for an API call, tagged, before it has a message.
    ///
    /// It has to happen *before* the run: `append` creates an untagged row when none exists, and a
    /// row that arrives as `native` can never be told apart from one a person typed. A row that
    /// already exists is left as it is.
    pub fn begin_api(&self, id: &str) -> Result<()> {
        self.begin_row(id, Self::API_ORIGIN)
    }

    /// Where a session came from, or `None` when there is no such row (`#509`).
    ///
    /// The send path asks this one question: a turn's agent is decided by the row's own `origin`,
    /// so a transcript opened by id is the bot's conversation too. One row rather than a listing —
    /// the dashboard answers a request per keystroke elsewhere and a full list here would be a
    /// scan to learn one string.
    pub fn origin(&self, id: &str) -> Result<Option<String>> {
        validate_id(id)?;
        self.with_db(|db| {
            let found = db
                .conn
                .query_row(
                    "SELECT origin FROM sessions WHERE id = ?1",
                    params![id],
                    |r| r.get::<_, String>(0),
                )
                .map(Some)
                .or_else(|e| match e {
                    rusqlite::Error::QueryReturnedNoRows => Ok(None),
                    other => Err(other),
                })?;
            Ok(found)
        })
    }

    /// Create the row for a bot's conversation, marked `bot:<name>`, before it has a message
    /// (`#509`).
    ///
    /// The row has to exist first for the same reason an API call's does: `append` creates an
    /// untagged row when none exists, and a bot's conversation that arrived as `native` would sit
    /// in the human's list for the rest of its life.
    pub fn begin_bot(&self, id: &str, name: &str) -> Result<()> {
        self.begin_row(id, &format!("{BOT_ORIGIN}{name}"))
    }

    /// The bot's live conversation, creating one when it has none (`#509`).
    ///
    /// One conversation is what "an identity" means: the Bots tab's open button and every later
    /// send land in the same transcript until it is cleared. A cleared one is archived, not
    /// deleted, so the next open starts a new row beside it and the count the tab shows still says
    /// it happened.
    pub fn bot_session(&self, name: &str) -> Result<String> {
        let origin = format!("{BOT_ORIGIN}{name}");
        for info in self.list_rows(true, true)? {
            if info.origin == origin && !info.archived {
                return Ok(info.id);
            }
        }
        let id = self.new_id();
        self.begin_bot(&id, name)?;
        Ok(id)
    }

    /// Every conversation `name` has that is still open, newest first: what clearing a bot
    /// archives (`#509`).
    pub fn bot_sessions(&self, name: &str) -> Result<Vec<String>> {
        let origin = format!("{BOT_ORIGIN}{name}");
        Ok(self
            .list_rows(true, true)?
            .into_iter()
            .filter(|info| info.origin == origin && !info.archived)
            .map(|info| info.id)
            .collect())
    }

    /// Create a session row carrying `origin`, before it has a message.
    fn begin_row(&self, id: &str, origin: &str) -> Result<()> {
        validate_id(id)?;
        let now = now_ms() as i64;
        self.with_db(|db| {
            db.conn.execute(
                "INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
                 VALUES (?1, ?2, ?2, NULL, NULL, 0, ?3)
                 ON CONFLICT(id) DO NOTHING",
                params![id, now, origin],
            )?;
            Ok(())
        })
    }

    /// Delete the API's own sessions older than `cutoff_ms` (unix milliseconds): the ones
    /// `/v1/chat/completions` leaves behind, and nothing else. Returns how many went.
    ///
    /// A script polling the API writes a session per call; without this they accumulate until the
    /// listing and the search degrade. Pinned sessions stay — a person who pinned one meant it —
    /// and so does every session a person started.
    pub fn prune_api_sessions(&self, cutoff_ms: u64) -> Result<usize> {
        let stale: Vec<String> = self
            .list()?
            .into_iter()
            .filter(|s| s.origin == Self::API_ORIGIN && !s.pinned && s.updated_ms < cutoff_ms)
            .map(|s| s.id)
            .collect();
        let mut pruned = 0usize;
        for id in stale {
            match self.delete(&id) {
                Ok(()) => pruned += 1,
                // Gone between the listing and the delete: a sweeper is not a place to care.
                Err(Error::Session(_)) => {}
                Err(e) => return Err(e),
            }
        }
        Ok(pruned)
    }

    /// Load all records in order. A row whose stored body cannot be parsed is an error
    /// naming the session and the record, because silently dropping a message would make
    /// the transcript lie.
    pub fn load_records(&self, id: &str) -> Result<Vec<Record>> {
        validate_id(id)?;
        // An unknown id is an error rather than an empty transcript: "there is nothing
        // here" and "this session does not exist" are different answers, and the second
        // one is what a mistyped id deserves.
        if !self.exists(id) {
            return Err(Error::Session(format!("no such session {id:?}")));
        }
        self.with_db(|db| {
            let mut stmt = db.conn.prepare(
                "SELECT seq, at_ms, body FROM messages WHERE session_id = ?1 ORDER BY seq",
            )?;
            let rows = stmt.query_map(params![id], |r| {
                Ok((
                    r.get::<_, i64>(0)?,
                    r.get::<_, i64>(1)?,
                    r.get::<_, String>(2)?,
                ))
            })?;
            let mut out = Vec::new();
            for row in rows {
                let (seq, at, body) = row?;
                let mut message: Message = serde_json::from_str(&body)
                    .map_err(|e| Error::Session(format!("{id}:{seq}: {e}")))?;
                // The row number travels with the message: a compiled handoff cites `[#N]`, and
                // a ref that cannot be resolved to a row is a dead end dressed up as a citation.
                message.seq = Some(seq.max(0) as u64);
                out.push(Record {
                    ts: at.max(0) as u64,
                    message,
                });
            }
            Ok(out)
        })
    }

    #[allow(clippy::unnecessary_wraps)] // kept symmetric with load_records' Result
    pub fn load(&self, id: &str) -> Result<Vec<Message>> {
        Ok(self
            .load_records(id)?
            .into_iter()
            .map(|r| r.message)
            .collect())
    }

    /// The name set with `rename`, if any.
    pub fn title(&self, id: &str) -> Result<Option<String>> {
        validate_id(id)?;
        self.with_db(|db| {
            let title: Option<Option<String>> = db
                .conn
                .query_row(
                    "SELECT title FROM sessions WHERE id = ?1",
                    params![id],
                    |r| r.get(0),
                )
                .optional()?;
            Ok(title.flatten())
        })
    }

    /// Give an existing session a title (trimmed; 1-200 characters, no control
    /// characters). The transcript is left untouched.
    ///
    /// A human's title outranks anything the machine writes, so this is the one path that sets
    /// [`TitleSource::User`] — and a later [`set_title`](Self::set_title) from the naming pass
    /// cannot take it back.
    pub fn rename(&self, id: &str, title: &str) -> Result<()> {
        validate_id(id)?;
        let title = title.trim();
        if title.is_empty() {
            return Err(Error::Session("title is empty".into()));
        }
        if title.chars().count() > MAX_TITLE_CHARS {
            return Err(Error::Session(format!(
                "title is longer than {MAX_TITLE_CHARS} characters"
            )));
        }
        if title.chars().any(char::is_control) {
            return Err(Error::Session("title contains control characters".into()));
        }
        let landed = self.set_title(id, title, TitleSource::User)?;
        if !landed {
            return Err(Error::Session(format!("no such session {id:?}")));
        }
        Ok(())
    }

    /// Write a title written by the machine, unless a better-sourced one is already there.
    ///
    /// `derived < llm < user`, enforced here rather than by whoever calls: the naming pass runs in
    /// a task of its own, so a rename landing between the read and the write is normal, and the
    /// database is the only place where "the user's name wins" can be a fact instead of a hope.
    /// Returns whether the row changed.
    pub fn set_title(&self, id: &str, title: &str, source: TitleSource) -> Result<bool> {
        validate_id(id)?;
        self.with_db(|db| {
            let n = db.conn.execute(
                // `derived < llm < user`, spelled out rather than looked up: a CASE here is one
                // statement with the rule inside it, where a helper function would be a second
                // place for the ranking to live.
                "UPDATE sessions SET title = ?2, title_source = ?3, title_note = NULL
                  WHERE id = ?1
                    AND (CASE title_source WHEN 'user' THEN 3 WHEN 'llm' THEN 2
                                           WHEN 'derived' THEN 1 ELSE 0 END)
                      < (CASE ?3 WHEN 'user' THEN 3 WHEN 'llm' THEN 2
                                 WHEN 'derived' THEN 1 ELSE 0 END)",
                params![id, title, source.as_str()],
            )?;
            Ok(n > 0)
        })
    }

    /// [`set_title`](Self::set_title) for a session found by id, only if nothing names it yet.
    ///
    /// This is stage one: it runs on the turn's own path, costs nothing, and cannot fail. A title
    /// that already exists is left alone whatever wrote it, so an imported or renamed session is
    /// never relabelled by the machine.
    pub fn title_if_unnamed(&self, id: &str, name: &str) -> Result<bool> {
        validate_id(id)?;
        let name = name.trim();
        if name.is_empty() || name.chars().any(char::is_control) {
            return Ok(false);
        }
        self.with_db(|db| {
            let n = db.conn.execute(
                "UPDATE sessions SET title = ?2, title_source = 'derived'
                  WHERE id = ?1 AND title IS NULL",
                params![id, name],
            )?;
            Ok(n > 0)
        })
    }

    /// Take the one naming attempt this session is allowed, or `None` when it has had it.
    ///
    /// The claim is a single `UPDATE`, so two processes racing on the same fresh session cannot
    /// both decide to spend a call — one gets the row, the other gets nothing.
    ///
    /// Two kinds of session are never claimed. A child of `delegate` has a name nobody reads
    /// outside the parent's list, and an `api` session is a headless call: naming one would put a
    /// second request on every programmatic turn, which is exactly the cost the cheap route exists
    /// to avoid. Both still get the derived name, which is free.
    ///
    /// Returns whether this caller owns the one call.
    pub fn claim_title_upgrade(&self, id: &str) -> Result<bool> {
        validate_id(id)?;
        self.with_db(|db| {
            let n = db.conn.execute(
                "UPDATE sessions SET title_note = 'trying'
                  WHERE id = ?1 AND title_source = 'derived' AND title_note IS NULL
                    AND origin NOT LIKE 'subagent:%' AND origin NOT LIKE 'bot:%'
                    AND origin NOT LIKE 'flare:%' AND origin <> 'api'",
                params![id],
            )?;
            Ok(n > 0)
        })
    }

    /// Record why the naming attempt did not land. The derived title stays, and the note is what
    /// stops a second call: the failure is remembered rather than retried on every resume.
    pub fn title_attempt_failed(&self, id: &str, why: &str) -> Result<()> {
        validate_id(id)?;
        let why: String = why.chars().take(300).collect();
        self.with_db(|db| {
            db.conn.execute(
                "UPDATE sessions SET title_note = ?2 WHERE id = ?1",
                params![id, why],
            )?;
            Ok(())
        })
    }

    /// Give up the claim without recording a failure: nothing was tried, so the session is still
    /// eligible if a later run is configured to name it.
    pub fn release_title_claim(&self, id: &str) -> Result<()> {
        validate_id(id)?;
        self.with_db(|db| {
            db.conn.execute(
                "UPDATE sessions SET title_note = NULL WHERE id = ?1 AND title_note = 'trying'",
                params![id],
            )?;
            Ok(())
        })
    }

    /// Record what a turn cost, as one JSON snapshot beside the session (#344).
    ///
    /// `updated_ms` is deliberately untouched: this is bookkeeping about a turn, not activity in
    /// the session, and a write that reordered the list would make a session nobody is talking to
    /// jump to the top of `Today`.
    ///
    /// A write against a session that no longer exists is not an error. The turn had already
    /// happened; the record goes with the transcript it describes, and a run whose session was
    /// deleted mid-flight must not fail over its own bookkeeping.
    pub fn set_last_cost(&self, id: &str, cost: &TurnCost) -> Result<()> {
        validate_id(id)?;
        let body = serde_json::to_string(cost)
            .map_err(|e| Error::Session(format!("a turn's cost did not encode: {e}")))?;
        self.with_db(|db| {
            db.conn.execute(
                "UPDATE sessions SET last_cost = ?2 WHERE id = ?1",
                params![id, body],
            )?;
            Ok(())
        })
    }

    /// Record what a model that can see said about one picture on a stored message (`#346`).
    ///
    /// Written once, on the turn that attached the picture, and read back by every later request.
    /// Without it a session that once attached a screenshot pays for the same description on every
    /// turn afterwards, and the prompt for a past turn changes under the conversation that is still
    /// talking about it — two ways to be wrong, both silent.
    /// Returns whether a stored picture was actually changed. `false` is not an error: the message
    /// or the picture is gone, and the description was for a turn that already happened — but the
    /// caller can now tell a write from a no-op, which it could not when this returned `()`.
    pub fn set_image_seen(&self, id: &str, seq: u64, index: usize, text: &str) -> Result<bool> {
        validate_id(id)?;
        let seq = i64::try_from(seq)
            .map_err(|_| Error::Session(format!("sequence {seq} is out of range")))?;
        self.with_db(|db| {
            // One transaction, because the body and the index are one decision: a crash between
            // them left a search hit whose content no longer matched the message it names.
            let tx = db.conn.unchecked_transaction()?;
            let row: Option<String> = tx
                .query_row(
                    "SELECT body FROM messages WHERE session_id = ?1 AND seq = ?2",
                    params![id, seq],
                    |r| r.get(0),
                )
                .optional()?;
            let Some(body) = row else {
                return Ok(false);
            };
            let mut message: crate::message::Message = serde_json::from_str(&body)
                .map_err(|e| Error::Session(format!("a stored message did not decode: {e}")))?;
            let Some(image) = message.images.get_mut(index) else {
                return Ok(false);
            };
            image.seen = Some(text.to_string());
            let encoded = serde_json::to_string(&message)
                .map_err(|e| Error::Session(format!("a message did not encode: {e}")))?;
            let n = tx.execute(
                "UPDATE messages SET body = ?3 WHERE session_id = ?1 AND seq = ?2",
                params![id, seq, encoded],
            )?;
            // Guarded like every other FTS write: on a build without FTS5 the virtual table does
            // not exist, and this used to fail *after* the body had been written.
            if db.fts {
                tx.execute(
                    "UPDATE messages_fts SET content = ?3 WHERE session_id = ?1 AND seq = ?2",
                    params![id, seq, searchable(&message)],
                )?;
            }
            tx.commit()?;
            Ok(n > 0)
        })
    }

    /// The last turn's numbers for one session, or `None` — never having run and having lost the
    /// record are the same answer here, because both mean "there is nothing honest to show".
    pub fn last_cost(&self, id: &str) -> Result<Option<TurnCost>> {
        validate_id(id)?;
        self.with_db(|db| {
            let body: Option<String> = db
                .conn
                .query_row(
                    "SELECT last_cost FROM sessions WHERE id = ?1",
                    params![id],
                    |r| r.get(0),
                )
                .optional()?
                .flatten();
            Ok(body.and_then(|s| serde_json::from_str::<TurnCost>(&s).ok()))
        })
    }

    /// Pin or unpin a session: a pinned one sorts first in every listing and no retention
    /// policy deletes it. The transcript is left untouched.
    pub fn set_pinned(&self, id: &str, pinned: bool) -> Result<()> {
        validate_id(id)?;
        self.with_db(|db| {
            let n = db.conn.execute(
                "UPDATE sessions SET pinned = ?2 WHERE id = ?1",
                params![id, i64::from(pinned)],
            )?;
            if n == 0 {
                return Err(Error::Session(format!("no such session {id:?}")));
            }
            Ok(())
        })
    }

    /// Archive or unarchive a session: an archived one is out of [`list`](Self::list) and out
    /// of every retention policy, and keeps its messages, its title and its place in
    /// [`search`](Self::search).
    ///
    /// The same shape as [`set_pinned`](Self::set_pinned) on purpose — one column, one
    /// `UPDATE`, and one function both surfaces call — so `archived` cannot be a thing the CLI
    /// knows and the dashboard guesses at.
    pub fn set_archived(&self, id: &str, archived: bool) -> Result<()> {
        validate_id(id)?;
        self.with_db(|db| {
            let n = db.conn.execute(
                "UPDATE sessions SET archived = ?2 WHERE id = ?1",
                params![id, i64::from(archived)],
            )?;
            if n == 0 {
                return Err(Error::Session(format!("no such session {id:?}")));
            }
            Ok(())
        })
    }

    /// The session's stored memory. `Ok(None)` if there is none; an error if the row is
    /// unreadable, too large or not valid JSON of the expected shape. The content is not
    /// validated here: see [`Memory::validate`] and [`usable_memory`](Self::usable_memory).
    pub fn memory(&self, id: &str) -> Result<Option<Memory>> {
        validate_id(id)?;
        self.with_db(|db| {
            let body: Option<String> = db
                .conn
                .query_row(
                    "SELECT body FROM memory WHERE session_id = ?1",
                    params![id],
                    |r| r.get(0),
                )
                .optional()?;
            let Some(body) = body else { return Ok(None) };
            if body.len() as u64 > MAX_MEMORY_FILE_BYTES {
                return Err(Error::Session(format!(
                    "{id}: memory is larger than {MAX_MEMORY_FILE_BYTES} bytes"
                )));
            }
            serde_json::from_str(&body)
                .map(Some)
                .map_err(|e| Error::Session(format!("{id}: memory: {e}")))
        })
    }

    /// The stored memory if it passes [`Memory::validate`]: a missing, unreadable, corrupt or
    /// invalid row is treated as no memory.
    pub fn readable_memory(&self, id: &str) -> Option<Memory> {
        self.memory(id)
            .ok()
            .flatten()
            .filter(|m| m.validate().is_ok())
    }

    /// Store the compiled handoff for `covered`, replacing whatever the record held.
    ///
    /// An existing memory that does *not* validate is replaced rather than preserved — a
    /// malformed record is not a fact worth defending, and refusing to save would leave the
    /// session with no handoff at all.
    pub fn save_handoff(
        &self,
        id: &str,
        covered: crate::context::Trimmed,
        span: (Option<u64>, Option<u64>),
        text: &str,
        judgement: Option<Judgement>,
    ) -> Result<()> {
        validate_id(id)?;
        let mut memory = self.current(id);
        memory.handoff = Some(Handoff {
            text: text.to_string(),
            version: crate::compact::VERSION.to_string(),
            covered_turns: covered.turns,
            covered_messages: covered.messages,
            covered_from: span.0,
            covered_to: span.1,
            generated_at_ms: now_ms(),
            judgement,
        });
        self.save_memory(id, &memory)
    }

    /// The current memory as the starting point for writing: the stored record when this build
    /// can read it, else a blank record of this build's schema. A record this build cannot read is
    /// replaced rather than preserved — it is not a fact worth defending, and refusing to write
    /// would leave the session with no memory at all.
    fn current(&self, id: &str) -> Memory {
        let mut memory = self.readable_memory(id).unwrap_or(Memory {
            version: MEMORY_VERSION,
            handoff: None,
        });
        // Writing makes this a record of *this* build's schema, so a v1 file that gains a handoff
        // is stamped v3 and an old summary field is left behind, unread.
        memory.version = MEMORY_VERSION;
        memory
    }

    /// Store `memory` for an existing session, replacing any earlier one. The transcript is
    /// never touched. Invalid memory is refused.
    ///
    /// Most callers want [`save_handoff`](Self::save_handoff), which builds the record around the
    /// document being stored; this is the raw setter.
    pub fn save_memory(&self, id: &str, memory: &Memory) -> Result<()> {
        validate_id(id)?;
        memory.validate().map_err(Error::Session)?;
        if !self.exists(id) {
            return Err(Error::Session(format!("no such session {id:?}")));
        }
        let body = serde_json::to_string(memory).map_err(|e| Error::Session(e.to_string()))?;
        // The reader refuses a body over the cap, and `readable_memory` turns that error into "no
        // memory" — so a record written past it is unreadable for the life of the session, and
        // every later `memory()` call errors while the agent silently recompiles on each request.
        // The store may not write what it cannot read back.
        if body.len() as u64 > MAX_MEMORY_FILE_BYTES {
            return Err(Error::Session(format!(
                "{id}: memory would be {} bytes, over the {MAX_MEMORY_FILE_BYTES}-byte record \
                 limit; store less, or raise `MAX_MEMORY_FILE_BYTES` in both the writer and the \
                 reader",
                body.len()
            )));
        }
        self.with_db(|db| {
            db.conn.execute(
                "INSERT INTO memory (session_id, body) VALUES (?1, ?2)
                 ON CONFLICT(session_id) DO UPDATE SET body = ?2",
                params![id, body],
            )?;
            Ok(())
        })
    }

    /// Remove a session's transcript, title and memory. Errors if it does not exist.
    pub fn delete(&self, id: &str) -> Result<()> {
        validate_id(id)?;
        self.with_db(|db| {
            // One transaction, because the two statements are one decision. `messages` rows go with
            // the session by `ON DELETE CASCADE`, but `messages_fts` is a separate virtual table
            // with no foreign key to lean on: a crash between the two deletes used to leave index
            // rows pointing at messages that no longer existed, and every later `search()` then
            // failed on the first one instead of answering.
            let tx = db.conn.unchecked_transaction()?;
            let n = tx.execute("DELETE FROM sessions WHERE id = ?1", params![id])?;
            if n == 0 {
                // The transaction is dropped, which rolls it back: nothing was deleted, so there is
                // nothing to commit.
                return Err(Error::Session(format!("no such session {id:?}")));
            }
            if db.fts {
                tx.execute(
                    "DELETE FROM messages_fts WHERE session_id = ?1",
                    params![id],
                )?;
            }
            tx.commit()?;
            Ok(())
        })?;
        // The lock file is not in the database, and a stale one would keep naming a
        // session that no longer exists.
        //
        // The legacy files are removed as well, and not for tidiness: the importer adds any
        // `<id>.jsonl` it does not already know, so leaving one behind would resurrect a
        // session the user deleted the next time the store opened.
        for path in [
            self.lock_path(id)?,
            self.dir.join(format!("{id}.jsonl")),
            self.dir.join(format!("{id}.meta.json")),
            self.dir.join(format!("{id}.memory.json")),
        ] {
            match std::fs::remove_file(&path) {
                Ok(()) => {}
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
                Err(e) => return Err(Error::io(&path, e)),
            }
        }
        Ok(())
    }

    /// What a retention policy would delete: sessions whose last activity is older than
    /// `keep_days` days, plus all but the newest `keep_count`. A limit of 0 is disabled; both 0
    /// selects nothing. Nothing is deleted here.
    ///
    /// Last activity is the newest record's timestamp. A session imported from a legacy
    /// file with no readable records keeps that file's modification time, so a corrupt old
    /// transcript can still be pruned.
    ///
    /// **A pinned session is never a candidate**, whatever the limits say, and the plan counts
    /// how many that kept out of reach so the caller can say so. A pinned session still holds
    /// its place in the ranking: the policy keeps N sessions, and a pinned one among them is
    /// still one of the N — the same accounting [`auto_prune`](Self::auto_prune)'s `protect` has
    /// always used.
    ///
    /// **An archived session is not a candidate either**, unless `include_archived` says so
    /// (`#240`): archiving is how a finished conversation stops taking a row, and a prune that
    /// quietly deleted the thing a person filed away would be a worse version of the delete it
    /// was chosen over. It keeps its place in the ranking too, like a pin, and is counted in
    /// [`PrunePlan::archived_kept`] so the caller can name the flag that would have taken it.
    pub fn prune_candidates(
        &self,
        keep_days: u64,
        keep_count: usize,
        now_ms: u64,
        include_archived: bool,
    ) -> Result<PrunePlan> {
        if keep_days == 0 && keep_count == 0 {
            return Ok(PrunePlan::default());
        }
        let mut sessions = self.session_ages()?;
        sessions.sort_by(|a, b| b.cmp(a));
        let cutoff = now_ms.saturating_sub(keep_days.saturating_mul(86_400_000));
        let mut plan = PrunePlan::default();
        for (i, (last, id, pinned, archived)) in sessions.into_iter().enumerate() {
            let over = (keep_count > 0 && i >= keep_count) || (keep_days > 0 && last < cutoff);
            if !over {
                continue;
            }
            if pinned {
                plan.pinned_kept += 1;
            } else if archived && !include_archived {
                plan.archived_kept += 1;
            } else {
                plan.candidates.push(id);
            }
        }
        Ok(plan)
    }

    /// `(updated_ms, id, pinned, archived)` for every session, oldest first.
    fn session_ages(&self) -> Result<Vec<(u64, String, bool, bool)>> {
        self.with_db(|db| {
            let mut stmt = db.conn.prepare(
                "SELECT updated_ms, id, pinned, archived FROM sessions ORDER BY updated_ms",
            )?;
            let rows = stmt.query_map([], |r| {
                let ms: i64 = r.get(0)?;
                let id: String = r.get(1)?;
                let pinned: i64 = r.get(2)?;
                let archived: i64 = r.get(3)?;
                Ok((ms.max(0) as u64, id, pinned != 0, archived != 0))
            })?;
            Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
        })
    }

    /// Apply a retention policy unattended, as `[sessions] auto_prune` does at CLI startup.
    /// Mirrors the manual `--force` rule: it deletes only when the policy would remove at
    /// most [`PRUNE_CONFIRM_ABOVE`] sessions, otherwise it deletes nothing and reports
    /// how many it would have removed. With both limits 0 it never deletes. `protect`
    /// (the session about to be resumed) is never deleted, even if it is old.
    ///
    /// An archived session is never deleted here: a policy that runs with nobody watching has
    /// no way to be given `--archived`, so the flag that would allow it is not one this path
    /// can take.
    pub fn auto_prune(
        &self,
        keep_days: u64,
        keep_count: usize,
        now_ms: u64,
        protect: Option<&str>,
    ) -> Result<AutoPrune> {
        if keep_days == 0 && keep_count == 0 {
            return Ok(AutoPrune::NoLimits);
        }
        let plan = self.prune_candidates(keep_days, keep_count, now_ms, false)?;
        let doomed: Vec<String> = plan
            .candidates
            .into_iter()
            .filter(|id| Some(id.as_str()) != protect)
            .collect();
        if doomed.is_empty() {
            return Ok(AutoPrune::Nothing);
        }
        if doomed.len() > PRUNE_CONFIRM_ABOVE {
            return Ok(AutoPrune::Skipped {
                would_remove: doomed.len(),
            });
        }
        let mut removed = 0;
        let mut failed = 0;
        for id in &doomed {
            match self.delete(id) {
                Ok(()) => removed += 1,
                Err(_) => failed += 1,
            }
        }
        Ok(AutoPrune::Pruned {
            removed,
            failed,
            pinned_kept: plan.pinned_kept,
        })
    }

    /// The full stored transcript: every request/response turn and tool call, in order.
    /// The system prompt is not stored in sessions, so it is not included.
    pub fn export(&self, id: &str, format: ExportFormat) -> Result<String> {
        let records = self.load_records(id)?;
        let title = self.title(id).ok().flatten();
        match format {
            ExportFormat::Json => export_json(id, title, &records),
            ExportFormat::Markdown => Ok(export_markdown(id, title.as_deref(), &records)),
        }
    }

    /// Sessions sorted newest first, pinned ones first of all — the list a person reads.
    ///
    /// Every surface lists through this method — `sessions list`, the `/resume` picker and the
    /// dashboard — so pinning is one ordering rule in one place rather than three.
    ///
    /// An **archived** session is not here, and that is the whole of what archiving means
    /// (`#240`): it keeps its messages, [`search`](Self::search) still finds it and
    /// [`list_with_archived`](Self::list_with_archived) still names it, so the one query that
    /// has to know about the flag is this one.
    pub fn list(&self) -> Result<Vec<SessionInfo>> {
        self.list_rows(false, false)
    }

    /// Every session, archived ones included and marked, in the same order.
    ///
    /// For the places that have to *show* an archived row: `sessions list --archived`, the
    /// dashboard's filter, and the name lookups behind `search` and the recall block — a hit in
    /// an archived session is still a hit, and a session named by an id with no title beside it
    /// reads as a session that was deleted.
    pub fn list_with_archived(&self) -> Result<Vec<SessionInfo>> {
        self.list_rows(true, false)
    }

    /// The bot conversations the Bots tab lists (`#509`), newest activity first.
    ///
    /// One query, the same one the human's list reads — a bot's sessions are *in* that list and
    /// filtered out of it, never a second table and never a second ordering rule. A bot's own
    /// row is what the tab groups: the newest conversation, when it last spoke, how much is in it.
    pub fn list_bots(&self) -> Result<Vec<BotSessions>> {
        let mut out: Vec<BotSessions> = Vec::new();
        for info in self.list_rows(true, true)? {
            let Some(name) = info.bot() else { continue };
            match out.iter_mut().find(|b| b.name == name) {
                // The listing is newest first, so the first row for a bot is its live one.
                Some(bot) => {
                    bot.sessions += 1;
                    if !info.archived {
                        bot.archived = false;
                    }
                }
                None => out.push(BotSessions {
                    name: name.to_string(),
                    sessions: 1,
                    messages: info.messages,
                    last_session: info.id.clone(),
                    last_activity_ms: info.updated_ms,
                    archived: info.archived,
                }),
            }
        }
        Ok(out)
    }

    /// One query, one `WHERE`, so the two listings cannot disagree about ordering.
    ///
    /// `include_bots = false` is the human's list (`#509`): a bot's conversation is a session, but
    /// it is not one a person wrote, and a bot answering on a lane would otherwise push every
    /// conversation of theirs down the sidebar. The Bots tab is where it shows, through
    /// [`list_bots`](Self::list_bots), and the search that can reach it says so.
    fn list_rows(&self, include_archived: bool, include_bots: bool) -> Result<Vec<SessionInfo>> {
        self.with_db(|db| {
            // `rowid DESC` is the tiebreak, not `id DESC`: two rows written in the same
            // millisecond tie on `updated_ms`, and an id is text — `…-9` sorts above `…-10`
            // lexically, which named a cleared bot conversation newer than the one opened after
            // it (`#531`). `rowid` is the order the rows were stored in, so a tie is broken by
            // which conversation is actually the later one.
            let mut stmt = db.conn.prepare(
                "SELECT id, title, preview, messages, updated_ms, origin, pinned, archived, last_cost
                   FROM sessions
                  WHERE (archived = 0 OR ?1) AND (?2 OR origin NOT LIKE 'bot:%')
                  ORDER BY pinned DESC, updated_ms DESC, rowid DESC",
            )?;
            let rows = stmt.query_map(
                params![i64::from(include_archived), i64::from(include_bots)],
                |r| {
                let updated: i64 = r.get(4)?;
                let messages: i64 = r.get(3)?;
                let pinned: i64 = r.get(6)?;
                let archived: i64 = r.get(7)?;
                let cost: Option<String> = r.get(8)?;
                Ok(SessionInfo {
                    id: r.get(0)?,
                    title: r.get(1)?,
                    preview: r.get::<_, Option<String>>(2)?.unwrap_or_default(),
                    messages: messages.max(0) as usize,
                    updated_ms: updated.max(0) as u64,
                    origin: r.get(5)?,
                    pinned: pinned != 0,
                    archived: archived != 0,
                    // A blob that will not parse reads as absent: the row then shows `--` rather
                    // than a number nobody can vouch for.
                    cost: cost.and_then(|s| serde_json::from_str::<TurnCost>(&s).ok()),
                })
            })?;
            Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
        })
    }

    /// Full-text search over the stored messages, newest first.
    ///
    /// Uses SQLite's FTS5 when the bundled library has it and `LIKE` when it does not — both are
    /// behind this one method, so callers never branch on it, and **both answer in the same order**:
    /// newest message first, ties broken by position. Which backend runs depends on how SQLite was
    /// compiled, and two installs must not disagree about what "the first 20 hits" means. FTS5
    /// matches on word boundaries, `LIKE` matches substrings; that difference is the price of the
    /// fallback, and it is one a searcher can see, unlike an arbitrary result order.
    pub fn search(&self, query: &str, limit: usize) -> Result<Vec<SearchHit>> {
        self.search_with(query, limit, false)
    }

    /// [`search`](Self::search), with child conversations in the answer when `include_children`.
    ///
    /// The human's discovery results leave bots and flares out (`#509`, `#171`): a bot answering
    /// on a lane, or a flare reading a crate, writes to
    /// the same archive, and "search my transcripts" that returned someone else's conversation —
    /// one the searcher never had — would be a search that lies about who said it. The agent's
    /// `session_search` exposes the flag; nothing else has a reason to.
    pub fn search_with(
        &self,
        query: &str,
        limit: usize,
        include_children: bool,
    ) -> Result<Vec<SearchHit>> {
        let q = query.trim();
        if q.is_empty() {
            return Ok(Vec::new());
        }
        let limit = limit.clamp(1, 1000) as i64;
        self.with_db(|db| Self::search_in(db, q, limit, db.fts, include_children))
    }

    /// Search one backend's way.
    ///
    /// `use_fts = false` is the fallback a build without FTS5 takes. It is a parameter rather than
    /// a read of `db.fts` so the tests can hold the fallback to the same answers on a build that
    /// has FTS5 — the two must agree, because which one runs depends on how SQLite was compiled
    /// and nobody should get different results from two installs.
    fn search_in(
        db: &Db,
        q: &str,
        limit: i64,
        use_fts: bool,
        include_children: bool,
    ) -> Result<Vec<SearchHit>> {
        let children = i64::from(include_children);
        let mut out = Vec::new();
        // The names first, because "the session I called X" is the strongest thing a search box
        // can be told: a session named `gateway restart loop` should answer to those words even
        // if nothing in its transcript ever used them together. A name hit points at `seq` 0 —
        // the name was made from the opening message, so that is where to read from — and says
        // `title` in the role column rather than pretending to be a message.
        let mut named = db.conn.prepare(
            "SELECT id, title, updated_ms FROM sessions
              WHERE title LIKE '%' || ?1 || '%' ESCAPE '\\'
                AND (?3 = 1 OR (origin NOT LIKE 'bot:%' AND origin NOT LIKE 'flare:%'))
              ORDER BY pinned DESC, archived ASC, updated_ms DESC LIMIT ?2",
        )?;
        let rows = named.query_map(params![like_literal(q), limit, children], |r| {
            Ok((
                r.get::<_, String>(0)?,
                r.get::<_, String>(1)?,
                r.get::<_, i64>(2)?,
            ))
        })?;
        for row in rows {
            let (session_id, title, updated_ms) = row?;
            out.push(SearchHit {
                session_id,
                seq: 0,
                at_ms: updated_ms.max(0) as u64,
                role: "title".to_string(),
                snippet: title,
            });
        }

        // Own-tail rows are skipped, and a skipped row does not count toward `limit`, so the read
        // is wider than the answer. If even that page held nothing but the caller's own calls,
        // widen again rather than answer "no match" about a transcript that does match: the last
        // few searches must never be able to hide the archive (`#498`).
        let mut budget = limit.saturating_mul(4).max(limit + 8);
        loop {
            let (found, read) =
                Self::message_hits(db, q, limit, budget, use_fts, include_children)?;
            let room_to_widen = read >= budget && budget < OWN_TAIL_BUDGET_CAP;
            if !found.is_empty() || !room_to_widen {
                out.extend(found);
                break;
            }
            budget = (budget * 4).min(OWN_TAIL_BUDGET_CAP);
        }
        Ok(out)
    }

    /// Up to `limit` message hits, read out of `budget` matching rows, and how many rows were read
    /// — the caller widens the budget when a page turned out to hold nothing.
    ///
    /// `use_fts = false` is the fallback a build without FTS5 takes. It is a parameter rather than
    /// a read of `db.fts` so the tests can hold the fallback to the same answers on a build that
    /// has FTS5 — the two must agree, because which one runs depends on how SQLite was compiled
    /// and nobody should get different results from two installs.
    fn message_hits(
        db: &Db,
        q: &str,
        limit: i64,
        budget: i64,
        use_fts: bool,
        include_children: bool,
    ) -> Result<(Vec<SearchHit>, i64)> {
        let children = i64::from(include_children);
        let mut found = Vec::new();
        let mut read = 0i64;
        if use_fts {
            // Every term quoted: a search box is not a place to raise a syntax error,
            // and doubled quotes are how FTS5 escapes one.
            let terms: Vec<String> = q
                .split_whitespace()
                .map(|t| format!("\"{}\"", t.replace('"', "\"\"")))
                .collect();
            let mut stmt = db.conn.prepare(
                // Joined back to `messages` for one reason: the ordering. FTS5 has no clock, and
                // without an ORDER BY it answers in rowid order, so `LIMIT` would cut an arbitrary
                // slice rather than the newest one. `sessions` rides along for the other reason a
                // row is joined: a bot's conversation is not the human's discovery (`#509`).
                "SELECT f.session_id, f.seq, f.content
                 FROM messages_fts f
                 JOIN messages m ON m.session_id = f.session_id AND m.seq = f.seq
                 JOIN sessions s ON s.id = f.session_id
                 WHERE f.messages_fts MATCH ?1
                   AND (?3 = 1 OR (s.origin NOT LIKE 'bot:%' AND s.origin NOT LIKE 'flare:%'))
                 ORDER BY m.at_ms DESC, m.seq DESC
                 LIMIT ?2",
            )?;
            let rows = stmt.query_map(params![terms.join(" "), budget, children], |r| {
                Ok((
                    r.get::<_, String>(0)?,
                    r.get::<_, i64>(1)?,
                    r.get::<_, String>(2)?,
                ))
            })?;
            for row in rows {
                let (session_id, seq, content) = row?;
                read += 1;
                if is_own_tail(&db.conn, &session_id, seq)? {
                    continue;
                }
                if let Some(found_hit) = hit(&db.conn, session_id, seq, &content)? {
                    found.push(found_hit);
                    if found.len() as i64 >= limit {
                        break;
                    }
                }
            }
        } else {
            // `ESCAPE '\'` and an escaped literal: `%` and `_` mean themselves in a search box, so
            // `100%` finds the text `100%` and not everything containing `100`.
            let mut stmt = db.conn.prepare(
                "SELECT m.session_id, m.seq, m.body FROM messages m
                 JOIN sessions s ON s.id = m.session_id
                 WHERE m.body LIKE '%' || ?1 || '%' ESCAPE '\\'
                   AND (?3 = 1 OR (s.origin NOT LIKE 'bot:%' AND s.origin NOT LIKE 'flare:%'))
                 ORDER BY m.at_ms DESC, m.seq DESC LIMIT ?2",
            )?;
            let rows = stmt.query_map(params![like_literal(q), budget, children], |r| {
                Ok((
                    r.get::<_, String>(0)?,
                    r.get::<_, i64>(1)?,
                    r.get::<_, String>(2)?,
                ))
            })?;
            for row in rows {
                let (session_id, seq, body) = row?;
                read += 1;
                let message: Message = serde_json::from_str(&body)
                    .map_err(|e| Error::Session(format!("{session_id}:{seq}: {e}")))?;
                if is_own_tail(&db.conn, &session_id, seq)? {
                    continue;
                }
                if let Some(found_hit) = hit(&db.conn, session_id, seq, &searchable(&message))? {
                    found.push(found_hit);
                    if found.len() as i64 >= limit {
                        break;
                    }
                }
            }
        }
        Ok((found, read))
    }

    /// Whether full-text search is available (the bundled library normally has it).
    pub fn has_fts(&self) -> bool {
        self.with_db(|db| Ok(db.fts)).unwrap_or(false)
    }
}

/// One search result: where the match is and enough text to recognise it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchHit {
    pub session_id: String,
    /// Position in the session, so the caller can load around it.
    pub seq: usize,
    pub at_ms: u64,
    pub role: String,
    /// The matching message's text, trimmed to a readable length around the match.
    pub snippet: String,
}

/// One hit, or `None` when the message it points at is gone.
///
/// The FTS index can name a row the `messages` table no longer holds — an index written by a build
/// whose delete was two statements, or a crash inside one. That is a stale index entry, not a
/// failure of the query, so it is dropped rather than turned into an error that would take every
/// other hit with it.
fn hit(
    conn: &Connection,
    session_id: String,
    seq: i64,
    content: &str,
) -> Result<Option<SearchHit>> {
    let found: Option<(i64, String)> = conn
        .query_row(
            "SELECT at_ms, role FROM messages WHERE session_id = ?1 AND seq = ?2",
            params![session_id, seq],
            |r| Ok((r.get(0)?, r.get(1)?)),
        )
        .map(Some)
        .or_else(|e| match e {
            rusqlite::Error::QueryReturnedNoRows => Ok(None),
            other => Err(other),
        })?;
    let Some((at_ms, role)) = found else {
        return Ok(None);
    };
    Ok(Some(SearchHit {
        session_id,
        seq: seq.max(0) as usize,
        at_ms: at_ms.max(0) as u64,
        role,
        snippet: snippet(content, 160),
    }))
}

/// The tool whose own calls are never a search result.
///
/// `session_search` searches the archive it is writing to, so every call it makes adds a row the
/// next call finds: the top hit is always the search that just ran, the result set grows, and the
/// model spends a turn re-reading its own tail instead of the answer (`#498`). A call to it, and
/// the answer to one, are the only rows a search drops.
const OWN_TAIL_TOOL: &str = "session_search";

/// How far back to look for the assistant row that made a tool call. A transcript's calls and
/// their answers are adjacent; anything further is another turn's call and cannot be this row's.
const OWN_TAIL_LOOKBACK: i64 = 20;

/// The most rows one search will read to get past the caller's own calls. A page of 512 matching
/// rows that is *all* own tail is not a search problem any more; the answer is "no match".
const OWN_TAIL_BUDGET_CAP: i64 = 512;

/// Whether the row at `(session_id, seq)` is a call to [`OWN_TAIL_TOOL`], or the answer to one.
///
/// Both shapes are dropped: the call row is the `assistant` message carrying the `tool_calls`, and
/// the answer is the `tool` message whose `tool_call_id` names that call. A row we cannot parse is
/// not ours — a search is not the place to fail on a body this build no longer understands.
fn is_own_tail(conn: &Connection, session_id: &str, seq: i64) -> Result<bool> {
    let body: Option<String> = conn
        .query_row(
            "SELECT body FROM messages WHERE session_id = ?1 AND seq = ?2",
            params![session_id, seq],
            |r| r.get(0),
        )
        .map(Some)
        .or_else(|e| match e {
            rusqlite::Error::QueryReturnedNoRows => Ok(None),
            other => Err(other),
        })?;
    let Some(body) = body else {
        return Ok(false);
    };
    let Ok(message) = serde_json::from_str::<Message>(&body) else {
        return Ok(false);
    };
    if message
        .tool_calls
        .iter()
        .any(|call| call.function.name == OWN_TAIL_TOOL)
    {
        return Ok(true);
    }
    let Some(answer_to) = message.tool_call_id.as_deref() else {
        return Ok(false);
    };
    let mut stmt = conn.prepare(
        "SELECT body FROM messages
          WHERE session_id = ?1 AND seq < ?2 AND role = 'assistant'
          ORDER BY seq DESC LIMIT ?3",
    )?;
    let rows = stmt.query_map(params![session_id, seq, OWN_TAIL_LOOKBACK], |r| {
        r.get::<_, String>(0)
    })?;
    for row in rows {
        let Ok(called) = serde_json::from_str::<Message>(&row?) else {
            continue;
        };
        if called
            .tool_calls
            .iter()
            .any(|call| call.id == answer_to && call.function.name == OWN_TAIL_TOOL)
        {
            return Ok(true);
        }
    }
    Ok(false)
}

/// A search string as a `LIKE` literal: `\`, `%` and `_` mean themselves in a search box, and the
/// query's `ESCAPE '\'` is what keeps them from being wildcards.
fn like_literal(q: &str) -> String {
    let mut out = String::with_capacity(q.len());
    for c in q.chars() {
        if matches!(c, '\\' | '%' | '_') {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

/// The text a message contributes to search: its content plus any tool call arguments,
/// so `git_status`-style calls are findable by what they did.
fn searchable(message: &Message) -> String {
    // The picture's label and any description of it are part of what the session says, so a search
    // can find the turn by what was in the screenshot (`#362`).
    let mut out = message.text_with_pictures();
    for call in &message.tool_calls {
        if !out.is_empty() {
            out.push('\n');
        }
        out.push_str(&call.function.name);
        out.push(' ');
        out.push_str(&call.function.arguments);
    }
    out
}

/// The columns [`SessionStore::flare_runs`] and [`SessionStore::flare_run`] both read, in the one
/// order they are selected: six columns, then the cost, in the same shape a session's row has.
fn run_row(r: &rusqlite::Row<'_>) -> rusqlite::Result<FlareRunRow> {
    let started: i64 = r.get(6)?;
    Ok(FlareRunRow {
        id: r.get(0)?,
        task: r.get(1)?,
        state: r.get(2)?,
        routes: r
            .get::<_, String>(3)?
            .split(',')
            .filter(|s| !s.is_empty())
            .map(str::to_string)
            .collect(),
        jobs: r.get::<_, i64>(4)?.max(0) as usize,
        parent: r.get(5)?,
        started_ms: started.max(0) as u64,
        finished_ms: r.get::<_, Option<i64>>(7)?.map(|v| v.max(0) as u64),
        prompt_tokens: r.get::<_, Option<i64>>(8)?.map(|v| v as u64),
        completion_tokens: r.get::<_, Option<i64>>(9)?.map(|v| v as u64),
        iterations: r.get::<_, Option<i64>>(10)?.unwrap_or(0).max(0) as usize,
    })
}

fn snippet(text: &str, max: usize) -> String {
    let one: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
    if one.chars().count() <= max {
        return one;
    }
    one.chars().take(max.saturating_sub(1)).collect::<String>() + "…"
}

fn role_name(role: Role) -> &'static str {
    match role {
        Role::System => "system",
        Role::User => "user",
        Role::Assistant => "assistant",
        Role::Tool => "tool",
    }
}

/// The open database plus what it turned out to support.
///
/// Crate-visible so tests can act on the connection (forcing a write failure); nothing
/// outside this module uses it for anything else.
pub(crate) struct Db {
    pub(crate) conn: Connection,
    /// FTS5 is compiled in and the table exists; otherwise [`SessionStore::search`] falls
    /// back to `LIKE`.
    fts: bool,
}

impl Db {
    fn open(dir: &Path) -> Result<Self> {
        std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
        // Owner-only before the database exists. `-wal` and `-shm` are created by SQLite beside
        // the file with `0666 & ~umask`, and are never chmodded by it: a `0600` `sessions.db` in
        // a `0775` directory is a transcript everybody on the host can read, and the sidecar holds
        // every turn not yet checkpointed. The mode is applied on open as well as on create,
        // because a directory made by an older build (or by hand) is still `0775` now.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
        }
        let path = dir.join(DB_FILE);
        let conn = Connection::open(&path).map_err(db_err(&path))?;
        // WAL: a reader (the dashboard, a `sessions list`) never blocks the CLI's writes.
        let _: String = conn
            .query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0))
            .map_err(db_err(&path))?;
        conn.execute_batch(
            "PRAGMA foreign_keys = ON;
             PRAGMA synchronous = NORMAL;
             PRAGMA busy_timeout = 5000;",
        )
        .map_err(db_err(&path))?;
        conn.execute_batch(SCHEMA).map_err(db_err(&path))?;
        // The sidecars exist once there has been a write, so this runs after the schema. The
        // directory already keeps them private; this is what keeps them private wherever the
        // files are copied to.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            for f in [
                path.clone(),
                path.with_extension("db-wal"),
                path.with_extension("db-shm"),
            ] {
                if f.exists() {
                    let _ = std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o600));
                }
            }
        }
        // `CREATE TABLE IF NOT EXISTS` does nothing to a table that already exists, so every
        // column added after the first release needs its own step here. Without it an older
        // `sessions.db` keeps opening and simply has no `pinned`, which shows up much later as
        // "no such column" on someone's real state directory.
        if !has_column(&conn, "sessions", "pinned").map_err(db_err(&path))? {
            conn.execute_batch("ALTER TABLE sessions ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0")
                .map_err(db_err(&path))?;
        }
        // `#240`: an archive flag. The `DEFAULT 0` is the whole migration — every session that
        // existed before this column was in the list, and stays there.
        if !has_column(&conn, "sessions", "archived").map_err(db_err(&path))? {
            conn.execute_batch(
                "ALTER TABLE sessions ADD COLUMN archived INTEGER NOT NULL DEFAULT 0",
            )
            .map_err(db_err(&path))?;
        }
        // `#344`: the last turn's numbers, as one JSON snapshot. Nullable on purpose — a session
        // that has never finished a turn has none, and "no record" must not look like a zero.
        // `#340`: who decided. `NULL` on a row written before the column existed is honest —
        // nobody recorded it — and `user` is what every answer through `eclipse approve` writes.
        if !has_column(&conn, "approvals", "by").map_err(db_err(&path))? {
            conn.execute_batch("ALTER TABLE approvals ADD COLUMN by TEXT")
                .map_err(db_err(&path))?;
        }
        if !has_column(&conn, "sessions", "last_cost").map_err(db_err(&path))? {
            conn.execute_batch("ALTER TABLE sessions ADD COLUMN last_cost TEXT")
                .map_err(db_err(&path))?;
        }
        // `title_source` says who wrote a title and `title_note` says what happened to the naming
        // attempt, which is also what stops a second one. Added as a pair: a database with one and
        // not the other would open and then fail on the first `NULL` it read.
        let title_source_added =
            !has_column(&conn, "sessions", "title_source").map_err(db_err(&path))?;
        if title_source_added {
            conn.execute_batch(
                "ALTER TABLE sessions ADD COLUMN title_source TEXT;
                 ALTER TABLE sessions ADD COLUMN title_note TEXT;",
            )
            .map_err(db_err(&path))?;
        } else if !has_column(&conn, "sessions", "title_note").map_err(db_err(&path))? {
            conn.execute_batch("ALTER TABLE sessions ADD COLUMN title_note TEXT")
                .map_err(db_err(&path))?;
        }
        if title_source_added {
            // Every title that exists before this column came into being was typed by a person:
            // `rename` was the only thing that wrote one. Saying so once, here, is what keeps the
            // naming pass from relabelling somebody's session as machine-named.
            conn.execute_batch("UPDATE sessions SET title_source = 'user' WHERE title IS NOT NULL")
                .map_err(db_err(&path))?;
        }

        let fts = match conn.execute_batch(FTS_SCHEMA) {
            Ok(()) => true,
            // A build without FTS5 is not an error: search falls back to LIKE.
            Err(_) => false,
        };

        let mut db = Self { conn, fts };
        let warnings = db.import_legacy(dir)?;
        for w in warnings {
            eprintln!("warning: {w}");
        }
        Ok(db)
    }

    /// Import every `<id>.jsonl` transcript that is not already in the database, once.
    ///
    /// The files are left exactly where they are: a database that turns out to be wrong
    /// must never be the reason someone's transcript is gone. Import is idempotent —
    /// a session id already present is skipped — so a deleted database re-imports cleanly.
    fn import_legacy(&mut self, dir: &Path) -> Result<Vec<String>> {
        let rd = match std::fs::read_dir(dir) {
            Ok(rd) => rd,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(e) => return Err(Error::io(dir, e)),
        };
        let mut files: Vec<PathBuf> = Vec::new();
        for entry in rd.flatten() {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) == Some("jsonl") {
                files.push(path);
            }
        }
        files.sort();
        let mut warnings = Vec::new();
        let tx = self.conn.transaction().map_err(db_err(dir))?;
        for path in files {
            let Some(id) = path.file_stem().and_then(|s| s.to_str()) else {
                continue;
            };
            if validate_id(id).is_err() {
                warnings.push(format!(
                    "{}: ignoring, not a valid session id",
                    path.display()
                ));
                continue;
            }
            let already: Option<i64> = tx
                .query_row("SELECT 1 FROM sessions WHERE id = ?1", params![id], |r| {
                    r.get(0)
                })
                .optional()
                .map_err(db_err(&path))?;
            if already.is_some() {
                continue;
            }
            match read_legacy(&path) {
                Ok(legacy) => {
                    let first = legacy.records.first().map(|r| r.ts);
                    let last = legacy.records.last().map(|r| r.ts);
                    let mtime = std::fs::metadata(&path)
                        .and_then(|m| m.modified())
                        .ok()
                        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
                        .map_or(0, |d| d.as_millis() as u64);
                    let created = first.unwrap_or(mtime) as i64;
                    let updated = last.unwrap_or(mtime) as i64;
                    let preview = legacy.preview();
                    tx.execute(
                        "INSERT INTO sessions
                           (id, created_ms, updated_ms, title, preview, messages, origin)
                         VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'jsonl')",
                        params![
                            id,
                            created,
                            updated,
                            legacy.title,
                            preview,
                            legacy.records.len() as i64
                        ],
                    )
                    .map_err(db_err(&path))?;
                    for (i, rec) in legacy.records.iter().enumerate() {
                        let body = serde_json::to_string(&rec.message)
                            .map_err(|e| Error::Session(e.to_string()))?;
                        tx.execute(
                            "INSERT INTO messages (session_id, seq, at_ms, role, body)
                             VALUES (?1, ?2, ?3, ?4, ?5)",
                            params![
                                id,
                                i as i64,
                                rec.ts as i64,
                                role_name(rec.message.role),
                                body
                            ],
                        )
                        .map_err(db_err(&path))?;
                        if self.fts {
                            tx.execute(
                                "INSERT INTO messages_fts (session_id, seq, content)
                                 VALUES (?1, ?2, ?3)",
                                params![id, i as i64, searchable(&rec.message)],
                            )
                            .map_err(db_err(&path))?;
                        }
                    }
                    if let Some(body) = legacy.memory {
                        // Stored as found: an unparseable sidecar is imported so that
                        // `memory()` can report it and `usable_memory()` can refuse it,
                        // rather than disappearing at import time.
                        tx.execute(
                            "INSERT OR REPLACE INTO memory (session_id, body) VALUES (?1, ?2)",
                            params![id, body],
                        )
                        .map_err(db_err(&path))?;
                    }
                    if let Some(w) = legacy.warning {
                        warnings.push(w);
                    }
                }
                Err(e) => {
                    // One unreadable transcript must not stop the import of the rest, and
                    // must not be deleted either.
                    warnings.push(format!("{}: not imported: {e}", path.display()));
                }
            }
        }
        tx.commit().map_err(db_err(dir))?;
        Ok(warnings)
    }
}

/// The database file inside the session directory.
const DB_FILE: &str = "sessions.db";

/// The file a store keeps its sessions in, under the directory it was given.
///
/// Public because a verb that only *counts* them must not open one: [`SessionStore::list`]
/// creates the directory, the database and its schema on first use, and a report is not a write.
pub fn db_path(dir: &Path) -> PathBuf {
    dir.join(DB_FILE)
}

const SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS sessions (
  id          TEXT PRIMARY KEY,
  created_ms  INTEGER NOT NULL,
  updated_ms  INTEGER NOT NULL,
  title       TEXT,
  preview     TEXT,
  messages    INTEGER NOT NULL DEFAULT 0,
  origin      TEXT NOT NULL DEFAULT 'native',
  pinned      INTEGER NOT NULL DEFAULT 0,
  archived    INTEGER NOT NULL DEFAULT 0,
  title_source TEXT,
  title_note  TEXT,
  last_cost   TEXT
);
CREATE INDEX IF NOT EXISTS sessions_by_activity ON sessions(updated_ms DESC);
CREATE TABLE IF NOT EXISTS messages (
  session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
  seq        INTEGER NOT NULL,
  at_ms      INTEGER NOT NULL,
  role       TEXT NOT NULL,
  body       TEXT NOT NULL,
  PRIMARY KEY (session_id, seq)
);
CREATE TABLE IF NOT EXISTS memory (
  session_id TEXT PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
  body       TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS approvals (
  session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
  seq        INTEGER NOT NULL,
  ord        INTEGER NOT NULL,
  call_id    TEXT NOT NULL,
  tool       TEXT NOT NULL,
  summary    TEXT NOT NULL,
  args       TEXT NOT NULL,
  decision   TEXT,
  decided_ms INTEGER,
  PRIMARY KEY (session_id, seq, ord)
);
CREATE INDEX IF NOT EXISTS approvals_by_call ON approvals(session_id, call_id);
-- `#340`: who answered a call, and a log that outlives the row.
--
-- `approvals` is deliberately transient — `clear_call` deletes the row once the answer is in the
-- transcript, because a row left behind would let a resume replay a call that already ran. That
-- makes it the wrong place to ask what the model waved through last week, so the decider goes
-- on the row (who answered *this* waiting call) and every ruling is also appended here, where
-- nothing ever deletes it.
CREATE TABLE IF NOT EXISTS approval_log (
  session_id TEXT NOT NULL,
  at_ms      INTEGER NOT NULL,
  call_id    TEXT NOT NULL,
  tool       TEXT NOT NULL,
  summary    TEXT NOT NULL,
  decision   TEXT NOT NULL,
  by         TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS approval_log_by_session ON approval_log(session_id, at_ms);
-- `#447`: how a tool call ended, kept beside the message rather than inside it. A stored `tool`
-- message is the model's wire shape and carries no verdict, so a replayed row used to read the
-- mark off the text and call a failed `read_file` a ✓. The call id is the key the dashboard
-- already joins on.
CREATE TABLE IF NOT EXISTS tool_outcomes (
  session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
  call_id    TEXT NOT NULL,
  is_error   INTEGER NOT NULL,
  PRIMARY KEY (session_id, call_id)
);
-- `#172`: one standing goal per session, and every judgement made about it. A new table rather
-- than a column, so an older `sessions.db` opens without a migration step and a session that has
-- never had a goal keeps no row at all. The foreign key is the whole of `deleting a session
-- deletes its goal`.
CREATE TABLE IF NOT EXISTS goals (
  session_id  TEXT PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
  text        TEXT NOT NULL,
  gate        TEXT,
  budget      INTEGER NOT NULL,
  turns       INTEGER NOT NULL DEFAULT 0,
  state       TEXT NOT NULL,
  note        TEXT,
  garbage     INTEGER NOT NULL DEFAULT 0,
  created_ms  INTEGER NOT NULL,
  updated_ms  INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS goal_turns (
  session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
  turn       INTEGER NOT NULL,
  verdict    TEXT NOT NULL,
  why        TEXT,
  at_ms      INTEGER NOT NULL,
  PRIMARY KEY (session_id, turn)
);
-- `#171`: a flare run and its N children. A run that cannot be listed after a restart is a run
-- that cannot be cancelled, so the ledger is a table rather than a field on the agent that
-- started it — and it is two tables because the run's cost is a sum over children that may have
-- failed, and a failed child's cost still happened.
CREATE TABLE IF NOT EXISTS flare_runs (
  id          TEXT PRIMARY KEY,
  task        TEXT NOT NULL,
  state       TEXT NOT NULL,
  routes      TEXT NOT NULL,
  jobs        INTEGER NOT NULL,
  parent      TEXT,
  started_ms  INTEGER NOT NULL,
  finished_ms INTEGER,
  prompt_tokens     INTEGER,
  completion_tokens INTEGER,
  iterations  INTEGER,
  cancel_requested INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS flare_runs_by_start ON flare_runs(started_ms DESC);
CREATE TABLE IF NOT EXISTS flare_jobs (
  run_id     TEXT NOT NULL REFERENCES flare_runs(id) ON DELETE CASCADE,
  n          INTEGER NOT NULL,
  route      TEXT NOT NULL,
  session_id TEXT,
  state      TEXT NOT NULL,
  prompt_tokens     INTEGER,
  completion_tokens INTEGER,
  iterations INTEGER,
  why        TEXT,
  PRIMARY KEY (run_id, n)
);
";

/// A plain FTS5 table: the message rows themselves stay the source of truth, so a build
/// without FTS5 loses nothing but the index.
const FTS_SCHEMA: &str = "
CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
  session_id UNINDEXED,
  seq        UNINDEXED,
  content
);
";

fn db_err(path: &Path) -> impl Fn(rusqlite::Error) -> Error + '_ {
    move |e| Error::Session(format!("{}: {e}", path.display()))
}

/// Whether `table` already has `column`. Used by the migration steps above, which cannot lean
/// on `CREATE TABLE IF NOT EXISTS`: that clause says nothing at all about an existing table.
fn has_column(conn: &Connection, table: &str, column: &str) -> rusqlite::Result<bool> {
    let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
    let mut rows = stmt.query([])?;
    while let Some(row) = rows.next()? {
        let name: String = row.get(1)?;
        if name == column {
            return Ok(true);
        }
    }
    Ok(false)
}

/// What a legacy `.jsonl` file held.
struct Legacy {
    records: Vec<Record>,
    title: Option<String>,
    /// The memory sidecar verbatim; parse failures are reported by `memory()`, not here.
    memory: Option<String>,
    warning: Option<String>,
}

impl Legacy {
    fn preview(&self) -> Option<String> {
        self.records
            .iter()
            .find(|r| r.message.role == Role::User)
            .and_then(|r| r.message.content.as_deref())
            .map(|t| {
                let one_line: String = t.split_whitespace().collect::<Vec<_>>().join(" ");
                one_line.chars().take(60).collect()
            })
    }
}

/// Read one legacy transcript, tolerating an interrupted final line.
///
/// Only an unterminated, unparseable *last* line is tolerated (a crash mid-append). A bad
/// line anywhere else means the file is not trustworthy, and importing part of it would
/// silently drop a message — so the whole file is refused and reported instead.
fn read_legacy(path: &Path) -> Result<Legacy> {
    let bytes = std::fs::read(path).map_err(|e| Error::io(path, e))?;
    let text = String::from_utf8_lossy(&bytes);
    let terminated = text.ends_with('\n');
    let lines: Vec<&str> = text.lines().collect();
    let mut records = Vec::new();
    let mut warning = None;
    for (i, line) in lines.iter().enumerate() {
        if line.trim().is_empty() {
            continue;
        }
        match serde_json::from_str::<Record>(line) {
            Ok(rec) => records.push(rec),
            Err(_) if i + 1 == lines.len() && !terminated => {
                warning = Some(format!(
                    "{}:{}: ignoring truncated trailing line ({} bytes)",
                    path.display(),
                    i + 1,
                    line.len()
                ));
            }
            Err(e) => return Err(Error::Session(format!("line {}: {e}", i + 1))),
        }
    }
    let dir = path.parent().unwrap_or(Path::new("."));
    let id = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
    let title = std::fs::read_to_string(dir.join(format!("{id}.meta.json")))
        .ok()
        .and_then(|t| serde_json::from_str::<Meta>(&t).ok())
        .map(|m| m.title);
    let memory = std::fs::read_to_string(dir.join(format!("{id}.memory.json")))
        .ok()
        .filter(|t| t.len() as u64 <= MAX_MEMORY_FILE_BYTES);
    Ok(Legacy {
        records,
        title,
        memory,
        warning,
    })
}

fn export_json(id: &str, title: Option<String>, records: &[Record]) -> Result<String> {
    let doc = serde_json::json!({
        "format": "eclipse-session/1",
        "id": id,
        "title": title,
        "messages": records,
    });
    let mut out = serde_json::to_string_pretty(&doc).map_err(|e| Error::Session(e.to_string()))?;
    out.push('\n');
    Ok(out)
}

/// Fence long enough that nothing inside `text` can close it early.
fn fenced(info: &str, text: &str) -> String {
    let (mut run, mut longest) = (0usize, 0usize);
    for c in text.chars() {
        run = if c == '`' { run + 1 } else { 0 };
        longest = longest.max(run);
    }
    let fence = "`".repeat((longest + 1).max(3));
    let nl = if text.ends_with('\n') { "" } else { "\n" };
    format!("{fence}{info}\n{text}{nl}{fence}\n")
}

fn export_markdown(id: &str, title: Option<&str>, records: &[Record]) -> String {
    use std::collections::HashMap;
    use std::fmt::Write as _;

    let mut out = String::new();
    let _ = writeln!(out, "# {}\n", title.unwrap_or(id).replace('\n', " "));
    let _ = writeln!(out, "- Session: `{id}`");
    let _ = writeln!(out, "- Messages: {}", records.len());
    if let Some(first) = records.first() {
        let _ = writeln!(out, "- Started: {} UTC", format_utc(first.ts));
    }
    out.push_str(
        "\n_The system prompt is not stored in sessions, so it is not part of this transcript._\n",
    );

    let mut tool_names: HashMap<&str, &str> = HashMap::new();
    for r in records {
        for c in &r.message.tool_calls {
            tool_names.insert(&c.id, &c.function.name);
        }
    }
    let mut answered: std::collections::HashSet<&str> = std::collections::HashSet::new();
    for r in records {
        if let Some(id) = r.message.tool_call_id.as_deref() {
            answered.insert(id);
        }
    }

    for (i, r) in records.iter().enumerate() {
        let m = &r.message;
        let who = match m.role {
            Role::System => "System".to_string(),
            Role::User => "User".to_string(),
            Role::Assistant => "Assistant".to_string(),
            Role::Tool => {
                let name = m
                    .tool_call_id
                    .as_deref()
                    .and_then(|c| tool_names.get(c).copied())
                    .unwrap_or("unknown tool");
                format!("Tool result: {name}")
            }
        };
        let _ = writeln!(out, "\n## {}. {who} ({} UTC)\n", i + 1, format_utc(r.ts));
        match m.role {
            Role::Tool => out.push_str(&fenced("", &m.text_with_pictures())),
            _ => {
                let text = m.text_with_pictures();
                if !text.is_empty() {
                    out.push_str(&text);
                    out.push('\n');
                }
            }
        }
        for c in &m.tool_calls {
            let args = &c.function.arguments;
            let _ = writeln!(
                out,
                "\n**Tool call** `{}` (id `{}`){}\n",
                c.function.name.replace('`', "'"),
                c.id.replace('`', "'"),
                if answered.contains(c.id.as_str()) {
                    ""
                } else {
                    " - no result recorded"
                }
            );
            match serde_json::from_str::<serde_json::Value>(args) {
                Ok(v) => out.push_str(&fenced(
                    "json",
                    &serde_json::to_string_pretty(&v).unwrap_or_else(|_| args.clone()),
                )),
                Err(_) => out.push_str(&fenced("", args)),
            }
        }
    }
    out
}

/// Format unix milliseconds as `YYYY-MM-DD HH:MM` (UTC).
pub fn format_utc(ms: u64) -> String {
    let secs = ms / 1000;
    let days = (secs / 86_400) as i64;
    let rem = secs % 86_400;
    // Howard Hinnant's civil-from-days algorithm.
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = yoe + era * 400 + i64::from(m <= 2);
    format!(
        "{y:04}-{m:02}-{d:02} {:02}:{:02}",
        rem / 3600,
        rem % 3600 / 60
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::{FunctionCall, ToolCall};

    fn store(dir: &Path) -> SessionStore {
        SessionStore::new(dir.join("sessions"))
    }

    fn call(id: &str, name: &str, args: &str) -> ToolCall {
        ToolCall {
            id: id.into(),
            kind: "function".into(),
            function: FunctionCall {
                name: name.into(),
                arguments: args.into(),
            },
        }
    }

    /// A session with one of each interesting message shape.
    fn transcript(store: &SessionStore, id: &str) {
        store.append(id, &Message::user("hello there")).unwrap();
        store
            .append(
                id,
                &Message::assistant_tool_calls(
                    Some("let me look".into()),
                    vec![call("c1", "read_file", r#"{"path":"a.txt"}"#)],
                ),
            )
            .unwrap();
        store
            .append(id, &Message::tool_result("c1", "file contents"))
            .unwrap();
        store.append(id, &Message::assistant("done")).unwrap();
    }

    /// `#447`: the verdict a replayed row draws, kept beside the message rather than inside it. A
    /// second write of the same call is the same write — the table is keyed by the call id — and a
    /// call nobody recorded simply has no mark.
    #[test]
    fn a_tool_outcome_is_recorded_beside_the_call_and_read_back() {
        let dir = tempfile::tempdir().unwrap();
        let store = SessionStore::new(dir.path().to_path_buf());
        let id = store.new_id();
        store.append(&id, &Message::user("read it")).unwrap();
        assert!(
            store.tool_outcomes(&id).unwrap().is_empty(),
            "nothing recorded is an empty map, not an error"
        );

        store.set_tool_outcome(&id, "c1", true).unwrap();
        store.set_tool_outcome(&id, "c2", false).unwrap();
        store.set_tool_outcome(&id, "c1", true).unwrap();

        let marks = store.tool_outcomes(&id).unwrap();
        assert_eq!(
            marks.len(),
            2,
            "the second write is the same write: {marks:?}"
        );
        assert_eq!(marks.get("c1"), Some(&true));
        assert_eq!(marks.get("c2"), Some(&false));
    }

    /// Insert a session directly, so age-based pruning can be tested without waiting.
    fn seed(store: &SessionStore, id: &str, updated_ms: u64) {
        store
            .with_db(|db| {
                db.conn.execute(
                    "INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
                     VALUES (?1, ?2, ?2, NULL, 'seeded', 1, 'native')",
                    params![id, updated_ms as i64],
                )?;
                Ok(())
            })
            .unwrap();
    }

    fn legacy_file(dir: &Path, id: &str, body: &str) -> PathBuf {
        std::fs::create_dir_all(dir).unwrap();
        let path = dir.join(format!("{id}.jsonl"));
        std::fs::write(&path, body).unwrap();
        path
    }

    fn line(m: &Message, ts: u64) -> String {
        let rec = Record {
            ts,
            message: m.clone(),
        };
        format!("{}\n", serde_json::to_string(&rec).unwrap())
    }

    #[test]
    fn append_and_load_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        assert!(!store.exists(&id), "a store knows only what was written");
        transcript(&store, &id);
        assert!(store.exists(&id));

        let messages = store.load(&id).unwrap();
        assert_eq!(messages.len(), 4);
        assert_eq!(messages[0], Message::user("hello there"));
        assert_eq!(messages[1].tool_calls.len(), 1);
        assert_eq!(messages[1].tool_calls[0].function.name, "read_file");
        assert_eq!(messages[1].content.as_deref(), Some("let me look"));
        assert_eq!(messages[2].tool_call_id.as_deref(), Some("c1"));
        assert_eq!(messages[2].content.as_deref(), Some("file contents"));
        assert_eq!(messages[3], Message::assistant("done"));
    }

    #[test]
    fn every_message_is_one_row_in_order() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        let records = store.load_records(&id).unwrap();
        let seqs: Vec<usize> = store
            .with_db(|db| {
                let mut stmt = db
                    .conn
                    .prepare("SELECT seq FROM messages WHERE session_id = ?1 ORDER BY seq")?;
                let rows = stmt.query_map(params![id], |r| r.get::<_, i64>(0))?;
                Ok(rows
                    .collect::<std::result::Result<Vec<_>, _>>()?
                    .into_iter()
                    .map(|s| s as usize)
                    .collect())
            })
            .unwrap();
        assert_eq!(seqs, [0, 1, 2, 3], "sequence numbers are dense and ordered");
        assert_eq!(records.len(), 4);
        assert!(
            records.windows(2).all(|w| w[0].ts <= w[1].ts),
            "timestamps do not run backwards"
        );
    }

    #[test]
    fn data_survives_a_new_store_handle() {
        let dir = tempfile::tempdir().unwrap();
        let id;
        {
            let first = store(dir.path());
            id = first.new_id();
            transcript(&first, &id);
            first.rename(&id, "kept title").unwrap();
        }
        let second = store(dir.path());
        assert_eq!(second.load(&id).unwrap().len(), 4);
        assert_eq!(second.title(&id).unwrap().as_deref(), Some("kept title"));
    }

    #[test]
    fn list_orders_newest_first_with_preview() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let a = store.new_id();
        store
            .append(&a, &Message::user("the older question"))
            .unwrap();
        std::thread::sleep(std::time::Duration::from_millis(5));
        let b = store.new_id();
        store
            .append(&b, &Message::user("the newer question"))
            .unwrap();

        let list = store.list().unwrap();
        assert_eq!(list.len(), 2);
        assert_eq!(list[0].id, b, "newest first");
        assert_eq!(list[0].preview, "the newer question");
        assert_eq!(list[0].messages, 1);
        assert_eq!(list[1].id, a);
        assert_eq!(list[0].label(), "the newer question");
    }

    #[test]
    fn the_preview_is_the_first_user_message_not_the_latest() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        store.append(&id, &Message::user("first thing")).unwrap();
        store.append(&id, &Message::user("second thing")).unwrap();
        let info = store.list().unwrap().into_iter().next().unwrap();
        assert_eq!(info.preview, "first thing");
        assert_eq!(info.messages, 2);
    }

    #[test]
    fn prune_candidates_by_age_and_count() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let now = 1_700_000_000_000u64;
        let day = 86_400_000u64;
        seed(&store, "old", now - 10 * day);
        seed(&store, "mid", now - 2 * day);
        seed(&store, "new", now - day / 24);

        assert_eq!(
            store.prune_candidates(3, 0, now, false).unwrap().candidates,
            ["old"],
            "older than three days"
        );
        assert_eq!(
            store.prune_candidates(0, 2, now, false).unwrap().candidates,
            ["old"],
            "all but the newest two"
        );
        let both = store.prune_candidates(3, 10, now, false).unwrap();
        assert_eq!(
            both.candidates,
            ["old"],
            "a session selected by either rule is pruned once"
        );
        assert!(store
            .prune_candidates(0, 0, now, false)
            .unwrap()
            .candidates
            .is_empty());
    }

    #[test]
    fn a_pinned_session_sorts_first_and_is_never_a_prune_candidate() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let now = 1_700_000_000_000u64;
        seed(&store, "oldest", now - 10 * 86_400_000);
        seed(&store, "newest", now - 86_400_000);

        store.set_pinned("oldest", true).unwrap();
        let list = store.list().unwrap();
        assert_eq!(list[0].id, "oldest", "pinned first, whatever the age");
        assert!(list[0].pinned);
        assert!(!list[1].pinned);

        // The age rule would take it; the pin keeps it and says so.
        let plan = store.prune_candidates(7, 0, now, false).unwrap();
        assert!(plan.candidates.is_empty(), "{:?}", plan.candidates);
        assert_eq!(plan.pinned_kept, 1);

        // And the unattended path agrees with the manual one.
        let outcome = store.auto_prune(7, 0, now, None).unwrap();
        assert_eq!(outcome, AutoPrune::Nothing);
        assert!(store.exists("oldest"));

        store.set_pinned("oldest", false).unwrap();
        assert_eq!(
            store.prune_candidates(7, 0, now, false).unwrap().candidates,
            ["oldest"]
        );
        assert!(!store.list().unwrap()[0].pinned, "unpinning is not sticky");
    }

    /// `#240`: archiving is not a soft delete. The session leaves the list and stays everywhere
    /// else — the search, the detail, the transcript — and a prune leaves it alone until it is
    /// told to take it.
    #[test]
    fn an_archived_session_leaves_the_list_and_stays_in_the_search() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let now = 1_700_000_000_000u64;
        seed(&store, "kept", now - 86_400_000);
        seed(&store, "filed", now - 10 * 86_400_000);
        store.rename("filed", "the nginx migration").unwrap();
        store
            .append("filed", &Message::user("the zfs pool was rebuilt"))
            .unwrap();
        // Writing a message makes a row the newest one; put it back where the policy will find
        // it, so this test is about the flag and not about the clock.
        store
            .with_db(|db| {
                db.conn.execute(
                    "UPDATE sessions SET updated_ms = ?2 WHERE id = ?1",
                    params!["filed", (now - 10 * 86_400_000) as i64],
                )?;
                Ok(())
            })
            .unwrap();

        store.set_archived("filed", true).unwrap();

        // Out of the list a person reads, in the one that says what happened to every row.
        let listed = store.list().unwrap();
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].id, "kept");
        let all = store.list_with_archived().unwrap();
        assert_eq!(all.len(), 2);
        assert!(all.iter().find(|s| s.id == "filed").unwrap().archived);
        assert!(!all.iter().find(|s| s.id == "kept").unwrap().archived);

        // Still found, by its name and by what was said in it — that is the difference between
        // an archive and a delete.
        assert!(
            store
                .search("nginx", 20)
                .unwrap()
                .iter()
                .any(|h| h.session_id == "filed"),
            "a name hit survives archiving"
        );
        assert!(
            store
                .search("zfs", 20)
                .unwrap()
                .iter()
                .any(|h| h.session_id == "filed"),
            "a message hit survives archiving"
        );
        assert_eq!(
            store.load("filed").unwrap().len(),
            1,
            "the transcript is there"
        );

        // A prune leaves it alone and counts it, and the flag is what changes the answer.
        let plan = store.prune_candidates(7, 0, now, false).unwrap();
        assert!(plan.candidates.is_empty(), "{:?}", plan.candidates);
        assert_eq!(plan.archived_kept, 1);
        assert_eq!(
            plan.pinned_kept, 0,
            "counted apart, so the sentence can differ"
        );
        assert_eq!(
            store.prune_candidates(7, 0, now, true).unwrap().candidates,
            ["filed"]
        );
        // The unattended path has no way to be given the flag, so it never takes one.
        assert_eq!(
            store.auto_prune(7, 0, now, None).unwrap(),
            AutoPrune::Nothing
        );

        // And unarchiving is the same write in the other direction.
        store.set_archived("filed", false).unwrap();
        assert_eq!(store.list().unwrap().len(), 2);
        assert!(matches!(
            store.set_archived("nope", true),
            Err(Error::Session(_))
        ));
    }

    /// The archive flag on a row that was written before it existed: the column arrives with a
    /// default, so an old row is in the list and nothing has to be backfilled.
    #[test]
    fn a_database_from_before_archiving_gains_the_column_in_place() {
        let dir = tempfile::tempdir().unwrap();
        {
            let dir = dir.path().join("sessions");
            std::fs::create_dir_all(&dir).unwrap();
            let conn = Connection::open(dir.join(DB_FILE)).unwrap();
            conn.execute_batch(
                "CREATE TABLE sessions (
                   id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
                   title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
                   origin TEXT NOT NULL DEFAULT 'native');
                 INSERT INTO sessions (id, created_ms, updated_ms, preview, messages, origin)
                   VALUES ('s1', 1, 2, 'an old session', 1, 'native');",
            )
            .unwrap();
        }
        let store = store(dir.path());
        let list = store.list().unwrap();
        assert_eq!(
            list.len(),
            1,
            "the old row is in the list, not archived by omission"
        );
        assert!(!list[0].archived);
        store.set_archived("s1", true).unwrap();
        assert!(store.list().unwrap().is_empty());
        assert!(store.list_with_archived().unwrap()[0].archived);
    }

    #[test]
    fn a_database_from_before_pinning_gains_the_column_in_place() {
        let dir = tempfile::tempdir().unwrap();
        let id;
        {
            // The schema as it was released, written by hand so the test does not depend on
            // this build's `SCHEMA` continuing to be the old one.
            let dir = dir.path().join("sessions");
            std::fs::create_dir_all(&dir).unwrap();
            let conn = Connection::open(dir.join(DB_FILE)).unwrap();
            conn.execute_batch(
                "CREATE TABLE sessions (
                   id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
                   title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
                   origin TEXT NOT NULL DEFAULT 'native');
                 INSERT INTO sessions (id, created_ms, updated_ms, preview, messages, origin)
                   VALUES ('s1', 1, 2, 'an old session', 1, 'native');",
            )
            .unwrap();
            id = "s1".to_string();
        }
        let store = store(dir.path());
        let list = store.list().unwrap();
        assert_eq!(list.len(), 1, "the old row still reads");
        assert_eq!(list[0].id, id);
        assert!(!list[0].pinned, "an old row is not pinned");
        store.set_pinned(&id, true).unwrap();
        assert!(store.list().unwrap()[0].pinned);
        assert_eq!(
            store
                .prune_candidates(0, 1, 1_700_000_000_000, false)
                .unwrap(),
            PrunePlan::default(),
            "one session, newest one kept"
        );
    }

    #[test]
    fn a_database_from_before_the_cost_record_gains_the_column_in_place() {
        let dir = tempfile::tempdir().unwrap();
        {
            let dir = dir.path().join("sessions");
            std::fs::create_dir_all(&dir).unwrap();
            let conn = Connection::open(dir.join(DB_FILE)).unwrap();
            conn.execute_batch(
                "CREATE TABLE sessions (
                   id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
                   title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
                   origin TEXT NOT NULL DEFAULT 'native');
                 INSERT INTO sessions (id, created_ms, updated_ms, preview, messages, origin)
                   VALUES ('s1', 1, 2, 'an old session', 1, 'native');",
            )
            .unwrap();
        }
        let store = store(dir.path());
        assert!(
            store.last_cost("s1").unwrap().is_none(),
            "an old row has no turn behind it, and no record is not a zero"
        );
        let prompt = 1_234_u64;
        let cost = TurnCost {
            at_ms: 7,
            ctx: "ctx 1.2K/8K ░░░░░░░░░░│░ 15%".to_string(),
            prompt_tokens: Some(prompt),
            ..TurnCost::default()
        };
        store.set_last_cost("s1", &cost).unwrap();
        assert_eq!(store.last_cost("s1").unwrap(), Some(cost));
    }

    /// The row a person reads says what a session cost, and says it after the page that paid for
    /// it is gone (#344). The listing is where it has to arrive: opening a session costs no
    /// request of its own, so the sidebar's row and the stats row cannot describe one session
    /// differently.
    #[test]
    fn a_turn_writes_its_cost_and_the_listing_reads_it_back() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        assert!(
            store.list().unwrap()[0].cost.is_none(),
            "a session with no finished turn has nothing to say about one"
        );
        let prompt = 30_000_u64;
        let cached = 28_000_u64;
        let cost = TurnCost {
            at_ms: 1_700_000_000_000,
            ctx: "ctx 30K/262K ██░░░░░░░░│░ 11%".to_string(),
            prompt_tokens: Some(prompt),
            completion_tokens: Some(400),
            cached_tokens: Some(cached),
            ttft_ms: Some(800),
            latency_ms: Some(13_000),
            tokens_per_sec: Some(63.0),
            window_tokens: Some(262_144),
        };
        store.set_last_cost(&id, &cost).unwrap();
        let listed = &store.list().unwrap()[0];
        assert_eq!(listed.cost.as_ref(), Some(&cost));
        let ctx = listed
            .cost
            .as_ref()
            .map(|c| c.ctx.as_str())
            .unwrap_or_default();
        assert!(
            ctx.contains("262K"),
            "the denominator the listing carries is the one that turn ran against: {ctx:?}"
        );
    }

    /// A cost write is bookkeeping, not activity: a session that is not being talked to must not
    /// jump to the top of `Today` because a turn of its own finished hours ago.
    #[test]
    fn recording_a_cost_does_not_move_the_session_up_the_list() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let older = store.new_id();
        let newer = store.new_id();
        transcript(&store, &older);
        transcript(&store, &newer);
        let before: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
        let target = before.last().expect("two sessions").clone();
        store
            .set_last_cost(
                &target,
                &TurnCost {
                    at_ms: 1,
                    ctx: "ctx --".to_string(),
                    ..TurnCost::default()
                },
            )
            .unwrap();
        let after: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
        assert_eq!(
            before, after,
            "the order is the store's, and a cost is not a move"
        );
    }

    /// `derived < llm < user`, and the rule lives in the store because the naming pass runs in a
    /// task of its own: a rename that lands between the read and the write has to win.
    #[test]
    fn a_persons_name_outranks_the_machines_and_outlives_a_later_attempt() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);

        assert!(
            store.title_if_unnamed(&id, "the opening message").unwrap(),
            "nothing names it yet, so the derived name lands"
        );
        assert!(
            !store
                .title_if_unnamed(&id, "a second derived name")
                .unwrap(),
            "stage one never relabels a session it has already named"
        );
        assert_eq!(
            store.title(&id).unwrap().as_deref(),
            Some("the opening message")
        );

        assert!(
            store
                .set_title(&id, "the model's name", TitleSource::Llm)
                .unwrap(),
            "a model name replaces a derived one"
        );
        assert!(
            !store
                .set_title(&id, "a second model name", TitleSource::Llm)
                .unwrap(),
            "one naming call means one name: it is not renamed by trying again"
        );

        store.rename(&id, "what I called it").unwrap();
        for source in [TitleSource::Llm, TitleSource::Derived] {
            assert!(
                !store.set_title(&id, "the machine again", source).unwrap(),
                "a person's name is final to {source:?}"
            );
        }
        assert_eq!(
            store.title(&id).unwrap().as_deref(),
            Some("what I called it")
        );
        assert_eq!(
            store.list().unwrap()[0].label(),
            "what I called it",
            "and the listing shows it"
        );
    }

    /// One call per session is a fact about the database: the claim is a single `UPDATE`, so a
    /// resume, a second process or a retry finds it taken. A failure is remembered as the reason
    /// the claim was spent, which is also what keeps the session from being tried again.
    #[test]
    fn the_naming_attempt_is_claimed_once_per_session() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        store.title_if_unnamed(&id, "a derived name").unwrap();

        assert!(
            store.claim_title_upgrade(&id).unwrap(),
            "the first caller owns it"
        );
        assert!(
            !store.claim_title_upgrade(&id).unwrap(),
            "and nobody else does"
        );
        store
            .title_attempt_failed(&id, "the reply was not a JSON object")
            .unwrap();
        assert!(
            !store.claim_title_upgrade(&id).unwrap(),
            "a refused answer is not retried on the next run"
        );
        assert_eq!(
            store.title(&id).unwrap().as_deref(),
            Some("a derived name"),
            "and the name is still there: a failure never leaves it empty"
        );

        // Nothing was tried here, so giving the claim back leaves the session eligible.
        let other = store.new_id();
        transcript(&store, &other);
        store.title_if_unnamed(&other, "another name").unwrap();
        assert!(store.claim_title_upgrade(&other).unwrap());
        store.release_title_claim(&other).unwrap();
        assert!(
            store.claim_title_upgrade(&other).unwrap(),
            "released, not failed"
        );
    }

    /// A child session's name is read by the parent's list and nobody types it in. The claim
    /// refuses those, so delegation never spends a call per child.
    #[test]
    fn a_delegated_child_session_is_never_named_by_a_call() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let parent = store.new_id();
        let child = store.new_id();
        store.append(&parent, &Message::user("big job")).unwrap();
        store.begin_subagent(&child, &parent, "fast").unwrap();
        store
            .append(&child, &Message::user("summarise this"))
            .unwrap();
        store.title_if_unnamed(&child, "summarise this").unwrap();
        assert!(
            !store.claim_title_upgrade(&child).unwrap(),
            "a child is named by its opening message and left alone"
        );

        let api = store.new_id();
        store.begin_api(&api).unwrap();
        store.append(&api, &Message::user("headless turn")).unwrap();
        store.title_if_unnamed(&api, "headless turn").unwrap();
        assert!(
            !store.claim_title_upgrade(&api).unwrap(),
            "a headless API session is named for free and never costs a call"
        );
    }

    /// The name answers a search: the session I called X is a lookup, not a scroll, even when no
    /// message in it ever used those words together.
    #[test]
    fn a_search_finds_a_session_by_the_name_it_was_given() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        store
            .append(&id, &Message::user("something else entirely"))
            .unwrap();
        store.append(&id, &Message::assistant("noted")).unwrap();
        store.rename(&id, "gateway restart loop").unwrap();

        for fts in [true, false] {
            // Both backends, because which one runs depends on how SQLite was compiled and the
            // two must answer the same question the same way.
            let hits = store
                .with_db(|db| SessionStore::search_in(db, "restart loop", 10, fts, false))
                .unwrap();
            let named: Vec<_> = hits.iter().filter(|h| h.role == "title").collect();
            assert_eq!(named.len(), 1, "fts={fts}: {:?}", hits);
            assert_eq!(named[0].session_id, id);
            assert_eq!(named[0].snippet, "gateway restart loop");
            assert_eq!(
                named[0].seq, 0,
                "a name is read from the top of the transcript"
            );
        }
        // A query that matches no name still searches the transcript.
        let hits = store.search("noted", 10).unwrap();
        assert!(hits.iter().all(|h| h.role != "title"));
        assert_eq!(hits.len(), 1);
    }

    /// `#498`: the rows a `session_search` writes into its own session are not results, and a page
    /// that holds nothing but them must not be reported as "no match" — the caller would be told
    /// its archive holds nothing while the match sat one row further down.
    #[test]
    fn a_page_of_the_tools_own_calls_does_not_hide_the_match_behind_them() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        store
            .append(&id, &Message::user("the needle is here"))
            .unwrap();
        for i in 0..12 {
            let call = crate::message::ToolCall {
                id: format!("call-{i}"),
                kind: "function".to_string(),
                function: crate::message::FunctionCall {
                    name: "session_search".to_string(),
                    arguments: "{\"query\":\"needle\"}".to_string(),
                },
            };
            store
                .append(&id, &Message::assistant_tool_calls(None, vec![call]))
                .unwrap();
            store
                .append(
                    &id,
                    &Message::tool_result(format!("call-{i}"), "archive: no match for needle"),
                )
                .unwrap();
        }

        for fts in [true, false] {
            // A limit of 1 is a budget of 9 rows, and the twenty-four own-tail rows are newer than
            // the match: without the widening this answers "no match" on both backends.
            let hits = store
                .with_db(|db| SessionStore::search_in(db, "needle", 1, fts, false))
                .unwrap();
            assert_eq!(hits.len(), 1, "fts={fts}: {hits:?}");
            assert_eq!(hits[0].role, "user", "fts={fts}: {hits:?}");
        }
    }

    /// A database from before names existed gains the two columns in place, and every title it
    /// already holds is taken to be a person's: nothing else wrote one.
    #[test]
    fn a_database_from_before_names_keeps_its_titles_and_learns_who_wrote_them() {
        let dir = tempfile::tempdir().unwrap();
        {
            let dir = dir.path().join("sessions");
            std::fs::create_dir_all(&dir).unwrap();
            let conn = Connection::open(dir.join(DB_FILE)).unwrap();
            conn.execute_batch(
                "CREATE TABLE sessions (
                   id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
                   title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
                   origin TEXT NOT NULL DEFAULT 'native', pinned INTEGER NOT NULL DEFAULT 0);
                 INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
                   VALUES ('named', 1, 2, 'what I called it', 'first words', 2, 'native'),
                          ('bare', 1, 2, NULL, 'first words', 2, 'native');",
            )
            .unwrap();
        }
        let store = store(dir.path());
        let list = store.list().unwrap();
        let named = list.iter().find(|s| s.id == "named").unwrap();
        assert_eq!(
            named.title.as_deref(),
            Some("what I called it"),
            "the title survives"
        );

        assert!(
            !store.title_if_unnamed("named", "a derived name").unwrap(),
            "an old title is a person's, so stage one leaves it"
        );
        assert!(
            !store.claim_title_upgrade("named").unwrap(),
            "and no call is spent on it either"
        );
        assert!(
            store.title_if_unnamed("bare", "a derived name").unwrap(),
            "a session that had no name gets one"
        );
        assert_eq!(
            store.title("bare").unwrap().as_deref(),
            Some("a derived name")
        );
    }

    #[test]
    fn deleting_a_session_removes_its_title_memory_and_lock_file() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("sessions");
        let store = store(dir.path());
        let a = store.new_id();
        let b = store.new_id();
        transcript(&store, &a);
        transcript(&store, &b);
        store.rename(&a, "doomed").unwrap();
        store
            .save_memory(&a, &memory("## Log\na summary", 2, 3))
            .unwrap();
        store
            .with_db(|db| {
                db.conn.execute(
                    "INSERT OR REPLACE INTO memory (session_id, body) VALUES (?1, '{}')",
                    params![a],
                )?;
                Ok(())
            })
            .unwrap();
        let lock = root.join(format!("{a}.lock"));
        std::fs::write(&lock, "pid 1\n").unwrap();

        store.delete(&a).unwrap();
        assert!(!store.exists(&a));
        assert!(store.exists(&b), "the other session is untouched");
        assert!(store.load(&b).unwrap().len() == 4);
        assert_eq!(store.memory(&a).unwrap(), None);
        assert!(!lock.exists(), "the lock file does not outlive the session");
        assert!(store.delete(&a).is_err(), "deleting twice is an error");
    }

    #[test]
    fn auto_prune_deletes_up_to_ten_sessions_and_refuses_more() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let now = 1_700_000_000_000u64;
        for i in 0..12 {
            seed(&store, &format!("s{i:02}"), now - (100 - i) * 86_400_000);
        }
        // Twelve candidates: over the limit, so nothing is deleted and the count is reported.
        assert_eq!(
            store.auto_prune(30, 0, now, None).unwrap(),
            AutoPrune::Skipped { would_remove: 12 }
        );
        assert_eq!(store.list().unwrap().len(), 12);
        // Ten is allowed.
        assert_eq!(
            store.auto_prune(0, 2, now, None).unwrap(),
            AutoPrune::Pruned {
                removed: 10,
                failed: 0,
                pinned_kept: 0
            }
        );
        assert_eq!(store.list().unwrap().len(), 2);
    }

    #[test]
    fn auto_prune_never_runs_without_a_limit_and_reports_nothing_to_do() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let now = 1_700_000_000_000u64;
        assert_eq!(
            store.auto_prune(0, 0, now, None).unwrap(),
            AutoPrune::NoLimits
        );
        seed(&store, "fresh", now);
        assert_eq!(
            store.auto_prune(30, 0, now, None).unwrap(),
            AutoPrune::Nothing
        );
        assert_eq!(store.list().unwrap().len(), 1);
    }

    #[test]
    fn auto_prune_spares_the_protected_session() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let now = 1_700_000_000_000u64;
        seed(&store, "keep-me", now - 90 * 86_400_000);
        seed(&store, "old-1", now - 90 * 86_400_000);
        let outcome = store.auto_prune(7, 0, now, Some("keep-me")).unwrap();
        assert_eq!(
            outcome,
            AutoPrune::Pruned {
                removed: 1,
                failed: 0,
                pinned_kept: 0
            }
        );
        assert!(
            store.exists("keep-me"),
            "the session being resumed survives"
        );
        assert!(!store.exists("old-1"));
    }

    #[test]
    fn rejects_path_traversal_ids() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        for bad in ["../etc/passwd", "a/b", "", "sp ace", "dot.dot"] {
            assert!(
                store.load(bad).is_err(),
                "{bad:?} must be refused before it reaches the database"
            );
            assert!(!store.exists(bad));
        }
    }

    #[test]
    fn a_corrupt_row_is_reported_with_its_session_and_position() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        store
            .with_db(|db| {
                db.conn.execute(
                    "INSERT INTO messages (session_id, seq, at_ms, role, body)
                     VALUES (?1, 99, 0, 'user', '{not json')",
                    params![id],
                )?;
                Ok(())
            })
            .unwrap();
        let err = store.load(&id).unwrap_err().to_string();
        assert!(err.contains(&id) && err.contains("99"), "{err}");
    }

    #[test]
    fn new_ids_are_unique() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let ids: std::collections::HashSet<String> = (0..50).map(|_| store.new_id()).collect();
        assert_eq!(ids.len(), 50);
        for id in &ids {
            validate_id(id).unwrap();
        }
    }

    #[test]
    fn utc_formatting() {
        assert_eq!(format_utc(0), "1970-01-01 00:00");
        assert_eq!(format_utc(1_700_000_000_000), "2023-11-14 22:13");
    }

    #[test]
    fn rename_sets_title_without_touching_the_transcript() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        let before = store.load(&id).unwrap();
        store.rename(&id, "  a name  ").unwrap();
        assert_eq!(store.title(&id).unwrap().as_deref(), Some("a name"));
        assert_eq!(store.load(&id).unwrap(), before);
        let listed = store.list().unwrap().into_iter().next().unwrap();
        assert_eq!(listed.label(), "a name", "the title wins over the preview");
    }

    #[test]
    fn rename_rejects_bad_titles_and_unknown_sessions() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        for bad in ["", "   "] {
            assert!(store.rename(&id, bad).is_err(), "{bad:?}");
        }
        assert!(store.rename(&id, &"x".repeat(201)).is_err());
        assert!(store.rename(&id, "bad\nname").is_err());
        assert!(store.rename("no-such-session", "fine").is_err());
        assert_eq!(store.title(&id).unwrap(), None);
    }

    #[test]
    fn json_export_is_the_complete_transcript() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        let out = store.export(&id, ExportFormat::Json).unwrap();
        let doc: serde_json::Value = serde_json::from_str(&out).unwrap();
        assert_eq!(doc["format"], "eclipse-session/1");
        assert_eq!(doc["id"], id);
        assert_eq!(doc["messages"].as_array().unwrap().len(), 4);
        assert_eq!(doc["messages"][0]["message"]["role"], "user");
        assert_eq!(
            doc["messages"][1]["message"]["tool_calls"][0]["function"]["name"],
            "read_file"
        );
        assert!(out.ends_with('\n'));
    }

    #[test]
    fn markdown_export_shows_turns_calls_and_results() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        let out = store.export(&id, ExportFormat::Markdown).unwrap();
        assert!(out.contains("# "), "a heading, even without a title: {out}");
        assert!(out.contains("## 1. User"));
        assert!(out.contains("## 2. Assistant"));
        assert!(out.contains("**Tool call** `read_file`"));
        assert!(out.contains("## 3. Tool result: read_file"));
        assert!(out.contains("```json"), "arguments are pretty-printed");
        assert!(!out.contains("no result recorded"), "the call was answered");
    }

    #[test]
    fn markdown_export_uses_the_title() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        store.rename(&id, "a named session").unwrap();
        let out = store.export(&id, ExportFormat::Markdown).unwrap();
        assert!(out.starts_with("# a named session\n"), "{out}");
    }

    /// No range endpoints. `Handoff::covers` refuses a document without them on purpose, and none
    /// of these tests is about reuse — they are about what the file holds.
    const NO_SPAN: (Option<u64>, Option<u64>) = (None, None);

    fn handoff(text: &str, turns: usize, messages: usize) -> Handoff {
        Handoff {
            text: text.into(),
            version: crate::compact::VERSION.into(),
            covered_turns: turns,
            covered_messages: messages,
            covered_from: None,
            covered_to: None,
            generated_at_ms: 1_700_000_000_000,
            judgement: None,
        }
    }

    fn memory(text: &str, turns: usize, messages: usize) -> Memory {
        Memory {
            version: MEMORY_VERSION,
            handoff: Some(handoff(text, turns, messages)),
        }
    }

    /// A file written by the build that still had a model-written summary: it loads, its summary
    /// is ignored rather than trusted or migrated, and the next handoff write replaces the record
    /// with one of this schema. Nothing is lost that matters — the summary was never the
    /// transcript, and the transcript is untouched.
    #[test]
    fn a_summary_era_memory_file_loads_with_its_summary_ignored() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        let v2 = r#"{"version":2,"summary":"old news","covered_turns":2,
                     "covered_messages":4,"generated_at_ms":1700000000000}"#;
        store
            .with_db(|db| {
                db.conn.execute(
                    "INSERT INTO memory (session_id, body) VALUES (?1, ?2)",
                    params![id, v2],
                )?;
                Ok(())
            })
            .unwrap();

        let m = store.memory(&id).unwrap().unwrap();
        assert_eq!(m.schema(), 2, "the file says what wrote it");
        assert_eq!(
            m.usable_handoff(),
            None,
            "a summary alone is not a handoff, and there is nothing else to read"
        );
        assert!(
            m.validate().is_err(),
            "a record with nothing in it is not memory"
        );

        store
            .save_handoff(
                &id,
                crate::context::Trimmed {
                    turns: 2,
                    messages: 4,
                },
                NO_SPAN,
                "## Log\n[#0]",
                None,
            )
            .unwrap();
        let after = store.memory(&id).unwrap().unwrap();
        assert_eq!(after.schema(), MEMORY_VERSION, "rewritten at this schema");
        assert_eq!(after.handoff.unwrap().text, "## Log\n[#0]");
        let raw = store
            .with_db(|db| {
                Ok(db
                    .conn
                    .query_row(
                        "SELECT body FROM memory WHERE session_id = ?1",
                        params![id],
                        |r| r.get::<_, String>(0),
                    )
                    .unwrap())
            })
            .unwrap();
        assert!(
            !raw.contains("summary"),
            "the field a summary-era build wrote is gone from the file: {raw}"
        );
    }

    #[test]
    fn saving_a_handoff_replaces_the_document_and_never_the_other_way_round() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);

        store
            .save_handoff(
                &id,
                crate::context::Trimmed {
                    turns: 1,
                    messages: 2,
                },
                NO_SPAN,
                "## Log\nA",
                None,
            )
            .unwrap();
        assert_eq!(
            store.readable_memory(&id).unwrap().handoff.unwrap().text,
            "## Log\nA"
        );

        // A wider range replaces it whole: a handoff is a document for one drop, not a prefix of
        // the next one.
        store
            .save_handoff(
                &id,
                crate::context::Trimmed {
                    turns: 3,
                    messages: 6,
                },
                NO_SPAN,
                "## Log\nB",
                Some(Judgement {
                    text: "- because the first answer settled it".into(),
                    model: "aux".into(),
                    generated_at_ms: 1,
                }),
            )
            .unwrap();
        let now = store.readable_memory(&id).unwrap();
        let h = now.handoff.unwrap();
        assert_eq!(h.text, "## Log\nB");
        assert_eq!(h.covered_turns, 3);
        assert_eq!(
            h.judgement.unwrap().model,
            "aux",
            "and the judgement travels with the document it belongs to"
        );
    }

    #[test]
    fn a_memory_from_a_newer_schema_is_refused_rather_than_half_read() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        let mut m = memory("## Log\nC", 1, 2);
        m.version = MEMORY_VERSION + 1;
        let why = m.validate().unwrap_err();
        assert!(why.contains("newer than this build"), "{why}");
        assert!(
            store.save_memory(&id, &m).is_err(),
            "a record this build cannot read is not written either"
        );
    }

    /// The store may not write a record its own reader refuses. Past the cap, `memory()` errors
    /// for ever and `readable_memory` reports "no memory", so the session recompiles on every
    /// request with no way back.
    #[test]
    fn a_memory_too_large_to_read_back_is_refused_at_the_write() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        let mut big = memory("## Log\n", 1, 2);
        big.handoff.as_mut().unwrap().text = "x".repeat(MAX_MEMORY_FILE_BYTES as usize);
        let err = store
            .save_memory(&id, &big)
            .expect_err("a record the reader would refuse is not written");
        assert!(err.to_string().contains("record limit"), "{err}");
        assert!(
            store.memory(&id).unwrap().is_none(),
            "nothing was stored, and the row did not become unreadable"
        );

        // The boundary itself is allowed: a record that serialises to exactly the cap reads back.
        let mut fits = memory("## Log\n", 1, 2);
        let overhead =
            serde_json::to_string(&fits).unwrap().len() - fits.handoff.as_ref().unwrap().text.len();
        fits.handoff.as_mut().unwrap().text = "x".repeat(MAX_MEMORY_FILE_BYTES as usize - overhead);
        store.save_memory(&id, &fits).expect("the cap itself fits");
        assert!(store.readable_memory(&id).is_some(), "and it reads back");
    }

    /// The counts describe a size, not a window. `Trimmed` is measured from `head_end`, so the
    /// same pair of numbers can name a different drop once the budget moves — and a document
    /// reused for the wrong one mentions messages that are still verbatim in the request.
    #[test]
    fn a_handoff_is_its_range_and_not_just_its_counts() {
        let mut h = handoff("## Log\nsomeone decided something", 1, 2);
        assert!(
            !h.covers(1, 2, Some(2), Some(3)),
            "a document with no endpoints cannot say which window it described"
        );
        h.covered_from = Some(0);
        h.covered_to = Some(1);
        assert!(h.covers(1, 2, Some(0), Some(1)));
        assert!(
            !h.covers(1, 2, Some(2), Some(3)),
            "the same size and the same counts, a different window"
        );
        assert!(
            !h.covers(1, 2, None, None),
            "no endpoints on the caller's side either"
        );
        h.covered_to = Some(9);
        assert!(
            !h.covers(1, 2, Some(0), Some(1)),
            "the end is part of the range"
        );
    }

    #[test]
    fn memory_round_trips_in_its_documented_shape_and_the_database_is_private() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        store
            .save_handoff(
                &id,
                crate::context::Trimmed {
                    turns: 2,
                    messages: 4,
                },
                NO_SPAN,
                "## Log\nthey agreed on the plan",
                None,
            )
            .unwrap();
        let raw = store
            .with_db(|db| {
                Ok(db
                    .conn
                    .query_row(
                        "SELECT body FROM memory WHERE session_id = ?1",
                        params![id],
                        |r| r.get::<_, String>(0),
                    )
                    .unwrap())
            })
            .unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap();
        assert_eq!(parsed["version"], MEMORY_VERSION);
        assert_eq!(parsed["handoff"]["covered_turns"], 2);
        assert_eq!(parsed["handoff"]["text"], "## Log\nthey agreed on the plan");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(store.dir().join("sessions.db"))
                .unwrap()
                .permissions()
                .mode()
                & 0o777;
            assert_eq!(
                mode, 0o600,
                "the database is owner-only, like the transcripts were"
            );
            // The main file is not the transcript: everything written since the last checkpoint
            // lives in `-wal`, which SQLite creates with the umask. The directory has to be
            // owner-only for that to be a guarantee, and the sidecar itself is chmodded too.
            let dir_mode = std::fs::metadata(store.dir()).unwrap().permissions().mode() & 0o777;
            assert_eq!(dir_mode, 0o700, "the session directory is owner-only");
            for sidecar in ["sessions.db-wal", "sessions.db-shm"] {
                let p = store.dir().join(sidecar);
                if !p.exists() {
                    continue;
                }
                let m = std::fs::metadata(&p).unwrap().permissions().mode() & 0o777;
                assert_eq!(m, 0o600, "{sidecar} is owner-only");
            }
        }
    }

    #[test]
    fn memory_validation_rejects_nonsense() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        let empty = Memory {
            version: MEMORY_VERSION,
            handoff: None,
        };
        assert!(empty.validate().is_err() && store.save_memory(&id, &empty).is_err());
        let mut m = memory(" padded ", 1, 1);
        assert!(m.validate().is_err(), "an untrimmed document is refused");
        m = memory("fine", 2, 1);
        assert!(m.validate().is_err(), "messages < turns is nonsense");
        m.handoff.as_mut().unwrap().covered_messages = 2;
        m.handoff.as_mut().unwrap().covered_turns = 0;
        assert!(m.validate().is_err(), "covering no turn is nonsense");
        m = memory("", 1, 2);
        assert!(m.validate().is_err(), "an empty document is not memory");
        let mut m = memory("fine", 2, 4);
        m.handoff.as_mut().unwrap().judgement = Some(Judgement {
            text: "\n- untrimmed".into(),
            model: "aux".into(),
            generated_at_ms: 1,
        });
        assert!(m.validate().is_err(), "an untrimmed judgement is refused");
        assert!(store.save_memory(&id, &memory("fine", 2, 4)).is_ok());
    }

    #[test]
    fn corrupt_or_invalid_memory_is_not_usable() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        store
            .with_db(|db| {
                db.conn.execute(
                    "INSERT INTO memory (session_id, body) VALUES (?1, 'not json')",
                    params![id],
                )?;
                Ok(())
            })
            .unwrap();
        assert!(
            store.memory(&id).is_err(),
            "corruption is reported, not hidden"
        );
        assert_eq!(store.readable_memory(&id), None, "and never used");

        store
            .save_memory(&id, &memory("valid again", 1, 1))
            .unwrap();
        assert!(store.readable_memory(&id).is_some());
    }

    #[test]
    fn memory_is_per_session() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let a = store.new_id();
        let b = store.new_id();
        store.append(&a, &Message::user("a")).unwrap();
        store.append(&b, &Message::user("b")).unwrap();
        store.save_memory(&a, &memory("about a", 1, 1)).unwrap();
        assert!(store.memory(&b).unwrap().is_none());
        assert_eq!(
            store.readable_memory(&a).unwrap().handoff.unwrap().text,
            "about a"
        );
    }

    #[test]
    fn delete_and_prune_remove_the_memory_too() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        store
            .save_memory(&id, &memory("gone with it", 1, 1))
            .unwrap();
        store.delete(&id).unwrap();
        assert!(
            store.load_records(&id).is_err(),
            "the session is gone, not empty"
        );
        assert_eq!(store.memory(&id).unwrap(), None);
    }

    // ---- legacy import ---------------------------------------------------------

    #[test]
    fn a_deleted_legacy_session_does_not_come_back() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("sessions");
        let path = legacy_file(
            &root,
            "deleted-me",
            &line(&Message::user("doomed"), 1_700_000_000_000),
        );
        let store = SessionStore::new(&root);
        assert!(store.exists("deleted-me"));
        store.delete("deleted-me").unwrap();
        assert!(!path.exists(), "the imported source goes with the session");
        drop(store);

        // A fresh handle over the same directory must not re-import it.
        let again = SessionStore::new(&root);
        assert!(
            !again.exists("deleted-me"),
            "a deleted session must stay deleted across restarts"
        );
        assert!(again.list().unwrap().is_empty());
    }

    #[test]
    fn a_legacy_transcript_is_imported_once_and_the_file_is_kept() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("sessions");
        let body = format!(
            "{}{}",
            line(&Message::user("from the old world"), 1_700_000_000_000),
            line(&Message::assistant("and the reply"), 1_700_000_001_000)
        );
        let path = legacy_file(&root, "legacy-1", &body);
        std::fs::write(root.join("legacy-1.meta.json"), r#"{"title":"old title"}"#).unwrap();

        let store = SessionStore::new(&root);
        let messages = store.load("legacy-1").unwrap();
        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0].content.as_deref(), Some("from the old world"));
        assert_eq!(
            store.title("legacy-1").unwrap().as_deref(),
            Some("old title")
        );
        assert!(path.exists(), "importing must not delete the source");

        let info = store.list().unwrap().into_iter().next().unwrap();
        assert_eq!(info.preview, "from the old world");
        assert_eq!(info.updated_ms, 1_700_000_001_000);

        // A second handle over the same directory finds it already imported, not doubled.
        drop(store);
        let again = SessionStore::new(&root);
        assert_eq!(again.load("legacy-1").unwrap().len(), 2);
        assert_eq!(again.list().unwrap().len(), 1);
    }

    #[test]
    fn a_truncated_legacy_tail_is_dropped_and_the_rest_is_imported() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("sessions");
        let good = line(&Message::user("complete"), 1_700_000_000_000);
        let body = format!("{good}{{\"ts\":1,\"message\":{{\"role\":\"user\"");
        legacy_file(&root, "half-written", &body);
        let store = SessionStore::new(&root);
        let messages = store.load("half-written").unwrap();
        assert_eq!(messages.len(), 1, "the complete record survived");
        assert_eq!(messages[0].content.as_deref(), Some("complete"));
    }

    #[test]
    fn a_complete_final_record_without_a_newline_is_kept() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("sessions");
        let body = line(&Message::user("no trailing newline"), 5)
            .trim_end()
            .to_string();
        legacy_file(&root, "unterminated", &body);
        let store = SessionStore::new(&root);
        assert_eq!(store.load("unterminated").unwrap().len(), 1);
    }

    #[test]
    fn a_legacy_file_corrupt_in_the_middle_is_refused_not_half_imported() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("sessions");
        let body = format!(
            "{}garbage\n{}",
            line(&Message::user("before"), 1),
            line(&Message::assistant("after"), 2)
        );
        let path = legacy_file(&root, "corrupt-mid", &body);
        let store = SessionStore::new(&root);
        assert!(
            !store.exists("corrupt-mid"),
            "importing part of it would silently drop a message"
        );
        assert!(path.exists(), "and the file is left for a human to look at");
        assert!(store.list().unwrap().is_empty());
    }

    #[test]
    fn an_empty_legacy_transcript_keeps_its_file_time_not_epoch() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("sessions");
        legacy_file(&root, "empty-one", "");
        let store = SessionStore::new(&root);
        let info = store.list().unwrap().into_iter().next().unwrap();
        assert_eq!(info.messages, 0);
        assert!(
            info.updated_ms > 1_600_000_000_000,
            "a corrupt transcript still ages from its mtime, not from 1970: {}",
            info.updated_ms
        );
    }

    #[test]
    fn a_legacy_memory_sidecar_is_imported() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("sessions");
        legacy_file(
            &root,
            "with-memory",
            &line(&Message::user("hi"), 1_700_000_000_000),
        );
        let m = memory("remembered from before", 2, 4);
        std::fs::write(
            root.join("with-memory.memory.json"),
            serde_json::to_string(&m).unwrap(),
        )
        .unwrap();
        let store = SessionStore::new(&root);
        assert_eq!(store.readable_memory("with-memory"), Some(m));
    }

    #[test]
    fn an_unparseable_legacy_memory_sidecar_is_imported_and_reported() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("sessions");
        legacy_file(
            &root,
            "bad-memory",
            &line(&Message::user("hi"), 1_700_000_000_000),
        );
        // Truncated JSON: the import has to fail loudly rather than invent an empty record.
        std::fs::write(
            root.join("bad-memory.memory.json"),
            r#"{"version":3,"handoff":{"#,
        )
        .unwrap();
        let store = SessionStore::new(&root);
        assert!(
            store.memory("bad-memory").is_err(),
            "an unparseable sidecar is an error to read, not silence"
        );
        assert_eq!(store.readable_memory("bad-memory"), None);
    }

    // ---- search ----------------------------------------------------------------

    #[test]
    fn search_finds_message_text_and_tool_arguments() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        store
            .append(&id, &Message::user("the deploy key lives in vault"))
            .unwrap();
        store
            .append(
                &id,
                &Message::assistant_tool_calls(
                    None,
                    vec![call("c9", "shell", r#"{"cmd":"systemctl status nginx"}"#)],
                ),
            )
            .unwrap();
        let other = store.new_id();
        store.append(&other, &Message::user("unrelated")).unwrap();

        let hits = store.search("vault", 10).unwrap();
        assert_eq!(hits.len(), 1, "{hits:?}");
        assert_eq!(hits[0].session_id, id);
        assert_eq!(hits[0].seq, 0);
        assert_eq!(hits[0].role, "user");
        assert!(hits[0].snippet.contains("vault"));

        let hits = store.search("nginx", 10).unwrap();
        assert_eq!(hits.len(), 1, "tool arguments are searchable: {hits:?}");
        assert_eq!(hits[0].seq, 1);

        assert!(store.search("nothing-said-this", 10).unwrap().is_empty());
        assert!(store.search("   ", 10).unwrap().is_empty());
    }

    /// A delete that fails halfway leaves the session alone.
    ///
    /// The index delete is made to fail (here: the index table is gone, which is what a corrupt or
    /// read-only index looks like from the caller's side). On a delete split across two unguarded
    /// statements the session row is already gone by then — by way of `ON DELETE CASCADE`, its
    /// messages too — so the caller is told the delete failed while it has in fact half-happened.
    /// Inside one transaction the rollback takes it back.
    #[test]
    fn a_delete_that_fails_halfway_leaves_the_session_alone() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        store
            .append(&id, &Message::user("an undeletable mention of widget"))
            .unwrap();
        if !store.with_db(|db| Ok(db.fts)).unwrap() {
            return; // nothing to fail without an index
        }
        store
            .with_db(|db| {
                db.conn.execute_batch("DROP TABLE messages_fts")?;
                Ok(())
            })
            .unwrap();

        assert!(
            store.delete(&id).is_err(),
            "the failed delete is reported to the caller"
        );

        store
            .with_db(|db| {
                let sessions: i64 = db.conn.query_row(
                    "SELECT count(*) FROM sessions WHERE id = ?1",
                    params![id],
                    |r| r.get(0),
                )?;
                assert_eq!(
                    sessions, 1,
                    "a delete that failed must not have half-happened"
                );
                let messages: i64 = db.conn.query_row(
                    "SELECT count(*) FROM messages WHERE session_id = ?1",
                    params![id],
                    |r| r.get(0),
                )?;
                assert_eq!(messages, 1, "its messages are still there too");
                Ok(())
            })
            .unwrap();

        // And a second delete is not confused by the corpse: it still reports the session as live.
        assert!(store.delete(&id).is_err());
    }

    /// A stale index row is not a search failure. Index entries can outlive the messages they name —
    /// written by a build whose delete was two statements, or by a crash between them — and the old
    /// `hit()` turned the first such row into an error that took every other hit with it.
    #[test]
    fn a_stale_index_row_is_skipped_rather_than_failing_the_search() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        store
            .append(&id, &Message::user("the live mention of widget"))
            .unwrap();

        // Simulate the half-deleted past: the message goes, its index row stays.
        store
            .with_db(|db| {
                db.conn
                    .execute("DELETE FROM messages WHERE session_id = ?1", params![id])?;
                Ok(())
            })
            .unwrap();

        let hits = store.search("widget", 10).unwrap();
        assert!(
            hits.is_empty(),
            "the orphan is dropped, not fatal: {hits:?}"
        );
    }

    /// Deleting a session takes its messages and its index rows together, in one transaction.
    #[test]
    fn deleting_a_session_leaves_nothing_of_it_behind() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        store
            .append(&id, &Message::user("a deletable mention of widget"))
            .unwrap();
        let keep = store.new_id();
        store
            .append(&keep, &Message::user("a kept mention of widget"))
            .unwrap();

        store.delete(&id).unwrap();

        store
            .with_db(|db| {
                let messages: i64 = db.conn.query_row(
                    "SELECT count(*) FROM messages WHERE session_id = ?1",
                    params![id],
                    |r| r.get(0),
                )?;
                assert_eq!(messages, 0, "messages go with the session");
                if db.fts {
                    let indexed: i64 = db.conn.query_row(
                        "SELECT count(*) FROM messages_fts WHERE session_id = ?1",
                        params![id],
                        |r| r.get(0),
                    )?;
                    assert_eq!(indexed, 0, "and so does the index, in the same transaction");
                }
                Ok(())
            })
            .unwrap();

        let hits = store.search("widget", 10).unwrap();
        assert_eq!(hits.len(), 1, "the other session is untouched: {hits:?}");
        assert_eq!(hits[0].session_id, keep);
        assert!(
            store.delete(&id).is_err(),
            "deleting it twice still says there is no such session"
        );
    }

    /// Both backends answer "newest first". Without the ORDER BY, FTS5 answers in rowid order — which
    /// is insertion order — so a `LIMIT` cut the oldest hits and two installs disagreed.
    #[test]
    fn search_answers_newest_first_whichever_backend_runs() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let older = store.new_id();
        store
            .append(&older, &Message::user("the older mention of gadget"))
            .unwrap();
        // Distinct milliseconds: `at_ms` is the write time, and a tie would make the assertion
        // about the tie-breaker rather than about recency.
        std::thread::sleep(std::time::Duration::from_millis(3));
        let newer = store.new_id();
        store
            .append(&newer, &Message::user("the newer mention of gadget"))
            .unwrap();

        store
            .with_db(|db| {
                for use_fts in [true, false] {
                    if use_fts && !db.fts {
                        continue;
                    }
                    let hits = SessionStore::search_in(db, "gadget", 1, use_fts, false).unwrap();
                    assert_eq!(hits.len(), 1, "fts={use_fts}");
                    assert_eq!(
                        hits[0].session_id, newer,
                        "a limit of one has to take the newest hit, not the first rowid (fts={use_fts})"
                    );
                }
                Ok(())
            })
            .unwrap();
    }

    #[test]
    fn search_treats_percent_and_underscore_as_text_not_wildcards() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        store
            .append(&id, &Message::user("disk is 100% full"))
            .unwrap();
        store
            .append(&id, &Message::user("disk is 100 percent full"))
            .unwrap();
        store
            .append(&id, &Message::user("the file a_b.txt is here"))
            .unwrap();
        store
            .append(&id, &Message::user("the file axb.txt is not"))
            .unwrap();

        // The fallback is the branch that can promise substrings, so this is the branch where a
        // wildcard would be a lie. (FTS5 is token-based: it would match `100` inside `100 percent`,
        // which is its documented behaviour, not a wildcard.)
        store
            .with_db(|db| {
                let percent = SessionStore::search_in(db, "100%", 10, false, false).unwrap();
                assert_eq!(
                    percent.len(),
                    1,
                    "`100%` is a substring, not `100` plus a wildcard: {percent:?}"
                );
                assert!(percent[0].snippet.contains("100% full"));

                let underscore = SessionStore::search_in(db, "a_b.txt", 10, false, false).unwrap();
                assert_eq!(
                    underscore.len(),
                    1,
                    "`_` is a character, not any character: {underscore:?}"
                );
                assert!(underscore[0].snippet.contains("a_b.txt"));
                Ok(())
            })
            .unwrap();
    }

    /// The escaping itself, where it can be seen: `\`, `%` and `_` each gain one backslash, and the
    /// query's `ESCAPE '\'` is what makes them text again.
    #[test]
    fn a_like_literal_escapes_every_wildcard_character() {
        assert_eq!(like_literal("plain"), "plain");
        assert_eq!(like_literal("100%"), r"100\%");
        assert_eq!(like_literal("a_b"), r"a\_b");
        assert_eq!(like_literal(r"C:\temp"), r"C:\\temp");
    }

    #[test]
    fn search_survives_query_syntax_that_would_break_fts() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        store
            .append(&id, &Message::user(r#"a "quoted" thing AND (parens)"#))
            .unwrap();
        // If these raised, a search box would be a place where users meet SQL errors.
        for q in [r#""quoted""#, "AND (parens)", "*", "a AND OR NOT", "-x"] {
            let _ = store.search(q, 5).unwrap();
        }
        assert_eq!(store.search("quoted", 5).unwrap().len(), 1);
    }

    #[test]
    fn search_results_carry_the_session_and_position() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        transcript(&store, &id);
        let hits = store.search("contents", 10).unwrap();
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].session_id, id);
        assert_eq!(hits[0].seq, 2, "the tool result is the third message");
        assert_eq!(hits[0].role, "tool");
        assert!(hits[0].at_ms > 0);
    }

    #[test]
    fn a_subagent_session_says_where_it_came_from_and_a_native_one_does_not() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let parent = store.new_id();
        let child = store.new_id();
        store.append(&parent, &Message::user("big job")).unwrap();
        store.begin_subagent(&child, &parent, "big:v2").unwrap();
        store.append(&child, &Message::user("sub job")).unwrap();

        let list = store.list().unwrap();
        let find = |id: &str| list.iter().find(|s| s.id == id).unwrap();
        assert_eq!(find(&parent).origin, "native");
        assert!(find(&parent).subagent().is_none());
        let origin = find(&child).subagent().unwrap();
        assert_eq!((origin.parent, origin.route), (parent.as_str(), "big:v2"));
        assert_eq!(
            find(&child).preview,
            "sub job",
            "the first message still names it"
        );
    }

    #[test]
    fn beginning_a_subagent_twice_keeps_the_first_origin() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        store.begin_subagent("c1", "p1", "big").unwrap();
        store.begin_subagent("c1", "p2", "other").unwrap();
        let info = store.list().unwrap().remove(0);
        assert_eq!(info.subagent().unwrap().parent, "p1");
        assert!(store.begin_subagent("c2", "../p", "big").is_err());
    }

    /// An API call is a run, not a conversation: it is tagged before the loop writes to it, so the
    /// row does not arrive as `native` and cannot be mistaken for something a person typed.
    #[test]
    fn an_api_session_keeps_its_tag_when_the_run_writes_to_it() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        store.begin_api(&id).unwrap();
        store.append(&id, &Message::user("ask")).unwrap();
        store.append(&id, &Message::assistant("answer")).unwrap();

        let info = store.list().unwrap().remove(0);
        assert_eq!(info.id, id);
        assert_eq!(info.origin, SessionStore::API_ORIGIN);
        assert!(info.subagent().is_none(), "tagged, not a child");
        assert_eq!(info.messages, 2, "and the transcript is really there");
    }

    /// The sweep is what keeps a polling script from filling the store: it takes the API's own old
    /// sessions, and nothing else. A session a person started, or pinned, is not the API's.
    #[test]
    fn the_sweep_takes_old_api_sessions_and_leaves_the_rest() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());

        let old_api = store.new_id();
        store.begin_api(&old_api).unwrap();
        store.append(&old_api, &Message::user("poll")).unwrap();

        let mine = store.new_id();
        store
            .append(&mine, &Message::user("a real conversation"))
            .unwrap();

        let pinned_api = store.new_id();
        store.begin_api(&pinned_api).unwrap();
        store
            .append(&pinned_api, &Message::user("keep me"))
            .unwrap();
        store.set_pinned(&pinned_api, true).unwrap();

        let pruned = store.prune_api_sessions(now_ms() + 1).unwrap();
        assert_eq!(pruned, 1, "only the API's own, unpinned session");
        let left: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
        assert!(
            left.contains(&mine),
            "a conversation is never swept: {left:?}"
        );
        assert!(left.contains(&pinned_api), "a pin is a decision: {left:?}");
        assert!(!left.contains(&old_api), "{left:?}");
    }

    /// A cutoff in the future is the same sweep; a cutoff of zero takes everything the API left,
    /// and a store with no API sessions is untouched.
    #[test]
    fn the_sweep_is_empty_when_there_is_nothing_the_api_left() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        store.append("n1", &Message::user("hello")).unwrap();
        assert_eq!(store.prune_api_sessions(u64::MAX).unwrap(), 0);
        assert_eq!(store.list().unwrap().len(), 1);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn only_a_session_a_live_run_holds_is_reported_as_held() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let wait = std::time::Duration::from_millis(0);
        let live = store.lock("live", wait).await.unwrap();
        // A finished run leaves its lock file behind; the OS has dropped the lock itself.
        drop(store.lock("finished", wait).await.unwrap());

        let held = held_locks(store.dir());
        assert_eq!(held.len(), 1, "{held:?}");
        assert_eq!(held[0].id, "live");
        assert!(held[0].holder.starts_with("pid "), "{held:?}");

        drop(live);
        assert!(held_locks(store.dir()).is_empty());
        assert!(held_locks(&dir.path().join("no-such-dir")).is_empty());
    }

    fn picture_message(text: Option<&str>, name: &str) -> Message {
        let mut m = match text {
            Some(t) => Message::user(t),
            None => Message {
                role: Role::User,
                content: None,
                reasoning: None,
                finish_reason: None,
                tool_calls: Vec::new(),
                tool_call_id: None,
                images: Vec::new(),
                seq: None,
            },
        };
        m.images.push(crate::message::ImagePart {
            name: name.into(),
            mime: "image/png".into(),
            url: "data:image/png;base64,AAAA".into(),
            seen: None,
        });
        m
    }

    /// `#384`: a write that changed nothing says so, and the write itself is one transaction — the
    /// body and the index cannot disagree after a crash between them.
    #[test]
    fn describing_a_picture_reports_whether_it_changed_anything() {
        let dir = tempfile::tempdir().unwrap();
        let store = SessionStore::new(dir.path().to_path_buf());
        let id = store.new_id();
        let seq = store
            .append_seq(&id, &picture_message(Some("look"), "shot.png"))
            .unwrap();
        assert!(
            store
                .set_image_seen(&id, seq as u64, 0, "a dashboard with a red chart")
                .unwrap(),
            "a picture that is there was described"
        );
        // The description is part of what the session says, so a search finds it.
        let hits = store.search("red chart", 5).unwrap();
        assert_eq!(hits.len(), 1, "the description is searchable: {hits:?}");
        // A second write of the same description is still a write: the picture exists.
        assert!(store.set_image_seen(&id, seq as u64, 0, "again").unwrap());
        // A message that is not there is not a write, and not an error either.
        assert!(
            !store.set_image_seen(&id, 999, 0, "nowhere").unwrap(),
            "a missing row used to answer Ok(()) — a caller could not tell it from a write"
        );
        // Nor is a picture index the message does not have.
        assert!(!store.set_image_seen(&id, seq as u64, 7, "no").unwrap());
    }

    /// `#388`: a first user row that says nothing must not take the preview slot, because the
    /// listing only fills a NULL and would show an empty title for the rest of the session.
    #[test]
    fn a_first_message_with_no_text_does_not_freeze_the_preview() {
        let dir = tempfile::tempdir().unwrap();
        let store = SessionStore::new(dir.path().to_path_buf());
        let id = store.new_id();
        // `Some("")`, not `None`: empty text is what an embedder sends beside a picture, and it is
        // the case that stored `""` — a `None` content already left the column NULL.
        store
            .append(&id, &picture_message(Some(""), "shot.png"))
            .unwrap();
        store
            .append(&id, &Message::user("actually, summarise yesterday"))
            .unwrap();
        let listed = store.list().unwrap();
        let row = listed.iter().find(|s| s.id == id).expect("listed");
        assert_eq!(
            row.preview.as_str(),
            "actually, summarise yesterday",
            "the first empty row took the preview: {:?}",
            row.preview
        );
    }

    // ---------------------------------------------------------------------------------------
    // `#509`: a bot's conversation is a session with `origin = bot:<name>` — the store, the
    // compaction, the cost ledger and this listing are reused, so the tests here hold the two
    // places the identity changes what the listing answers: whose list it is in, and what a
    // search returns.
    // ---------------------------------------------------------------------------------------

    #[test]
    fn a_bot_conversation_is_not_in_the_humans_list() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let mine = store.new_id();
        store
            .append(&mine, &Message::user("the human asked this"))
            .unwrap();
        let theirs = store.bot_session("nox").unwrap();
        store
            .append(&theirs, &Message::user("the bot said this"))
            .unwrap();

        let listed: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
        assert_eq!(
            listed,
            vec![mine.clone()],
            "a bot's conversation left the sidebar alone"
        );

        // Archived ones are the other filter, and it does not smuggle bots back in.
        let archived: Vec<String> = store
            .list_with_archived()
            .unwrap()
            .into_iter()
            .map(|s| s.id)
            .collect();
        assert_eq!(archived, vec![mine], "`show archived` is not `show bots`");
    }

    #[test]
    fn list_bots_groups_every_conversation_under_its_name() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let first = store.bot_session("nox").unwrap();
        store.append(&first, &Message::user("one")).unwrap();
        // Cleared, then opened again: two conversations, one identity.
        for id in store.bot_sessions("nox").unwrap() {
            store.set_archived(&id, true).unwrap();
        }
        let second = store.bot_session("nox").unwrap();
        assert_ne!(
            first, second,
            "a cleared conversation is not the one reopened"
        );
        store.append(&second, &Message::user("two")).unwrap();

        // Another bot, and a human, so the grouping has something to leave out.
        let other = store.bot_session("lux").unwrap();
        store.append(&other, &Message::user("three")).unwrap();
        let mine = store.new_id();
        store.append(&mine, &Message::user("four")).unwrap();

        let bots = store.list_bots().unwrap();
        assert_eq!(bots.len(), 2, "one row per identity: {bots:?}");
        assert_eq!(bots[0].name, "lux", "newest activity first");
        let nox = bots.iter().find(|b| b.name == "nox").unwrap();
        assert_eq!(nox.sessions, 2, "both conversations counted");
        assert_eq!(nox.last_session, second, "the row opens the newest");
        assert_eq!(nox.messages, 1);
        assert!(
            !nox.archived,
            "one archived conversation is not a cleared bot"
        );
    }

    /// Two rows written in the same millisecond tie on `updated_ms`, and the tiebreak used to be
    /// `id DESC` — text, where `…-9` sorts above `…-10`. CI caught it once: a *cleared* bot
    /// conversation was listed as the bot's live one over the conversation opened after it. The
    /// tiebreak is the order the rows were stored in, so this holds for `sessions list` too.
    #[test]
    fn two_sessions_in_the_same_millisecond_are_ordered_by_when_they_were_stored() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        store.list().unwrap(); // the store exists before a row is written into it
        let at = 1_796_297_799_945_i64;
        // The pair the failure printed, and a human pair whose text order is the wrong way round.
        let rows = [
            ("1796297799945-11001-9", "bot:nox"),
            ("1796297799945-11001-10", "bot:nox"),
            ("1796297799945-11001-2", "native"),
            ("1796297799945-11001-11", "native"),
        ];
        store
            .with_db(|db| {
                for (id, origin) in rows {
                    db.conn.execute(
                        "INSERT INTO sessions (id, created_ms, updated_ms, messages, origin)
                         VALUES (?1, ?2, ?3, 1, ?4)",
                        params![id, at, at, origin],
                    )?;
                }
                Ok(())
            })
            .unwrap();

        let listed: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
        assert_eq!(
            listed,
            ["1796297799945-11001-11", "1796297799945-11001-2"],
            "a tie is broken by which row was stored later, not by its text"
        );

        let nox = store
            .list_bots()
            .unwrap()
            .into_iter()
            .find(|b| b.name == "nox")
            .expect("the bot's two conversations");
        assert_eq!(nox.sessions, 2);
        assert_eq!(
            nox.last_session, "1796297799945-11001-10",
            "the conversation opened second is the live one"
        );
    }

    #[test]
    fn a_search_leaves_a_bots_conversation_out_unless_asked() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let mine = store.new_id();
        store
            .append(&mine, &Message::user("the vault code is in the drawer"))
            .unwrap();
        let bots = store.bot_session("nox").unwrap();
        store
            .append(&bots, &Message::user("the vault code is on the lane"))
            .unwrap();

        let found = store.search("vault", 10).unwrap();
        assert_eq!(
            found.len(),
            1,
            "the human's search found a bot's row: {found:?}"
        );
        assert_eq!(found[0].session_id, mine);

        let asked = store.search_with("vault", 10, true).unwrap();
        assert_eq!(
            asked.len(),
            2,
            "`bots = true` is how a bot's rows are asked for"
        );
        assert!(asked.iter().any(|h| h.session_id == bots));

        // A name search is the other half of the query: it must not leak one either.
        store
            .set_title(&bots, "never mention the vault", TitleSource::User)
            .unwrap();
        let named = store.search("never", 10).unwrap();
        assert!(
            named.is_empty(),
            "a bot's title answered the human's search: {named:?}"
        );
        let named = store.search_with("never", 10, true).unwrap();
        assert_eq!(named.len(), 1);
    }

    #[test]
    fn a_title_is_never_claimed_for_a_bot() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let mine = store.new_id();
        store.append(&mine, &Message::user("hello")).unwrap();
        store
            .set_title(&mine, "derived name", TitleSource::Derived)
            .unwrap();
        assert!(
            store.claim_title_upgrade(&mine).unwrap(),
            "a person's conversation may be named by a model"
        );

        let bots = store.bot_session("nox").unwrap();
        store.append(&bots, &Message::user("hello")).unwrap();
        store
            .set_title(&bots, "derived name", TitleSource::Derived)
            .unwrap();
        assert!(
            !store.claim_title_upgrade(&bots).unwrap(),
            "a naming call per turn is the cost this rule exists to avoid"
        );
    }

    #[test]
    fn a_bot_conversation_says_which_bot_it_belongs_to() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.bot_session("nox").unwrap();
        store.append(&id, &Message::user("hello")).unwrap();
        // The row's own `origin` is where the send path reads the identity from, so that is what
        // is asserted on the store: one string, and a name that survives being spelled back into
        // a URL and a prompt.
        assert_eq!(store.origin(&id).unwrap().as_deref(), Some("bot:nox"));

        let info = SessionInfo {
            id,
            messages: 1,
            updated_ms: 0,
            preview: "hello".into(),
            title: None,
            origin: "bot:nox".into(),
            pinned: false,
            archived: false,
            cost: None,
        };
        assert_eq!(info.bot(), Some("nox"));
        assert!(info.is_bot());
        assert!(info.subagent().is_none());
        assert!(
            info.tagged_label().starts_with("[bot \u{b7} nox]"),
            "{}",
            info.tagged_label()
        );

        // A name with a colon in it is not a name: the origin parser refuses it rather than
        // reading it as two.
        let odd = SessionInfo {
            origin: "bot:a:b".to_string(),
            ..info
        };
        assert_eq!(odd.bot(), None);
        // An empty name is the other mistake: `bot:` with nobody behind it.
        let empty = SessionInfo {
            origin: "bot:".to_string(),
            ..odd
        };
        assert_eq!(empty.bot(), None);
    }

    // ---------------------------------------------------------------------------------------
    // `#171`: a flare run is N sessions with `origin = "flare:<run>:<n>"`, and the position in
    // that string is what a run listing orders by and what the lead's result cites.
    // ---------------------------------------------------------------------------------------

    #[test]
    fn a_flare_run_is_a_set_of_sessions_with_their_positions() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let run = "f-1";
        // Started out of order on purpose: the run starts them in whatever order slots free up,
        // and the listing still reads 1..N.
        let mut ids = Vec::new();
        for n in [2usize, 1, 3] {
            let id = store.new_id();
            store.begin_flare(&id, run, n).unwrap();
            store
                .append(&id, &Message::user(format!("flare {n} reading")))
                .unwrap();
            ids.push((n, id));
        }

        let listed = store.flares_of(run).unwrap();
        assert_eq!(
            listed
                .iter()
                .filter_map(|s| s.flare().map(|f| f.n))
                .collect::<Vec<_>>(),
            vec![1, 2, 3],
            "the run's order is the lead's order, not the order they finished"
        );
        assert_eq!(listed[0].flare().unwrap().run, run);
        assert!(
            listed[0].tagged_label().starts_with("[flare \u{b7} f-1/1]"),
            "{}",
            listed[0].tagged_label()
        );
        // A flare is not a subagent and not a bot: three prefixes, three answers.
        assert!(listed[0].subagent().is_none());
        assert!(!listed[0].is_bot());

        // Another run's flares are not this run's.
        let other = store.new_id();
        store.begin_flare(&other, "f-2", 1).unwrap();
        assert_eq!(store.flares_of(run).unwrap().len(), 3);

        // A run id carries no colon, because the position is the last field.
        let bad = store.new_id();
        assert!(store.begin_flare(&bad, "f:1", 1).is_err());
        // A row whose tail is not a number is not a flare this build wrote.
        let odd = SessionInfo {
            origin: "flare:run:two".into(),
            ..listed[0].clone()
        };
        assert!(odd.flare().is_none());
        assert!(SessionInfo {
            origin: "flare::1".into(),
            ..listed[0].clone()
        }
        .flare()
        .is_none());
    }

    #[test]
    fn a_search_leaves_a_flares_transcript_out_unless_asked() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let mine = store.new_id();
        store
            .append(&mine, &Message::user("the retry loop is in worker.rs"))
            .unwrap();
        let flare = store.new_id();
        store.begin_flare(&flare, "f-9", 1).unwrap();
        store
            .append(&flare, &Message::user("the retry loop is in pool.rs"))
            .unwrap();

        let found = store.search("retry", 10).unwrap();
        assert_eq!(found.len(), 1, "the human found a flare's row: {found:?}");
        assert_eq!(found[0].session_id, mine);

        let asked = store.search_with("retry", 10, true).unwrap();
        assert_eq!(
            asked.len(),
            2,
            "`children = true` is how those rows are asked for"
        );
    }

    #[test]
    fn a_flare_is_never_named_by_a_model() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        store.begin_flare(&id, "f-3", 1).unwrap();
        store.append(&id, &Message::user("reading")).unwrap();
        store
            .set_title(&id, "derived name", TitleSource::Derived)
            .unwrap();
        assert!(
            !store.claim_title_upgrade(&id).unwrap(),
            "a transient worker does not get a paid naming call"
        );
    }

    /// Make the named statement fail, the way a crash or a full disk lands between two writes: a
    /// trigger on the second half of a pair the code claims is atomic (`#565`).
    fn refuse(store: &SessionStore, on: &str) {
        store
            .with_db(|db| {
                db.conn.execute_batch(&format!(
                    "CREATE TRIGGER refused {on} BEGIN SELECT RAISE(ABORT, 'refused by the test'); END"
                ))?;
                Ok(())
            })
            .unwrap();
    }

    /// `#565`: `clear_goal` is two deletes under a comment claiming they were one. The second one
    /// is refused here, which is where a crash lands: with autocommit the goal had already gone
    /// and its judgements were left behind, to be inherited by the next goal this session sets.
    #[test]
    fn a_goal_clear_that_fails_on_its_last_delete_clears_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        let goal =
            crate::goals::Goal::new(&id, "ship the release", None, Some(5), 1_700_000_000_000);
        store.set_goal(&goal).unwrap();
        store
            .record_goal_turn(
                &id,
                &crate::goals::Judgement {
                    turn: 1,
                    verdict: "continue".into(),
                    why: None,
                    at_ms: 1_700_000_000_001,
                },
            )
            .unwrap();
        refuse(&store, "BEFORE DELETE ON goal_turns");

        assert!(
            store.clear_goal(&id).is_err(),
            "the second delete was refused, so the clear cannot report itself as done"
        );
        assert!(
            store.goal(&id).unwrap().is_some(),
            "the goal went on its own, leaving its judgements for the next goal to inherit"
        );
        assert_eq!(
            store.goal_turns(&id).unwrap().len(),
            1,
            "the judgements of a goal that was not cleared"
        );
    }

    /// `#565`: `set_goal` writes the session row and then the goal. Written apart, a failure
    /// between them left a session nobody opened, listed as an empty conversation; the row is
    /// there for the goal, so it goes with it.
    #[test]
    fn a_goal_that_cannot_be_saved_does_not_leave_a_session_behind() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        refuse(&store, "BEFORE INSERT ON goals");

        let goal = crate::goals::Goal::new(&id, "ship the release", None, None, 1_700_000_000_000);
        assert!(store.set_goal(&goal).is_err(), "the goal write was refused");

        let rows: i64 = store
            .with_db(|db| {
                Ok(db.conn.query_row(
                    "SELECT COUNT(*) FROM sessions WHERE id = ?1",
                    params![id],
                    |r| r.get(0),
                )?)
            })
            .unwrap();
        assert_eq!(
            rows, 0,
            "the session row outlived the goal it was written for"
        );
    }

    /// `#565`: the answer on an `approvals` row and its `approval_log` entry are one act — the
    /// comment there said "written in the same transaction as the answer" and the code used two
    /// autocommit statements. When the log row cannot be written, the answer must not be left
    /// behind: the row is deleted once the answer is in the transcript, and "who let this
    /// through" would then have no answer at all.
    #[test]
    fn a_ruling_that_cannot_be_logged_does_not_land() {
        let dir = tempfile::tempdir().unwrap();
        let store = store(dir.path());
        let id = store.new_id();
        store.append(&id, &Message::user("run it")).unwrap();
        store
            .record_pending(
                &id,
                1,
                &[crate::approvals::Pending::new(
                    "c1",
                    "shell",
                    "rm -rf build".into(),
                    "{}".into(),
                )],
            )
            .unwrap();
        refuse(&store, "BEFORE INSERT ON approval_log");

        assert!(store
            .decide_pending(&id, 1, 0, &crate::approvals::Decision::Allow, "user")
            .is_err());

        let rows = store.pending_calls(&id).unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(
            rows[0].decision, None,
            "the answer landed without the log row that says who gave it"
        );
    }
}