ironbridge-cli 2.0.1

Universal chat session manager - harvest, merge, and analyze AI chat history from VS Code, Cursor, and other editors
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
// Copyright (c) 2024-2026 Nervosys LLC
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-IronBridge-Commercial
//! Write and query endpoints the web UI depends on.
//!
//! These back the twelve calls `ironbridge-web` was making against routes that did
//! not exist, so most of the Chat page returned 404 for every action.
//!
//! Everything here targets the *harvest* schema -- `sessions` carrying a
//! `session_json` blob, with messages living inside `session_json.requests` --
//! because that is what the existing read handlers in `handlers_simple` parse.
//! Writing to the normalized `messages` table from `sql/schema.sql` instead
//! would produce rows that `GET /api/sessions/{id}` cannot see, which is worse
//! than not implementing the endpoint at all.

use actix_web::{http::StatusCode, web, HttpResponse, Responder};
use rusqlite::{params, Connection, OptionalExtension};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use super::state::AppState;

// =============================================================================
// Response helpers
// =============================================================================

/// Same envelope `handlers_simple` uses -- the client unwraps `{success, data}`
/// -- but with a status code that matches what actually happened. The existing
/// helper answers 500 for everything, which turns "no such session" into "the
/// server is broken".
#[derive(Serialize)]
struct Envelope<T> {
    success: bool,
    data: Option<T>,
    error: Option<String>,
}

fn ok<T: Serialize>(data: T) -> HttpResponse {
    HttpResponse::Ok().json(Envelope {
        success: true,
        data: Some(data),
        error: None,
    })
}

fn created<T: Serialize>(data: T) -> HttpResponse {
    HttpResponse::Created().json(Envelope {
        success: true,
        data: Some(data),
        error: None,
    })
}

fn fail(status: StatusCode, message: impl AsRef<str>) -> HttpResponse {
    HttpResponse::build(status).json(Envelope::<()> {
        success: false,
        data: None,
        error: Some(message.as_ref().to_string()),
    })
}

fn not_found(what: &str) -> HttpResponse {
    fail(StatusCode::NOT_FOUND, format!("{what} not found"))
}

fn db_error(e: impl std::fmt::Display) -> HttpResponse {
    fail(
        StatusCode::INTERNAL_SERVER_ERROR,
        format!("Database error: {e}"),
    )
}

fn now_secs() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

// =============================================================================
// Sessions
// =============================================================================

#[derive(Deserialize)]
pub struct CreateSessionBody {
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub provider: Option<String>,
    #[serde(default, alias = "workspaceId")]
    pub workspace_id: Option<String>,
    #[serde(default, alias = "workspacePath")]
    pub workspace_path: Option<String>,
    #[serde(default)]
    pub model: Option<String>,
}

/// `POST /api/sessions`
pub async fn create_session(
    state: web::Data<AppState>,
    body: web::Json<CreateSessionBody>,
) -> impl Responder {
    let db = state.db.lock().unwrap();
    let id = uuid::Uuid::new_v4().to_string();
    let now = now_secs();
    let title = body.title.clone().unwrap_or_else(|| "New session".into());
    let provider = body.provider.clone().unwrap_or_else(|| "ironbridge".into());

    // An empty `requests` array is the shape the read path expects; a session
    // with a NULL or absent blob deserializes to no messages and then every
    // append has to special-case it.
    let session_json = json!({
        "requests": [],
        "creationDate": now,
        "model": body.model,
    });

    let inserted = db.conn.execute(
        "INSERT INTO sessions
            (id, provider, workspace_id, workspace_path, title, message_count,
             created_at, updated_at, harvested_at, session_json)
         VALUES (?1, ?2, ?3, ?4, ?5, 0, ?6, ?6, ?6, ?7)",
        params![
            id,
            provider,
            body.workspace_id,
            body.workspace_path,
            title,
            now,
            session_json.to_string(),
        ],
    );

    match inserted {
        Ok(_) => created(json!({
            "id": id,
            "title": title,
            "provider": provider,
            "workspace_id": body.workspace_id,
            "workspace_path": body.workspace_path,
            "message_count": 0,
            "created_at": now,
            "updated_at": now,
            "messages": [],
        })),
        Err(e) => db_error(e),
    }
}

/// `DELETE /api/sessions/{id}`
pub async fn delete_session(state: web::Data<AppState>, path: web::Path<String>) -> impl Responder {
    let db = state.db.lock().unwrap();
    let id = path.into_inner();

    // messages_v2 has no ON DELETE CASCADE in the harvest schema, so orphan
    // rows would survive the session and inflate every message count.
    if table_exists(&db.conn, "messages_v2") {
        if let Err(e) = db
            .conn
            .execute("DELETE FROM messages_v2 WHERE session_id = ?1", params![id])
        {
            return db_error(e);
        }
    }

    match db
        .conn
        .execute("DELETE FROM sessions WHERE id = ?1", params![id])
    {
        Ok(0) => not_found("Session"),
        Ok(_) => ok(json!({ "id": id, "deleted": true })),
        Err(e) => db_error(e),
    }
}

#[derive(Deserialize)]
pub struct CreateMessageBody {
    #[serde(default)]
    pub role: Option<String>,
    #[serde(default)]
    pub content: Option<String>,
    #[serde(default, alias = "modelId")]
    pub model_id: Option<String>,
}

/// `POST /api/sessions/{id}/messages`
///
/// Appends into `session_json.requests` in the shape
/// `extract_messages_from_session` reads back: one request object holds a user
/// message and the assistant response to it. An assistant message therefore
/// attaches to the trailing request rather than starting a new one.
pub async fn create_message(
    state: web::Data<AppState>,
    path: web::Path<String>,
    body: web::Json<CreateMessageBody>,
) -> impl Responder {
    let db = state.db.lock().unwrap();
    let session_id = path.into_inner();

    let content = body.content.clone().unwrap_or_default();
    if content.trim().is_empty() {
        return fail(StatusCode::BAD_REQUEST, "content is required");
    }
    let role = body.role.clone().unwrap_or_else(|| "user".into());
    if !matches!(role.as_str(), "user" | "assistant" | "system") {
        return fail(
            StatusCode::BAD_REQUEST,
            format!("unsupported role '{role}'; expected user, assistant or system"),
        );
    }

    let raw: Option<String> = match db
        .conn
        .query_row(
            "SELECT session_json FROM sessions WHERE id = ?1",
            params![session_id],
            |row| row.get(0),
        )
        .optional()
    {
        Ok(v) => v,
        Err(e) => return db_error(e),
    };
    let Some(raw) = raw else {
        return not_found("Session");
    };

    let mut session: Value = serde_json::from_str(&raw).unwrap_or_else(|_| json!({}));
    if !session
        .get("requests")
        .map(|r| r.is_array())
        .unwrap_or(false)
    {
        session["requests"] = json!([]);
    }
    let now = now_secs();
    let message_id = uuid::Uuid::new_v4().to_string();

    {
        let requests = session["requests"].as_array_mut().expect("array above");
        if role == "assistant" {
            // Attach to the last request still lacking a response; otherwise
            // the reader would pair this reply with the wrong prompt.
            let slot = requests
                .iter_mut()
                .rev()
                .find(|r| r.get("response").is_none());
            match slot {
                Some(request) => {
                    request["response"] = json!([{ "value": content }]);
                    request["responseId"] = json!(message_id);
                }
                None => requests.push(json!({
                    "requestId": uuid::Uuid::new_v4().to_string(),
                    "responseId": message_id,
                    "timestamp": now,
                    "modelId": body.model_id,
                    "response": [{ "value": content }],
                })),
            }
        } else {
            requests.push(json!({
                "requestId": message_id,
                "timestamp": now,
                "modelId": body.model_id,
                "message": { "text": content },
            }));
        }
    }

    let count = session["requests"]
        .as_array()
        .map(|r| {
            r.iter()
                .map(|req| {
                    usize::from(req.get("message").is_some())
                        + usize::from(req.get("response").is_some())
                })
                .sum::<usize>()
        })
        .unwrap_or(0) as i64;

    if let Err(e) = db.conn.execute(
        "UPDATE sessions SET session_json = ?1, message_count = ?2, updated_at = ?3
         WHERE id = ?4",
        params![session.to_string(), count, now, session_id],
    ) {
        return db_error(e);
    }

    created(json!({
        "id": message_id,
        "session_id": session_id,
        "role": role,
        "content": content,
        "created_at": now,
        "message_count": count,
    }))
}

// =============================================================================
// Checkpoints
// =============================================================================

/// The harvest database predates checkpoints, so the table is created on
/// demand rather than assumed. Kept to the columns the web client's
/// `Checkpoint` type actually reads.
fn ensure_checkpoints_table(conn: &Connection) -> rusqlite::Result<()> {
    conn.execute_batch(
        "CREATE TABLE IF NOT EXISTS api_checkpoints (
            id TEXT PRIMARY KEY,
            session_id TEXT NOT NULL,
            name TEXT NOT NULL,
            description TEXT,
            message_id TEXT,
            git_commit TEXT,
            git_branch TEXT,
            created_at INTEGER NOT NULL,
            metadata TEXT
        );
        CREATE INDEX IF NOT EXISTS idx_api_checkpoints_session
            ON api_checkpoints(session_id);",
    )
}

fn checkpoint_json(row: &rusqlite::Row) -> rusqlite::Result<Value> {
    let metadata: Option<String> = row.get(8)?;
    Ok(json!({
        "id": row.get::<_, String>(0)?,
        "sessionId": row.get::<_, String>(1)?,
        "name": row.get::<_, String>(2)?,
        "description": row.get::<_, Option<String>>(3)?,
        "messageId": row.get::<_, Option<String>>(4)?,
        "gitCommit": row.get::<_, Option<String>>(5)?,
        "gitBranch": row.get::<_, Option<String>>(6)?,
        "createdAt": row.get::<_, i64>(7)?,
        "metadata": metadata.and_then(|m| serde_json::from_str::<Value>(&m).ok()),
    }))
}

/// `GET /api/sessions/{id}/checkpoints`
pub async fn list_checkpoints(
    state: web::Data<AppState>,
    path: web::Path<String>,
) -> impl Responder {
    let db = state.db.lock().unwrap();
    let session_id = path.into_inner();

    if let Err(e) = ensure_checkpoints_table(&db.conn) {
        return db_error(e);
    }

    let result = (|| -> rusqlite::Result<Vec<Value>> {
        let mut stmt = db.conn.prepare(
            "SELECT id, session_id, name, description, message_id, git_commit,
                    git_branch, created_at, metadata
             FROM api_checkpoints WHERE session_id = ?1 ORDER BY created_at DESC",
        )?;
        let rows = stmt.query_map(params![session_id], checkpoint_json)?;
        rows.collect()
    })();

    match result {
        Ok(rows) => ok(rows),
        Err(e) => db_error(e),
    }
}

#[derive(Deserialize)]
pub struct CreateCheckpointBody {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default, alias = "messageId")]
    pub message_id: Option<String>,
    #[serde(default, alias = "gitCommit")]
    pub git_commit: Option<String>,
    #[serde(default, alias = "gitBranch")]
    pub git_branch: Option<String>,
    #[serde(default)]
    pub metadata: Option<Value>,
}

/// `POST /api/sessions/{id}/checkpoints`
pub async fn create_checkpoint(
    state: web::Data<AppState>,
    path: web::Path<String>,
    body: web::Json<CreateCheckpointBody>,
) -> impl Responder {
    let db = state.db.lock().unwrap();
    let session_id = path.into_inner();

    let exists: Option<i64> = match db
        .conn
        .query_row(
            "SELECT 1 FROM sessions WHERE id = ?1",
            params![session_id],
            |row| row.get(0),
        )
        .optional()
    {
        Ok(v) => v,
        Err(e) => return db_error(e),
    };
    if exists.is_none() {
        return not_found("Session");
    }

    if let Err(e) = ensure_checkpoints_table(&db.conn) {
        return db_error(e);
    }

    let id = uuid::Uuid::new_v4().to_string();
    let now = now_secs();
    let name = body
        .name
        .clone()
        .unwrap_or_else(|| format!("Checkpoint {now}"));
    let metadata = body.metadata.as_ref().map(|m| m.to_string());

    if let Err(e) = db.conn.execute(
        "INSERT INTO api_checkpoints
            (id, session_id, name, description, message_id, git_commit, git_branch,
             created_at, metadata)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
        params![
            id,
            session_id,
            name,
            body.description,
            body.message_id,
            body.git_commit,
            body.git_branch,
            now,
            metadata,
        ],
    ) {
        return db_error(e);
    }

    created(json!({
        "id": id,
        "sessionId": session_id,
        "name": name,
        "description": body.description,
        "messageId": body.message_id,
        "gitCommit": body.git_commit,
        "gitBranch": body.git_branch,
        "createdAt": now,
        "metadata": body.metadata,
    }))
}

// =============================================================================
// Git commits
// =============================================================================

/// `GET /api/sessions/{id}/commits`
///
/// Commits from the workspace the session belongs to. Returns an empty list
/// -- not an error -- when the workspace is not a git repository or `git` is
/// not on PATH: "this session has no commits" is the honest answer there, and
/// the Chat page renders it as an empty panel rather than a failure.
pub async fn session_commits(
    state: web::Data<AppState>,
    path: web::Path<String>,
) -> impl Responder {
    let session_id = path.into_inner();

    let workspace_path: Option<Option<String>> = {
        let db = state.db.lock().unwrap();
        match db
            .conn
            .query_row(
                "SELECT workspace_path FROM sessions WHERE id = ?1",
                params![session_id],
                |row| row.get(0),
            )
            .optional()
        {
            Ok(v) => v,
            Err(e) => return db_error(e),
        }
    };

    let Some(workspace_path) = workspace_path else {
        return not_found("Session");
    };
    let Some(dir) = workspace_path.filter(|p| !p.trim().is_empty()) else {
        return ok(Vec::<Value>::new());
    };

    match git_log(&dir, &session_id) {
        Ok(commits) => ok(commits),
        Err(_) => ok(Vec::<Value>::new()),
    }
}

/// Shell out to `git`; there is no git library in the dependency tree.
fn git_log(dir: &str, session_id: &str) -> Result<Vec<Value>, std::io::Error> {
    // Unit separator between fields and record separator between commits, so
    // a commit message containing a newline or a tab cannot corrupt parsing.
    let out = std::process::Command::new("git")
        .args([
            "-C",
            dir,
            "log",
            "-n",
            "50",
            "--format=%H\x1f%h\x1f%s\x1f%an\x1f%ae\x1f%at\x1e",
        ])
        .output()?;

    if !out.status.success() {
        return Ok(Vec::new());
    }

    let branch = std::process::Command::new("git")
        .args(["-C", dir, "rev-parse", "--abbrev-ref", "HEAD"])
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_default();

    let stdout = String::from_utf8_lossy(&out.stdout);
    let commits = stdout
        .split('\x1e')
        .filter(|rec| !rec.trim().is_empty())
        .filter_map(|rec| {
            let f: Vec<&str> = rec.trim_start_matches('\n').split('\x1f').collect();
            if f.len() < 6 {
                return None;
            }
            Some(json!({
                "hash": f[0],
                "shortHash": f[1],
                "message": f[2],
                "author": f[3],
                "email": f[4],
                "timestamp": f[5].parse::<i64>().unwrap_or(0),
                "branch": branch,
                "sessionId": session_id,
                "messageId": Value::Null,
            }))
        })
        .collect();

    Ok(commits)
}

// =============================================================================
// Search
// =============================================================================

#[derive(Deserialize)]
pub struct SearchQuery {
    #[serde(default)]
    pub q: String,
    #[serde(default)]
    pub limit: Option<u32>,
}

/// `GET /api/search`
///
/// Returns `SearchResult[]` -- the shape the client's `search.query` declares.
/// This is a title/content substring search, not semantic: there is no
/// embedding index behind the REST API, and pretending otherwise is how the
/// old zero-vector embeddings bug happened.
pub async fn search(state: web::Data<AppState>, query: web::Query<SearchQuery>) -> impl Responder {
    let db = state.db.lock().unwrap();
    let q = query.q.trim();
    if q.is_empty() {
        return ok(Vec::<Value>::new());
    }
    let limit = query.limit.unwrap_or(50).min(500) as i64;
    let term = format!("%{q}%");

    let result = (|| -> rusqlite::Result<Vec<Value>> {
        let mut stmt = db.conn.prepare(
            "SELECT id, title, provider, workspace_id, updated_at
             FROM sessions
             WHERE title LIKE ?1 COLLATE NOCASE
             ORDER BY updated_at DESC LIMIT ?2",
        )?;
        let mut results: Vec<Value> = stmt
            .query_map(params![term, limit], |row| {
                Ok(json!({
                    "type": "session",
                    "id": row.get::<_, String>(0)?,
                    "title": row.get::<_, String>(1)?,
                    "provider": row.get::<_, Option<String>>(2)?,
                    "workspaceId": row.get::<_, Option<String>>(3)?,
                    "timestamp": row.get::<_, Option<i64>>(4)?,
                }))
            })?
            .collect::<rusqlite::Result<Vec<_>>>()?;

        // Message hits, when the normalized table is present.
        if table_exists(&db.conn, "messages_v2") && (results.len() as i64) < limit {
            let remaining = limit - results.len() as i64;

            // Fast path: the FTS5 index, when it exists and the query yields a
            // usable MATCH expression. This turns a full `content_raw LIKE`
            // scan -- O(rows), the slow part of search on a large history --
            // into an indexed lookup. `snippet()` and `rank` are valid here
            // because `messages_fts` is matched directly, with no GROUP BY and
            // no wrapping subquery (the two shapes SQLite rejects with "unable
            // to use function snippet in the requested context"). Any FTS error
            // falls through to the LIKE scan, so the fast path can only ever add
            // speed, never remove a result the substring scan would have found.
            let fts_hits: Option<Vec<Value>> = if table_exists(&db.conn, "messages_fts") {
                fts_query_from(q).and_then(|match_q| {
                    (|| -> rusqlite::Result<Vec<Value>> {
                        let mut stmt = db.conn.prepare(
                            "SELECT m.session_id, s.title,
                                    snippet(messages_fts, 0, '', '', '...', 40),
                                    s.updated_at
                             FROM messages_fts
                             JOIN messages_v2 m ON m.id = messages_fts.rowid
                             JOIN sessions s ON s.id = m.session_id
                             WHERE messages_fts MATCH ?1
                             ORDER BY rank LIMIT ?2",
                        )?;
                        let rows = stmt
                            .query_map(params![match_q, remaining], |row| {
                                Ok(json!({
                                    "type": "message",
                                    "id": row.get::<_, String>(0)?,
                                    "sessionId": row.get::<_, String>(0)?,
                                    "title": row.get::<_, String>(1)?,
                                    "snippet": row.get::<_, String>(2)?,
                                    "timestamp": row.get::<_, Option<i64>>(3)?,
                                }))
                            })?
                            .collect::<rusqlite::Result<Vec<_>>>()?;
                        Ok(rows)
                    })()
                    .ok()
                })
            } else {
                None
            };

            let hits: Vec<Value> = match fts_hits {
                Some(hits) => hits,
                None => {
                    // Fallback: the substring scan. Always correct, just slower.
                    let mut stmt = db.conn.prepare(
                        "SELECT m.session_id, s.title, m.content_raw, s.updated_at
                         FROM messages_v2 m JOIN sessions s ON s.id = m.session_id
                         WHERE m.content_raw LIKE ?1 COLLATE NOCASE
                         ORDER BY s.updated_at DESC LIMIT ?2",
                    )?;
                    let rows = stmt
                        .query_map(params![term, remaining], |row| {
                            let content: String = row.get(2)?;
                            Ok(json!({
                                "type": "message",
                                "id": row.get::<_, String>(0)?,
                                "sessionId": row.get::<_, String>(0)?,
                                "title": row.get::<_, String>(1)?,
                                "snippet": snippet(&content, 200),
                                "timestamp": row.get::<_, Option<i64>>(3)?,
                            }))
                        })?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    rows
                }
            };
            for hit in hits {
                results.push(hit);
            }
        }

        Ok(results)
    })();

    match result {
        Ok(rows) => ok(rows),
        Err(e) => db_error(e),
    }
}

/// Turn a user's free-text query into a safe FTS5 MATCH expression.
///
/// Each whitespace-separated token becomes a prefix term (`token*`), AND-ed
/// together, so "quick sort" matches a message with a word starting "quick"
/// and one starting "sort". Prefix matching is what a search box is expected
/// to do -- "quick" finding "quicksort" -- and is closer to the old substring
/// behaviour than exact-token matching would be.
///
/// Every token is reduced to alphanumerics and `_` first, so an FTS operator,
/// a stray quote or a bare `*` in the input can never assemble into a
/// malformed MATCH expression. When nothing usable survives (a query of pure
/// punctuation), this returns `None` and the caller uses the LIKE scan, which
/// has no such syntax to trip over.
fn fts_query_from(user: &str) -> Option<String> {
    let terms: Vec<String> = user
        .split_whitespace()
        .map(|tok| {
            tok.chars()
                .filter(|c| c.is_alphanumeric() || *c == '_')
                .collect::<String>()
        })
        .filter(|t| !t.is_empty())
        .map(|t| format!("{t}*"))
        .collect();
    if terms.is_empty() {
        None
    } else {
        Some(terms.join(" "))
    }
}

/// Character-wise, because a byte slice would panic in the middle of a
/// multi-byte character.
fn snippet(text: &str, max_chars: usize) -> String {
    let trimmed = text.trim();
    if trimmed.chars().count() <= max_chars {
        return trimmed.to_string();
    }
    let head: String = trimmed.chars().take(max_chars).collect();
    format!("{head}...")
}

// =============================================================================
// Statistics
// =============================================================================

/// `GET /api/stats/providers`
///
/// `Record<provider, {sessions, messages, tokens}>`. Token counts are reported
/// as 0 where the harvest schema stores none, rather than being estimated --
/// an invented number here would show up in the UI as fact.
pub async fn provider_stats(state: web::Data<AppState>) -> impl Responder {
    let db = state.db.lock().unwrap();

    let result = (|| -> rusqlite::Result<Value> {
        let mut stmt = db.conn.prepare(
            "SELECT provider, COUNT(*), COALESCE(SUM(message_count), 0)
             FROM sessions GROUP BY provider ORDER BY provider",
        )?;
        let rows = stmt.query_map([], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, i64>(1)?,
                row.get::<_, i64>(2)?,
            ))
        })?;

        let mut out = serde_json::Map::new();
        for row in rows {
            let (provider, sessions, messages) = row?;
            out.insert(
                provider,
                json!({ "sessions": sessions, "messages": messages, "tokens": 0 }),
            );
        }
        Ok(Value::Object(out))
    })();

    match result {
        Ok(stats) => ok(stats),
        Err(e) => db_error(e),
    }
}

// =============================================================================
// Swarms
// =============================================================================

#[derive(Deserialize)]
pub struct UpdateSwarmBody {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub orchestration: Option<String>,
    #[serde(default)]
    pub agents: Option<Value>,
    #[serde(default, alias = "maxIterations")]
    pub max_iterations: Option<i64>,
    #[serde(default)]
    pub status: Option<String>,
}

/// `PUT /api/swarms/{id}`
pub async fn update_swarm(
    state: web::Data<AppState>,
    path: web::Path<String>,
    body: web::Json<UpdateSwarmBody>,
) -> impl Responder {
    let db = state.db.lock().unwrap();
    let id = path.into_inner();

    // The swarms table is created on demand by the other swarm handlers, so it
    // may not exist yet; without this an update is a 500 rather than a 404.
    if let Err(e) = super::handlers_simple::init_swarms_table(&db.conn) {
        return db_error(e);
    }

    // COALESCE so an omitted field keeps its stored value instead of being
    // nulled -- the client sends partial updates.
    let agents = body.agents.as_ref().map(|a| a.to_string());
    let updated = db.conn.execute(
        "UPDATE swarms SET
            name = COALESCE(?1, name),
            description = COALESCE(?2, description),
            orchestration = COALESCE(?3, orchestration),
            agents = COALESCE(?4, agents),
            max_iterations = COALESCE(?5, max_iterations),
            status = COALESCE(?6, status),
            updated_at = ?7
         WHERE id = ?8",
        params![
            body.name,
            body.description,
            body.orchestration,
            agents,
            body.max_iterations,
            body.status,
            now_secs(),
            id,
        ],
    );

    match updated {
        Ok(0) => not_found("Swarm"),
        Ok(_) => ok(json!({ "id": id, "updated": true })),
        Err(e) => db_error(e),
    }
}

// =============================================================================
// Providers
// =============================================================================

/// `POST /api/providers/{id}/test`
///
/// Reports reachability, measured. For a locally hosted provider that means an
/// actual HTTP request; for one whose endpoint we cannot know from here it
/// means saying so, rather than returning a cheerful `success: true` that
/// tested nothing.
pub async fn test_provider(path: web::Path<String>) -> impl Responder {
    let id = path.into_inner();

    // Each server exposes a different liveness path; LM Studio has no
    // /api/tags, so probing one shape for both would report it as down.
    let probe = match id.as_str() {
        "ollama" => format!(
            "{}/api/tags",
            std::env::var("OLLAMA_HOST")
                .unwrap_or_else(|_| "http://localhost:11434".into())
                .trim_end_matches('/')
        ),
        "lmstudio" => "http://localhost:1234/v1/models".to_string(),
        _ => {
            return fail(
                StatusCode::NOT_IMPLEMENTED,
                format!(
                    "No connectivity test for '{id}'. Only locally hosted providers \
                     (ollama, lmstudio) expose an endpoint this server can reach."
                ),
            )
        }
    };

    let started = std::time::Instant::now();
    let client = match reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(5))
        .build()
    {
        Ok(c) => c,
        Err(e) => return db_error(e),
    };

    match client.get(&probe).send().await {
        Ok(resp) if resp.status().is_success() => ok(json!({
            "success": true,
            "latency": started.elapsed().as_millis() as u64,
        })),
        Ok(resp) => fail(
            StatusCode::BAD_GATEWAY,
            format!("{id} answered {}", resp.status()),
        ),
        Err(e) => fail(StatusCode::BAD_GATEWAY, format!("{id} unreachable: {e}")),
    }
}

// =============================================================================
// Chat completions
// =============================================================================

#[derive(Deserialize)]
pub struct CompletionBody {
    #[serde(default)]
    pub model: Option<String>,
    #[serde(default)]
    pub messages: Vec<CompletionMessage>,
    #[serde(default)]
    pub temperature: Option<f32>,
    #[serde(default, alias = "maxTokens")]
    pub max_tokens: Option<u32>,
}

#[derive(Deserialize, Serialize, Clone)]
pub struct CompletionMessage {
    pub role: String,
    pub content: String,
}

/// `POST /api/chat/completions`
///
/// A thin proxy to an OpenAI-compatible endpoint, configured exactly like
/// `ironbridge analyze`: `OPENAI_API_KEY` and `OPENAI_BASE_URL`. Without a key this
/// returns 503 and says what to set. It does not fall back to a canned reply --
/// a fabricated completion presented as model output is the worst possible
/// failure mode for this endpoint.
pub async fn chat_completion(body: web::Json<CompletionBody>) -> impl Responder {
    if body.messages.is_empty() {
        return fail(StatusCode::BAD_REQUEST, "messages is required");
    }

    let api_key = std::env::var("OPENAI_API_KEY").unwrap_or_default();
    if api_key.trim().is_empty() {
        return fail(
            StatusCode::SERVICE_UNAVAILABLE,
            "No model configured. Set OPENAI_API_KEY (and OPENAI_BASE_URL for a \
             local or self-hosted endpoint) on the server.",
        );
    }
    let base_url = std::env::var("OPENAI_BASE_URL")
        .unwrap_or_else(|_| "https://api.openai.com/v1".into())
        .trim_end_matches('/')
        .to_string();
    let model = body
        .model
        .clone()
        .filter(|m| !m.trim().is_empty())
        .unwrap_or_else(|| "gpt-4o-mini".into());

    let client = match reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(120))
        .build()
    {
        Ok(c) => c,
        Err(e) => return db_error(e),
    };

    let mut payload = json!({
        "model": model,
        "messages": body.messages,
        "stream": false,
    });
    if let Some(t) = body.temperature {
        payload["temperature"] = json!(t);
    }
    if let Some(m) = body.max_tokens {
        payload["max_tokens"] = json!(m);
    }

    let response = client
        .post(format!("{base_url}/chat/completions"))
        .bearer_auth(&api_key)
        .json(&payload)
        .send()
        .await;

    let response = match response {
        Ok(r) => r,
        Err(e) => return fail(StatusCode::BAD_GATEWAY, format!("Model unreachable: {e}")),
    };

    let status = response.status();
    let raw = response.text().await.unwrap_or_default();
    if !status.is_success() {
        return fail(
            StatusCode::BAD_GATEWAY,
            format!("Model returned {status}: {}", snippet(&raw, 300)),
        );
    }

    let parsed: Value = match serde_json::from_str(&raw) {
        Ok(v) => v,
        Err(e) => {
            return fail(
                StatusCode::BAD_GATEWAY,
                format!("Model returned unparseable JSON: {e}"),
            )
        }
    };

    let content = parsed
        .pointer("/choices/0/message/content")
        .and_then(|c| c.as_str())
        .unwrap_or_default()
        .to_string();
    let finish = parsed
        .pointer("/choices/0/finish_reason")
        .and_then(|f| f.as_str())
        .unwrap_or("stop");

    ok(json!({
        "id": parsed.get("id").and_then(|i| i.as_str()).unwrap_or_default(),
        "model": parsed.get("model").and_then(|m| m.as_str()).unwrap_or(&model),
        "content": content,
        "message": { "role": "assistant", "content": content },
        "finishReason": finish,
        "usage": parsed.get("usage").cloned().unwrap_or(Value::Null),
    }))
}

// =============================================================================
// Harvest
// =============================================================================

/// `POST /api/harvest`
///
/// Runs the same harvest the CLI runs, on a blocking thread -- it walks the
/// filesystem and can take minutes. Counts are measured by differencing the
/// session table around the run, because `harvest_run` reports to stdout and
/// returns nothing this endpoint could relay.
pub async fn run_harvest(state: web::Data<AppState>) -> impl Responder {
    let before = match count_sessions(&state) {
        Ok(n) => n,
        Err(e) => return db_error(e),
    };

    // Against the database this server opened, not the CLI's default. If the
    // server was pointed at a custom path, harvesting into the default one
    // would import sessions the API can never see and report a count of zero.
    let db_path = state.db_path.to_string_lossy().to_string();

    // Incremental: an API-triggered harvest should pick up what is new, not
    // re-walk and re-parse every session on the machine.
    let outcome = web::block(move || {
        crate::commands::harvest_run(Some(&db_path), None, None, true, false, None, false)
    })
    .await;

    let errors = match outcome {
        Ok(Ok(())) => Vec::new(),
        Ok(Err(e)) => vec![e.to_string()],
        Err(e) => vec![format!("harvest thread failed: {e}")],
    };

    let after = match count_sessions(&state) {
        Ok(n) => n,
        Err(e) => return db_error(e),
    };

    ok(json!({
        "success": errors.is_empty(),
        "sessionsImported": (after - before).max(0),
        "messagesImported": 0,
        "errors": errors,
        "warnings": [],
    }))
}

fn count_sessions(state: &web::Data<AppState>) -> rusqlite::Result<i64> {
    let db = state.db.lock().unwrap();
    db.conn
        .query_row("SELECT COUNT(*) FROM sessions", [], |row| row.get(0))
}

// =============================================================================
// Shared helpers
// =============================================================================

fn table_exists(conn: &Connection, name: &str) -> bool {
    conn.query_row(
        "SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?1",
        params![name],
        |_| Ok(true),
    )
    .optional()
    .ok()
    .flatten()
    .unwrap_or(false)
}

// =============================================================================
// Timeline statistics
// =============================================================================

#[derive(Deserialize)]
pub struct TimelineQuery {
    #[serde(default)]
    pub days: Option<u32>,
}

/// `GET /api/stats/timeline`
///
/// Sessions and messages per calendar day, oldest first. Days with no
/// activity are omitted rather than zero-filled: the store knows nothing
/// about a day on which nothing happened, and inventing rows would make an
/// empty database look like a quiet one.
pub async fn timeline_stats(
    state: web::Data<AppState>,
    query: web::Query<TimelineQuery>,
) -> impl Responder {
    let db = state.db.lock().unwrap();
    let days = query.days.unwrap_or(30).clamp(1, 365) as i64;
    let cutoff = now_secs() - days * 86_400;

    let result = (|| -> rusqlite::Result<Vec<Value>> {
        let mut stmt = db.conn.prepare(
            "SELECT date(created_at, 'unixepoch') AS day,
                    COUNT(*) AS sessions,
                    COALESCE(SUM(message_count), 0) AS messages
             FROM sessions
             WHERE created_at >= ?1
             GROUP BY day
             ORDER BY day",
        )?;
        let rows = stmt.query_map(params![cutoff], |row| {
            Ok(json!({
                "date": row.get::<_, String>(0)?,
                "sessions": row.get::<_, i64>(1)?,
                "messages": row.get::<_, i64>(2)?,
            }))
        })?;
        rows.collect()
    })();

    match result {
        Ok(rows) => ok(json!({ "days": days, "points": rows })),
        Err(e) => db_error(e),
    }
}

// =============================================================================
// Workspace writes
// =============================================================================

#[derive(Deserialize)]
pub struct WorkspaceBody {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub path: Option<String>,
    #[serde(default)]
    pub provider: Option<String>,
}

/// `POST /api/workspaces`
pub async fn create_workspace(
    state: web::Data<AppState>,
    body: web::Json<WorkspaceBody>,
) -> impl Responder {
    let Some(name) = body.name.clone().filter(|n| !n.trim().is_empty()) else {
        return fail(StatusCode::BAD_REQUEST, "name is required");
    };

    let db = state.db.lock().unwrap();
    let id = uuid::Uuid::new_v4().to_string();
    let now = now_secs();

    let inserted = db.conn.execute(
        "INSERT INTO workspaces (id, name, path, provider, created_at, updated_at)
         VALUES (?1, ?2, ?3, ?4, ?5, ?5)",
        params![id, name, body.path, body.provider, now],
    );

    match inserted {
        Ok(_) => created(json!({
            "id": id,
            "name": name,
            "path": body.path,
            "provider": body.provider,
            "created_at": now,
            "updated_at": now,
        })),
        Err(e) => db_error(e),
    }
}

/// `PUT /api/workspaces/{id}`
pub async fn update_workspace(
    state: web::Data<AppState>,
    path: web::Path<String>,
    body: web::Json<WorkspaceBody>,
) -> impl Responder {
    let db = state.db.lock().unwrap();
    let id = path.into_inner();

    // COALESCE so an omitted field keeps its stored value.
    let updated = db.conn.execute(
        "UPDATE workspaces SET
            name = COALESCE(?1, name),
            path = COALESCE(?2, path),
            provider = COALESCE(?3, provider),
            updated_at = ?4
         WHERE id = ?5",
        params![body.name, body.path, body.provider, now_secs(), id],
    );

    match updated {
        Ok(0) => not_found("Workspace"),
        Ok(_) => ok(json!({ "id": id, "updated": true })),
        Err(e) => db_error(e),
    }
}

/// `DELETE /api/workspaces/{id}`
///
/// Sessions that belonged to it are kept and detached, not deleted. Removing
/// a workspace record is a bookkeeping act; destroying the conversations
/// filed under it is not, and should never be a side effect of one.
pub async fn delete_workspace(
    state: web::Data<AppState>,
    path: web::Path<String>,
) -> impl Responder {
    let db = state.db.lock().unwrap();
    let id = path.into_inner();

    if let Err(e) = db.conn.execute(
        "UPDATE sessions SET workspace_id = NULL WHERE workspace_id = ?1",
        params![id],
    ) {
        return db_error(e);
    }

    match db
        .conn
        .execute("DELETE FROM workspaces WHERE id = ?1", params![id])
    {
        Ok(0) => not_found("Workspace"),
        Ok(_) => ok(json!({ "id": id, "deleted": true, "sessionsDetached": true })),
        Err(e) => db_error(e),
    }
}

// =============================================================================
// Fork, merge and export
// =============================================================================

/// Read a session's stored blob and denormalized title.
fn load_session(conn: &Connection, id: &str) -> rusqlite::Result<Option<(String, String, String)>> {
    conn.query_row(
        "SELECT title, provider, session_json FROM sessions WHERE id = ?1",
        params![id],
        |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
    )
    .optional()
}

fn request_count(session: &Value) -> i64 {
    session
        .get("requests")
        .and_then(|r| r.as_array())
        .map(|r| {
            r.iter()
                .map(|req| {
                    i64::from(req.get("message").is_some())
                        + i64::from(req.get("response").is_some())
                })
                .sum()
        })
        .unwrap_or(0)
}

#[derive(Deserialize)]
pub struct ForkBody {
    #[serde(default)]
    pub title: Option<String>,
}

/// `POST /api/sessions/{id}/fork`
///
/// Copies the conversation into a new session. The copy is independent --
/// appending to either afterwards does not affect the other -- and records
/// its origin in `parentSessionId` so the lineage is not lost.
pub async fn fork_session(
    state: web::Data<AppState>,
    path: web::Path<String>,
    body: web::Json<ForkBody>,
) -> impl Responder {
    let db = state.db.lock().unwrap();
    let source_id = path.into_inner();

    let loaded = match load_session(&db.conn, &source_id) {
        Ok(v) => v,
        Err(e) => return db_error(e),
    };
    let Some((title, provider, raw)) = loaded else {
        return not_found("Session");
    };

    let mut session: Value =
        serde_json::from_str(&raw).unwrap_or_else(|_| json!({ "requests": [] }));
    session["forkedFrom"] = json!(source_id);

    let new_id = uuid::Uuid::new_v4().to_string();
    let new_title = body
        .title
        .clone()
        .filter(|t| !t.trim().is_empty())
        .unwrap_or_else(|| format!("{title} (fork)"));
    let now = now_secs();
    let count = request_count(&session);

    let inserted = db.conn.execute(
        "INSERT INTO sessions
            (id, provider, workspace_id, workspace_path, title, message_count,
             created_at, updated_at, harvested_at, session_json)
         SELECT ?1, ?2, workspace_id, workspace_path, ?3, ?4, ?5, ?5, ?5, ?6
         FROM sessions WHERE id = ?7",
        params![
            new_id,
            provider,
            new_title,
            count,
            now,
            session.to_string(),
            source_id
        ],
    );

    match inserted {
        Ok(_) => created(json!({
            "id": new_id,
            "title": new_title,
            "provider": provider,
            "parentSessionId": source_id,
            "message_count": count,
            "created_at": now,
        })),
        Err(e) => db_error(e),
    }
}

#[derive(Deserialize)]
pub struct MergeBody {
    #[serde(default, alias = "sessionIds")]
    pub session_ids: Vec<String>,
    #[serde(default)]
    pub title: Option<String>,
}

/// `POST /api/sessions/merge`
///
/// Concatenates several sessions into a new one, in the order given. The
/// sources are left untouched: a merge that consumed its inputs would make
/// an accidental merge unrecoverable, and the caller can delete them after
/// checking the result.
pub async fn merge_sessions(
    state: web::Data<AppState>,
    body: web::Json<MergeBody>,
) -> impl Responder {
    if body.session_ids.len() < 2 {
        return fail(
            StatusCode::BAD_REQUEST,
            "sessionIds must name at least two sessions",
        );
    }

    let db = state.db.lock().unwrap();
    let mut requests: Vec<Value> = Vec::new();
    let mut provider = String::from("ironbridge");

    for (i, id) in body.session_ids.iter().enumerate() {
        let loaded = match load_session(&db.conn, id) {
            Ok(v) => v,
            Err(e) => return db_error(e),
        };
        let Some((_, source_provider, raw)) = loaded else {
            return fail(StatusCode::NOT_FOUND, format!("Session {id} not found"));
        };
        if i == 0 {
            provider = source_provider;
        }
        let session: Value = serde_json::from_str(&raw).unwrap_or_else(|_| json!({}));
        if let Some(rs) = session.get("requests").and_then(|r| r.as_array()) {
            // Tag each turn with where it came from, so a merged transcript
            // can still be traced back.
            for r in rs {
                let mut r = r.clone();
                r["mergedFrom"] = json!(id);
                requests.push(r);
            }
        }
    }

    let merged = json!({ "requests": requests, "mergedFrom": body.session_ids });
    let count = request_count(&merged);
    let new_id = uuid::Uuid::new_v4().to_string();
    let title = body
        .title
        .clone()
        .filter(|t| !t.trim().is_empty())
        .unwrap_or_else(|| format!("Merge of {} sessions", body.session_ids.len()));
    let now = now_secs();

    let inserted = db.conn.execute(
        "INSERT INTO sessions
            (id, provider, title, message_count, created_at, updated_at,
             harvested_at, session_json)
         VALUES (?1, ?2, ?3, ?4, ?5, ?5, ?5, ?6)",
        params![new_id, provider, title, count, now, merged.to_string()],
    );

    match inserted {
        Ok(_) => created(json!({
            "id": new_id,
            "title": title,
            "provider": provider,
            "message_count": count,
            "mergedFrom": body.session_ids,
            "created_at": now,
        })),
        Err(e) => db_error(e),
    }
}

#[derive(Deserialize)]
pub struct ExportQuery {
    #[serde(default)]
    pub format: Option<String>,
}

/// `GET /api/sessions/{id}/export`
///
/// `format=json` returns the stored blob; `format=markdown` renders the
/// transcript. Served as a download with a filename, because the point of
/// this endpoint is to get a file out.
pub async fn export_session(
    state: web::Data<AppState>,
    path: web::Path<String>,
    query: web::Query<ExportQuery>,
) -> impl Responder {
    let db = state.db.lock().unwrap();
    let id = path.into_inner();

    let loaded = match load_session(&db.conn, &id) {
        Ok(v) => v,
        Err(e) => return db_error(e),
    };
    let Some((title, _, raw)) = loaded else {
        return not_found("Session");
    };

    let format = query.format.clone().unwrap_or_else(|| "json".into());
    let session: Value = serde_json::from_str(&raw).unwrap_or_else(|_| json!({}));

    let (body, mime, ext) = match format.as_str() {
        "json" => (raw, "application/json", "json"),
        "markdown" | "md" => (render_markdown(&title, &session), "text/markdown", "md"),
        other => {
            return fail(
                StatusCode::BAD_REQUEST,
                format!("unsupported format '{other}'; expected json or markdown"),
            )
        }
    };

    HttpResponse::Ok()
        .content_type(mime)
        .insert_header((
            "Content-Disposition",
            format!("attachment; filename=\"{}.{ext}\"", safe_filename(&title)),
        ))
        .body(body)
}

/// Render the transcript the same way the read path reconstructs it, so an
/// export matches what `GET /sessions/{id}` shows.
fn render_markdown(title: &str, session: &Value) -> String {
    let mut out = format!("# {title}\n\n");
    if let Some(requests) = session.get("requests").and_then(|r| r.as_array()) {
        for request in requests {
            if let Some(text) = request
                .pointer("/message/text")
                .and_then(|t| t.as_str())
                .filter(|t| !t.is_empty())
            {
                out.push_str("## User\n\n");
                out.push_str(text);
                out.push_str("\n\n");
            }
            if let Some(response) = request.get("response") {
                let text = response
                    .as_array()
                    .map(|parts| {
                        parts
                            .iter()
                            .filter_map(|p| p.get("value").and_then(|v| v.as_str()))
                            .collect::<Vec<_>>()
                            .join("")
                    })
                    .or_else(|| response.as_str().map(|s| s.to_string()))
                    .unwrap_or_default();
                if !text.is_empty() {
                    out.push_str("## Assistant\n\n");
                    out.push_str(&text);
                    out.push_str("\n\n");
                }
            }
        }
    }
    out
}

/// Strip anything that would make a filename awkward or unsafe on any of the
/// three platforms this runs on.
fn safe_filename(title: &str) -> String {
    let cleaned: String = title
        .chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '-'
            }
        })
        .collect();
    let trimmed = cleaned.trim_matches('-');
    if trimmed.is_empty() {
        "session".to_string()
    } else {
        trimmed.chars().take(60).collect()
    }
}

// =============================================================================
// Session sharing
// =============================================================================
//
// A share is a token that grants read access to one session *through this
// server*. Nothing is uploaded anywhere.
//
// That is a deliberate choice, not a shortcut. IronBridge holds a person's entire
// chat history on their own machine; making "share" mean "transmit a
// conversation to a third party" is a decision with privacy consequences that
// belongs to whoever runs it, not to the code. A local token is useful for the
// cases that motivated the feature -- opening a session in another tab, handing
// a colleague a URL on the same network, embedding a link in a ticket on an
// internal host -- and it cannot leak anything the server was not already
// serving.
//
// Consequences worth knowing:
//   - A link only works while this server is reachable by the recipient.
//   - Anyone who has the token can read that session. It is a bearer
//     credential, which is why it is 256 bits from the OS random source and
//     why expiry and revocation both exist.

/// Table for outbound share tokens.
///
/// Distinct from the existing `share_links`, which records *inbound* provider
/// URLs (a ChatGPT or Claude share someone imported). Reusing that table would
/// conflate "a link I was given" with "a link I handed out".
fn ensure_shares_table(conn: &Connection) -> rusqlite::Result<()> {
    conn.execute_batch(
        "CREATE TABLE IF NOT EXISTS session_shares (
            token TEXT PRIMARY KEY,
            session_id TEXT NOT NULL,
            created_at INTEGER NOT NULL,
            expires_at INTEGER,
            revoked INTEGER NOT NULL DEFAULT 0,
            access_count INTEGER NOT NULL DEFAULT 0,
            last_accessed INTEGER
        );
        CREATE INDEX IF NOT EXISTS idx_session_shares_session
            ON session_shares(session_id);",
    )
}

/// 256 bits from the OS random source, hex encoded.
///
/// `uuid::Uuid::new_v4` would be 122 bits and is designed for uniqueness, not
/// unguessability. This value is a bearer credential.
fn new_share_token() -> String {
    use rand::RngCore;
    let mut bytes = [0u8; 32];
    rand::rngs::OsRng.fill_bytes(&mut bytes);
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

#[derive(Deserialize)]
pub struct CreateShareBody {
    /// Hours until the link stops working. Omit for a link that does not
    /// expire on its own -- revocation is then the only way to close it.
    #[serde(default, alias = "expiresInHours")]
    pub expires_in_hours: Option<i64>,
}

/// `POST /api/sessions/{id}/share`
pub async fn create_share(
    state: web::Data<AppState>,
    path: web::Path<String>,
    body: web::Json<CreateShareBody>,
) -> impl Responder {
    let db = state.db.lock().unwrap();
    let session_id = path.into_inner();

    let exists: Option<i64> = match db
        .conn
        .query_row(
            "SELECT 1 FROM sessions WHERE id = ?1",
            params![session_id],
            |row| row.get(0),
        )
        .optional()
    {
        Ok(v) => v,
        Err(e) => return db_error(e),
    };
    if exists.is_none() {
        return not_found("Session");
    }

    if let Err(e) = ensure_shares_table(&db.conn) {
        return db_error(e);
    }

    let hours = body.expires_in_hours;
    if matches!(hours, Some(h) if h <= 0) {
        return fail(
            StatusCode::BAD_REQUEST,
            "expiresInHours must be positive; omit it for a link that does not expire",
        );
    }

    let token = new_share_token();
    let now = now_secs();
    let expires_at = hours.map(|h| now + h * 3600);

    if let Err(e) = db.conn.execute(
        "INSERT INTO session_shares (token, session_id, created_at, expires_at)
         VALUES (?1, ?2, ?3, ?4)",
        params![token, session_id, now, expires_at],
    ) {
        return db_error(e);
    }

    created(json!({
        "token": token,
        "sessionId": session_id,
        "path": format!("/api/shared/{token}"),
        "createdAt": now,
        "expiresAt": expires_at,
        "revoked": false,
        "note": "Readable through this server only; nothing was uploaded.",
    }))
}

/// `GET /api/sessions/{id}/share`
///
/// Lists the links handed out for a session so they can be audited and
/// revoked. The token is returned in full: this is the owner's own view, and
/// a list of links you cannot copy is not much use.
pub async fn list_shares(state: web::Data<AppState>, path: web::Path<String>) -> impl Responder {
    let db = state.db.lock().unwrap();
    let session_id = path.into_inner();

    if let Err(e) = ensure_shares_table(&db.conn) {
        return db_error(e);
    }

    let now = now_secs();
    let result = (|| -> rusqlite::Result<Vec<Value>> {
        let mut stmt = db.conn.prepare(
            "SELECT token, created_at, expires_at, revoked, access_count, last_accessed
             FROM session_shares WHERE session_id = ?1 ORDER BY created_at DESC",
        )?;
        let rows = stmt.query_map(params![session_id], |row| {
            let expires_at: Option<i64> = row.get(2)?;
            let revoked: i64 = row.get(3)?;
            // Derived on read, like the inbox's permission expiry: a sweeper
            // that has not run yet must never make a dead link look live.
            let status = if revoked != 0 {
                "revoked"
            } else if expires_at.is_some_and(|e| e <= now) {
                "expired"
            } else {
                "active"
            };
            Ok(json!({
                "token": row.get::<_, String>(0)?,
                "createdAt": row.get::<_, i64>(1)?,
                "expiresAt": expires_at,
                "status": status,
                "accessCount": row.get::<_, i64>(4)?,
                "lastAccessed": row.get::<_, Option<i64>>(5)?,
            }))
        })?;
        rows.collect()
    })();

    match result {
        Ok(rows) => ok(rows),
        Err(e) => db_error(e),
    }
}

/// `DELETE /api/shared/{token}`
///
/// Revokes rather than deletes, so the access count and creation time survive
/// as a record that the link existed.
pub async fn revoke_share(state: web::Data<AppState>, path: web::Path<String>) -> impl Responder {
    let db = state.db.lock().unwrap();
    let token = path.into_inner();

    if let Err(e) = ensure_shares_table(&db.conn) {
        return db_error(e);
    }

    match db.conn.execute(
        "UPDATE session_shares SET revoked = 1 WHERE token = ?1",
        params![token],
    ) {
        Ok(0) => not_found("Share link"),
        Ok(_) => ok(json!({ "revoked": true })),
        Err(e) => db_error(e),
    }
}

/// `GET /api/shared/{token}`
///
/// Read a shared session. Answers 404 for a token that is unknown, revoked or
/// expired -- all three indistinguishable from outside, so a probe cannot use
/// the response to tell a real-but-closed link from a guess.
pub async fn read_shared(state: web::Data<AppState>, path: web::Path<String>) -> impl Responder {
    let db = state.db.lock().unwrap();
    let token = path.into_inner();

    if let Err(e) = ensure_shares_table(&db.conn) {
        return db_error(e);
    }

    let now = now_secs();
    let row: Option<(String, Option<i64>, i64)> = match db
        .conn
        .query_row(
            "SELECT session_id, expires_at, revoked FROM session_shares WHERE token = ?1",
            params![token],
            |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
        )
        .optional()
    {
        Ok(v) => v,
        Err(e) => return db_error(e),
    };

    let Some((session_id, expires_at, revoked)) = row else {
        return not_found("Share link");
    };
    if revoked != 0 || expires_at.is_some_and(|e| e <= now) {
        return not_found("Share link");
    }

    let loaded = match load_session(&db.conn, &session_id) {
        Ok(v) => v,
        Err(e) => return db_error(e),
    };
    let Some((title, provider, raw)) = loaded else {
        // The session was deleted after the link was made.
        return not_found("Session");
    };

    // Best-effort: a failed bookkeeping update must not deny a valid read.
    let _ = db.conn.execute(
        "UPDATE session_shares
         SET access_count = access_count + 1, last_accessed = ?1
         WHERE token = ?2",
        params![now, token],
    );

    let session: Value = serde_json::from_str(&raw).unwrap_or_else(|_| json!({}));
    ok(json!({
        "id": session_id,
        "title": title,
        "provider": provider,
        "messages": super::handlers_simple::extract_messages_from_session(&session),
        "readOnly": true,
    }))
}

// =============================================================================
// Semantic search
// =============================================================================
//
// Indexing is a separate, explicit step. Embedding every message in a store
// costs money and time proportional to its size, so a query must never
// silently trigger one: `GET /search/semantic` searches whatever has been
// indexed and says how much that was, and `POST /search/semantic/index` is
// what does the work.
//
// Without OPENAI_API_KEY both answer 503 naming the variable, exactly like
// /chat/completions. There is no lexical fallback here on purpose -- returning
// substring matches from an endpoint called "semantic" is how the old
// zero-vector embeddings bug looked from the outside: plausible output that
// silently was not the thing requested. `/search` already does substring
// matching and is the honest place for it.

/// Where vectors live. Shares the `embeddings` table from `sql/schema.sql`,
/// which has existed unused since the schema was written -- nothing in the
/// tree ever inserted a row.
fn ensure_embeddings_table(conn: &Connection) -> rusqlite::Result<()> {
    conn.execute_batch(
        "CREATE TABLE IF NOT EXISTS embeddings (
            id TEXT PRIMARY KEY,
            source_type TEXT NOT NULL,
            source_id TEXT NOT NULL,
            model TEXT NOT NULL,
            dimensions INTEGER NOT NULL,
            vector BLOB NOT NULL,
            created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
            metadata TEXT,
            UNIQUE(source_type, source_id, model)
        );
        CREATE INDEX IF NOT EXISTS idx_embeddings_source
            ON embeddings(source_type, model);",
    )
}

pub(crate) fn embedding_model() -> String {
    std::env::var("IRONBRIDGE_EMBEDDING_MODEL")
        .unwrap_or_else(|_| "text-embedding-3-small".to_string())
}

/// Little-endian f32 blob. SQLite has no vector type; this keeps the encoding
/// in one place so the reader cannot disagree with the writer.
pub(crate) fn encode_vector(v: &[f32]) -> Vec<u8> {
    v.iter().flat_map(|f| f.to_le_bytes()).collect()
}

pub(crate) fn decode_vector(bytes: &[u8]) -> Vec<f32> {
    bytes
        .chunks_exact(4)
        .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
        .collect()
}

/// Cosine similarity. Returns 0.0 for a zero-magnitude vector rather than
/// NaN, so one degenerate row cannot poison a whole ranking.
pub(crate) fn cosine(a: &[f32], b: &[f32]) -> f32 {
    if a.len() != b.len() {
        return 0.0;
    }
    let (mut dot, mut na, mut nb) = (0.0f32, 0.0f32, 0.0f32);
    for (x, y) in a.iter().zip(b.iter()) {
        dot += x * y;
        na += x * x;
        nb += y * y;
    }
    if na == 0.0 || nb == 0.0 {
        return 0.0;
    }
    dot / (na.sqrt() * nb.sqrt())
}

pub(crate) struct Embedder {
    client: reqwest::Client,
    api_key: String,
    base_url: String,
    model: String,
}

impl Embedder {
    /// `None` when no key is configured -- the caller turns that into a 503
    /// rather than proceeding with something that cannot work.
    pub(crate) fn from_env() -> Option<Self> {
        let api_key = std::env::var("OPENAI_API_KEY").unwrap_or_default();
        if api_key.trim().is_empty() {
            return None;
        }
        Some(Self {
            client: reqwest::Client::builder()
                .timeout(std::time::Duration::from_secs(60))
                .build()
                .ok()?,
            api_key,
            base_url: std::env::var("OPENAI_BASE_URL")
                .unwrap_or_else(|_| "https://api.openai.com/v1".into())
                .trim_end_matches('/')
                .to_string(),
            model: embedding_model(),
        })
    }

    /// One vector per input, in input order.
    ///
    /// The order check is not paranoia: the API returns an `index` per item and
    /// nothing guarantees the array arrives sorted. Trusting position silently
    /// attaches every embedding to the wrong text, which looks like a working
    /// index that returns nonsense.
    pub(crate) async fn embed(&self, inputs: &[String]) -> Result<Vec<Vec<f32>>, String> {
        #[derive(serde::Deserialize)]
        struct Item {
            embedding: Vec<f32>,
            index: usize,
        }
        #[derive(serde::Deserialize)]
        struct Resp {
            data: Vec<Item>,
        }

        let response = self
            .client
            .post(format!("{}/embeddings", self.base_url))
            .bearer_auth(&self.api_key)
            .json(&json!({ "model": self.model, "input": inputs }))
            .send()
            .await
            .map_err(|e| format!("embedding request failed: {e}"))?;

        let status = response.status();
        let text = response.text().await.unwrap_or_default();
        if !status.is_success() {
            return Err(format!(
                "embedding API returned {status}: {}",
                snippet(&text, 200)
            ));
        }

        let parsed: Resp = serde_json::from_str(&text)
            .map_err(|e| format!("embedding API returned unparseable JSON: {e}"))?;
        if parsed.data.len() != inputs.len() {
            return Err(format!(
                "embedding API returned {} vectors for {} inputs",
                parsed.data.len(),
                inputs.len()
            ));
        }

        let mut out = vec![Vec::new(); inputs.len()];
        for item in parsed.data {
            if item.index >= out.len() {
                return Err(format!(
                    "embedding API returned out-of-range index {}",
                    item.index
                ));
            }
            out[item.index] = item.embedding;
        }
        if out.iter().any(|v| v.is_empty()) {
            return Err("embedding API skipped an input".to_string());
        }
        Ok(out)
    }
}

/// Sessions rendered to one text per session, for embedding.
fn indexable_sessions(
    conn: &Connection,
    limit: i64,
) -> rusqlite::Result<Vec<(String, String, String)>> {
    let mut stmt = conn.prepare(
        "SELECT id, title, session_json FROM sessions ORDER BY updated_at DESC LIMIT ?1",
    )?;
    let rows = stmt.query_map(params![limit], |row| {
        let id: String = row.get(0)?;
        let title: String = row.get(1)?;
        let raw: String = row.get(2)?;
        Ok((id, title, raw))
    })?;
    rows.collect()
}

/// Title plus transcript, truncated. Embedding endpoints have token limits and
/// a whole session can exceed them; the head of a conversation is the part
/// that characterises it.
fn session_text(title: &str, raw: &str) -> String {
    let session: Value = serde_json::from_str(raw).unwrap_or_else(|_| json!({}));
    let mut text = String::from(title);
    if let Some(requests) = session.get("requests").and_then(|r| r.as_array()) {
        for request in requests {
            if let Some(t) = request.pointer("/message/text").and_then(|t| t.as_str()) {
                text.push('\n');
                text.push_str(t);
            }
            if let Some(parts) = request.get("response").and_then(|r| r.as_array()) {
                for p in parts {
                    if let Some(v) = p.get("value").and_then(|v| v.as_str()) {
                        text.push('\n');
                        text.push_str(v);
                    }
                }
            }
            if text.chars().count() > 6000 {
                break;
            }
        }
    }
    text.chars().take(6000).collect()
}

#[derive(Deserialize)]
pub struct IndexBody {
    /// How many of the most recently updated sessions to consider.
    #[serde(default)]
    pub limit: Option<i64>,
    /// Re-embed sessions that already have a vector for this model.
    #[serde(default)]
    pub force: Option<bool>,
}

/// `POST /api/search/semantic/index`
///
/// Embeds sessions that have no vector yet and reports what it did. Runs
/// synchronously: it is an explicit administrative action, and a caller that
/// asked to build an index should be told when it finished and what it cost.
pub async fn build_semantic_index(
    state: web::Data<AppState>,
    body: web::Json<IndexBody>,
) -> impl Responder {
    let Some(embedder) = Embedder::from_env() else {
        return fail(
            StatusCode::SERVICE_UNAVAILABLE,
            "No embedding model configured. Set OPENAI_API_KEY (and OPENAI_BASE_URL \
             for a local or self-hosted endpoint) on the server.",
        );
    };

    let limit = body.limit.unwrap_or(200).clamp(1, 2000);
    let force = body.force.unwrap_or(false);
    let model = embedder.model.clone();

    // Collect the work under the lock, then release it: embedding is a network
    // round trip and holding the database mutex across it would stall every
    // other request.
    let pending: Vec<(String, String)> = {
        let db = state.db.lock().unwrap();
        if let Err(e) = ensure_embeddings_table(&db.conn) {
            return db_error(e);
        }
        let sessions = match indexable_sessions(&db.conn, limit) {
            Ok(s) => s,
            Err(e) => return db_error(e),
        };
        let mut pending = Vec::new();
        for (id, title, raw) in sessions {
            if !force {
                let seen: Option<i64> = db
                    .conn
                    .query_row(
                        "SELECT 1 FROM embeddings
                         WHERE source_type = 'session' AND source_id = ?1 AND model = ?2",
                        params![id, model],
                        |r| r.get(0),
                    )
                    .optional()
                    .unwrap_or(None);
                if seen.is_some() {
                    continue;
                }
            }
            pending.push((id, session_text(&title, &raw)));
        }
        pending
    };

    if pending.is_empty() {
        return ok(json!({
            "model": model,
            "indexed": 0,
            "skipped": 0,
            "note": "Everything in range already has a vector for this model. Pass force to rebuild.",
        }));
    }

    // Batched: one request per session would be needlessly slow and costly.
    let mut indexed = 0usize;
    for chunk in pending.chunks(32) {
        let texts: Vec<String> = chunk.iter().map(|(_, t)| t.clone()).collect();
        let vectors = match embedder.embed(&texts).await {
            Ok(v) => v,
            Err(e) => {
                // Report partial progress rather than pretending nothing
                // happened: the rows already written are real.
                return fail(
                    StatusCode::BAD_GATEWAY,
                    format!("{e} (indexed {indexed} before this failure)"),
                );
            }
        };

        let db = state.db.lock().unwrap();
        for ((id, _), vector) in chunk.iter().zip(vectors.iter()) {
            let blob = encode_vector(vector);
            let row_id = uuid::Uuid::new_v4().to_string();
            if let Err(e) = db.conn.execute(
                "INSERT INTO embeddings
                    (id, source_type, source_id, model, dimensions, vector, created_at)
                 VALUES (?1, 'session', ?2, ?3, ?4, ?5, ?6)
                 ON CONFLICT(source_type, source_id, model)
                 DO UPDATE SET vector = excluded.vector,
                               dimensions = excluded.dimensions,
                               created_at = excluded.created_at",
                params![row_id, id, model, vector.len() as i64, blob, now_secs()],
            ) {
                return db_error(e);
            }
            indexed += 1;
        }
    }

    ok(json!({ "model": model, "indexed": indexed }))
}

#[derive(Deserialize)]
pub struct SemanticQuery {
    #[serde(default)]
    pub q: String,
    #[serde(default)]
    pub limit: Option<usize>,
}

/// `GET /api/search/semantic`
///
/// Ranks indexed sessions by cosine similarity to the query. Reports how many
/// vectors it searched, so an empty result from an empty index is
/// distinguishable from an empty result from a real one -- the difference
/// between "nothing matched" and "nothing to match against".
pub async fn semantic_search(
    state: web::Data<AppState>,
    query: web::Query<SemanticQuery>,
) -> impl Responder {
    let q = query.q.trim().to_string();
    if q.is_empty() {
        return fail(StatusCode::BAD_REQUEST, "q is required");
    }
    let limit = query.limit.unwrap_or(10).clamp(1, 100);

    let Some(embedder) = Embedder::from_env() else {
        return fail(
            StatusCode::SERVICE_UNAVAILABLE,
            "No embedding model configured. Set OPENAI_API_KEY (and OPENAI_BASE_URL \
             for a local or self-hosted endpoint) on the server.",
        );
    };
    let model = embedder.model.clone();

    let rows: Vec<(String, Vec<f32>)> = {
        let db = state.db.lock().unwrap();
        if let Err(e) = ensure_embeddings_table(&db.conn) {
            return db_error(e);
        }
        let collected = (|| -> rusqlite::Result<Vec<(String, Vec<f32>)>> {
            let mut stmt = db.conn.prepare(
                "SELECT source_id, vector FROM embeddings
                 WHERE source_type = 'session' AND model = ?1",
            )?;
            let it = stmt.query_map(params![model], |row| {
                let id: String = row.get(0)?;
                let blob: Vec<u8> = row.get(1)?;
                Ok((id, decode_vector(&blob)))
            })?;
            it.collect()
        })();
        match collected {
            Ok(v) => v,
            Err(e) => return db_error(e),
        }
    };

    if rows.is_empty() {
        return ok(json!({
            "query": q,
            "model": model,
            "searched": 0,
            "results": [],
            "note": "No sessions are indexed for this model. POST /api/search/semantic/index first.",
        }));
    }

    let query_vector = match embedder.embed(std::slice::from_ref(&q)).await {
        Ok(v) => v.into_iter().next().unwrap_or_default(),
        Err(e) => return fail(StatusCode::BAD_GATEWAY, e),
    };

    let mut scored: Vec<(String, f32)> = rows
        .into_iter()
        .map(|(id, v)| {
            let s = cosine(&query_vector, &v);
            (id, s)
        })
        .collect();
    let searched = scored.len();
    scored.sort_by(|a, b| b.1.total_cmp(&a.1));
    scored.truncate(limit);

    // Titles for the winners only.
    let db = state.db.lock().unwrap();
    let results: Vec<Value> = scored
        .into_iter()
        .map(|(id, score)| {
            let title: Option<String> = db
                .conn
                .query_row(
                    "SELECT title FROM sessions WHERE id = ?1",
                    params![id],
                    |r| r.get(0),
                )
                .optional()
                .unwrap_or(None);
            json!({
                "type": "session",
                "id": id,
                "title": title,
                "score": score,
            })
        })
        .collect();

    ok(json!({
        "query": q,
        "model": model,
        "searched": searched,
        "results": results,
    }))
}
/// Add these routes to the server's existing `/api` scope.
///
/// Deliberately *not* a second `web::scope("/api")`. Actix matches scopes in
/// registration order, and a scope that matches the prefix handles the request
/// even when no resource inside it matches -- so an extra `/api` scope
/// registered first silently swallowed every read route in `configure_routes`
/// and the whole API 404'd. Sharing one scope is the only arrangement that
/// works. (`/api/inbox` gets away with its own scope because its prefix is
/// narrower and cannot shadow anything else.)
///
/// Routes with a path that the shared scope already registers -- `/sessions`,
/// `/sessions/{id}`, `/swarms/{id}` -- are merged into that resource by actix
/// rather than shadowing it, so the existing `GET` handlers keep working.
pub(super) fn attach_write_routes(scope: actix_web::Scope) -> actix_web::Scope {
    scope
        .route("/sessions", web::post().to(create_session))
        .route("/sessions/{id}", web::delete().to(delete_session))
        .route("/sessions/{id}/messages", web::post().to(create_message))
        .route(
            "/sessions/{id}/checkpoints",
            web::get().to(list_checkpoints),
        )
        .route(
            "/sessions/{id}/checkpoints",
            web::post().to(create_checkpoint),
        )
        .route("/sessions/{id}/commits", web::get().to(session_commits))
        .route("/search", web::get().to(search))
        .route("/stats/providers", web::get().to(provider_stats))
        .route("/swarms/{id}", web::put().to(update_swarm))
        .route("/providers/{id}/test", web::post().to(test_provider))
        .route("/chat/completions", web::post().to(chat_completion))
        .route("/harvest", web::post().to(run_harvest))
        .route("/stats/timeline", web::get().to(timeline_stats))
        .route("/workspaces", web::post().to(create_workspace))
        .route("/workspaces/{id}", web::put().to(update_workspace))
        .route("/workspaces/{id}", web::delete().to(delete_workspace))
        .route("/sessions/{id}/fork", web::post().to(fork_session))
        .route("/sessions/merge", web::post().to(merge_sessions))
        .route("/sessions/{id}/export", web::get().to(export_session))
        .route("/sessions/{id}/share", web::post().to(create_share))
        .route("/sessions/{id}/share", web::get().to(list_shares))
        .route("/shared/{token}", web::get().to(read_shared))
        .route("/shared/{token}", web::delete().to(revoke_share))
        .route("/search/semantic", web::get().to(semantic_search))
        .route(
            "/search/semantic/index",
            web::post().to(build_semantic_index),
        )
}

/// Test-only: these routes alone, under their own `/api` scope.
///
/// Safe here precisely because nothing else is mounted alongside them.
#[cfg(test)]
fn configure_write_routes(cfg: &mut web::ServiceConfig) {
    cfg.service(attach_write_routes(web::scope("/api")));
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ChatDatabase;
    use actix_web::{test, App};
    use std::path::PathBuf;

    /// Builds the database the way `start_server` does -- harvest schema
    /// first, then open -- so these tests also cover the ordering that makes
    /// every session endpoint work on a machine that never ran a harvest.
    fn temp_state(tag: &str) -> (web::Data<AppState>, tempfile::TempDir) {
        let dir = tempfile::tempdir().expect("tempdir");
        let path: PathBuf = dir.path().join(format!("{tag}.db"));
        crate::commands::create_harvest_database(&path).expect("harvest schema");
        let db = ChatDatabase::open(&path).expect("open");
        (web::Data::new(AppState::new(db, path)), dir)
    }

    macro_rules! app {
        ($state:expr) => {
            test::init_service(
                App::new()
                    .app_data($state.clone())
                    .configure(configure_write_routes),
            )
            .await
        };
    }

    async fn body_json(resp: actix_web::dev::ServiceResponse) -> Value {
        let bytes = test::read_body(resp).await;
        serde_json::from_slice(&bytes).expect("json body")
    }

    async fn make_session<S>(app: &S) -> String
    where
        S: actix_web::dev::Service<
            actix_http::Request,
            Response = actix_web::dev::ServiceResponse,
            Error = actix_web::Error,
        >,
    {
        let resp = test::call_service(
            app,
            test::TestRequest::post()
                .uri("/api/sessions")
                .set_json(json!({ "title": "S" }))
                .to_request(),
        )
        .await;
        body_json(resp).await["data"]["id"]
            .as_str()
            .expect("id")
            .to_string()
    }

    #[tokio::test]
    async fn a_created_session_is_readable_and_starts_empty() {
        let (state, _d) = temp_state("create");
        let app = app!(state);

        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/sessions")
                .set_json(json!({ "title": "Hello", "provider": "copilot" }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::CREATED);

        let body = body_json(resp).await;
        assert_eq!(body["data"]["title"], "Hello");
        assert_eq!(body["data"]["message_count"], 0);
        assert!(body["data"]["id"].as_str().is_some_and(|s| !s.is_empty()));
    }

    #[tokio::test]
    async fn deleting_a_session_that_does_not_exist_is_404_not_500() {
        let (state, _d) = temp_state("del404");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::delete()
                .uri("/api/sessions/nope")
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn a_deleted_session_is_gone() {
        let (state, _d) = temp_state("del");
        let app = app!(state);
        let id = make_session(&app).await;

        let resp = test::call_service(
            &app,
            test::TestRequest::delete()
                .uri(&format!("/api/sessions/{id}"))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);

        let db = state.db.lock().unwrap();
        let remaining: i64 = db
            .conn
            .query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))
            .unwrap();
        assert_eq!(remaining, 0);
    }

    #[tokio::test]
    async fn a_user_message_then_an_assistant_reply_pair_into_one_request() {
        let (state, _d) = temp_state("msg");
        let app = app!(state);
        let id = make_session(&app).await;

        for (role, content) in [("user", "ping"), ("assistant", "pong")] {
            let resp = test::call_service(
                &app,
                test::TestRequest::post()
                    .uri(&format!("/api/sessions/{id}/messages"))
                    .set_json(json!({ "role": role, "content": content }))
                    .to_request(),
            )
            .await;
            assert_eq!(resp.status(), StatusCode::CREATED, "{role} rejected");
        }

        // The reply must attach to the existing request rather than open a new
        // one, or the read path pairs it with the wrong prompt.
        let db = state.db.lock().unwrap();
        let raw: String = db
            .conn
            .query_row(
                "SELECT session_json FROM sessions WHERE id = ?1",
                params![id],
                |r| r.get(0),
            )
            .unwrap();
        let parsed: Value = serde_json::from_str(&raw).unwrap();
        let requests = parsed["requests"].as_array().unwrap();
        assert_eq!(
            requests.len(),
            1,
            "reply should not create a second request"
        );
        assert_eq!(requests[0]["message"]["text"], "ping");
        assert_eq!(requests[0]["response"][0]["value"], "pong");

        let count: i64 = db
            .conn
            .query_row(
                "SELECT message_count FROM sessions WHERE id = ?1",
                params![id],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(count, 2);
    }

    #[tokio::test]
    async fn an_empty_message_is_rejected_rather_than_stored() {
        let (state, _d) = temp_state("empty");
        let app = app!(state);
        let id = make_session(&app).await;

        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri(&format!("/api/sessions/{id}/messages"))
                .set_json(json!({ "role": "user", "content": "   " }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn an_unknown_role_is_rejected() {
        let (state, _d) = temp_state("role");
        let app = app!(state);
        let id = make_session(&app).await;

        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri(&format!("/api/sessions/{id}/messages"))
                .set_json(json!({ "role": "wizard", "content": "abracadabra" }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn posting_a_message_to_a_missing_session_is_404() {
        let (state, _d) = temp_state("msg404");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/sessions/ghost/messages")
                .set_json(json!({ "role": "user", "content": "hi" }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn checkpoints_round_trip() {
        let (state, _d) = temp_state("ckpt");
        let app = app!(state);
        let id = make_session(&app).await;

        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri(&format!("/api/sessions/{id}/checkpoints"))
                .set_json(json!({ "name": "before refactor", "gitBranch": "main" }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::CREATED);

        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri(&format!("/api/sessions/{id}/checkpoints"))
                .to_request(),
        )
        .await;
        let body = body_json(resp).await;
        let rows = body["data"].as_array().expect("array");
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0]["name"], "before refactor");
        assert_eq!(rows[0]["gitBranch"], "main");
    }

    #[tokio::test]
    async fn listing_checkpoints_on_a_fresh_database_is_empty_not_an_error() {
        // The table is created on demand; a missing one must not read as 500.
        let (state, _d) = temp_state("ckpt-empty");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri("/api/sessions/whatever/checkpoints")
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_json(resp).await["data"], json!([]));
    }

    #[tokio::test]
    async fn a_checkpoint_on_a_missing_session_is_404() {
        let (state, _d) = temp_state("ckpt404");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/sessions/ghost/checkpoints")
                .set_json(json!({ "name": "x" }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn search_matches_titles_and_ignores_case() {
        let (state, _d) = temp_state("search");
        let app = app!(state);
        for title in ["Rust Refactor", "unrelated"] {
            test::call_service(
                &app,
                test::TestRequest::post()
                    .uri("/api/sessions")
                    .set_json(json!({ "title": title }))
                    .to_request(),
            )
            .await;
        }

        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri("/api/search?q=rust")
                .to_request(),
        )
        .await;
        let body = body_json(resp).await;
        let rows = body["data"].as_array().expect("array");
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0]["title"], "Rust Refactor");
        assert_eq!(rows[0]["type"], "session");
    }

    /// Search finds a term in message *content*, not just the title, and
    /// returns a snippet. This branch of `/api/search` was untested; the CLI's
    /// content search shipped broken for months behind exactly that kind of
    /// gap, so it is worth a live assertion here.
    #[tokio::test]
    async fn search_finds_message_content_with_a_snippet() {
        let (state, _d) = temp_state("search-content");
        let app = app!(state);
        let sid = make_session(&app).await;
        {
            let db = state.db.lock().unwrap();
            db.conn
                .execute(
                    "INSERT INTO messages_v2 (session_id, message_index, role, content_raw)
                     VALUES (?1, 0, 'assistant', 'a long discussion about quicksort partitioning and pivots')",
                    params![sid],
                )
                .expect("insert message");
        }

        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri("/api/search?q=quicksort")
                .to_request(),
        )
        .await;
        let body = body_json(resp).await;
        let rows = body["data"].as_array().expect("array");
        let hit = rows
            .iter()
            .find(|r| r["type"] == "message")
            .expect("a message-content hit");
        assert_eq!(hit["sessionId"], sid);
        assert!(
            hit["snippet"]
                .as_str()
                .unwrap_or_default()
                .contains("quicksort"),
            "snippet missing the term: {}",
            hit["snippet"]
        );
    }

    /// A word prefix matches: "quick" finds "quicksort". The FTS fast path
    /// searches by prefix term, which is what a search box is expected to do.
    #[tokio::test]
    async fn search_matches_a_word_prefix() {
        let (state, _d) = temp_state("search-prefix");
        let app = app!(state);
        let sid = make_session(&app).await;
        {
            let db = state.db.lock().unwrap();
            db.conn
                .execute(
                    "INSERT INTO messages_v2 (session_id, message_index, role, content_raw)
                     VALUES (?1, 0, 'assistant', 'implementing quicksort today')",
                    params![sid],
                )
                .expect("insert message");
        }
        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri("/api/search?q=quick")
                .to_request(),
        )
        .await;
        let body = body_json(resp).await;
        let rows = body["data"].as_array().expect("array");
        assert!(
            rows.iter()
                .any(|r| r["type"] == "message" && r["sessionId"] == sid),
            "prefix search found nothing: {rows:?}"
        );
    }

    /// Without the FTS index, search still works via the LIKE fallback -- and
    /// because LIKE is a substring match, a mid-word fragment ("sort" inside
    /// "quicksort") that the token-prefix index could not find proves the
    /// fallback actually ran.
    #[tokio::test]
    async fn search_falls_back_to_like_without_the_fts_index() {
        let (state, _d) = temp_state("search-fallback");
        let app = app!(state);
        let sid = make_session(&app).await;
        {
            let db = state.db.lock().unwrap();
            db.conn
                .execute(
                    "INSERT INTO messages_v2 (session_id, message_index, role, content_raw)
                     VALUES (?1, 0, 'assistant', 'implementing quicksort today')",
                    params![sid],
                )
                .expect("insert message");
            db.conn
                .execute_batch(
                    "DROP TRIGGER IF EXISTS messages_v2_ai;
                     DROP TRIGGER IF EXISTS messages_v2_ad;
                     DROP TRIGGER IF EXISTS messages_v2_au;
                     DROP TABLE IF EXISTS messages_fts;",
                )
                .expect("drop fts");
        }
        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri("/api/search?q=sort")
                .to_request(),
        )
        .await;
        let body = body_json(resp).await;
        let rows = body["data"].as_array().expect("array");
        assert!(
            rows.iter()
                .any(|r| r["type"] == "message" && r["sessionId"] == sid),
            "LIKE fallback found nothing: {rows:?}"
        );
    }

    #[test]
    fn fts_query_from_sanitises_and_prefixes() {
        assert_eq!(
            fts_query_from("quick sort").as_deref(),
            Some("quick* sort*")
        );
        assert_eq!(fts_query_from("a*b (c)").as_deref(), Some("ab* c*"));
        assert_eq!(fts_query_from("   "), None);
        assert_eq!(fts_query_from("!@#$"), None);
    }

    #[tokio::test]
    async fn an_empty_search_returns_nothing_rather_than_everything() {
        let (state, _d) = temp_state("search-empty");
        let app = app!(state);
        make_session(&app).await;
        let resp = test::call_service(
            &app,
            test::TestRequest::get().uri("/api/search?q=").to_request(),
        )
        .await;
        assert_eq!(body_json(resp).await["data"], json!([]));
    }

    #[tokio::test]
    async fn provider_stats_group_by_provider() {
        let (state, _d) = temp_state("stats");
        let app = app!(state);
        for provider in ["copilot", "copilot", "cursor"] {
            test::call_service(
                &app,
                test::TestRequest::post()
                    .uri("/api/sessions")
                    .set_json(json!({ "title": "t", "provider": provider }))
                    .to_request(),
            )
            .await;
        }

        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri("/api/stats/providers")
                .to_request(),
        )
        .await;
        let body = body_json(resp).await;
        assert_eq!(body["data"]["copilot"]["sessions"], 2);
        assert_eq!(body["data"]["cursor"]["sessions"], 1);
    }

    #[tokio::test]
    async fn updating_a_missing_swarm_is_404() {
        let (state, _d) = temp_state("swarm");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::put()
                .uri("/api/swarms/ghost")
                .set_json(json!({ "name": "renamed" }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn a_completion_with_no_messages_is_rejected_before_any_network_call() {
        let (state, _d) = temp_state("chat-empty");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/chat/completions")
                .set_json(json!({ "messages": [] }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn a_completion_without_a_configured_model_says_so() {
        // Never a canned reply: a fabricated completion presented as model
        // output would be the worst failure this endpoint could have.
        if !std::env::var("OPENAI_API_KEY")
            .unwrap_or_default()
            .trim()
            .is_empty()
        {
            return; // A real key is configured; the no-key contract does not apply.
        }
        let (state, _d) = temp_state("chat");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/chat/completions")
                .set_json(json!({ "messages": [{ "role": "user", "content": "hi" }] }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
        let body = body_json(resp).await;
        assert!(body["error"]
            .as_str()
            .unwrap_or_default()
            .contains("OPENAI_API_KEY"));
    }

    #[tokio::test]
    async fn an_untestable_provider_says_so_rather_than_reporting_success() {
        let (state, _d) = temp_state("ptest");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/providers/copilot/test")
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::NOT_IMPLEMENTED);
    }

    #[tokio::test]
    async fn commits_for_a_session_without_a_workspace_are_empty() {
        let (state, _d) = temp_state("commits");
        let app = app!(state);
        let id = make_session(&app).await;
        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri(&format!("/api/sessions/{id}/commits"))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_json(resp).await["data"], json!([]));
    }

    #[tokio::test]
    async fn commits_for_a_missing_session_are_404() {
        let (state, _d) = temp_state("commits404");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri("/api/sessions/ghost/commits")
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[test]
    fn snippet_does_not_split_a_multibyte_character() {
        let text = "\u{3042}".repeat(300);
        let out = snippet(&text, 200);
        assert!(out.ends_with("..."));
        assert_eq!(out.chars().count(), 203);
    }

    // ---------------------------------------------------------------------
    // Timeline
    // ---------------------------------------------------------------------

    #[tokio::test]
    async fn the_timeline_groups_sessions_by_day() {
        let (state, _d) = temp_state("timeline");
        let app = app!(state);
        for _ in 0..3 {
            make_session(&app).await;
        }

        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri("/api/stats/timeline?days=7")
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        let points = body["data"]["points"].as_array().expect("points");
        assert_eq!(points.len(), 1, "three sessions today is one day");
        assert_eq!(points[0]["sessions"], 3);
    }

    /// Quiet days are omitted rather than zero-filled, so an empty store reads
    /// as empty instead of as a run of zeroes it never recorded.
    #[tokio::test]
    async fn an_empty_store_has_no_timeline_points() {
        let (state, _d) = temp_state("timeline-empty");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri("/api/stats/timeline")
                .to_request(),
        )
        .await;
        assert_eq!(body_json(resp).await["data"]["points"], json!([]));
    }

    // ---------------------------------------------------------------------
    // Workspaces
    // ---------------------------------------------------------------------

    #[tokio::test]
    async fn a_workspace_round_trips_and_deleting_it_keeps_its_sessions() {
        let (state, _d) = temp_state("ws");
        let app = app!(state);

        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/workspaces")
                .set_json(json!({ "name": "proj", "path": "/tmp/proj" }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::CREATED);
        let ws_id = body_json(resp).await["data"]["id"]
            .as_str()
            .expect("id")
            .to_string();

        // A session filed under it.
        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/sessions")
                .set_json(json!({ "title": "s", "workspaceId": ws_id }))
                .to_request(),
        )
        .await;
        let session_id = body_json(resp).await["data"]["id"]
            .as_str()
            .expect("id")
            .to_string();

        let resp = test::call_service(
            &app,
            test::TestRequest::delete()
                .uri(&format!("/api/workspaces/{ws_id}"))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);

        // The conversation must survive; only its filing is undone.
        let db = state.db.lock().unwrap();
        let (count, workspace): (i64, Option<String>) = db
            .conn
            .query_row(
                "SELECT COUNT(*), MAX(workspace_id) FROM sessions WHERE id = ?1",
                params![session_id],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .unwrap();
        assert_eq!(
            count, 1,
            "deleting a workspace must not delete its sessions"
        );
        assert!(workspace.is_none(), "the session should be detached");
    }

    #[tokio::test]
    async fn a_workspace_needs_a_name() {
        let (state, _d) = temp_state("ws-noname");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/workspaces")
                .set_json(json!({ "path": "/tmp/x" }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn updating_a_missing_workspace_is_404() {
        let (state, _d) = temp_state("ws-404");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::put()
                .uri("/api/workspaces/ghost")
                .set_json(json!({ "name": "x" }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    // ---------------------------------------------------------------------
    // Fork, merge, export
    // ---------------------------------------------------------------------

    async fn session_with_exchange<S>(app: &S) -> String
    where
        S: actix_web::dev::Service<
            actix_http::Request,
            Response = actix_web::dev::ServiceResponse,
            Error = actix_web::Error,
        >,
    {
        let id = make_session(app).await;
        for (role, content) in [("user", "ping"), ("assistant", "pong")] {
            test::call_service(
                app,
                test::TestRequest::post()
                    .uri(&format!("/api/sessions/{id}/messages"))
                    .set_json(json!({ "role": role, "content": content }))
                    .to_request(),
            )
            .await;
        }
        id
    }

    /// A fork must be independent: appending to the copy must not touch the
    /// original, or "fork" would mean "alias".
    #[tokio::test]
    async fn a_fork_is_independent_of_its_source() {
        let (state, _d) = temp_state("fork");
        let app = app!(state);
        let source = session_with_exchange(&app).await;

        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri(&format!("/api/sessions/{source}/fork"))
                .set_json(json!({}))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::CREATED);
        let body = body_json(resp).await;
        let fork = body["data"]["id"].as_str().expect("id").to_string();
        assert_eq!(body["data"]["parentSessionId"], source);
        assert_eq!(body["data"]["message_count"], 2);

        test::call_service(
            &app,
            test::TestRequest::post()
                .uri(&format!("/api/sessions/{fork}/messages"))
                .set_json(json!({ "role": "user", "content": "only in the fork" }))
                .to_request(),
        )
        .await;

        let db = state.db.lock().unwrap();
        let source_count: i64 = db
            .conn
            .query_row(
                "SELECT message_count FROM sessions WHERE id = ?1",
                params![source],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(source_count, 2, "the source must be untouched");
    }

    #[tokio::test]
    async fn forking_a_missing_session_is_404() {
        let (state, _d) = temp_state("fork404");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/sessions/ghost/fork")
                .set_json(json!({}))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    /// Merging must not consume its inputs -- an accidental merge has to be
    /// recoverable.
    #[tokio::test]
    async fn merging_leaves_the_sources_intact() {
        let (state, _d) = temp_state("merge");
        let app = app!(state);
        let a = session_with_exchange(&app).await;
        let b = session_with_exchange(&app).await;

        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/sessions/merge")
                .set_json(json!({ "sessionIds": [a, b], "title": "combined" }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::CREATED);
        let body = body_json(resp).await;
        assert_eq!(body["data"]["message_count"], 4);
        assert_eq!(body["data"]["title"], "combined");

        let db = state.db.lock().unwrap();
        let remaining: i64 = db
            .conn
            .query_row(
                "SELECT COUNT(*) FROM sessions WHERE id IN (?1, ?2)",
                params![a, b],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(remaining, 2, "merge must not delete its sources");
    }

    #[tokio::test]
    async fn merging_fewer_than_two_sessions_is_rejected() {
        let (state, _d) = temp_state("merge-one");
        let app = app!(state);
        let a = make_session(&app).await;
        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/sessions/merge")
                .set_json(json!({ "sessionIds": [a] }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn merging_names_the_session_it_could_not_find() {
        let (state, _d) = temp_state("merge-missing");
        let app = app!(state);
        let a = make_session(&app).await;
        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/sessions/merge")
                .set_json(json!({ "sessionIds": [a, "ghost"] }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn export_renders_markdown_and_json() {
        let (state, _d) = temp_state("export");
        let app = app!(state);
        let id = session_with_exchange(&app).await;

        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri(&format!("/api/sessions/{id}/export?format=markdown"))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = String::from_utf8(test::read_body(resp).await.to_vec()).unwrap();
        assert!(body.contains("## User"), "missing user turn:\n{body}");
        assert!(body.contains("ping"), "missing prompt text");
        assert!(body.contains("pong"), "missing reply text");

        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri(&format!("/api/sessions/{id}/export?format=json"))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn an_unknown_export_format_is_rejected() {
        let (state, _d) = temp_state("export-bad");
        let app = app!(state);
        let id = make_session(&app).await;
        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri(&format!("/api/sessions/{id}/export?format=pdf"))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn a_filename_is_stripped_of_path_characters() {
        assert_eq!(safe_filename("../../etc/passwd"), "etc-passwd");
        assert_eq!(safe_filename("a/b\\c:d"), "a-b-c-d");
        assert_eq!(safe_filename("   "), "session");
        assert!(safe_filename(&"x".repeat(200)).chars().count() <= 60);
    }

    // ---------------------------------------------------------------------
    // Sharing
    // ---------------------------------------------------------------------

    #[tokio::test]
    async fn a_share_link_reads_the_session_then_stops_when_revoked() {
        let (state, _d) = temp_state("share");
        let app = app!(state);
        let id = session_with_exchange(&app).await;

        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri(&format!("/api/sessions/{id}/share"))
                .set_json(json!({}))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::CREATED);
        let body = body_json(resp).await;
        let token = body["data"]["token"].as_str().expect("token").to_string();
        assert_eq!(token.len(), 64, "expected 256 bits of hex");

        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri(&format!("/api/shared/{token}"))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let shared = body_json(resp).await;
        assert_eq!(shared["data"]["id"], id);
        assert_eq!(shared["data"]["readOnly"], true);

        let resp = test::call_service(
            &app,
            test::TestRequest::delete()
                .uri(&format!("/api/shared/{token}"))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);

        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri(&format!("/api/shared/{token}"))
                .to_request(),
        )
        .await;
        assert_eq!(
            resp.status(),
            StatusCode::NOT_FOUND,
            "a revoked link must stop working"
        );
    }

    /// Expiry is derived on read. Without that, a link stays live until some
    /// sweeper runs -- which is exactly the failure the inbox had.
    #[tokio::test]
    async fn an_expired_link_is_dead_without_anything_having_swept_it() {
        let (state, _d) = temp_state("share-exp");
        let app = app!(state);
        let id = make_session(&app).await;

        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri(&format!("/api/sessions/{id}/share"))
                .set_json(json!({ "expiresInHours": 1 }))
                .to_request(),
        )
        .await;
        let token = body_json(resp).await["data"]["token"]
            .as_str()
            .expect("token")
            .to_string();

        // Backdate it rather than sleeping.
        {
            let db = state.db.lock().unwrap();
            db.conn
                .execute(
                    "UPDATE session_shares SET expires_at = ?1 WHERE token = ?2",
                    params![now_secs() - 60, token],
                )
                .unwrap();
        }

        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri(&format!("/api/shared/{token}"))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);

        // And the owner's listing should say so, not show it as active.
        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri(&format!("/api/sessions/{id}/share"))
                .to_request(),
        )
        .await;
        let rows = body_json(resp).await;
        assert_eq!(rows["data"][0]["status"], "expired");
    }

    #[tokio::test]
    async fn an_unknown_share_token_is_404_not_500() {
        let (state, _d) = temp_state("share-unknown");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri("/api/shared/deadbeef")
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn sharing_a_missing_session_is_404() {
        let (state, _d) = temp_state("share-404");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/sessions/ghost/share")
                .set_json(json!({}))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn a_non_positive_expiry_is_rejected() {
        let (state, _d) = temp_state("share-badexp");
        let app = app!(state);
        let id = make_session(&app).await;
        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri(&format!("/api/sessions/{id}/share"))
                .set_json(json!({ "expiresInHours": 0 }))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn share_tokens_do_not_repeat() {
        let a = new_share_token();
        let b = new_share_token();
        assert_ne!(a, b);
        assert_eq!(a.len(), 64);
        assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
    }

    // ---------------------------------------------------------------------
    // Semantic search
    // ---------------------------------------------------------------------

    #[test]
    fn cosine_is_one_for_identical_vectors_and_zero_for_orthogonal() {
        assert!((cosine(&[1.0, 0.0], &[1.0, 0.0]) - 1.0).abs() < 1e-6);
        assert!(cosine(&[1.0, 0.0], &[0.0, 1.0]).abs() < 1e-6);
        assert!((cosine(&[1.0, 0.0], &[-1.0, 0.0]) + 1.0).abs() < 1e-6);
    }

    /// A zero vector must score 0, not NaN -- one degenerate row would
    /// otherwise scramble the whole ranking when sorted.
    #[test]
    fn cosine_handles_degenerate_input() {
        assert_eq!(cosine(&[0.0, 0.0], &[1.0, 1.0]), 0.0);
        assert_eq!(cosine(&[1.0], &[1.0, 2.0]), 0.0, "length mismatch scores 0");
    }

    #[test]
    fn vectors_survive_the_blob_round_trip() {
        let v = vec![0.5f32, -1.25, 0.0, 3.75];
        assert_eq!(decode_vector(&encode_vector(&v)), v);
    }

    #[tokio::test]
    async fn semantic_search_without_a_key_says_what_to_set() {
        if !std::env::var("OPENAI_API_KEY")
            .unwrap_or_default()
            .trim()
            .is_empty()
        {
            return; // a real key is configured; this contract does not apply
        }
        let (state, _d) = temp_state("sem");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri("/api/search/semantic?q=hello")
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
        let body = body_json(resp).await;
        assert!(body["error"]
            .as_str()
            .unwrap_or_default()
            .contains("OPENAI_API_KEY"));
    }

    /// It must refuse rather than quietly falling back to substring matching.
    /// `/search` is where that behaviour lives, and an endpoint called
    /// "semantic" returning lexical hits is the failure this codebase already
    /// had once with zero-vector embeddings.
    #[tokio::test]
    async fn semantic_search_does_not_fall_back_to_substring_matching() {
        if !std::env::var("OPENAI_API_KEY")
            .unwrap_or_default()
            .trim()
            .is_empty()
        {
            return;
        }
        let (state, _d) = temp_state("sem-nofallback");
        let app = app!(state);
        test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/sessions")
                .set_json(json!({ "title": "hello world" }))
                .to_request(),
        )
        .await;

        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri("/api/search/semantic?q=hello")
                .to_request(),
        )
        .await;
        assert_eq!(
            resp.status(),
            StatusCode::SERVICE_UNAVAILABLE,
            "an exact-title match must not be returned as a semantic result"
        );
    }

    #[tokio::test]
    async fn an_empty_semantic_query_is_rejected_before_any_network_call() {
        let (state, _d) = temp_state("sem-empty");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::get()
                .uri("/api/search/semantic?q=")
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn indexing_without_a_key_says_what_to_set() {
        if !std::env::var("OPENAI_API_KEY")
            .unwrap_or_default()
            .trim()
            .is_empty()
        {
            return;
        }
        let (state, _d) = temp_state("sem-index");
        let app = app!(state);
        let resp = test::call_service(
            &app,
            test::TestRequest::post()
                .uri("/api/search/semantic/index")
                .set_json(json!({}))
                .to_request(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
    }
}

/// Tests for the embedding client's network contract.
///
/// The embed-index-rank path was shipped and documented as unverified: no
/// embedding endpoint had ever answered it. These stand up a real HTTP server
/// and drive the real client against it, so the request shape, the auth
/// header, the response parsing and -- most importantly -- the reordering are
/// exercised against actual traffic rather than asserted about.
#[cfg(test)]
mod embedder_network_tests {
    use super::Embedder;
    use actix_web::{web, App, HttpResponse, HttpServer};
    use serde_json::json;
    use std::sync::{Arc, Mutex};

    /// What the last request carried, so the test can assert on it.
    #[derive(Default)]
    struct Seen {
        authorization: Option<String>,
        model: Option<String>,
        inputs: Vec<String>,
    }

    /// Start a local OpenAI-compatible `/embeddings` endpoint.
    ///
    /// `shuffle` returns `data` in reverse order with correct `index` fields,
    /// which is legal and which the real API gives no guarantee against.
    async fn serve(shuffle: bool) -> (String, Arc<Mutex<Seen>>) {
        let seen = Arc::new(Mutex::new(Seen::default()));
        let captured = seen.clone();

        let server = HttpServer::new(move || {
            let captured = captured.clone();
            App::new().route(
                "/embeddings",
                web::post().to(
                    move |req: actix_web::HttpRequest, body: web::Json<serde_json::Value>| {
                        let captured = captured.clone();
                        async move {
                            let auth = req
                                .headers()
                                .get("authorization")
                                .and_then(|v| v.to_str().ok())
                                .map(str::to_string);
                            let inputs: Vec<String> = body["input"]
                                .as_array()
                                .map(|a| {
                                    a.iter()
                                        .map(|v| v.as_str().unwrap_or_default().to_string())
                                        .collect()
                                })
                                .unwrap_or_default();
                            {
                                let mut s = captured.lock().unwrap();
                                s.authorization = auth;
                                s.model = body["model"].as_str().map(str::to_string);
                                s.inputs = inputs.clone();
                            }

                            // One dimension per input position, so a vector is
                            // trivially traceable back to the text it came from.
                            let mut data: Vec<serde_json::Value> = inputs
                                .iter()
                                .enumerate()
                                .map(|(i, _)| {
                                    let mut v = vec![0.0f32; inputs.len()];
                                    v[i] = 1.0;
                                    json!({ "object": "embedding", "index": i, "embedding": v })
                                })
                                .collect();
                            if shuffle {
                                data.reverse();
                            }
                            HttpResponse::Ok().json(json!({ "object": "list", "data": data }))
                        }
                    },
                ),
            )
        })
        .bind(("127.0.0.1", 0))
        .expect("bind");

        let port = server.addrs()[0].port();
        let running = server.run();
        tokio::spawn(running);
        (format!("http://127.0.0.1:{port}"), seen)
    }

    fn embedder(base_url: String) -> Embedder {
        Embedder {
            client: reqwest::Client::new(),
            api_key: "test-key".to_string(),
            base_url,
            model: "test-model".to_string(),
        }
    }

    /// The one that matters. The API returns an `index` per item and does not
    /// promise sorted output; trusting array position attaches every vector to
    /// the wrong text, which looks like a working index returning nonsense.
    #[tokio::test]
    async fn vectors_come_back_in_input_order_even_when_the_api_shuffles_them() {
        let (base, _seen) = serve(true).await;
        let inputs = vec![
            "first".to_string(),
            "second".to_string(),
            "third".to_string(),
        ];
        let out = embedder(base).embed(&inputs).await.expect("embed");

        assert_eq!(out.len(), 3);
        // Input i was answered with a one-hot vector at dimension i, so this
        // fails loudly if the reordering is dropped.
        for (i, v) in out.iter().enumerate() {
            assert_eq!(v[i], 1.0, "input {i} got the wrong vector: {v:?}");
            assert_eq!(v.iter().filter(|x| **x != 0.0).count(), 1);
        }
    }

    #[tokio::test]
    async fn the_request_carries_the_bearer_token_and_the_model() {
        let (base, seen) = serve(false).await;
        let inputs = vec!["hello".to_string()];
        embedder(base).embed(&inputs).await.expect("embed");

        let s = seen.lock().unwrap();
        assert_eq!(s.authorization.as_deref(), Some("Bearer test-key"));
        assert_eq!(s.model.as_deref(), Some("test-model"));
        assert_eq!(s.inputs, inputs);
    }

    /// A short count means some input silently got no vector. Returning what
    /// arrived would attach vectors to the wrong texts from that point on.
    #[tokio::test]
    async fn a_response_with_fewer_vectors_than_inputs_is_an_error() {
        let server = HttpServer::new(|| {
            App::new().route(
                "/embeddings",
                web::post().to(|| async {
                    HttpResponse::Ok().json(json!({
                        "data": [{ "object": "embedding", "index": 0, "embedding": [1.0] }]
                    }))
                }),
            )
        })
        .bind(("127.0.0.1", 0))
        .expect("bind");
        let port = server.addrs()[0].port();
        tokio::spawn(server.run());

        let err = embedder(format!("http://127.0.0.1:{port}"))
            .embed(&["a".to_string(), "b".to_string()])
            .await
            .expect_err("a short response must not be accepted");
        assert!(err.contains("1 vectors for 2 inputs"), "{err}");
    }

    /// An upstream failure must surface, not be mistaken for an empty result.
    #[tokio::test]
    async fn an_error_status_is_reported_with_the_body() {
        let server = HttpServer::new(|| {
            App::new().route(
                "/embeddings",
                web::post().to(|| async {
                    HttpResponse::Unauthorized().json(json!({ "error": { "message": "bad key" } }))
                }),
            )
        })
        .bind(("127.0.0.1", 0))
        .expect("bind");
        let port = server.addrs()[0].port();
        tokio::spawn(server.run());

        let err = embedder(format!("http://127.0.0.1:{port}"))
            .embed(&["a".to_string()])
            .await
            .expect_err("401 must be an error");
        assert!(err.contains("401"), "{err}");
        assert!(err.contains("bad key"), "{err}");
    }
}