ouija 0.1.0-alpha.201

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

use axum::body::Bytes;
use axum::extract::{ConnectInfo, Query, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::Json;
use serde::Deserialize;
use serde_json::json;

use crate::scheduler;
use crate::state::SharedState;
use crate::tmux;
use crate::transport;

/// Max description length before truncation.
const MAX_DESCRIPTION_LEN: usize = 200;
/// Max characters of npub to display as fallback node name.
const NPUB_DISPLAY_LEN: usize = 16;
/// Timeout for peer connect handshake.
const CONNECT_TIMEOUT_SECS: u64 = 10;
/// Max task runs to return in the list endpoint.
const MAX_TASK_RUNS_RETURNED: usize = 50;

/// Normalize a user-supplied optional string: trim whitespace and treat
/// empty/whitespace-only strings as absent.
///
/// Applied at the API boundary on fields like `model` and `effort` where
/// `Some("")` is always a mistake (serialized form of a CLI flag without a
/// value, or a JSON client passing an empty placeholder) and must not flow
/// through as if it were an explicit override.
pub(crate) fn normalize_optional_string(input: Option<String>) -> Option<String> {
    input
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

/// Extract a short project description from a project directory.
///
/// Tries in order: `Cargo.toml` description field, `package.json` description,
/// first non-heading non-empty line of `README.md` (truncated to 200 chars).
pub(crate) fn extract_project_description(project_dir: &str) -> Option<String> {
    let dir = Path::new(project_dir);

    // Try Cargo.toml
    if let Ok(contents) = std::fs::read_to_string(dir.join("Cargo.toml")) {
        for line in contents.lines() {
            let line = line.trim();
            if let Some(rest) = line.strip_prefix("description") {
                let rest = rest.trim_start();
                if let Some(rest) = rest.strip_prefix('=') {
                    let val = rest.trim().trim_matches('"');
                    if !val.is_empty() {
                        return Some(val.to_string());
                    }
                }
            }
        }
    }

    // Try package.json
    if let Ok(contents) = std::fs::read_to_string(dir.join("package.json")) {
        if let Ok(json) = serde_json::from_str::<serde_json::Value>(&contents) {
            if let Some(desc) = json["description"].as_str() {
                if !desc.is_empty() {
                    return Some(desc.to_string());
                }
            }
        }
    }

    // Try README.md — first non-heading, non-empty line
    if let Ok(contents) = std::fs::read_to_string(dir.join("README.md")) {
        for line in contents.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }
            let truncated = if trimmed.len() > MAX_DESCRIPTION_LEN {
                format!("{}...", &trimmed[..MAX_DESCRIPTION_LEN])
            } else {
                trimmed.to_string()
            };
            return Some(truncated);
        }
    }

    None
}

/// Return status of a single session by name.
pub async fn get_session(
    State(state): State<SharedState>,
    axum::extract::Path(name): axum::extract::Path<String>,
) -> (StatusCode, Json<serde_json::Value>) {
    let proto = state.protocol.read().await;
    match proto.sessions.get(&name) {
        Some(s) => {
            let stale = s.metadata.is_stale();
            (
                StatusCode::OK,
                Json(json!({
                    "id": s.id,
                    "pane": s.pane,
                    "origin": s.origin.label(),
                    "vim_mode": s.metadata.vim_mode,
                    "project_dir": s.metadata.project_dir,
                    "role": s.metadata.role,
                    "bulletin": s.metadata.bulletin,
                    "networked": s.metadata.networked,
                    "worktree": s.metadata.worktree,
                    "model": s.metadata.model,
                    "effort": s.metadata.effort,
                    "last_metadata_update": s.metadata.last_metadata_update,
                    "stale": stale,
                    "backend_session_id": s.metadata.backend_session_id,
                    "backend": s.metadata.backend,
                    "reminder": s.metadata.reminder,
                    "prompt": s.metadata.prompt,
                    "iteration": s.metadata.iteration,
                    "iteration_log": s.metadata.iteration_log,
                    "last_iteration_at": s.metadata.last_iteration_at,
                    "worktree_present": s.metadata.worktree_present,
                })),
            )
        }
        None => (
            StatusCode::NOT_FOUND,
            Json(json!({"error": format!("session '{}' not found", name)})),
        ),
    }
}

/// Return daemon status, sessions, nodes, and transport info.
pub async fn status(State(state): State<SharedState>) -> Json<serde_json::Value> {
    let proto = state.protocol.read().await;
    let nodes = state.nodes.read().await;
    let transports = state.transports().await;

    let sessions_list: Vec<_> = proto
        .sessions
        .values()
        .map(|s| {
            let stale = s.metadata.is_stale();
            json!({
                "id": s.id,
                "pane": s.pane,
                "origin": s.origin.label(),
                "vim_mode": s.metadata.vim_mode,
                "project_dir": s.metadata.project_dir,
                "role": s.metadata.role,
                "bulletin": s.metadata.bulletin,
                "networked": s.metadata.networked,
                "worktree": s.metadata.worktree,
                "model": s.metadata.model,
                "effort": s.metadata.effort,
                "last_metadata_update": s.metadata.last_metadata_update,
                "stale": stale,
                "backend_session_id": s.metadata.backend_session_id,
                "backend": s.metadata.backend,
                "reminder": s.metadata.reminder,
                "prompt": s.metadata.prompt,
                "iteration": s.metadata.iteration,
                "iteration_log": s.metadata.iteration_log,
                "last_iteration_at": s.metadata.last_iteration_at,
                "worktree_present": s.metadata.worktree_present,
            })
        })
        .collect();
    drop(proto);

    let nodes_list: Vec<_> = nodes
        .values()
        .map(|p| {
            json!({
                "name": p.name,
                "daemon_id": p.daemon_id,
            })
        })
        .collect();

    let transports_list: Vec<_> = transports
        .values()
        .map(|t| {
            json!({
                "name": t.transport_name(),
                "ready": t.is_ready(),
                "endpoint_id": t.endpoint_id(),
            })
        })
        .collect();

    // Deprecated compat: "transport" = first transport name, "endpoint_id" = first endpoint
    let first_transport = transports.values().next();
    let compat_transport = first_transport.map(|t| t.transport_name());
    let compat_endpoint_id = first_transport.and_then(|t| t.endpoint_id());

    let assistant_panes: Vec<_> = state
        .cached_assistant_panes()
        .await
        .into_iter()
        .map(|p| json!({ "pane_id": p.pane_id, "session": p.session_name }))
        .collect();

    Json(json!({
        "version": env!("CARGO_PKG_VERSION"),
        "daemon": state.config.name,
        "daemon_id": state.config.npub,
        "port": state.config.port,
        "transports": transports_list,
        "transport": compat_transport,
        "endpoint_id": compat_endpoint_id,
        "sessions": sessions_list,
        "nodes": nodes_list,
        "assistant_panes": assistant_panes,
    }))
}

#[derive(Debug, Deserialize, Default)]
pub struct TicketQuery {
    /// Relay URLs for nostr transport (?relay=url1&relay=url2 or comma-separated).
    #[serde(default, deserialize_with = "deserialize_string_or_seq")]
    relay: Vec<String>,
}

/// Accept a single string or a sequence for query params.
///
/// `serde_urlencoded` (used by axum's `Query`) cannot deserialize repeated
/// query keys (`?relay=a&relay=b`) into `Vec<String>`. This deserializer
/// accepts a single string and wraps it in a vec instead of failing.
fn deserialize_string_or_seq<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de;

    struct StringOrSeq;

    impl<'de> de::Visitor<'de> for StringOrSeq {
        type Value = Vec<String>;

        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("a string or sequence of strings")
        }

        fn visit_str<E: de::Error>(self, v: &str) -> Result<Vec<String>, E> {
            Ok(vec![v.to_string()])
        }

        fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<String>, A::Error> {
            let mut v = Vec::new();
            while let Some(s) = seq.next_element()? {
                v.push(s);
            }
            Ok(v)
        }
    }

    deserializer.deserialize_any(StringOrSeq)
}

/// Generate a connect ticket for remote peer pairing.
pub async fn ticket(
    State(state): State<SharedState>,
    Query(query): Query<TicketQuery>,
) -> (StatusCode, Json<serde_json::Value>) {
    let t = if !query.relay.is_empty() {
        match crate::nostr_transport::ensure_active(&state, query.relay).await {
            Ok(t) => t,
            Err(e) => {
                let msg = format!("failed to start nostr transport: {e}");
                tracing::error!("{msg}");
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(json!({ "error": msg })),
                );
            }
        }
    } else {
        let Some(t) = state.transport_by_name("nostr").await else {
            return (
                StatusCode::SERVICE_UNAVAILABLE,
                Json(json!({ "error": "nostr transport is not active" })),
            );
        };
        t
    };
    match t.ticket_string().await {
        Some(ticket) => (
            StatusCode::OK,
            Json(json!({
                "ticket": ticket,
                "endpoint_id": t.endpoint_id(),
                "transport": "nostr",
            })),
        ),
        None => (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({ "error": "nostr transport not ready" })),
        ),
    }
}

#[derive(Debug, Deserialize, Default)]
pub struct RegenerateQuery {
    confirm: Option<bool>,
}

/// Regenerate the connect secret and return a new ticket.
pub async fn regenerate_ticket(
    State(state): State<SharedState>,
    Query(query): Query<RegenerateQuery>,
) -> (StatusCode, Json<serde_json::Value>) {
    let Some(t) = state.transport_by_name("nostr").await else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({ "error": "nostr transport is not active" })),
        );
    };

    if query.confirm != Some(true) {
        return (
            StatusCode::OK,
            Json(json!({
                "warning": "This will destroy your nostr identity (nsec). All nodes must re-connect. Add ?confirm=true to proceed.",
                "transport": "nostr",
            })),
        );
    }

    match t
        .regenerate(&state.config.config_dir, &state.config.data_dir)
        .await
    {
        Ok(ticket) => (
            StatusCode::OK,
            Json(json!({ "ticket": ticket, "transport": "nostr" })),
        ),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({ "error": e.to_string() })),
        ),
    }
}

#[derive(Debug, Deserialize)]
pub struct ConnectBody {
    ticket: String,
    name: Option<String>,
}

/// Initiate a Nostr connection to a remote peer via ticket.
pub async fn connect(
    State(state): State<SharedState>,
    Json(body): Json<ConnectBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    // Strip #secret suffix for validation — the nprofile is before the '#'
    let nprofile_part = body
        .ticket
        .split_once('#')
        .map_or(body.ticket.as_str(), |(left, _)| left);
    if !nprofile_part.starts_with("nprofile1") {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "ticket must be an nprofile1 string" })),
        );
    }

    tracing::info!(
        "connect request received (ticket len={})",
        body.ticket.len()
    );

    // Check for duplicate connection by npub
    let peer_npub = extract_npub(&body.ticket);
    if let Some(ref npub) = peer_npub {
        let node_name = body
            .name
            .as_deref()
            .unwrap_or(&npub[..NPUB_DISPLAY_LEN.min(npub.len())]);
        if let Err(existing) = state.try_add_node(npub, node_name) {
            let msg = format!("already connected to this daemon as '{existing}'");
            tracing::info!("connect rejected: {msg}");
            return (StatusCode::CONFLICT, Json(json!({ "error": msg })));
        }
    }

    // Lazily activate nostr transport using relays from the nprofile
    let t = if let Some(t) = state.transport_by_name("nostr").await {
        t
    } else {
        let relays = extract_nprofile_relays(&body.ticket);
        match crate::nostr_transport::ensure_active(&state, relays).await {
            Ok(t) => t,
            Err(e) => {
                let msg = format!("failed to start nostr transport: {e}");
                tracing::error!("{msg}");
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(json!({ "error": msg })),
                );
            }
        }
    };

    let connect_fut = t.connect(&body.ticket, state.clone(), true);
    match tokio::time::timeout(
        std::time::Duration::from_secs(CONNECT_TIMEOUT_SECS),
        connect_fut,
    )
    .await
    {
        Err(_) => {
            tracing::warn!("connect timed out after 10s waiting for peer");
            return (
                StatusCode::GATEWAY_TIMEOUT,
                Json(json!({ "error": "connect timed out waiting for peer" })),
            );
        }
        Ok(Err(e)) => {
            tracing::error!("connect failed: {e}");
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": format!("connect failed: {e}") })),
            );
        }
        Ok(Ok(())) => {}
    }

    if let Err(e) = crate::persistence::add_connection(
        &state.config.data_dir,
        &body.ticket,
        body.name.as_deref(),
        peer_npub.as_deref(),
    ) {
        tracing::warn!("failed to persist connection: {e}");
    }

    // Don't broadcast sessions here — the remote peer may not have processed
    // our ConnectRequest yet, so it would reject the SessionList as unauthorized.
    // Session exchange happens naturally: once the peer authorizes us, it broadcasts
    // its sessions; we process them as a new peer and broadcast ours back.
    // The periodic 5s broadcast in the main loop also provides resilience.
    tracing::info!("node connected successfully via nostr");
    (
        StatusCode::OK,
        Json(json!({ "status": "connected", "transport": "nostr" })),
    )
}

/// Strip the `#secret` suffix from a ticket, returning just the nprofile.
fn strip_ticket_secret(ticket: &str) -> &str {
    ticket.split_once('#').map_or(ticket, |(left, _)| left)
}

/// Extract relay URLs from an nprofile bech32 string.
fn extract_nprofile_relays(ticket: &str) -> Vec<String> {
    use nostr_sdk::prelude::*;
    Nip19Profile::from_bech32(strip_ticket_secret(ticket))
        .map(|p| p.relays.into_iter().map(|r| r.to_string()).collect())
        .unwrap_or_default()
}

/// Extract the daemon npub from an nprofile ticket.
pub fn extract_npub(ticket: &str) -> Option<String> {
    use nostr_sdk::prelude::*;
    Nip19Profile::from_bech32(strip_ticket_secret(ticket))
        .ok()
        .and_then(|p| p.public_key.to_bech32().ok())
}

#[derive(Debug, Deserialize)]
pub struct RegisterBody {
    id: String,
    pane: Option<String>,
    #[serde(default)]
    vim_mode: bool,
    project_dir: Option<String>,
    role: Option<String>,
    bulletin: Option<String>,
    /// Defaults to true if omitted.
    #[serde(default)]
    networked: Option<bool>,
    #[serde(alias = "claude_session_id")]
    backend_session_id: Option<String>,
    /// Which coding assistant backend to use (e.g. "claude-code", "codex").
    #[serde(default)]
    backend: Option<String>,
    /// Reminder text re-injected on idle.
    #[serde(default)]
    reminder: Option<String>,
}

/// Parse `/proc/net/tcp` to find the socket inode whose *local* endpoint
/// matches `needle` (an address string in the kernel's little-endian hex
/// format, e.g. `0100007F:8012`). Pure function, unit-testable.
fn parse_tcp_inode_for_local(tcp_table: &str, needle: &str) -> Option<u64> {
    for line in tcp_table.lines().skip(1) {
        let cols: Vec<&str> = line.split_whitespace().collect();
        if cols.len() >= 10 && cols[1] == needle {
            return cols[9].parse().ok();
        }
    }
    None
}

/// Format a `SocketAddr` into the `AABBCCDD:EEFF` encoding used by
/// `/proc/net/tcp` (IPv4 only; IPv6 not supported because the daemon binds
/// loopback). Returns None for IPv6 peers.
fn needle_for_loopback_peer(peer: SocketAddr) -> Option<String> {
    let std::net::IpAddr::V4(v4) = peer.ip() else {
        return None;
    };
    let o = v4.octets();
    Some(format!(
        "{:02X}{:02X}{:02X}{:02X}:{:04X}",
        o[3],
        o[2],
        o[1],
        o[0],
        peer.port()
    ))
}

/// Resolve the PID + cmdline of a local TCP peer by walking `/proc`. Linux
/// only; returns None on other platforms or when resolution fails (socket
/// already closed, permission denied, peer is IPv6, etc.).
#[cfg(target_os = "linux")]
fn resolve_loopback_peer(peer: SocketAddr) -> Option<String> {
    let needle = needle_for_loopback_peer(peer)?;
    let tcp_table = std::fs::read_to_string("/proc/net/tcp").ok()?;
    let inode = parse_tcp_inode_for_local(&tcp_table, &needle)?;
    let socket_target = format!("socket:[{inode}]");

    for entry in std::fs::read_dir("/proc").ok()?.flatten() {
        let name = entry.file_name();
        let pid = match name.to_str() {
            Some(s) if s.chars().all(|c| c.is_ascii_digit()) => s,
            _ => continue,
        };
        let fd_dir = entry.path().join("fd");
        let Ok(fds) = std::fs::read_dir(&fd_dir) else {
            continue;
        };
        for fd in fds.flatten() {
            if let Ok(link) = std::fs::read_link(fd.path())
                && link.to_str() == Some(socket_target.as_str())
            {
                let cmdline = std::fs::read_to_string(entry.path().join("cmdline"))
                    .unwrap_or_default()
                    .replace('\0', " ")
                    .trim_end()
                    .to_string();
                return Some(format!("pid={pid} cmd={cmdline:?}"));
            }
        }
    }
    None
}

#[cfg(not(target_os = "linux"))]
fn resolve_loopback_peer(_peer: SocketAddr) -> Option<String> {
    None
}

/// Register a new local session with optional metadata.
pub async fn register(
    State(state): State<SharedState>,
    ConnectInfo(peer): ConnectInfo<SocketAddr>,
    headers: HeaderMap,
    body_bytes: Bytes,
) -> (StatusCode, Json<serde_json::Value>) {
    // Diagnostic (issue #14): log peer address, User-Agent, the raw JSON body
    // (preserves unknown fields), and — on Linux — the caller PID+cmdline
    // resolved via /proc/net/tcp + /proc/<pid>/fd walk. Resolving inside the
    // handler catches the caller before TIME_WAIT loses the socket→PID mapping.
    let user_agent = headers
        .get(header::USER_AGENT)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("-");
    let raw_body = String::from_utf8_lossy(&body_bytes);
    let caller = resolve_loopback_peer(peer).unwrap_or_else(|| "pid=unknown".to_string());
    tracing::info!(
        target: "ouija::api::register",
        peer = %peer,
        user_agent = %user_agent,
        caller = %caller,
        "/api/register: raw_body={}",
        raw_body,
    );

    let body: RegisterBody = match serde_json::from_slice(&body_bytes) {
        Ok(b) => b,
        Err(e) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({ "error": format!("invalid JSON: {e}") })),
            );
        }
    };

    if body.id.contains('/') {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "session ID must not contain '/'" })),
        );
    }
    let project_description = body
        .project_dir
        .as_deref()
        .and_then(extract_project_description);
    let metadata = crate::state::SessionMetadata {
        vim_mode: body.vim_mode,
        project_dir: body.project_dir,
        role: body.role,
        bulletin: body.bulletin,
        networked: body.networked.unwrap_or(true),
        backend_session_id: body.backend_session_id,
        backend: body.backend,
        project_description,
        reminder: body.reminder,
        ..Default::default()
    };
    if let Some(ref p) = body.pane {
        let names = state.backends.all_process_names();
        let refs: Vec<&str> = names.iter().map(|s| s.as_str()).collect();
        if !crate::tmux::pane_alive(p, &refs) {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({ "error": format!("pane {p} does not exist") })),
            );
        }
    }
    // Auto-detect backend from pane process tree if not explicitly provided
    let backend = match metadata.backend {
        Some(ref b) => Some(b.clone()),
        None => match body.pane {
            Some(ref p) => state.detect_backend_in_pane(p).await,
            None => None,
        },
    };
    let proto_meta = crate::daemon_protocol::SessionMeta {
        project_dir: metadata.project_dir.clone(),
        role: metadata.role.clone(),
        bulletin: metadata.bulletin.clone(),
        networked: metadata.networked,
        worktree: metadata.worktree,
        vim_mode: metadata.vim_mode,
        backend,
        backend_session_id: metadata.backend_session_id.clone(),
        reminder: metadata.reminder.clone(),
        ..Default::default()
    };
    let effects = state
        .apply_and_execute(crate::daemon_protocol::Event::Register {
            id: body.id.clone(),
            pane: body.pane.clone(),
            metadata: proto_meta,
        })
        .await;
    let (session_id, _replaced) = match effects.iter().find_map(|e| match e {
        crate::daemon_protocol::Effect::RegisterOk {
            session_id,
            replaced,
        } => Some((session_id.clone(), replaced.clone())),
        _ => None,
    }) {
        Some(ok) => ok,
        None => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": "unexpected register result" })),
            );
        }
    };

    (
        StatusCode::OK,
        Json(json!({
            "registered": session_id,
            "pane": body.pane,
        })),
    )
}

#[derive(Debug, Deserialize)]
pub struct SendBody {
    from: String,
    to: String,
    message: String,
    #[serde(default)]
    expects_reply: bool,
    #[serde(default)]
    responds_to: Option<u64>,
    #[serde(default)]
    done: bool,
}

/// Send a message from one session to another.
pub async fn send_msg(
    State(state): State<SharedState>,
    Json(body): Json<SendBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    if body.from == body.to {
        let suffix = format!("/{}", body.to);
        let prefix = format!("{}/", body.to);
        let proto = state.protocol.read().await;
        let suggestions: Vec<&str> = proto
            .sessions
            .keys()
            .filter(|k| k.ends_with(&suffix) || k.starts_with(&prefix))
            .map(|k| k.as_str())
            .collect();
        let hint = if suggestions.is_empty() {
            "If you meant a remote session, use the full node-prefixed name (e.g. 'node/session'). GET /api/status to see all available targets.".to_string()
        } else {
            format!(
                "Did you mean one of these remote sessions? {} — GET /api/status to check.",
                suggestions.join(", ")
            )
        };
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": format!("cannot send a message to yourself. {hint}") })),
        );
    }
    let effects = state
        .apply_and_execute(crate::daemon_protocol::Event::Send {
            from: body.from,
            to: body.to,
            message: body.message,
            expects_reply: body.expects_reply,
            responds_to: body.responds_to,
            done: body.done,
        })
        .await;

    if let Some((method, msg_id)) = effects.iter().find_map(|e| match e {
        crate::daemon_protocol::Effect::SendDelivered { method, msg_id, .. } => {
            Some((method.clone(), *msg_id))
        }
        _ => None,
    }) {
        (
            StatusCode::OK,
            Json(json!({
                "status": "delivered",
                "method": method,
                "msg_id": msg_id,
            })),
        )
    } else if let Some((reason, renamed_to)) = effects.iter().find_map(|e| match e {
        crate::daemon_protocol::Effect::SendFailed {
            reason, renamed_to, ..
        } => Some((reason.clone(), renamed_to.clone())),
        _ => None,
    }) {
        let mut body = json!({ "error": reason });
        if let Some(new_id) = renamed_to {
            body["renamed_to"] = json!(new_id);
        }
        (StatusCode::NOT_FOUND, Json(body))
    } else {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({ "error": "unexpected send result" })),
        )
    }
}

#[derive(Debug, Deserialize)]
pub struct RenameBody {
    old_id: String,
    new_id: String,
}

/// Rename an existing session.
pub async fn rename(
    State(state): State<SharedState>,
    Json(body): Json<RenameBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    let effects = state
        .apply_and_execute(crate::daemon_protocol::Event::Rename {
            old_id: body.old_id.clone(),
            new_id: body.new_id.clone(),
        })
        .await;
    if effects
        .iter()
        .any(|e| matches!(e, crate::daemon_protocol::Effect::RenameOk { .. }))
    {
        (
            StatusCode::OK,
            Json(json!({ "renamed": body.old_id, "to": body.new_id })),
        )
    } else {
        let reason = effects
            .iter()
            .find_map(|e| match e {
                crate::daemon_protocol::Effect::RenameFailed { reason } => Some(reason.clone()),
                _ => None,
            })
            .unwrap_or_else(|| format!("session '{}' not found", body.old_id));
        (StatusCode::NOT_FOUND, Json(json!({ "error": reason })))
    }
}

#[derive(Debug, Deserialize)]
pub struct RemoveBody {
    id: String,
    #[serde(default)]
    keep_worktree: Option<bool>,
}

/// Unregister a session by ID.
pub async fn remove(
    State(state): State<SharedState>,
    Json(body): Json<RemoveBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    let effects = state
        .apply_and_execute(crate::daemon_protocol::Event::Remove {
            id: body.id.clone(),
            keep_worktree: body.keep_worktree.unwrap_or(false),
        })
        .await;
    if effects
        .iter()
        .any(|e| matches!(e, crate::daemon_protocol::Effect::RemoveOk { .. }))
    {
        (StatusCode::OK, Json(json!({ "removed": body.id })))
    } else {
        let reason = effects
            .iter()
            .find_map(|e| match e {
                crate::daemon_protocol::Effect::RemoveFailed { reason, .. } => Some(reason.clone()),
                _ => None,
            })
            .unwrap_or_else(|| format!("session '{}' not found", body.id));
        (StatusCode::NOT_FOUND, Json(json!({ "error": reason })))
    }
}

#[derive(Debug, Deserialize)]
pub struct SessionUpdateBody {
    id: String,
    networked: Option<bool>,
    role: Option<String>,
    project_dir: Option<String>,
    bulletin: Option<String>,
}

/// Update a session's metadata (role, bulletin, project_dir, etc.).
pub async fn update_session(
    State(state): State<SharedState>,
    Json(body): Json<SessionUpdateBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    // Validate session exists and is not remote
    {
        let proto = state.protocol.read().await;
        let Some(session) = proto.sessions.get(&body.id) else {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({ "error": format!("session '{}' not found", body.id) })),
            );
        };
        if matches!(session.origin, crate::daemon_protocol::Origin::Remote(_)) {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({ "error": "cannot update remote session" })),
            );
        }
    }

    state
        .apply_and_execute(crate::daemon_protocol::Event::UpdateMetadata {
            id: body.id.clone(),
            role: body.role,
            bulletin: body.bulletin,
            project_dir: body.project_dir,
            networked: body.networked,
        })
        .await;

    let proto = state.protocol.read().await;
    let response = if let Some(s) = proto.sessions.get(&body.id) {
        json!({
            "updated": s.id,
            "networked": s.metadata.networked,
            "role": s.metadata.role,
            "bulletin": s.metadata.bulletin,
            "project_dir": s.metadata.project_dir,
        })
    } else {
        json!({ "updated": body.id })
    };

    (StatusCode::OK, Json(response))
}

#[derive(Debug, Deserialize)]
pub struct InjectBody {
    pane: String,
    message: String,
    #[serde(default)]
    vim_mode: bool,
}

/// Inject text into a tmux pane via the queued writer.
pub async fn inject(
    State(state): State<SharedState>,
    Json(body): Json<InjectBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    let session_id = {
        let proto = state.protocol.read().await;
        match proto
            .sessions
            .values()
            .find(|s| s.pane.as_deref() == Some(&body.pane))
            .map(|s| s.id.clone())
        {
            Some(id) => id,
            None => {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({"error": "no session registered for this pane"})),
                );
            }
        }
    };
    match tmux::locked_inject(
        &state,
        &session_id,
        &body.pane,
        &body.message,
        body.vim_mode,
    )
    .await
    {
        Ok(()) => (StatusCode::OK, Json(json!({ "status": "injected" }))),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({ "error": e.to_string() })),
        ),
    }
}

// --- Compact ---

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CompactBody {
    #[serde(default)]
    pub continuation: Option<String>,
}

/// Trigger backend-aware compaction. Callers pass the same `{continuation}` body
/// for every backend; the endpoint routes by `delivery_mode()`:
///
/// - TUI backends (e.g. Claude Code) receive the compact slash command via tmux,
///   and the continuation is parked on the session agent for the post-compact
///   hook to drain. `compacted: true` on the response means the compact command
///   was successfully queued; the backend performs the actual compaction
///   asynchronously. `continuation_delivered` is always `false` on this
///   branch because delivery (if any) happens later — after this response
///   returns — when the post-compact hook drains the parked continuation.
/// - HTTP backends (e.g. OpenCode) call `POST /session/:id/summarize` on the
///   opencode serve with `{providerID, modelID}` resolved from the session's
///   configured model (falling back to `/config/providers` defaults). The
///   request is synchronous — it blocks until opencode's compaction loop
///   completes — so a 2xx response means the context has really been shrunk.
///   On success, the continuation (if any) is delivered as a fresh user turn
///   via `prompt_async`. `compacted: true` means the summarize call
///   succeeded; `continuation_delivered: <bool>` reports whether the
///   continuation turn landed on the session in this same request.
///
/// HTTP partial-success: if summarize succeeds but the continuation delivery
/// fails, the endpoint returns 200 with `{compacted: true,
/// continuation_delivered: false, error}` rather than 502. The compaction
/// side effect already happened — a 502 would tempt the caller to retry the
/// whole compact and pay for a second summarize LLM call.
///
/// Breaking changes vs. the prior version of this endpoint:
/// - Response envelope changed from `{status:"compact_triggered"}` to
///   `{status:"ok", compacted: <bool>, continuation_delivered: <bool>}`.
///   Callers asserting on the old literal must update.
/// - Request body is now strict: `CompactBody` rejects unknown fields (e.g. a
///   typo like `{"continuatino": "..."}` now returns 400 instead of silently
///   dropping the value).
///
/// Concurrency: when a `continuation` is supplied the TUI branch rejects
/// concurrent compact attempts with 409 to prevent overwriting an in-flight
/// caller's continuation. The HTTP branch currently has no concurrency guard
/// — two racing /compact calls on the same opencode session will each pay
/// for a separate summarize LLM call. See follow-up.
pub async fn compact(
    State(state): State<SharedState>,
    axum::extract::Path(session_id): axum::extract::Path<String>,
    Json(body): Json<CompactBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    let (status, value) = compact_inner(&state, session_id, body).await;
    (status, Json(value))
}

/// Build the success envelope promised by [`compact`]'s docstring:
/// `{status, compacted, continuation_delivered}`, with an optional `error`
/// field appended for the HTTP partial-success case.
///
/// The shape must stay consistent across backends so a typed client
/// deserializer works uniformly on TUI and HTTP responses. On TUI the caller
/// always passes `continuation_delivered = false` because TUI delivery is
/// asynchronous: the continuation is parked on the session agent and the
/// post-compact hook drains it after this response has already returned, so
/// at response-construction time nothing has been synchronously delivered.
fn compact_success_body(continuation_delivered: bool, error: Option<String>) -> serde_json::Value {
    let mut body = json!({
        "status": "ok",
        "compacted": true,
        "continuation_delivered": continuation_delivered,
    });
    if let Some(err) = error {
        body["error"] = json!(err);
    }
    body
}

async fn compact_inner(
    state: &std::sync::Arc<crate::state::AppState>,
    session_id: String,
    body: CompactBody,
) -> (StatusCode, serde_json::Value) {
    // Normalize: trim surrounding whitespace so the same string reaches both
    // tmux paste and prompt_async, and treat empty/whitespace-only as None so
    // both branches apply the same "no continuation" rule.
    let continuation = body.continuation.and_then(|s| {
        let trimmed = s.trim();
        if trimmed.is_empty() {
            None
        } else {
            Some(trimmed.to_string())
        }
    });

    // Read everything we need under a single lock acquisition so a racing
    // session mutation can't split backend_session_id from pane/project_dir
    // or flip the backend type between the lookup and the dispatch decision.
    let lookup = {
        let proto = state.protocol.read().await;
        match proto.sessions.get(&session_id) {
            Some(s) => SessionLookup {
                pane: s.pane.clone(),
                backend_session_id: s.metadata.backend_session_id.clone(),
                project_dir: s.metadata.project_dir.clone(),
                backend_name: s.metadata.backend.clone(),
                model: s.metadata.model.clone(),
                effort: s.metadata.effort.clone(),
            },
            None => {
                return (
                    StatusCode::NOT_FOUND,
                    json!({"error": format!("session '{}' not found", session_id)}),
                );
            }
        }
    };

    // Resolve the backend from the name captured above rather than re-reading
    // the protocol lock — prevents the branch decision from diverging from the
    // metadata it was taken on.
    let backend = match lookup.backend_name.as_deref() {
        Some(name) => state
            .backends
            .get(name)
            .unwrap_or_else(|| state.backends.default()),
        None => state.backends.default(),
    };

    match backend.delivery_mode() {
        crate::backend::DeliveryMode::TuiInjection => {
            let Some(pane) = lookup.pane else {
                return (
                    StatusCode::BAD_REQUEST,
                    json!({"error": "session has no pane (remote sessions cannot be compacted)"}),
                );
            };
            let Some(compact_cmd) = backend.compact_command().map(str::to_string) else {
                return (
                    StatusCode::BAD_REQUEST,
                    json!({"error": format!("backend '{}' does not support compact", backend.name())}),
                );
            };

            // Atomically acquire the compact slot. If another compact already parked a
            // continuation on this session, reject with 409 so the in-flight operation
            // isn't silently overwritten. Parking before injection is required so the
            // slot is reserved by the time /compact reaches the pane; the rollback below
            // releases the slot when injection fails synchronously so a later compact
            // doesn't see a stale continuation.
            let parked = if let Some(ref text) = continuation {
                let acquired = state
                    .try_set_pending_compact_continuation(&session_id, text.clone())
                    .await;
                if !acquired {
                    return (
                        StatusCode::CONFLICT,
                        json!({"error": "another compact continuation is already pending for this session"}),
                    );
                }
                true
            } else {
                false
            };

            if let Err(e) =
                tmux::locked_inject(state, &session_id, &pane, &compact_cmd, false).await
            {
                if parked {
                    // Rollback: drain what we just parked so a later compact doesn't
                    // splice this stale continuation into an unrelated turn. If the
                    // drain RPC comes back with nothing unexpectedly, log it — the
                    // slot may stay reserved and block future compacts until the
                    // agent is restarted.
                    if state
                        .drain_agent_compact_continuation(&session_id)
                        .await
                        .is_none()
                    {
                        tracing::warn!(
                            session = %session_id,
                            "rollback drain returned None after successful try-set; slot may be orphaned",
                        );
                    }
                }
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    json!({"error": e.to_string()}),
                );
            }

            // On TUI, delivery (if any) happens asynchronously via the
            // post-compact hook draining the parked continuation, so nothing
            // has been delivered at response time — always `false` here.
            (StatusCode::OK, compact_success_body(false, None))
        }
        crate::backend::DeliveryMode::HttpApi { .. } => {
            let Some(backend_session_id) = lookup.backend_session_id else {
                return (
                    StatusCode::BAD_REQUEST,
                    json!({
                        "error": format!(
                            "session has no backend_session_id (backend '{}' not attached)",
                            backend.name()
                        )
                    }),
                );
            };

            let Some((provider_id, model_id)) =
                resolve_opencode_compact_model(state, lookup.model.as_deref()).await
            else {
                return (
                    StatusCode::BAD_REQUEST,
                    json!({
                        "error": "cannot resolve provider/model for summarize: session has no parseable `model` \
                                  (expected \"providerID/modelID\") and /config/providers is unreachable \
                                  or empty. Configure the session with `ouija spawn-session --model <p/m>` \
                                  or ensure opencode serve has at least one configured provider."
                    }),
                );
            };

            // Opencode runs /summarize synchronously — the request blocks
            // until the compaction LLM call and the follow-up prompt.loop
            // complete. That can take tens of seconds up to a few minutes
            // for a long session; 300s is a generous ceiling that matches
            // what the TUI path effectively allows by not timing out at all.
            let port = state.opencode_serve_port();
            let summarize_url =
                format!("http://127.0.0.1:{port}/session/{backend_session_id}/summarize");
            let summarize_body = json!({
                "providerID": provider_id,
                "modelID": model_id,
            });
            let mut summarize_req = state
                .http_client
                .post(&summarize_url)
                .json(&summarize_body)
                .timeout(std::time::Duration::from_secs(300));
            if let Some(dir) = lookup.project_dir.as_deref() {
                summarize_req = summarize_req.header("x-opencode-directory", dir);
            }
            match summarize_req.send().await {
                Ok(r) if r.status().is_success() => {}
                Ok(r) => {
                    let status = r.status();
                    let text = r.text().await.unwrap_or_default();
                    return (
                        StatusCode::BAD_GATEWAY,
                        json!({"error": format!("opencode /summarize returned {status}: {text}")}),
                    );
                }
                Err(e) => {
                    return (
                        StatusCode::BAD_GATEWAY,
                        json!({"error": format!("opencode /summarize request failed: {e}")}),
                    );
                }
            }

            // Context is now compacted on the opencode server. If the caller
            // supplied a continuation, deliver it as a fresh user turn. A
            // delivery failure here is surfaced as 200 + continuation_delivered:
            // false (not 502) because the compaction side effect already
            // happened — a 502 would tempt the caller to retry the whole
            // compact, paying for a second summarize on an already-compacted
            // session.
            let continuation_delivered = if let Some(continuation) = continuation {
                match tmux::deliver_via_http(
                    state,
                    &backend_session_id,
                    lookup.project_dir.as_deref(),
                    &continuation,
                    lookup.model.as_deref(),
                    lookup.effort.as_deref(),
                )
                .await
                {
                    Ok(()) => true,
                    Err(e) => {
                        tracing::warn!(
                            session = %session_id,
                            "continuation delivery failed after successful summarize: {e}"
                        );
                        return (
                            StatusCode::OK,
                            compact_success_body(
                                false,
                                Some(format!("opencode continuation delivery failed: {e}")),
                            ),
                        );
                    }
                }
            } else {
                false
            };

            (
                StatusCode::OK,
                compact_success_body(continuation_delivered, None),
            )
        }
    }
}

struct SessionLookup {
    pane: Option<String>,
    backend_session_id: Option<String>,
    project_dir: Option<String>,
    backend_name: Option<String>,
    model: Option<String>,
    effort: Option<String>,
}

// --- Nodes ---

/// List connected remote nodes with their sessions.
pub async fn nodes(State(state): State<SharedState>) -> Json<serde_json::Value> {
    let connected = state.nodes.read().await;

    // Self entry first
    let self_entry = json!({
        "name": state.config.name,
        "npub": state.config.npub,
        "status": "self",
        "transport": null,
        "since": null,
    });

    let mut entries: Vec<serde_json::Value> = vec![self_entry];

    for p in connected.values() {
        entries.push(json!({
            "name": p.name,
            "npub": p.daemon_id,
            "status": "connected",
            "transport": null,
            "since": p.connected_at.format("%H:%M:%S").to_string(),
        }));
    }

    // Add saved (persisted) connections that aren't currently connected
    let connected_names: std::collections::HashSet<&str> =
        connected.values().map(|p| p.name.as_str()).collect();

    if let Ok(conns) = crate::persistence::load_connections(&state.config.data_dir) {
        for conn in &conns {
            if let Some(name) = &conn.node_name
                && connected_names.contains(name.as_str())
            {
                continue;
            }
            entries.push(json!({
                "name": conn.node_name,
                "npub": conn.daemon_npub,
                "status": "saved",
                "transport": "nostr",
                "since": conn.connected_at.format("%Y-%m-%d").to_string(),
            }));
        }
    }

    Json(json!({ "nodes": entries }))
}

#[derive(Debug, Deserialize)]
pub struct DisconnectNodeBody {
    daemon_id: String,
}

/// Disconnect a remote node and remove its sessions.
pub async fn disconnect_node(
    State(state): State<SharedState>,
    Json(body): Json<DisconnectNodeBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    let removed = state.disconnect_node(&body.daemon_id).await;
    (
        StatusCode::OK,
        Json(json!({
            "disconnected": body.daemon_id,
            "sessions_removed": removed,
        })),
    )
}

// --- Settings ---

/// Return the current daemon settings.
pub async fn get_settings(State(state): State<SharedState>) -> Json<serde_json::Value> {
    let settings = state.settings.read().await;
    Json(json!({
        "auto_register": settings.auto_register,
    }))
}

#[derive(Debug, Deserialize)]
pub struct SettingsUpdateBody {
    auto_register: Option<bool>,
    projects_dir: Option<String>,
    idle_timeout_secs: Option<u64>,
    reaper_interval_secs: Option<u64>,
    max_local_sessions: Option<u64>,
}

/// Patch daemon settings and persist to disk.
pub async fn update_settings(
    State(state): State<SharedState>,
    Json(body): Json<SettingsUpdateBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    let mut settings = state.settings.write().await;
    if let Some(v) = body.auto_register {
        settings.auto_register = v;
    }
    let projects_dir_changed = body.projects_dir.is_some();
    if let Some(v) = body.projects_dir {
        settings.projects_dir = Some(v);
    }
    if let Some(v) = body.idle_timeout_secs {
        settings.idle_timeout_secs = v;
    }
    if let Some(v) = body.reaper_interval_secs {
        settings.reaper_interval_secs = v;
    }
    if let Some(v) = body.max_local_sessions {
        settings.max_local_sessions = v;
    }
    if let Err(e) = crate::persistence::save_settings(&state.config.config_dir, &settings) {
        tracing::warn!("failed to save settings: {e}");
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({ "error": format!("failed to save: {e}") })),
        );
    }
    // Drop the write lock before spawning the refresh
    drop(settings);
    // Rebuild project index when projects_dir changes
    if projects_dir_changed {
        let s = state.clone();
        tokio::spawn(async move {
            crate::project_index::refresh_index(&s).await;
        });
    }
    let settings = state.settings.read().await;
    (
        StatusCode::OK,
        Json(json!({
            "status": "saved",
            "settings": {
                "auto_register": settings.auto_register,
                "projects_dir": settings.projects_dir,
            }
        })),
    )
}

/// Bulk-set `networked` on all local sessions.
pub async fn bulk_update_sessions(
    State(state): State<SharedState>,
    Json(body): Json<BulkSessionUpdateBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    let mut count = 0;
    {
        let mut proto = state.protocol.write().await;
        for session in proto.sessions.values_mut() {
            if matches!(session.origin, crate::daemon_protocol::Origin::Local) {
                if let Some(v) = body.networked {
                    if session.metadata.networked != v {
                        session.metadata.networked = v;
                        count += 1;
                    }
                }
            }
        }
    }
    if count > 0 {
        transport::broadcast_local_sessions(&state).await;
    }
    (StatusCode::OK, Json(json!({ "updated": count })))
}

#[derive(Debug, Deserialize)]
pub struct BulkSessionUpdateBody {
    networked: Option<bool>,
}

/// Return the list of configured Nostr relay URLs.
pub async fn get_relays(State(state): State<SharedState>) -> Json<serde_json::Value> {
    let relays = crate::nostr_transport::load_relays(&state.config.data_dir);
    Json(json!({ "relays": relays }))
}

#[derive(Debug, Deserialize)]
pub struct RelaysUpdateBody {
    relays: Vec<String>,
}

/// Replace the Nostr relay list and persist to disk.
pub async fn update_relays(
    State(state): State<SharedState>,
    Json(body): Json<RelaysUpdateBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    // Validate relay URLs
    let relays: Vec<String> = body
        .relays
        .into_iter()
        .map(|r| r.trim().to_string())
        .filter(|r| !r.is_empty())
        .collect();

    if let Err(e) = crate::nostr_transport::save_relays(&state.config.data_dir, &relays) {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({ "error": format!("failed to save: {e}") })),
        );
    }
    (
        StatusCode::OK,
        Json(json!({ "status": "saved", "relays": relays })),
    )
}

// --- Scheduled Tasks ---

/// List all scheduled tasks sorted by creation time.
pub async fn list_tasks(State(state): State<SharedState>) -> Json<serde_json::Value> {
    let tasks = state.scheduled_tasks.read().await;
    let mut list: Vec<&scheduler::ScheduledTask> = tasks.values().collect();
    list.sort_by_key(|t| &t.created_at);
    let entries: Vec<serde_json::Value> = list
        .iter()
        .map(|t| {
            json!({
                "id": t.id,
                "name": t.name,
                "cron": t.cron,
                "target_session": t.target_session,
                "enabled": t.enabled,
                "next_run": t.next_run,
                "last_run": t.last_run,
                "last_status": t.last_status,
                "run_count": t.run_count,
                "project_dir": t.project_dir,
                "once": t.once,
                "backend_session_id": t.backend_session_id,
                "on_fire": t.on_fire,
            })
        })
        .collect();
    Json(json!({ "tasks": entries }))
}

#[derive(Debug, Deserialize)]
pub struct CreateTaskBody {
    name: String,
    cron: String,
    target_session: Option<String>,
    prompt: Option<String>,
    reminder: Option<String>,
    project_dir: Option<String>,
    #[serde(default)]
    once: Option<bool>,
    #[serde(alias = "claude_session_id")]
    backend_session_id: Option<String>,
    #[serde(default)]
    on_fire: Option<crate::scheduler::OnFire>,
}

/// Create a new scheduled task with a cron expression.
pub async fn create_task(
    State(state): State<SharedState>,
    Json(body): Json<CreateTaskBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    if let Err(e) = scheduler::validate_cron(&body.cron) {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": format!("invalid cron: {e}") })),
        );
    }

    let mut task = scheduler::new_task(
        body.name,
        body.cron,
        body.target_session,
        body.prompt,
        body.reminder,
        body.once.unwrap_or(false),
        body.backend_session_id,
        body.on_fire.unwrap_or_default(),
    );
    task.project_dir = body.project_dir;

    let id = task.id.clone();
    state.add_task(task).await;

    (StatusCode::OK, Json(json!({ "created": id })))
}

#[derive(Debug, Deserialize)]
pub struct TaskIdBody {
    id: String,
}

/// Delete a scheduled task by ID.
pub async fn delete_task(
    State(state): State<SharedState>,
    Json(body): Json<TaskIdBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    match state.remove_task(&body.id).await {
        Some(_) => (StatusCode::OK, Json(json!({ "deleted": body.id }))),
        None => (
            StatusCode::NOT_FOUND,
            Json(json!({ "error": format!("task '{}' not found", body.id) })),
        ),
    }
}

/// Enable a disabled scheduled task.
pub async fn enable_task(
    State(state): State<SharedState>,
    Json(body): Json<TaskIdBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    let tasks = state.scheduled_tasks.read().await;
    if !tasks.contains_key(&body.id) {
        return (
            StatusCode::NOT_FOUND,
            Json(json!({ "error": format!("task '{}' not found", body.id) })),
        );
    }
    drop(tasks);
    state
        .update_task(&body.id, |t| {
            t.enabled = true;
            t.next_run = scheduler::compute_next_run(&t.cron);
        })
        .await;
    (StatusCode::OK, Json(json!({ "enabled": body.id })))
}

/// Disable a scheduled task without deleting it.
pub async fn disable_task(
    State(state): State<SharedState>,
    Json(body): Json<TaskIdBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    let tasks = state.scheduled_tasks.read().await;
    if !tasks.contains_key(&body.id) {
        return (
            StatusCode::NOT_FOUND,
            Json(json!({ "error": format!("task '{}' not found", body.id) })),
        );
    }
    drop(tasks);
    state
        .update_task(&body.id, |t| {
            t.enabled = false;
            t.next_run = None;
        })
        .await;
    (StatusCode::OK, Json(json!({ "disabled": body.id })))
}

/// Immediately fire a scheduled task, ignoring its cron schedule.
pub async fn trigger_task(
    State(state): State<SharedState>,
    Json(body): Json<TaskIdBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    {
        let tasks = state.scheduled_tasks.read().await;
        if !tasks.contains_key(&body.id) {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({ "error": format!("task '{}' not found", body.id) })),
            );
        }
    }
    scheduler::execute_task(&state, &body.id).await;
    (StatusCode::OK, Json(json!({ "triggered": body.id })))
}

#[derive(Debug, Deserialize, Default)]
pub struct TaskRunsQuery {
    task: Option<String>,
}

/// Return recent task execution history, newest first.
pub async fn list_task_runs(
    State(state): State<SharedState>,
    Query(query): Query<TaskRunsQuery>,
) -> Json<serde_json::Value> {
    let runs = state.task_runs.read().await;
    let entries: Vec<serde_json::Value> = runs
        .iter()
        .rev()
        .filter(|r| query.task.as_ref().is_none_or(|id| r.task_id == *id))
        .take(MAX_TASK_RUNS_RETURNED)
        .map(|r| {
            json!({
                "task_id": r.task_id,
                "task_name": r.task_name,
                "timestamp": r.timestamp,
                "status": r.status,
                "error": r.error,
                "session_name": r.session_name,
                "revived_pane": r.revived_pane,
            })
        })
        .collect();
    Json(json!({ "runs": entries }))
}

// --- Human sessions ---

#[derive(Debug, Deserialize)]
pub struct AddHumanBody {
    pub npub: String,
    pub name: String,
    pub default_session: Option<String>,
}

/// Add or update a human Nostr session configuration.
pub async fn add_human(
    State(state): State<SharedState>,
    Json(body): Json<AddHumanBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    let name = body.name.trim().to_string();
    if name.is_empty() || name.contains('/') {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "invalid name" })),
        );
    }

    // Reject if name conflicts with an existing non-human session
    {
        let proto = state.protocol.read().await;
        if proto
            .sessions
            .get(&name)
            .is_some_and(|s| !matches!(s.origin, crate::daemon_protocol::Origin::Human(_)))
        {
            return (
                StatusCode::CONFLICT,
                Json(json!({ "error": "name conflicts with existing session" })),
            );
        }
    }

    let mut settings = state.settings.write().await;
    if settings.human_sessions.iter().any(|h| h.name == name) {
        return (
            StatusCode::CONFLICT,
            Json(json!({ "error": "human session already exists" })),
        );
    }

    let human = crate::persistence::HumanSession {
        npub: body.npub.clone(),
        name: name.clone(),
        default_session: body.default_session,
        welcomed: false,
    };
    settings.human_sessions.push(human);

    if let Err(e) = crate::persistence::save_settings(&state.config.config_dir, &settings) {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({ "error": format!("failed to save: {e}") })),
        );
    }
    drop(settings);

    // Register the human session in protocol state
    {
        let mut proto = state.protocol.write().await;
        proto.sessions.entry(name.clone()).or_insert_with(|| {
            crate::daemon_protocol::SessionEntry {
                id: name.clone(),
                pane: None,
                origin: crate::daemon_protocol::Origin::Human(body.npub.clone()),
                metadata: crate::daemon_protocol::SessionMeta {
                    role: Some("human".to_string()),
                    networked: false,
                    ..Default::default()
                },
                ..Default::default()
            }
        });
    }

    (
        StatusCode::OK,
        Json(json!({ "status": "added", "name": name })),
    )
}

#[derive(Debug, Deserialize)]
pub struct RemoveHumanBody {
    pub name: String,
}

/// Remove a human session configuration by name.
pub async fn remove_human(
    State(state): State<SharedState>,
    Json(body): Json<RemoveHumanBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    let mut settings = state.settings.write().await;
    let before = settings.human_sessions.len();
    settings.human_sessions.retain(|h| h.name != body.name);
    if settings.human_sessions.len() == before {
        return (StatusCode::NOT_FOUND, Json(json!({ "error": "not found" })));
    }

    if let Err(e) = crate::persistence::save_settings(&state.config.config_dir, &settings) {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({ "error": format!("failed to save: {e}") })),
        );
    }
    drop(settings);

    // Remove the session from protocol state
    {
        let mut proto = state.protocol.write().await;
        if proto
            .sessions
            .get(&body.name)
            .is_some_and(|s| matches!(s.origin, crate::daemon_protocol::Origin::Human(_)))
        {
            proto.sessions.remove(&body.name);
        }
    }

    (StatusCode::OK, Json(json!({ "status": "removed" })))
}

/// List configured human Nostr sessions.
pub async fn list_humans(State(state): State<SharedState>) -> Json<serde_json::Value> {
    let settings = state.settings.read().await;
    let humans: Vec<serde_json::Value> = settings
        .human_sessions
        .iter()
        .map(|h| {
            json!({
                "name": h.name,
                "npub": h.npub,
                "default_session": h.default_session,
            })
        })
        .collect();
    Json(json!({ "humans": humans }))
}

// --- Session lifecycle ---

#[derive(Debug, Deserialize)]
pub struct SessionNameBody {
    name: String,
    #[serde(default)]
    fresh: Option<bool>,
    #[serde(default)]
    worktree: Option<bool>,
    #[serde(default)]
    project_dir: Option<String>,
    #[serde(default)]
    prompt: Option<String>,
    #[serde(default)]
    from: Option<String>,
    /// Which coding assistant backend to use (e.g. "claude-code", "codex").
    #[serde(default)]
    backend: Option<String>,
    /// Which LLM model to use.
    ///
    /// Passed through to the backend: for claude-code this becomes
    /// `claude --model <X>`; for opencode it is split on the first `/` into
    /// `providerID/modelID` and sent on each `prompt_async` body.
    #[serde(default)]
    model: Option<String>,
    /// Reasoning effort / variant for the model.
    ///
    /// For claude-code: passed as `claude --effort <X>`.
    /// For opencode: sent as `variant` on each `prompt_async` body.
    #[serde(default)]
    effort: Option<String>,
    #[serde(default)]
    reminder: Option<String>,
    /// Git branch name for worktree sessions. If omitted, defaults to the session name.
    #[serde(default)]
    branch: Option<String>,
    /// Base branch to create the worktree branch from. If omitted, branches from HEAD.
    #[serde(default)]
    base_branch: Option<String>,
    /// On kill, preserve the worktree directory instead of cleaning it up.
    /// Defaults to false (cleanup) when omitted.
    #[serde(default)]
    keep_worktree: Option<bool>,
    /// Opt-in to the data-destructive worktree reset on respawn.
    ///
    /// When the worktree dir already exists and `base_branch` is supplied,
    /// ouija used to unconditionally `git checkout -B <branch> <base>`,
    /// silently discarding every commit the branch was ahead of base
    /// (hub#528). The default is now `false`: ouija skips the reset and
    /// WARNs if the branch is ahead. Callers that *want* the reset (e.g. a
    /// legitimate "redraft from scratch" flow) must pass `force_reset=true`
    /// so the intent is explicit and auditable.
    #[serde(default)]
    force_reset: Option<bool>,
}

/// Return a warning message when the caller's request carries
/// destructive intent (`force_reset=true` or a `base_branch` override)
/// that the restart path cannot honor.
///
/// `/api/sessions/start` routes to `restart_session` when the named
/// session is already registered. `restart_session` reuses the existing
/// worktree dir from `SessionMeta.project_dir` as-is and does not call
/// `create_ouija_worktree`, so `base_branch` and `force_reset` have no
/// downstream hook to act on. This predicate centralizes the "dropped
/// intent" check so the API handler can `tracing::warn!` before routing
/// — making the drop auditable from daemon logs even when hub cannot
/// act on the return envelope (202 Accepted is sent before the work
/// runs, per the ExistingOrOtherDesignDecision recorded on hub#528).
///
/// Returns `None` when the body does not assert any restart-incompatible
/// intent. Returns `Some(msg)` with a single diagnostic line when it
/// does. Caller emits the warn; predicate stays pure for unit testing.
fn restart_drops_destructive_intent(body: &SessionNameBody) -> Option<String> {
    let mut dropped: Vec<&str> = Vec::new();
    if body.force_reset == Some(true) {
        dropped.push("force_reset=true");
    }
    if body.base_branch.is_some() {
        dropped.push("base_branch");
    }
    if dropped.is_empty() {
        return None;
    }
    Some(format!(
        "session '{}' is already registered, routing to restart_session \
         which cannot act on {}; destructive intent silently dropped. \
         File a ticket for a sync reset endpoint if this is load-bearing.",
        body.name,
        dropped.join(", ")
    ))
}

/// Kill the coding assistant process in a session's tmux pane.
pub async fn kill_session(
    State(state): State<SharedState>,
    Json(body): Json<SessionNameBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    let result = if body.keep_worktree.unwrap_or(false) {
        crate::nostr_transport::kill_session_keep_worktree(&state, &body.name).await
    } else {
        crate::nostr_transport::kill_session(&state, &body.name).await
    };
    (StatusCode::OK, Json(json!({ "result": result })))
}

/// Prune stale sessions whose worktree is missing.
///
/// Default dry-run: returns IDs that would be pruned without removing.
/// With confirm=true: removes sessions via Remove { keep_worktree: true }
/// to avoid triggering CleanupWorktree on already-missing dirs.
pub async fn prune_stale_sessions(
    State(state): State<SharedState>,
    Json(body): Json<PruneStaleBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    let stale_sessions: Vec<(String, String)> = {
        let proto = state.protocol.read().await;
        proto
            .sessions
            .values()
            .filter(|s| {
                matches!(s.origin, crate::daemon_protocol::Origin::Local)
                    && s.metadata.worktree_present == Some(false)
            })
            .filter_map(|s| s.metadata.project_dir.as_ref().map(|d| (s.id.clone(), d.clone())))
            .collect()
    };
    if !body.confirm {
        return (
            StatusCode::OK,
            Json(json!({ "dry_run": true, "would_prune": stale_sessions.iter().map(|(id, _)| id).cloned().collect::<Vec<_>>() })),
        );
    }
    let mut pruned = Vec::new();
    let mut errors = Vec::new();
    let mut already_gone = Vec::new();
    // Single batched apply: the handler runs each session's RemoveIfStale guard
    // under one write lock and coalesces Persist + BroadcastSessionList into
    // one of each, rather than N full state writes for N stale sessions.
    let input_ids: Vec<String> = stale_sessions.iter().map(|(id, _)| id.clone()).collect();
    let effects = state
        .apply_and_execute(crate::daemon_protocol::Event::PruneStale {
            sessions: stale_sessions,
        })
        .await;
    let pruned_set: std::collections::HashSet<String> = effects
        .iter()
        .filter_map(|e| match e {
            crate::daemon_protocol::Effect::RemoveOk { id } => Some(id.clone()),
            _ => None,
        })
        .collect();
    // Bucket failures via the structured RemoveFailureKind discriminator —
    // never via reason substring matching (which would misclassify any session
    // id or project_dir that happens to contain a substring like "not found").
    let already_gone_set: std::collections::HashSet<String> = effects
        .iter()
        .filter_map(|e| match e {
            crate::daemon_protocol::Effect::RemoveFailed { id, kind, .. }
                if *kind == crate::daemon_protocol::RemoveFailureKind::NotFound =>
            {
                Some(id.clone())
            }
            _ => None,
        })
        .collect();
    for id in input_ids {
        if pruned_set.contains(&id) {
            pruned.push(id);
        } else if already_gone_set.contains(&id) {
            tracing::debug!("session {} vanished between snapshot and prune", id);
            already_gone.push(id);
        } else {
            tracing::warn!("failed to prune session {} (no longer stale or guard tripped)", id);
            errors.push(id);
        }
    }
    let response = if errors.is_empty() && already_gone.is_empty() {
        json!({ "dry_run": false, "pruned": pruned })
    } else {
        let mut obj = serde_json::Map::new();
        obj.insert("dry_run".into(), serde_json::Value::Bool(false));
        obj.insert("pruned".into(), serde_json::Value::Array(pruned.into_iter().map(serde_json::Value::String).collect()));
        if !errors.is_empty() {
            obj.insert("errors".into(), serde_json::Value::Array(errors.into_iter().map(serde_json::Value::String).collect()));
        }
        if !already_gone.is_empty() {
            obj.insert("already_gone".into(), serde_json::Value::Array(already_gone.into_iter().map(serde_json::Value::String).collect()));
        }
        serde_json::Value::Object(obj)
    };
    (StatusCode::OK, Json(response))
}

#[derive(serde::Deserialize)]
pub struct PruneStaleBody {
    #[serde(default)]
    confirm: bool,
}

/// Start a new session in a tmux pane, optionally in a worktree.
pub async fn start_session(
    State(state): State<SharedState>,
    Json(body): Json<SessionNameBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    // Normalize at the boundary: `Some("")` or `Some("   ")` must not flow
    // through as an explicit override — it would clobber prev_metadata on
    // restart with an empty string and produce malformed CLI invocations.
    let mut body = body;
    body.model = normalize_optional_string(body.model);
    body.effort = normalize_optional_string(body.effort);

    // Return 202 immediately — all work (registration + boot) happens in background.
    let name = body.name.clone();
    let state2 = state.clone();
    tokio::spawn(async move {
        // If session already exists, restart with fresh context instead of failing.
        let exists = state2
            .protocol
            .read()
            .await
            .sessions
            .contains_key(&body.name);
        if exists {
            tracing::info!(
                "session '{}' exists, restarting with fresh context",
                body.name
            );
            if let Some(msg) = restart_drops_destructive_intent(&body) {
                tracing::warn!("{msg}");
            }
            let (_result, _msg_id) = crate::nostr_transport::restart_session(
                &state2,
                &body.name,
                true, // fresh
                body.prompt.as_deref(),
                body.from.as_deref(),
                None, // expects_reply not used for session start
                body.backend.as_deref(),
                body.model.as_deref(),
                body.effort.as_deref(),
                body.reminder.as_deref(),
            )
            .await;

            tracing::info!("async session restart complete: {}", body.name);
            return;
        }

        let (result, _prompt_msg_id) = crate::nostr_transport::start_session(
            &state2,
            &body.name,
            body.worktree,
            body.project_dir.as_deref(),
            body.prompt.as_deref(),
            body.from.as_deref(),
            None, // expects_reply not used for session start
            body.backend.as_deref(),
            body.model.as_deref(),
            body.effort.as_deref(),
            body.reminder.as_deref(),
            body.branch.as_deref(),
            body.base_branch.as_deref(),
            body.force_reset.unwrap_or(false),
        )
        .await;

        tracing::info!(
            "async session start complete: {}, result: {result}",
            body.name
        );
    });

    (
        StatusCode::ACCEPTED,
        Json(json!({ "session": name, "status": "starting" })),
    )
}

/// Kill and restart a session, optionally with a fresh conversation.
pub async fn restart_session(
    State(state): State<SharedState>,
    Json(body): Json<SessionNameBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    // Normalize at the boundary; see start_session for rationale.
    let mut body = body;
    body.model = normalize_optional_string(body.model);
    body.effort = normalize_optional_string(body.effort);

    // restart_session shares SessionNameBody with start_session, so
    // `force_reset` and `base_branch` deserialize here too — but the
    // underlying `nostr_transport::restart_session` does not accept or
    // act on them (no create_ouija_worktree call; the worktree is
    // reused as-is from prev_metadata.project_dir). Warn-log the drop
    // so the caller's opt-in is visible in daemon logs. Same predicate
    // and same rationale as the /api/sessions/start exists branch
    // (hub#528 review).
    if let Some(msg) = restart_drops_destructive_intent(&body) {
        tracing::warn!("{msg}");
    }

    let fresh = body.fresh.unwrap_or(false);
    let (result, _prompt_msg_id) = crate::nostr_transport::restart_session(
        &state,
        &body.name,
        fresh,
        body.prompt.as_deref(),
        body.from.as_deref(),
        None, // expects_reply not used for session restart
        body.backend.as_deref(),
        body.model.as_deref(),
        body.effort.as_deref(),
        body.reminder.as_deref(),
    )
    .await;

    (StatusCode::OK, Json(json!({ "result": result })))
}

/// Check if interactive mode is currently blocked.
pub async fn get_block_interactive(
    State(_state): State<SharedState>,
    axum::extract::Path(_pane): axum::extract::Path<String>,
) -> Json<serde_json::Value> {
    // block_interactive is no longer tracked in protocol state
    Json(json!({ "block_interactive": false }))
}

/// Clear the interactive block flag (no-op, kept for compat).
pub async fn clear_block_interactive(
    State(_state): State<SharedState>,
    axum::extract::Path(_pane): axum::extract::Path<String>,
) -> StatusCode {
    // block_interactive is no longer tracked in protocol state
    StatusCode::OK
}

/// Resolve a pane URL segment to the session id registered on that pane.
///
/// Axum percent-decodes path segments, so a literal tmux pane id like `%74`
/// placed raw in the URL arrives here as `t` (0x74 == ASCII `t`). Callers
/// must therefore send the pane *suffix* (just the number). We tolerate an
/// optional leading `%` defensively so a future caller that correctly
/// URL-encodes the percent as `%25` (extracted value: `%74`) also works.
///
/// See issue #646: `/api/pane/{pane}/...` routes used to silently 404 on
/// raw `%`-prefixed pane ids, and one handler (get_pending_replies) even
/// masked the bug by returning `200 + []` on pane lookup miss.
fn resolve_pane_to_session(proto: &crate::daemon_protocol::DaemonState, raw: &str) -> Option<String> {
    let suffix = raw.strip_prefix('%').unwrap_or(raw);
    let pane_id = format!("%{suffix}");
    proto
        .sessions
        .values()
        .find(|s| s.pane.as_deref() == Some(&pane_id))
        .map(|s| s.id.clone())
}

/// Return pending reply entries for a session identified by pane.
///
/// Returns 404 when the pane is not registered: the old fail-open behaviour
/// (`200 + []` on miss) masked the silent-404 bug described above.
pub async fn get_pending_replies(
    State(state): State<SharedState>,
    axum::extract::Path(pane): axum::extract::Path<String>,
) -> (StatusCode, Json<serde_json::Value>) {
    let (status, value) = get_pending_replies_inner(&state, pane).await;
    (status, Json(value))
}

async fn get_pending_replies_inner(
    state: &SharedState,
    pane: String,
) -> (StatusCode, serde_json::Value) {
    let session_id = {
        let proto = state.protocol.read().await;
        resolve_pane_to_session(&proto, &pane)
    };
    let Some(id) = session_id else {
        return (
            StatusCode::NOT_FOUND,
            json!({ "error": format!("pane '{pane}' is not registered") }),
        );
    };
    let replies = state.query_agent_pending_replies(&id).await;
    let list: Vec<_> = replies
        .iter()
        .map(|r| json!({ "msg_id": r.msg_id, "from": r.from, "message": r.message, "received_at": r.received_at }))
        .collect();
    (
        StatusCode::OK,
        json!({ "pending_replies": list, "count": list.len() }),
    )
}

/// Clear a pending reply from a specific sender on a pane's session.
///
/// Returns a JSON acknowledgement on success so callers can distinguish
/// "actually cleared something" (`cleared >= 1`) from "pane exists but the
/// named sender had no pending slot" (`cleared: 0`). 404 means the pane is
/// not registered; the response body includes a JSON `error` field.
pub async fn delete_pending_reply(
    State(state): State<SharedState>,
    axum::extract::Path((pane, from)): axum::extract::Path<(String, String)>,
) -> (StatusCode, Json<serde_json::Value>) {
    let (status, value) = delete_pending_reply_inner(&state, pane, from).await;
    (status, Json(value))
}

async fn delete_pending_reply_inner(
    state: &SharedState,
    pane: String,
    from: String,
) -> (StatusCode, serde_json::Value) {
    let session_id = {
        let proto = state.protocol.read().await;
        resolve_pane_to_session(&proto, &pane)
    };
    let Some(id) = session_id else {
        return (
            StatusCode::NOT_FOUND,
            json!({ "error": format!("pane '{pane}' is not registered") }),
        );
    };
    let cleared = {
        let mut proto = state.protocol.write().await;
        proto.clear_pending_reply_from(&id, &from)
    };
    (StatusCode::OK, json!({ "cleared": cleared }))
}

/// Notify the session agent that the coding assistant has stopped in a pane.
///
/// Idempotent: returns 200 even when the pane is not registered. Hooks call
/// this on every Stop, and a transient pane-lookup miss should not surface
/// as an error to the hook script.
pub async fn session_stopped(
    State(state): State<SharedState>,
    axum::extract::Path(pane): axum::extract::Path<String>,
) -> StatusCode {
    let session_id = {
        let proto = state.protocol.read().await;
        resolve_pane_to_session(&proto, &pane)
    };
    if let Some(id) = session_id {
        state
            .notify_agent(&id, crate::session_agent::SessionMsg::Stopped)
            .await;
    }
    StatusCode::OK
}

/// Notify the session agent that the coding assistant is active in a pane.
///
/// Idempotent: see `session_stopped` for the 200-on-miss rationale.
pub async fn session_active(
    State(state): State<SharedState>,
    axum::extract::Path(pane): axum::extract::Path<String>,
) -> StatusCode {
    let session_id = {
        let proto = state.protocol.read().await;
        resolve_pane_to_session(&proto, &pane)
    };
    if let Some(id) = session_id {
        state
            .notify_agent(&id, crate::session_agent::SessionMsg::Active)
            .await;
    }
    StatusCode::OK
}

/// Deliver a pending prompt for the given session, if one is queued.
fn deliver_pending_prompt(state: &SharedState, session_name: &str) -> bool {
    let pending = state.pending_prompts.lock().unwrap().remove(session_name);
    let Some((pane_id, prompt)) = pending else {
        return false;
    };
    let state = state.clone();
    let sid = session_name.to_string();
    tokio::spawn(async move {
        if let Err(e) = crate::tmux::locked_inject(&state, &sid, &pane_id, &prompt, false).await {
            tracing::warn!("readiness prompt delivery failed for {sid}: {e}");
        } else {
            tracing::info!("delivered queued prompt to {sid} via readiness signal");
        }
    });
    true
}

/// Handle a readiness signal from an HttpApi session's plugin.
pub async fn session_ready(
    State(state): State<SharedState>,
    axum::extract::Path(session_id): axum::extract::Path<String>,
) -> Json<serde_json::Value> {
    let delivered = deliver_pending_prompt(&state, &session_id);
    Json(json!({"delivered": delivered}))
}

/// Handle a readiness signal keyed by opencode backend session ID.
/// Resolves the ouija session name internally, avoiding plugin-side race conditions.
///
/// Resolution order:
/// 1. Direct lookup by `backend_session_id` — hub-spawned sessions and any
///    previously-adopted session already have this bound.
/// 2. Adoption — query opencode serve for the session's directory, then
///    look for a pre-existing local ouija session in that directory whose
///    `backend_session_id` is still unset. This handles the case where the
///    daemon knew about the session before opencode attached a backend ID.
/// 3. Auto-provision (issue #35) — when the caller is a human/agent starting
///    opencode themselves in a fresh directory, there is no pre-existing
///    record to adopt. Scan tmux for the opencode pane in that directory and
///    create a fresh session record with the backend_session_id bound.
///    Gated by the `auto_register` setting so operators who opted out of
///    implicit registration keep the strict behaviour.
pub async fn backend_session_ready(
    State(state): State<SharedState>,
    axum::extract::Path(backend_sid): axum::extract::Path<String>,
    body_bytes: Bytes,
) -> Json<serde_json::Value> {
    // Parse the body as optional hints. An empty body, `{}`, or malformed
    // JSON all degrade cleanly to "no hints" — older plugin builds POST an
    // empty body, and we must not 400 them.
    let hints = if body_bytes.is_empty() {
        BackendSessionReadyHints::default()
    } else {
        match serde_json::from_slice::<BackendSessionReadyHints>(&body_bytes) {
            Ok(h) => h,
            Err(e) => {
                // Log so operators can see the fallback — without this, a
                // plugin bug or a wire-format drift would silently route
                // every request through the slow scan path with no clue.
                tracing::debug!(
                    target: "ouija::api::backend_session_ready",
                    "failed to parse readiness hints ({e}); falling back to scan path"
                );
                BackendSessionReadyHints::default()
            }
        }
    };
    Json(backend_session_ready_inner_with_hints(&state, backend_sid, hints).await)
}

/// Optional hints the opencode plugin may send in the readiness POST body.
/// Both fields present: skip the opencode-serve dir lookup AND the tmux
/// scan-by-dir, using the explicit values directly. Otherwise fall back to
/// the existing resolve-by-scan path (see the decision recorded on this
/// task — partial hints are an out-of-scope refactor).
///
/// The plugin-side body is a forward-compatible contract: future plugin
/// releases will add fields (plugin_version, tty_path, etc.) that older
/// daemons MUST be able to ignore without discarding the fields they do
/// know. That is why there is no `deny_unknown_fields` — Postel's law
/// applies at the plugin-to-daemon boundary.
#[derive(Debug, Default, Deserialize)]
struct BackendSessionReadyHints {
    #[serde(default)]
    pane: Option<String>,
    #[serde(default)]
    cwd: Option<String>,
}

#[cfg(test)]
async fn backend_session_ready_inner(
    state: &std::sync::Arc<crate::state::AppState>,
    backend_sid: String,
) -> serde_json::Value {
    backend_session_ready_inner_with_hints(state, backend_sid, BackendSessionReadyHints::default())
        .await
}

async fn backend_session_ready_inner_with_hints(
    state: &std::sync::Arc<crate::state::AppState>,
    backend_sid: String,
    hints: BackendSessionReadyHints,
) -> serde_json::Value {
    // Step 1: direct lookup. This runs FIRST regardless of hints — hub-
    // spawned and previously-adopted sessions must win over any hint-derived
    // id, or a stale plugin cwd could shadow the real session.
    let session_name = {
        let proto = state.protocol.read().await;
        proto
            .sessions
            .values()
            .find(|s| s.metadata.backend_session_id.as_deref() == Some(&backend_sid))
            .map(|s| s.id.clone())
    };

    let name = if let Some(n) = session_name {
        n
    } else {
        // Step 2: adoption. Consumes one opencode-serve round-trip internally;
        // we redo it here in step 3 if adoption misses, since auto-provision
        // needs the dir too. The double call is intentionally kept to preserve
        // adoption's existing call signature (and fail-mode coverage) for this
        // surgical change — dir lookup is a cheap loopback GET.
        let adopted = adopt_backend_session_id(state, &backend_sid).await;

        if let Some(n) = adopted {
            n
        } else {
            // Step 3: auto-provision for ad-hoc opencode sessions (issue #35).
            let auto_register = state.settings.read().await.auto_register;
            if !auto_register {
                tracing::debug!(
                    "auto_register disabled; declining to auto-provision for backend_session_id {backend_sid}"
                );
                return json!({"delivered": false, "error": "no session with this backend_session_id"});
            }

            // Fast path: plugin sent both pane + cwd. Skip the opencode-serve
            // round-trip AND the tmux pane scan and use the hints directly.
            if let (Some(pane), Some(cwd)) = (hints.pane.as_deref(), hints.cwd.as_deref()) {
                if let Some(n) =
                    auto_provision_with_explicit_pane(state, &backend_sid, pane, cwd).await
                {
                    n
                } else {
                    return json!({"delivered": false, "error": "no session with this backend_session_id"});
                }
            } else {
                // Fallback: resolve dir from opencode serve, then scan tmux.
                let Some(dir) = lookup_opencode_session_dir(state, &backend_sid).await else {
                    return json!({"delivered": false, "error": "no session with this backend_session_id"});
                };

                let Some(n) = auto_provision_from_backend_session(state, &backend_sid, &dir).await
                else {
                    return json!({"delivered": false, "error": "no session with this backend_session_id"});
                };
                n
            }
        }
    };

    let delivered = deliver_pending_prompt(state, &name);
    json!({"delivered": delivered, "session": name})
}

/// Auto-provision a fresh session record for an opencode backend session that
/// has no pre-existing ouija entry (issue #35).
///
/// Finds the tmux pane currently running opencode in `dir`. On exactly one
/// match, registers a new session with the backend_session_id bound atomically.
/// Fails closed (returns `None`) on zero or multiple matching panes — we
/// cannot map a backend_session_id to a pane in that case, same principle as
/// `disambiguate_adoption_candidates`.
///
/// The tmux pane scan is indirected through `AppState::list_assistant_panes`
/// so unit tests can seed `cached_assistant_panes` rather than shelling out
/// to a real tmux server.
async fn auto_provision_from_backend_session(
    state: &std::sync::Arc<crate::state::AppState>,
    backend_sid: &str,
    dir: &str,
) -> Option<String> {
    // Race guard 1: another concurrent ready callback may have already
    // bound this backend_session_id while we were doing the dir lookup.
    // Short-circuit here so we surface the concurrent winner's id (which
    // the caller returns to the plugin as `session`) instead of either
    // inventing a new id or failing closed because the pane is now filtered
    // out of the "unregistered panes" set. Must run BEFORE the pane filter:
    // the winner's session binds the pane, so the filter would drop it.
    {
        let proto = state.protocol.read().await;
        if let Some(existing) = proto
            .sessions
            .values()
            .find(|s| s.metadata.backend_session_id.as_deref() == Some(backend_sid))
        {
            return Some(existing.id.clone());
        }
    }

    // Snapshot the current pane layout and the registered pane → session map.
    let panes = state.list_assistant_panes().await;
    let registered_panes: std::collections::HashSet<String> = {
        let proto = state.protocol.read().await;
        proto
            .sessions
            .values()
            .filter(|s| matches!(s.origin, crate::daemon_protocol::Origin::Local))
            .filter_map(|s| s.pane.clone())
            .collect()
    };

    // Filter to panes in the target dir that are not already registered.
    let candidates: Vec<String> = panes
        .into_iter()
        .filter(|p| {
            !registered_panes.contains(&p.pane_id)
                && p.pane_current_path
                    .as_deref()
                    .map(|path| crate::state::resolve_project_root(path) == dir)
                    .unwrap_or(false)
        })
        .map(|p| p.pane_id)
        .collect();

    let pane_id = match candidates.len() {
        1 => candidates.into_iter().next().unwrap(),
        0 => {
            tracing::warn!(
                "auto-provision declined: no tmux pane running opencode in dir {dir} for backend_session_id {backend_sid}"
            );
            return None;
        }
        n => {
            // Same fail-closed principle as disambiguate_adoption_candidates:
            // with multiple opencode panes in the same dir, the daemon has
            // no way to tell which one this backend_session_id belongs to.
            // Let the user disambiguate via `ouija register ...`.
            tracing::warn!(
                "auto-provision declined: {n} opencode panes in dir {dir}; cannot map backend_session_id {backend_sid} unambiguously"
            );
            return None;
        }
    };

    register_auto_provisioned_session(state, backend_sid, &pane_id, dir).await
}

/// Auto-provision using an explicit `(pane, dir)` pair supplied by the
/// opencode plugin in the readiness POST body. Skips the opencode-serve
/// dir lookup and the tmux pane scan lookup-by-dir, but still verifies the
/// pane against the same two invariants the scan path enforces:
///
/// 1. The pane must appear in `list_assistant_panes`. This rejects stale
///    `TMUX_PANE` values (pane died between capture and POST), inherited
///    env vars from non-opencode callers, and any other caller who hands
///    us a pane id that isn't actually running an assistant process.
/// 2. The pane must not already be bound to another Local session. Without
///    this filter, `apply_register`'s pane-dedup silently evicts whoever
///    currently owns the pane — a concurrent claude-code SessionStart, a
///    prior auto-provision, or a manual `ouija register` would all be
///    vulnerable. Fail closed instead; the operator can disambiguate via
///    `ouija register` if they really want to reassign the pane.
///
/// Race guards and apply_register dedup still protect against concurrent
/// writers as before.
async fn auto_provision_with_explicit_pane(
    state: &std::sync::Arc<crate::state::AppState>,
    backend_sid: &str,
    pane: &str,
    cwd: &str,
) -> Option<String> {
    // Validate cwd BEFORE resolving / deriving anything from it. Every
    // other ouija code path treats project_dir as an absolute path with
    // at least one non-root segment, so reject degenerate input at the
    // boundary rather than letting it corrupt the session record.
    //
    // - Empty string: Path::file_name() returns None → basename falls
    //   through to "unnamed" in register_auto_provisioned_session; also
    //   project_dir would be persisted as "".
    // - Bare "/": same file_name() = None pathology; and no realistic
    //   caller has / as their project root.
    // - Relative (no leading "/"): would poison downstream comparisons
    //   (adoption, scan-by-dir, bulletin dedup) that string-compare
    //   project_dir against absolute paths.
    if cwd.is_empty() || cwd == "/" || !cwd.starts_with('/') {
        tracing::warn!(
            "auto-provision declined: invalid hint cwd {cwd:?} (must be absolute, non-empty, non-root) for backend_session_id {backend_sid}"
        );
        return None;
    }

    // Resolve worktree paths up to the repo root, matching the
    // scan-path's behaviour so the session id we derive is stable
    // across /repo and /repo/.claude/worktrees/<branch>.
    let dir = crate::state::resolve_project_root(cwd);

    // Race guard: the backend_session_id may already be bound. Surface
    // the concurrent winner rather than racing a second Register that
    // apply_register's pane-dedup would resolve by evicting them.
    {
        let proto = state.protocol.read().await;
        if let Some(existing) = proto
            .sessions
            .values()
            .find(|s| s.metadata.backend_session_id.as_deref() == Some(backend_sid))
        {
            return Some(existing.id.clone());
        }
    }

    // Defense 1: the supplied pane must be in list_assistant_panes. This is
    // the same liveness + is-an-assistant-pane check the scan path applies
    // implicitly when it iterates find_assistant_panes results.
    let panes = state.list_assistant_panes().await;
    if !panes.iter().any(|p| p.pane_id == pane) {
        tracing::warn!(
            "auto-provision declined: hint pane {pane} is not among current assistant panes (backend_session_id {backend_sid})"
        );
        return None;
    }

    // Defense 2: the supplied pane must not already belong to another
    // Local session. Matches the `registered_panes` filter in the scan path
    // (auto_provision_from_backend_session). Without this, apply_register's
    // pane-dedup would silently evict the current owner.
    {
        let proto = state.protocol.read().await;
        let already_bound = proto.sessions.values().any(|s| {
            matches!(s.origin, crate::daemon_protocol::Origin::Local)
                && s.pane.as_deref() == Some(pane)
        });
        if already_bound {
            tracing::warn!(
                "auto-provision declined: hint pane {pane} is already bound to another local session (backend_session_id {backend_sid})"
            );
            return None;
        }
    }

    register_auto_provisioned_session(state, backend_sid, pane, dir).await
}

/// Inner helper: derive the session id, re-check the race, and apply the
/// Register. Shared by both the scan-path and the explicit-hint path so
/// the id-derivation + race-guard + metadata layout stay in one place.
async fn register_auto_provisioned_session(
    state: &std::sync::Arc<crate::state::AppState>,
    backend_sid: &str,
    pane_id: &str,
    dir: &str,
) -> Option<String> {
    // Derive a unique session id from the dir basename.
    let basename = std::path::Path::new(dir)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("unnamed");
    let base_id = crate::state::sanitize_session_id(basename);
    if base_id.is_empty() {
        tracing::warn!(
            "auto-provision declined: could not derive a session id from dir {dir} (basename='{basename}')"
        );
        return None;
    }

    // Race guard: re-check the backend_session_id under the same lock we
    // use to build id_to_pane, so the winning concurrent writer is visible
    // to every subsequent branch. Without this, a writer that landed between
    // the top-of-function guard and this point would cause us to pick a
    // suffix-bumped id and run a redundant Register. apply_register's
    // pane-dedup would then evict the winner's session by pane (different
    // id, same pane) — stomping their atomic bind.
    let id = {
        let proto = state.protocol.read().await;
        if let Some(existing) = proto
            .sessions
            .values()
            .find(|s| s.metadata.backend_session_id.as_deref() == Some(backend_sid))
        {
            return Some(existing.id.clone());
        }
        let id_to_pane: std::collections::HashMap<String, Option<String>> = proto
            .sessions
            .iter()
            .map(|(id, s)| (id.clone(), s.pane.clone()))
            .collect();
        crate::state::resolve_unique_session_id(&id_to_pane, &base_id, Some(pane_id))
    };

    tracing::info!(
        "auto-provisioned session '{id}' for pane {pane_id} / backend_session_id {backend_sid} (dir: {dir})"
    );

    let metadata = crate::daemon_protocol::SessionMeta {
        project_dir: Some(dir.to_string()),
        role: Some(format!("working on {basename}")),
        backend: Some("opencode".into()),
        backend_session_id: Some(backend_sid.to_string()),
        ..Default::default()
    };
    state
        .apply_and_execute(crate::daemon_protocol::Event::Register {
            id: id.clone(),
            pane: Some(pane_id.to_string()),
            metadata,
        })
        .await;

    Some(id)
}

/// Choose at most one candidate session ID for adoption (issue #15).
/// Returns None for zero or >1 candidates — ambiguity is fail-closed.
fn disambiguate_adoption_candidates(
    backend_sid: &str,
    dir: &str,
    candidates: Vec<String>,
) -> Option<String> {
    match candidates.len() {
        0 => None,
        1 => candidates.into_iter().next(),
        n => {
            tracing::warn!(
                "refusing to adopt backend_session_id {backend_sid}: {n} ambiguous candidates in dir {dir}: {candidates:?}"
            );
            None
        }
    }
}

/// Query the opencode serve for the project directory associated with a
/// `backend_session_id`. Returns `None` if the serve is unreachable, the
/// session is unknown to the serve, or the response lacks a `directory` field.
///
/// Extracted so the auto-provision path (issue #35) can reuse the resolved
/// directory without a second HTTP round-trip after adoption misses.
async fn lookup_opencode_session_dir(
    state: &std::sync::Arc<crate::state::AppState>,
    backend_sid: &str,
) -> Option<String> {
    let port = state.opencode_serve_port();
    let url = format!("http://127.0.0.1:{port}/session/{backend_sid}");
    let resp = state
        .http_client
        .get(&url)
        .timeout(std::time::Duration::from_secs(3))
        .send()
        .await
        .ok()?;
    if !resp.status().is_success() {
        return None;
    }
    let body: serde_json::Value = resp.json().await.ok()?;
    body["directory"].as_str().map(str::to_string)
}

/// Parse an opencode model string of the form `"providerID/modelID"` into its
/// two segments. Splits on the first `/` only (matching opencode's parser at
/// `packages/opencode/src/provider/provider.ts`), trims each segment, and
/// rejects empty segments on either side so callers don't send
/// `providerID: " "` or `modelID: ""` to opencode's summarize endpoint.
///
/// Kept separate from [`crate::nostr_transport::opencode_prompt_body`] (which
/// has the same parse embedded) so /summarize can reuse the tuple shape
/// directly. The two parsers must stay consistent: a model string that
/// `opencode_prompt_body` accepts for `prompt_async` must also parse here so
/// the same session isn't rejected for compaction.
fn parse_opencode_model(model: &str) -> Option<(String, String)> {
    let trimmed = model.trim();
    let (provider, model_id) = trimmed.split_once('/')?;
    let provider = provider.trim();
    let model_id = model_id.trim();
    if provider.is_empty() || model_id.is_empty() {
        return None;
    }
    Some((provider.to_string(), model_id.to_string()))
}

/// Resolve `(providerID, modelID)` for the opencode `/session/:id/summarize`
/// endpoint. First tries to parse the session's configured model (set via
/// `ouija spawn-session --model`); if absent or unparseable, falls back to
/// GET `/config/providers` and picks the first entry in the `default` map.
///
/// Returns `None` when neither source yields a pair — e.g. the session has no
/// `model` and the opencode serve is unreachable or has no configured
/// providers. Callers should surface this as a 400, since `/summarize` cannot
/// be called without a concrete provider+model pair.
async fn resolve_opencode_compact_model(
    state: &std::sync::Arc<crate::state::AppState>,
    session_model: Option<&str>,
) -> Option<(String, String)> {
    if let Some(m) = session_model
        && let Some(pair) = parse_opencode_model(m)
    {
        return Some(pair);
    }

    let port = state.opencode_serve_port();
    let url = format!("http://127.0.0.1:{port}/config/providers");
    let resp = state
        .http_client
        .get(&url)
        .timeout(std::time::Duration::from_secs(5))
        .send()
        .await
        .ok()?;
    if !resp.status().is_success() {
        return None;
    }
    let body: serde_json::Value = resp.json().await.ok()?;
    let default_map = body.get("default")?.as_object()?;
    // `default` is a map from providerID → first-configured modelID. Picking
    // `.next()` is non-deterministic across runs when multiple providers are
    // configured, but for the summarize call any configured default is
    // acceptable — the caller's preferred model (when set on the session)
    // always takes precedence via the short-circuit above.
    let (provider, model) = default_map.iter().next()?;
    let model_id = model.as_str()?;
    Some((provider.clone(), model_id.to_string()))
}

/// Query the opencode serve for a session's directory, find the matching ouija
/// session, and set its `backend_session_id` + `backend`.
async fn adopt_backend_session_id(
    state: &std::sync::Arc<crate::state::AppState>,
    backend_sid: &str,
) -> Option<String> {
    let dir = lookup_opencode_session_dir(state, backend_sid).await?;

    // Collect ALL local ouija sessions matching this directory that lack a
    // backend_session_id (issue #15). Silently picking the first match — as
    // the original implementation did — lets an adopt for session A clobber
    // the metadata of unrelated session B when both live in the same dir
    // (hashbrown iteration order is effectively random). Fail closed on
    // ambiguity: adopt only when exactly one candidate exists.
    let candidates: Vec<String> = {
        let proto = state.protocol.read().await;
        proto
            .sessions
            .values()
            .filter(|s| {
                matches!(s.origin, crate::daemon_protocol::Origin::Local)
                    && s.metadata.project_dir.as_deref() == Some(dir.as_str())
                    && s.metadata.backend_session_id.is_none()
            })
            .map(|s| s.id.clone())
            .collect()
    };

    let session_id = disambiguate_adoption_candidates(backend_sid, &dir, candidates)?;

    tracing::info!(
        "adopting backend_session_id {backend_sid} for session {session_id} (dir: {dir})"
    );

    // Update the session metadata with backend info
    state
        .apply_and_execute(crate::daemon_protocol::Event::AdoptBackend {
            id: session_id.clone(),
            backend: "opencode".into(),
            backend_session_id: backend_sid.to_string(),
        })
        .await;

    Some(session_id)
}

/// List indexed projects from the configured projects directory.
pub async fn list_projects(
    State(state): State<SharedState>,
) -> axum::Json<Vec<crate::project_index::ProjectInfo>> {
    let index = state.project_index.read().await;
    let mut projects: Vec<_> = index.values().cloned().collect();
    projects.sort_by(|a, b| a.name.cmp(&b.name));
    axum::Json(projects)
}

// ── Clear reminder (REST equivalent of removed MCP tool) ─────────────

#[derive(Deserialize)]
pub struct ClearReminderBody {
    pub from: String,
    pub clearing_id: u64,
}

pub async fn clear_reminder(
    State(state): State<SharedState>,
    Json(body): Json<ClearReminderBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    state
        .notify_agent(
            &body.from,
            crate::session_agent::SessionMsg::ClearReminder {
                clearing_id: body.clearing_id,
            },
        )
        .await;
    (
        StatusCode::OK,
        Json(json!({
            "cleared": body.clearing_id,
            "session": body.from,
            "hint": "Reminder paused. It will resume after new activity (incoming message, hook fire, etc.)."
        })),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn normalize_optional_string_passthrough() {
        assert_eq!(
            normalize_optional_string(Some("sonnet".into())),
            Some("sonnet".into())
        );
        assert_eq!(normalize_optional_string(None), None);
    }

    #[test]
    fn normalize_optional_string_trims_and_drops_empty() {
        assert_eq!(normalize_optional_string(Some("".into())), None);
        assert_eq!(normalize_optional_string(Some("   ".into())), None);
        assert_eq!(normalize_optional_string(Some("\t\n ".into())), None);
        assert_eq!(
            normalize_optional_string(Some("  opus  ".into())),
            Some("opus".into())
        );
    }

    #[test]
    fn disambiguate_single_candidate_adopts() {
        let got = disambiguate_adoption_candidates("ses_x", "/repo", vec!["only".into()]);
        assert_eq!(got.as_deref(), Some("only"));
    }

    #[test]
    fn disambiguate_zero_candidates_fails() {
        let got = disambiguate_adoption_candidates("ses_x", "/repo", vec![]);
        assert!(got.is_none());
    }

    #[test]
    fn disambiguate_multiple_candidates_fails_closed() {
        // Two or more sessions in the same project_dir with no backend_session_id
        // must NOT be silently resolved — adopt_backend_session_id has no way
        // to know which one the backend SID actually belongs to (issue #15).
        let got = disambiguate_adoption_candidates(
            "ses_x",
            "/repo",
            vec!["hub".into(), "hub-skill-probe".into()],
        );
        assert!(got.is_none());
    }

    #[test]
    fn needle_for_127_0_0_1_encodes_little_endian_hex() {
        let peer: SocketAddr = "127.0.0.1:45084".parse().unwrap();
        // 127.0.0.1 little-endian = 01 00 00 7F → "0100007F"; port 45084 = 0xB01C
        assert_eq!(
            needle_for_loopback_peer(peer).as_deref(),
            Some("0100007F:B01C")
        );
    }

    #[test]
    fn parse_tcp_inode_finds_matching_local() {
        let table = "\
  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode\n\
   0: 0100007F:B01C 0100007F:1EC8 01 00000000:00000000 00:00000000 00000000  1000        0 1234567 1 0000000000000000 20 4 20 10 -1\n\
   1: 0100007F:1EC8 0100007F:B01C 01 00000000:00000000 00:00000000 00000000  1000        0 7654321 1 0000000000000000 20 4 20 10 -1\n";
        assert_eq!(
            parse_tcp_inode_for_local(table, "0100007F:B01C"),
            Some(1234567)
        );
        assert_eq!(
            parse_tcp_inode_for_local(table, "0100007F:1EC8"),
            Some(7654321)
        );
        assert_eq!(parse_tcp_inode_for_local(table, "0100007F:FFFF"), None);
    }

    #[test]
    fn parse_tcp_inode_skips_header_and_short_lines() {
        let table = "sl  local_address rem_address   st\nshort line\n";
        assert!(parse_tcp_inode_for_local(table, "0100007F:0001").is_none());
    }

    #[test]
    fn extract_from_cargo_toml() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname = \"foo\"\ndescription = \"A test crate\"\n",
        )
        .unwrap();
        let desc = extract_project_description(dir.path().to_str().unwrap());
        assert_eq!(desc.as_deref(), Some("A test crate"));
    }

    #[test]
    fn extract_from_package_json() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"name":"foo","description":"A JS project"}"#,
        )
        .unwrap();
        let desc = extract_project_description(dir.path().to_str().unwrap());
        assert_eq!(desc.as_deref(), Some("A JS project"));
    }

    #[test]
    fn extract_from_readme() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("README.md"),
            "# My Project\n\nThis is a great project.\n",
        )
        .unwrap();
        let desc = extract_project_description(dir.path().to_str().unwrap());
        assert_eq!(desc.as_deref(), Some("This is a great project."));
    }

    #[test]
    fn extract_cargo_toml_preferred_over_readme() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\ndescription = \"From cargo\"\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("README.md"), "# Title\n\nFrom readme\n").unwrap();
        let desc = extract_project_description(dir.path().to_str().unwrap());
        assert_eq!(desc.as_deref(), Some("From cargo"));
    }

    #[test]
    fn extract_missing_files_returns_none() {
        let dir = tempfile::tempdir().unwrap();
        assert!(extract_project_description(dir.path().to_str().unwrap()).is_none());
    }

    // --- compact endpoint ---

    #[tokio::test]
    async fn compact_session_not_found_returns_404() {
        let state = crate::state::AppState::new_for_test();
        let (status, body) = compact_inner(
            &state,
            "ghost".into(),
            CompactBody {
                continuation: Some("go".into()),
            },
        )
        .await;
        assert_eq!(status, StatusCode::NOT_FOUND);
        assert!(body["error"].as_str().unwrap().contains("not found"));
    }

    #[tokio::test]
    async fn compact_cc_without_pane_returns_400() {
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "cc-no-pane".into(),
                pane: None,
                metadata: crate::daemon_protocol::SessionMeta {
                    backend: Some("claude-code".into()),
                    ..Default::default()
                },
            })
            .await;

        let (status, body) = compact_inner(
            &state,
            "cc-no-pane".into(),
            CompactBody {
                continuation: Some("go".into()),
            },
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert!(body["error"].as_str().unwrap().contains("pane"));
    }

    #[tokio::test]
    async fn compact_oc_without_backend_session_id_returns_400() {
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "oc-no-sid".into(),
                pane: None,
                metadata: crate::daemon_protocol::SessionMeta {
                    backend: Some("opencode".into()),
                    backend_session_id: None,
                    ..Default::default()
                },
            })
            .await;

        let (status, body) = compact_inner(
            &state,
            "oc-no-sid".into(),
            CompactBody {
                continuation: Some("go".into()),
            },
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert!(
            body["error"]
                .as_str()
                .unwrap()
                .contains("backend_session_id"),
            "expected error to mention backend_session_id, got: {}",
            body["error"]
        );
    }

    #[tokio::test]
    async fn compact_oc_summarize_failure_returns_502() {
        // In the test env, opencode_serve_port() == 320 (privileged, unbound)
        // so the POST connection is refused. The HTTP branch now calls
        // /summarize before delivery, so the failure surfaces at that step.
        // A 502 (rather than a silent 200) is required so the caller can
        // distinguish "compact didn't happen" from "compact done".
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "oc-fail".into(),
                pane: None,
                metadata: crate::daemon_protocol::SessionMeta {
                    backend: Some("opencode".into()),
                    backend_session_id: Some("ses_probe".into()),
                    // A parseable model short-circuits /config/providers, so
                    // the 502 is specifically the /summarize failure rather
                    // than model-resolution failure (covered in a separate
                    // test below).
                    model: Some("anthropic/claude-sonnet-4-6".into()),
                    ..Default::default()
                },
            })
            .await;

        let (status, body) = compact_inner(
            &state,
            "oc-fail".into(),
            CompactBody {
                continuation: Some("keep going".into()),
            },
        )
        .await;
        assert_eq!(status, StatusCode::BAD_GATEWAY);
        let err = body["error"].as_str().unwrap_or_default();
        assert!(
            err.contains("summarize"),
            "expected error to mention /summarize, got: {err}"
        );
    }

    #[tokio::test]
    async fn compact_oc_bare_compact_is_no_longer_rejected_at_api_boundary() {
        // Before this change, a bare /compact (no continuation) on an HTTP
        // backend was rejected with 400 at the API boundary because phase-1
        // had no context-shrink path. With real summarize wired up, a bare
        // /compact is a legitimate request (just shrink context, deliver
        // nothing). The test env has no opencode serve, so the call reaches
        // /summarize and fails there with 502 — which is the proof that the
        // request was accepted for processing rather than rejected upfront.
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "oc-no-cont".into(),
                pane: None,
                metadata: crate::daemon_protocol::SessionMeta {
                    backend: Some("opencode".into()),
                    backend_session_id: Some("ses_probe".into()),
                    model: Some("anthropic/claude-sonnet-4-6".into()),
                    ..Default::default()
                },
            })
            .await;

        let (status, body) = compact_inner(
            &state,
            "oc-no-cont".into(),
            CompactBody { continuation: None },
        )
        .await;
        assert_eq!(
            status,
            StatusCode::BAD_GATEWAY,
            "bare /compact must now progress to the summarize call (which 502s in the test env), \
             not get rejected at the API boundary"
        );
        assert!(
            body["error"]
                .as_str()
                .unwrap_or_default()
                .contains("summarize"),
            "expected error to mention /summarize, got: {}",
            body["error"]
        );
    }

    #[tokio::test]
    async fn compact_oc_empty_continuation_normalizes_to_bare_compact() {
        // Whitespace-only continuation is normalized to None upstream, so
        // this is equivalent to the bare-compact case — progresses to
        // summarize and 502s in the test env. The assertion catches a
        // regression where whitespace would be treated as a meaningful
        // continuation and sent through prompt_async.
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "oc-empty-cont".into(),
                pane: None,
                metadata: crate::daemon_protocol::SessionMeta {
                    backend: Some("opencode".into()),
                    backend_session_id: Some("ses_probe".into()),
                    model: Some("anthropic/claude-sonnet-4-6".into()),
                    ..Default::default()
                },
            })
            .await;

        let (status, body) = compact_inner(
            &state,
            "oc-empty-cont".into(),
            CompactBody {
                continuation: Some("   ".into()),
            },
        )
        .await;
        assert_eq!(status, StatusCode::BAD_GATEWAY);
        assert!(
            body["error"]
                .as_str()
                .unwrap_or_default()
                .contains("summarize"),
            "expected error to mention /summarize, got: {}",
            body["error"]
        );
    }

    #[tokio::test]
    async fn compact_oc_without_model_and_serve_unreachable_returns_400() {
        // If the session has no `model` AND opencode serve is unreachable
        // (so /config/providers also can't supply a default), the endpoint
        // cannot build a valid {providerID, modelID} body for /summarize.
        // It must reject with 400 up-front rather than reach a 502 — a 400
        // is the actionable signal for the operator ("configure a model").
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "oc-no-model".into(),
                pane: None,
                metadata: crate::daemon_protocol::SessionMeta {
                    backend: Some("opencode".into()),
                    backend_session_id: Some("ses_probe".into()),
                    model: None,
                    ..Default::default()
                },
            })
            .await;

        let (status, body) = compact_inner(
            &state,
            "oc-no-model".into(),
            CompactBody {
                continuation: Some("keep going".into()),
            },
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        let err = body["error"].as_str().unwrap_or_default();
        assert!(
            err.contains("provider") || err.contains("model"),
            "expected error to mention provider/model resolution, got: {err}"
        );
    }

    #[test]
    fn compact_body_rejects_unknown_fields() {
        // Guard against silently-swallowed typos like {"continuatino": "..."}.
        let bad = serde_json::json!({"continuatino": "oops"});
        let err = serde_json::from_value::<CompactBody>(bad).unwrap_err();
        assert!(
            err.to_string().contains("unknown field"),
            "expected unknown-field error, got: {err}"
        );
    }

    #[test]
    fn compact_success_body_matches_docstring_envelope() {
        // compact()'s docstring advertises {status, compacted, continuation_delivered}
        // as the success envelope across BOTH backends. A typed deserializer that
        // requires all three fields must work against TUI responses too, so the
        // TUI and HTTP full-success sites must route through the same builder.
        let body = compact_success_body(false, None);
        let obj = body.as_object().expect("success body is a JSON object");
        assert_eq!(
            obj.len(),
            3,
            "success body must have exactly 3 keys; got {:?}",
            obj.keys().collect::<Vec<_>>()
        );
        assert_eq!(body["status"], "ok");
        assert_eq!(body["compacted"], true);
        assert_eq!(body["continuation_delivered"], false);
    }

    #[test]
    fn compact_success_body_propagates_continuation_delivered_flag() {
        assert_eq!(
            compact_success_body(true, None)["continuation_delivered"],
            true
        );
        assert_eq!(
            compact_success_body(false, None)["continuation_delivered"],
            false
        );
    }

    #[test]
    fn compact_success_body_with_error_preserves_envelope() {
        // The HTTP partial-success path (summarize OK, delivery failed) adds an
        // `error` field on top of the same envelope so callers can read a
        // human-readable reason without losing the shape a typed deserializer
        // expects. All four fields must be present and the base envelope must
        // not be mutated.
        let body = compact_success_body(false, Some("boom".into()));
        let obj = body.as_object().expect("success body is a JSON object");
        assert_eq!(obj.len(), 4);
        assert_eq!(body["status"], "ok");
        assert_eq!(body["compacted"], true);
        assert_eq!(body["continuation_delivered"], false);
        assert_eq!(body["error"], "boom");
    }

    #[tokio::test]
    async fn compact_cc_inject_failure_drains_parked_continuation() {
        // When locked_inject fails AFTER the compact slot has been reserved, the
        // rollback must drain what we parked so the next /compact on this session
        // doesn't 409 forever and the post-compact hook doesn't splice a stale
        // continuation into an unrelated turn. The inject path shells out to tmux,
        // so in the test env it fails after the inject-queue's 3 retries — takes
        // ~1.5s of real time but exercises the exact failure mode.
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "cc-inject-fail".into(),
                pane: Some("%999999999".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    backend: Some("claude-code".into()),
                    ..Default::default()
                },
            })
            .await;

        let (status, _body) = compact_inner(
            &state,
            "cc-inject-fail".into(),
            CompactBody {
                continuation: Some("rollback me".into()),
            },
        )
        .await;
        assert_eq!(
            status,
            StatusCode::INTERNAL_SERVER_ERROR,
            "expected inject failure to surface as 500"
        );

        // Critical: the slot must be free so a follow-up compact can proceed.
        let pending = state
            .drain_agent_compact_continuation("cc-inject-fail")
            .await;
        assert_eq!(
            pending, None,
            "rollback must drain the parked continuation on inject failure — slot was not released"
        );
    }

    #[tokio::test]
    async fn compact_cc_with_pending_continuation_returns_409() {
        // Simulates a second compact arriving while the first is still in flight.
        // The second caller must NOT overwrite the first caller's continuation;
        // the endpoint returns 409 Conflict instead.
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "cc-busy".into(),
                pane: Some("%1".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    backend: Some("claude-code".into()),
                    ..Default::default()
                },
            })
            .await;

        // Pre-park a continuation to simulate an in-flight compact
        let acquired = state
            .try_set_pending_compact_continuation("cc-busy", "first".into())
            .await;
        assert!(acquired, "slot should be empty for a fresh session");

        let (status, body) = compact_inner(
            &state,
            "cc-busy".into(),
            CompactBody {
                continuation: Some("second".into()),
            },
        )
        .await;
        assert_eq!(status, StatusCode::CONFLICT);
        let err = body["error"].as_str().unwrap();
        assert!(
            err.contains("pending") || err.contains("in progress"),
            "expected error to mention pending/in-progress, got: {err}"
        );

        // Critically: the first continuation must still be parked, not overwritten
        let pending = state.drain_agent_compact_continuation("cc-busy").await;
        assert_eq!(
            pending.as_deref(),
            Some("first"),
            "first caller's continuation must not be overwritten by the rejected second attempt"
        );
    }

    // --- lookup_opencode_session_dir ---

    #[tokio::test]
    async fn lookup_opencode_session_dir_returns_none_when_serve_unreachable() {
        // The test env binds opencode_serve_port() to config.port + 320.
        // For new_for_test(), config.port = 0 → port 320 (privileged, unbound),
        // so the GET will fail with connection refused. The helper must not
        // panic and must surface the failure as None so callers can fall back
        // gracefully (e.g. to the auto-provision path or the strict error).
        let state = crate::state::AppState::new_for_test();
        let dir = lookup_opencode_session_dir(&state, "ses_does_not_exist").await;
        assert!(
            dir.is_none(),
            "unreachable opencode serve must produce None, got Some({dir:?})"
        );
    }

    // --- parse_opencode_model / resolve_opencode_compact_model ---

    #[test]
    fn parse_opencode_model_two_segments() {
        assert_eq!(
            parse_opencode_model("anthropic/claude-sonnet-4-6"),
            Some(("anthropic".into(), "claude-sonnet-4-6".into()))
        );
    }

    #[test]
    fn parse_opencode_model_splits_on_first_slash_only() {
        // Opencode's parser keeps trailing slashes in the modelID segment;
        // mirror that so `openrouter/openai/gpt-5.4` maps to the same
        // providerID our `prompt_async` delivery uses.
        assert_eq!(
            parse_opencode_model("openrouter/openai/gpt-5.4"),
            Some(("openrouter".into(), "openai/gpt-5.4".into()))
        );
    }

    #[test]
    fn parse_opencode_model_trims_whitespace_per_segment() {
        assert_eq!(
            parse_opencode_model("  openrouter / gpt-5.4  "),
            Some(("openrouter".into(), "gpt-5.4".into()))
        );
    }

    #[test]
    fn parse_opencode_model_rejects_no_slash() {
        assert_eq!(parse_opencode_model("sonnet"), None);
        assert_eq!(parse_opencode_model(""), None);
        assert_eq!(parse_opencode_model("   "), None);
    }

    #[test]
    fn parse_opencode_model_rejects_empty_segment() {
        assert_eq!(parse_opencode_model("/"), None);
        assert_eq!(parse_opencode_model("anthropic/"), None);
        assert_eq!(parse_opencode_model("/sonnet"), None);
        assert_eq!(parse_opencode_model("  /  "), None);
        assert_eq!(parse_opencode_model("anthropic/   "), None);
    }

    #[tokio::test]
    async fn resolve_opencode_compact_model_uses_session_model_when_parseable() {
        // Session model is the primary source — when set and parseable, the
        // helper must not even attempt the /config/providers HTTP call.
        let state = crate::state::AppState::new_for_test();
        let result =
            resolve_opencode_compact_model(&state, Some("anthropic/claude-sonnet-4-6")).await;
        assert_eq!(
            result,
            Some(("anthropic".into(), "claude-sonnet-4-6".into()))
        );
    }

    #[tokio::test]
    async fn resolve_opencode_compact_model_returns_none_when_no_model_and_serve_unreachable() {
        // No session model, opencode serve unreachable in test env
        // (opencode_serve_port() == 320 for config.port=0) → both sources
        // fail → None. The compact endpoint must surface this as a 400 so
        // the caller knows summarize cannot proceed.
        let state = crate::state::AppState::new_for_test();
        let result = resolve_opencode_compact_model(&state, None).await;
        assert_eq!(result, None);
    }

    #[tokio::test]
    async fn resolve_opencode_compact_model_falls_through_on_unparseable_session_model() {
        // An unparseable session model (e.g. bare "sonnet" with no provider
        // segment) must not be used as-is; the helper falls through to the
        // /config/providers fallback rather than invent a providerID.
        let state = crate::state::AppState::new_for_test();
        let result = resolve_opencode_compact_model(&state, Some("sonnet")).await;
        assert_eq!(result, None, "bare 'sonnet' must not be accepted as a pair");
    }

    // --- auto_provision_from_backend_session (issue #35) ---

    fn pane_in(dir: &str, pane_id: &str) -> crate::tmux::TmuxPane {
        crate::tmux::TmuxPane {
            pane_id: pane_id.into(),
            session_name: "test".into(),
            pane_current_path: Some(dir.into()),
        }
    }

    #[tokio::test]
    async fn auto_provision_creates_session_for_single_matching_pane() {
        // Issue #35: opencode TUI started in a fresh dir with no pre-existing
        // ouija record. After direct lookup and adoption both miss, the
        // daemon must auto-provision a session record so the user's first
        // `ouija` CLI call resolves the pane.
        let state = crate::state::AppState::new_for_test();
        // Seed the cached pane snapshot — in tests, list_assistant_panes
        // reads from this rather than shelling out to tmux.
        *state.cached_assistant_panes.write().await = vec![pane_in("/tmp/freshproject", "%17")];

        let result =
            auto_provision_from_backend_session(&state, "ses_brand_new", "/tmp/freshproject").await;

        let session_id = result.expect("auto-provision must succeed for exactly one matching pane");
        assert_eq!(session_id, "freshproject");

        // Verify state mutations end-to-end.
        let proto = state.protocol.read().await;
        let session = proto
            .sessions
            .get(&session_id)
            .expect("session must exist in protocol state");
        assert_eq!(session.pane.as_deref(), Some("%17"), "pane must be bound");
        assert_eq!(
            session.metadata.backend.as_deref(),
            Some("opencode"),
            "backend must be opencode"
        );
        assert_eq!(
            session.metadata.backend_session_id.as_deref(),
            Some("ses_brand_new"),
            "backend_session_id must be bound atomically with the Register"
        );
        assert_eq!(
            session.metadata.project_dir.as_deref(),
            Some("/tmp/freshproject"),
            "project_dir must be set"
        );
        drop(proto);

        // The pane must now resolve back to the new session, which is the
        // end-state that unblocks the ouija CLI's `@ouija_session` / pane
        // lookup inside the user's terminal.
        let resolved = state.find_session_by_pane("%17").await;
        assert_eq!(
            resolved.as_deref(),
            Some("freshproject"),
            "find_session_by_pane must resolve the auto-provisioned pane"
        );
    }

    #[tokio::test]
    async fn auto_provision_declines_when_no_pane_matches_dir() {
        // Zero tmux panes running opencode in the target directory. The daemon
        // cannot invent a pane, so it must fail closed and leave state empty.
        // The user's workaround (explicit `ouija register ...`) still applies.
        let state = crate::state::AppState::new_for_test();
        // Seed a pane in a DIFFERENT dir so list_assistant_panes is non-empty
        // but no candidate matches the target. Catches regressions where an
        // empty vs. non-empty cache path diverges.
        *state.cached_assistant_panes.write().await = vec![pane_in("/tmp/someother", "%11")];

        let result =
            auto_provision_from_backend_session(&state, "ses_unmatched", "/tmp/freshproject").await;

        assert!(
            result.is_none(),
            "auto-provision must decline with zero matching panes, got Some({result:?})"
        );
        let proto = state.protocol.read().await;
        assert!(
            proto.sessions.is_empty(),
            "no session must be created on zero-match decline, got: {:?}",
            proto.sessions.keys().collect::<Vec<_>>()
        );
    }

    #[tokio::test]
    async fn auto_provision_declines_on_ambiguous_multiple_panes() {
        // Two opencode panes in the same project dir — very common when a
        // user iterates on a feature in split panes. The daemon has no way
        // to know which pane this backend_session_id belongs to, so it must
        // fail closed for the same reason disambiguate_adoption_candidates
        // does (issue #15). User disambiguates via `ouija register ...`.
        let state = crate::state::AppState::new_for_test();
        *state.cached_assistant_panes.write().await = vec![
            pane_in("/tmp/freshproject", "%17"),
            pane_in("/tmp/freshproject", "%23"),
        ];

        let result =
            auto_provision_from_backend_session(&state, "ses_ambiguous", "/tmp/freshproject").await;

        assert!(
            result.is_none(),
            "auto-provision must decline on >=2 matching panes, got Some({result:?})"
        );
        let proto = state.protocol.read().await;
        assert!(
            proto.sessions.is_empty(),
            "no session must be created on ambiguity decline"
        );
    }

    #[tokio::test]
    async fn auto_provision_skips_panes_already_registered() {
        // A pane that already owns a session (different backend_session_id,
        // or none at all) must not be re-registered by auto-provision. This
        // protects sessions created via the claude-code SessionStart hook or
        // the periodic scan_and_autoregister_panes loop from being stomped
        // when an unrelated opencode readiness signal arrives.
        let state = crate::state::AppState::new_for_test();
        *state.cached_assistant_panes.write().await = vec![pane_in("/tmp/freshproject", "%17")];
        // Pre-register the pane to a different session.
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "preexisting".into(),
                pane: Some("%17".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    project_dir: Some("/tmp/freshproject".into()),
                    ..Default::default()
                },
            })
            .await;

        let result =
            auto_provision_from_backend_session(&state, "ses_intruder", "/tmp/freshproject").await;

        assert!(
            result.is_none(),
            "auto-provision must skip already-registered panes, got Some({result:?})"
        );
        let proto = state.protocol.read().await;
        assert_eq!(
            proto.sessions.len(),
            1,
            "no additional session must be created, got: {:?}",
            proto.sessions.keys().collect::<Vec<_>>()
        );
        let preexisting = proto.sessions.get("preexisting").unwrap();
        assert!(
            preexisting.metadata.backend_session_id.is_none(),
            "pre-existing session must NOT be clobbered with the intruder's backend_session_id"
        );
    }

    #[tokio::test]
    async fn auto_provision_short_circuits_when_concurrent_call_won_the_race() {
        // Simulate the case where a concurrent backend-session/ready callback
        // has just completed auto-provision by the time this one reaches the
        // recheck point. The recheck must return the concurrent result instead
        // of racing a second Register (which would churn @ouija_session under
        // the user's feet with a different suffix).
        let state = crate::state::AppState::new_for_test();
        *state.cached_assistant_panes.write().await = vec![pane_in("/tmp/freshproject", "%17")];
        // Seed a session that already owns the backend_session_id — the
        // state the "winning" concurrent call would have left behind.
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "already-bound".into(),
                pane: Some("%17".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    project_dir: Some("/tmp/freshproject".into()),
                    backend: Some("opencode".into()),
                    backend_session_id: Some("ses_raced".into()),
                    ..Default::default()
                },
            })
            .await;

        let result =
            auto_provision_from_backend_session(&state, "ses_raced", "/tmp/freshproject").await;

        assert_eq!(
            result.as_deref(),
            Some("already-bound"),
            "recheck must surface the concurrent winner's id, not invent a new one"
        );
        let proto = state.protocol.read().await;
        assert_eq!(
            proto.sessions.len(),
            1,
            "no extra session must be created on the lost race"
        );
    }

    // --- backend_session_ready_inner (end-to-end through the outer handler) ---

    #[tokio::test]
    async fn backend_session_ready_respects_auto_register_disabled() {
        // auto_register=false is the operator opt-out. Even with a matching
        // tmux pane in the target dir, the daemon must not invent a session
        // record behind the operator's back. The request carries the strict
        // error the pre-#35 daemon returned.
        let state = crate::state::AppState::new_for_test();
        state.settings.write().await.auto_register = false;
        *state.cached_assistant_panes.write().await = vec![pane_in("/tmp/freshproject", "%17")];

        let response = backend_session_ready_inner(&state, "ses_gated".into()).await;

        assert_eq!(response["delivered"], false);
        assert!(
            response["error"]
                .as_str()
                .unwrap_or("")
                .contains("no session with this backend_session_id"),
            "expected strict error, got: {response}"
        );
        assert!(response.get("session").is_none());

        let proto = state.protocol.read().await;
        assert!(
            proto.sessions.is_empty(),
            "no session must be created when auto_register is disabled"
        );
    }

    #[tokio::test]
    async fn backend_session_ready_returns_strict_error_when_serve_unreachable() {
        // opencode serve binds at config.port + 320 = 320 in new_for_test(),
        // so the GET connection is refused. lookup_opencode_session_dir
        // surfaces this as None, the outer handler must keep the historical
        // strict error rather than creating a session with an invented dir.
        let state = crate::state::AppState::new_for_test();
        // Even with a pane cached, serve unreachable -> no dir -> no
        // auto-provision. This guards against a future refactor that tries
        // to synthesize a dir from the pane's pane_current_path.
        *state.cached_assistant_panes.write().await = vec![pane_in("/tmp/freshproject", "%17")];

        let response = backend_session_ready_inner(&state, "ses_no_serve".into()).await;

        assert_eq!(response["delivered"], false);
        assert!(
            response["error"]
                .as_str()
                .unwrap_or("")
                .contains("no session with this backend_session_id"),
            "expected strict error, got: {response}"
        );
        let proto = state.protocol.read().await;
        assert!(
            proto.sessions.is_empty(),
            "no session must be created when opencode serve is unreachable"
        );
    }

    #[tokio::test]
    async fn backend_session_ready_direct_lookup_hits_when_session_already_bound() {
        // Fast path: the backend_session_id is already attached to a session
        // (hub-spawned, or a prior auto-provision). The handler returns the
        // session name without touching the opencode serve or the pane scan.
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "prebound".into(),
                pane: Some("%17".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    project_dir: Some("/tmp/freshproject".into()),
                    backend: Some("opencode".into()),
                    backend_session_id: Some("ses_known".into()),
                    ..Default::default()
                },
            })
            .await;

        let response = backend_session_ready_inner(&state, "ses_known".into()).await;

        assert_eq!(
            response["session"].as_str(),
            Some("prebound"),
            "direct lookup must surface the session id, got: {response}"
        );
    }

    // --- Plugin-sent pane + cwd hints (fast-path) ---

    #[tokio::test]
    async fn backend_session_ready_uses_explicit_pane_and_cwd_hints() {
        // Happy path for the enriched opencode plugin: when both pane and
        // cwd arrive in the body, skip the opencode-serve round-trip AND the
        // scan-path's list-panes-by-dir filter. The pane still has to appear
        // in list_assistant_panes (defense 1 of the hint-path validation),
        // so seed it under a DIFFERENT directory than the hint cwd — that
        // proves the hint cwd is used for dir derivation, not the pane's
        // pane_current_path that the scan path would have consulted.
        let state = crate::state::AppState::new_for_test();
        *state.cached_assistant_panes.write().await = vec![pane_in("/tmp/different-dir", "%31")];

        let hints = BackendSessionReadyHints {
            pane: Some("%31".into()),
            cwd: Some("/tmp/explicit-project".into()),
        };

        let response =
            backend_session_ready_inner_with_hints(&state, "ses_explicit".into(), hints).await;

        assert_eq!(
            response["session"].as_str(),
            Some("explicit-project"),
            "hint path must auto-provision with id derived from cwd basename, got: {response}"
        );

        // State mutations end-to-end: note that project_dir follows the
        // explicit cwd hint, NOT the pane's cached pane_current_path —
        // the scan path would have resolved /tmp/different-dir here.
        let proto = state.protocol.read().await;
        let session = proto
            .sessions
            .get("explicit-project")
            .expect("session exists");
        assert_eq!(session.pane.as_deref(), Some("%31"));
        assert_eq!(
            session.metadata.backend_session_id.as_deref(),
            Some("ses_explicit"),
        );
        assert_eq!(
            session.metadata.project_dir.as_deref(),
            Some("/tmp/explicit-project"),
        );
    }

    #[tokio::test]
    async fn backend_session_ready_explicit_hints_respect_auto_register_disabled() {
        // auto_register=false opts out of implicit session creation
        // regardless of whether the plugin sent explicit hints. The hint
        // shortcut must not bypass the operator guardrail.
        let state = crate::state::AppState::new_for_test();
        state.settings.write().await.auto_register = false;

        let hints = BackendSessionReadyHints {
            pane: Some("%31".into()),
            cwd: Some("/tmp/explicit-project".into()),
        };

        let response =
            backend_session_ready_inner_with_hints(&state, "ses_gated_with_hints".into(), hints)
                .await;

        assert_eq!(response["delivered"], false);
        assert!(
            response["error"]
                .as_str()
                .unwrap_or("")
                .contains("no session with this backend_session_id"),
            "expected strict error, got: {response}"
        );
        let proto = state.protocol.read().await;
        assert!(
            proto.sessions.is_empty(),
            "hints must not bypass the auto_register opt-out"
        );
    }

    #[tokio::test]
    async fn backend_session_ready_partial_hints_fall_back_to_scan_path() {
        // Only pane, no cwd: do NOT take the fast-path. Fall through to the
        // existing opencode-serve dir lookup. In the test env the serve is
        // unreachable, so the expected end-state is the strict error — this
        // test pins the fallback behaviour rather than relying on a
        // future half-hint shortcut that is explicitly out of scope
        // (see the "partial hints fall back entirely" decision on this task).
        let state = crate::state::AppState::new_for_test();
        // Seed a matching pane anyway. Hint path must NOT fire (cwd missing),
        // so the scan path will run and miss because opencode serve is down.
        *state.cached_assistant_panes.write().await = vec![pane_in("/tmp/half-hinted", "%31")];

        let hints = BackendSessionReadyHints {
            pane: Some("%31".into()),
            cwd: None,
        };

        let response =
            backend_session_ready_inner_with_hints(&state, "ses_half".into(), hints).await;

        // Fallback path: no dir -> strict error, no session.
        assert_eq!(response["delivered"], false);
        assert!(response.get("session").is_none());
        let proto = state.protocol.read().await;
        assert!(proto.sessions.is_empty());
    }

    #[tokio::test]
    async fn backend_session_ready_explicit_hints_direct_lookup_still_wins() {
        // When the backend_session_id is already bound to a session, the
        // direct-lookup fast path in step 1 must short-circuit BEFORE the
        // hint path runs. Otherwise an existing session with a different
        // id could be shadowed by a newly-invented one derived from the
        // hint cwd.
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "prebound".into(),
                pane: Some("%17".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    project_dir: Some("/tmp/some-real-project".into()),
                    backend: Some("opencode".into()),
                    backend_session_id: Some("ses_known".into()),
                    ..Default::default()
                },
            })
            .await;

        let hints = BackendSessionReadyHints {
            pane: Some("%99".into()),
            cwd: Some("/tmp/unrelated".into()),
        };

        let response =
            backend_session_ready_inner_with_hints(&state, "ses_known".into(), hints).await;

        assert_eq!(
            response["session"].as_str(),
            Some("prebound"),
            "direct lookup must win even when hints point elsewhere, got: {response}"
        );
        let proto = state.protocol.read().await;
        assert_eq!(
            proto.sessions.len(),
            1,
            "no session must be created from the hints when direct lookup hits"
        );
    }

    // --- Hint-path pane validation (review item: defense parity with scan path) ---

    #[tokio::test]
    async fn hint_path_rejects_pane_not_in_assistant_panes() {
        // Defense parity with scan path: a caller that POSTs an arbitrary
        // pane id that isn't actually running opencode must NOT be able to
        // create a ghost session bound to a dead pane. The scan path enforces
        // this implicitly by only considering panes from list_assistant_panes;
        // the hint path must match that contract explicitly.
        let state = crate::state::AppState::new_for_test();
        // Seed panes that do NOT include %99.
        *state.cached_assistant_panes.write().await = vec![pane_in("/tmp/unrelated", "%11")];

        let result = auto_provision_with_explicit_pane(
            &state,
            "ses_ghost",
            "%99", // not in list_assistant_panes
            "/tmp/freshproject",
        )
        .await;

        assert!(
            result.is_none(),
            "hint path must reject a pane that is not in list_assistant_panes, got Some({result:?})"
        );
        let proto = state.protocol.read().await;
        assert!(
            proto.sessions.is_empty(),
            "no session must be created for an unverified pane"
        );
    }

    #[tokio::test]
    async fn hint_path_rejects_empty_cwd() {
        // Degenerate cwd = "" makes Path::file_name() return None, which
        // register_auto_provisioned_session turns into the literal "unnamed".
        // And project_dir would be persisted as the empty string. Reject
        // this at the hint-path entry rather than letting it corrupt state.
        let state = crate::state::AppState::new_for_test();
        *state.cached_assistant_panes.write().await = vec![pane_in("/tmp/ignored", "%17")];

        let result = auto_provision_with_explicit_pane(
            &state,
            "ses_bad_cwd",
            "%17",
            "", // degenerate cwd
        )
        .await;

        assert!(
            result.is_none(),
            "empty cwd must be rejected, got Some({result:?})"
        );
        assert!(state.protocol.read().await.sessions.is_empty());
    }

    #[tokio::test]
    async fn hint_path_rejects_bare_root_cwd() {
        // cwd = "/" has the same file_name() = None pathology: basename
        // falls through to "unnamed" and project_dir is persisted as "/".
        // No realistic caller has / as their project root.
        let state = crate::state::AppState::new_for_test();
        *state.cached_assistant_panes.write().await = vec![pane_in("/tmp/ignored", "%17")];

        let result = auto_provision_with_explicit_pane(&state, "ses_root_cwd", "%17", "/").await;

        assert!(
            result.is_none(),
            "bare `/` cwd must be rejected, got Some({result:?})"
        );
        assert!(state.protocol.read().await.sessions.is_empty());
    }

    #[tokio::test]
    async fn hint_path_rejects_relative_cwd() {
        // Every other ouija code path treats project_dir as absolute.
        // Accepting relative paths here would poison downstream comparisons
        // (adoption, scan-by-dir, bulletin dedup, etc.) that string-compare
        // project_dir. Reject at the boundary instead.
        let state = crate::state::AppState::new_for_test();
        *state.cached_assistant_panes.write().await = vec![pane_in("/tmp/ignored", "%17")];

        let result =
            auto_provision_with_explicit_pane(&state, "ses_rel_cwd", "%17", "relative/path").await;

        assert!(
            result.is_none(),
            "relative cwd must be rejected, got Some({result:?})"
        );
        assert!(state.protocol.read().await.sessions.is_empty());
    }

    // --- Hint body forward-compat (review item: drop deny_unknown_fields) ---

    #[test]
    fn hints_tolerate_unknown_fields_for_forward_compat() {
        // The readiness body is a plugin-side contract that will grow over
        // time (plugin_version, tty_path, etc.). With deny_unknown_fields,
        // a newer plugin talking to an older daemon would fail parsing; the
        // unwrap_or_default() at the handler entry then silently discards
        // BOTH pane and cwd, triggering a slow scan-path fallback with no
        // diagnostic. Postel's law: accept unknown fields, use the known
        // ones. This test pins that contract.
        let body =
            br#"{"pane":"%17","cwd":"/tmp/foo","tty_path":"/dev/pts/3","plugin_version":"2.0"}"#;
        let hints: BackendSessionReadyHints =
            serde_json::from_slice(body).expect("unknown fields must not fail parsing");
        assert_eq!(hints.pane.as_deref(), Some("%17"));
        assert_eq!(hints.cwd.as_deref(), Some("/tmp/foo"));
    }

    #[tokio::test]
    async fn hint_path_rejects_pane_already_registered_to_another_session() {
        // Silent-hijack guard: the scan path filters out panes already owned
        // by another Local session (api.rs:2154-2175). Without the same filter
        // on the hint path, apply_register's pane-dedup silently evicts
        // whoever currently owns the pane. A concurrent claude-code
        // SessionStart, a prior auto-provision, or a manual `ouija register`
        // would all be vulnerable. The hint path must fail closed instead.
        let state = crate::state::AppState::new_for_test();
        *state.cached_assistant_panes.write().await = vec![pane_in("/tmp/freshproject", "%17")];
        // Pre-bind the pane to another session (e.g. the claude-code hook
        // got there first).
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "prebound".into(),
                pane: Some("%17".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    project_dir: Some("/tmp/freshproject".into()),
                    ..Default::default()
                },
            })
            .await;

        let result = auto_provision_with_explicit_pane(
            &state,
            "ses_hijacker",
            "%17", // already owned by `prebound`
            "/tmp/freshproject",
        )
        .await;

        assert!(
            result.is_none(),
            "hint path must refuse to hijack an already-registered pane, got Some({result:?})"
        );
        let proto = state.protocol.read().await;
        assert_eq!(
            proto.sessions.len(),
            1,
            "the victim session must survive intact"
        );
        let survivor = proto.sessions.get("prebound").unwrap();
        assert!(
            survivor.metadata.backend_session_id.is_none(),
            "victim's metadata must not be rewritten with the hijacker's backend_session_id"
        );
    }

    // --- force_reset plumbing (hub#528 guard) ---

    #[test]
    fn session_name_body_parses_force_reset_when_present() {
        // Hub opts in to the data-destructive reset by passing force_reset=true.
        let body: SessionNameBody = serde_json::from_str(
            r#"{"name":"s","worktree":true,"base_branch":"main","force_reset":true}"#,
        )
        .expect("body parses");
        assert_eq!(
            body.force_reset,
            Some(true),
            "force_reset=true must deserialize to Some(true)"
        );
    }

    #[test]
    fn session_name_body_force_reset_defaults_to_none() {
        // When the caller omits the field, it must default to None —
        // which start_session treats as force_reset=false (the safe default).
        let body: SessionNameBody = serde_json::from_str(r#"{"name":"s"}"#).expect("body parses");
        assert_eq!(
            body.force_reset, None,
            "omitted force_reset must deserialize to None (safe default)"
        );
    }

    // --- Dropped-intent predicate on the restart path (hub#528 review) ---
    //
    // `/api/sessions/start` routes to `restart_session` when the named
    // session is already registered. `restart_session` does not plumb
    // `base_branch` or `force_reset` into `create_ouija_worktree` — it
    // reuses the existing worktree dir as-is. Without a warning, a
    // caller that explicitly opted in with `force_reset=true` on a
    // registered session would see a 202 Accepted indistinguishable from
    // the reset being honored.
    //
    // The `restart_drops_destructive_intent` predicate is the single
    // source of truth for when that warning should fire. The API handler
    // calls it inside the `exists` branch; tests lock in the predicate's
    // behavior so the warning never silently regresses.

    #[test]
    fn restart_drops_destructive_intent_fires_for_force_reset_true() {
        let body: SessionNameBody =
            serde_json::from_str(r#"{"name":"s","force_reset":true}"#).unwrap();
        let warn = restart_drops_destructive_intent(&body);
        assert!(
            warn.is_some(),
            "force_reset=true on the restart path must produce a warn message"
        );
        let msg = warn.unwrap();
        assert!(
            msg.contains("force_reset"),
            "warn message must mention force_reset, got: {msg}"
        );
    }

    #[test]
    fn restart_drops_destructive_intent_fires_for_base_branch() {
        let body: SessionNameBody =
            serde_json::from_str(r#"{"name":"s","base_branch":"main"}"#).unwrap();
        let warn = restart_drops_destructive_intent(&body);
        assert!(
            warn.is_some(),
            "base_branch on the restart path must produce a warn message — \
             restart_session cannot act on it"
        );
        assert!(
            warn.unwrap().contains("base_branch"),
            "warn message must mention base_branch"
        );
    }

    #[test]
    fn restart_drops_destructive_intent_silent_when_no_opt_in() {
        let body: SessionNameBody = serde_json::from_str(r#"{"name":"s"}"#).unwrap();
        assert!(
            restart_drops_destructive_intent(&body).is_none(),
            "no opt-in supplied, no warn"
        );
    }

    #[test]
    fn restart_drops_destructive_intent_silent_when_force_reset_false() {
        // Explicit force_reset=false is not an opt-in; nothing is dropped.
        let body: SessionNameBody =
            serde_json::from_str(r#"{"name":"s","force_reset":false}"#).unwrap();
        assert!(
            restart_drops_destructive_intent(&body).is_none(),
            "force_reset=false is not an opt-in; no warn"
        );
    }

    // --- /api/pane/{pane}/... routing and %-prefix tolerance (issue #646) ---
    //
    // Regression harness for "silent 404 on %-prefixed pane ids". Axum
    // percent-decodes path segments, so a literal `%74` on the wire arrives
    // at the handler as `t`. Callers now send the pane *suffix* (without the
    // leading `%`), and the handler tolerates both forms defensively.

    #[tokio::test]
    async fn resolve_pane_to_session_accepts_bare_suffix() {
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "sess-a".into(),
                pane: Some("%74".into()),
                metadata: crate::daemon_protocol::SessionMeta::default(),
            })
            .await;

        let proto = state.protocol.read().await;
        assert_eq!(
            resolve_pane_to_session(&proto, "74").as_deref(),
            Some("sess-a"),
            "bare numeric suffix must resolve"
        );
    }

    #[tokio::test]
    async fn resolve_pane_to_session_accepts_percent_prefix() {
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "sess-a".into(),
                pane: Some("%74".into()),
                metadata: crate::daemon_protocol::SessionMeta::default(),
            })
            .await;

        let proto = state.protocol.read().await;
        assert_eq!(
            resolve_pane_to_session(&proto, "%74").as_deref(),
            Some("sess-a"),
            "%-prefixed form must also resolve (future %25-encoded callers)"
        );
    }

    #[tokio::test]
    async fn resolve_pane_to_session_none_for_unknown_pane() {
        let state = crate::state::AppState::new_for_test();
        let proto = state.protocol.read().await;
        assert!(resolve_pane_to_session(&proto, "999").is_none());
        assert!(resolve_pane_to_session(&proto, "%999").is_none());
    }

    #[tokio::test]
    async fn get_pending_replies_returns_404_for_unknown_pane() {
        // Fail-closed: the old code returned 200 + empty list for an unknown
        // pane, which masked the %-prefix silent-404 bug for read callers.
        let state = crate::state::AppState::new_for_test();
        let (status, _) = get_pending_replies_inner(&state, "999".into()).await;
        assert_eq!(
            status,
            StatusCode::NOT_FOUND,
            "unknown pane must 404, never 200 + empty"
        );
    }

    #[tokio::test]
    async fn get_pending_replies_returns_200_for_known_pane() {
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "sess-a".into(),
                pane: Some("%74".into()),
                metadata: crate::daemon_protocol::SessionMeta::default(),
            })
            .await;

        let (status, body) = get_pending_replies_inner(&state, "74".into()).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body["count"].as_u64(), Some(0));
    }

    #[tokio::test]
    async fn delete_pending_reply_returns_404_for_unknown_pane() {
        let state = crate::state::AppState::new_for_test();
        let (status, body) =
            delete_pending_reply_inner(&state, "999".into(), "sender".into()).await;
        assert_eq!(status, StatusCode::NOT_FOUND);
        assert!(
            body["error"].as_str().is_some(),
            "404 response must include a JSON error field, got: {body}"
        );
    }

    #[tokio::test]
    async fn delete_pending_reply_returns_cleared_count_when_slot_existed() {
        // Acceptance criterion: callers must be able to distinguish
        // "actually cleared something" from "nothing to clear". The body
        // returns `cleared: N` where N > 0 when a real slot was removed.
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "sender-a".into(),
                pane: Some("%74".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    networked: true,
                    ..Default::default()
                },
            })
            .await;
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "receiver-b".into(),
                pane: Some("%99".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    networked: true,
                    ..Default::default()
                },
            })
            .await;
        state
            .apply_and_execute(crate::daemon_protocol::Event::Send {
                from: "sender-a".into(),
                to: "receiver-b".into(),
                message: "do a thing".into(),
                expects_reply: true,
                responds_to: None,
                done: false,
            })
            .await;

        let (status, body) =
            delete_pending_reply_inner(&state, "99".into(), "sender-a".into()).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(
            body["cleared"].as_u64(),
            Some(1),
            "one slot existed → cleared must be 1, got body: {body}"
        );
    }

    #[tokio::test]
    async fn delete_pending_reply_reports_cleared_zero_when_nothing_to_clear() {
        // The pane is registered but the named sender has no pending slot.
        // This must not 404 (the pane exists) and must not lie about
        // clearing something — cleared is 0 so the caller can distinguish
        // "slot was cleared" from "nothing to clear; possibly already gone".
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "receiver-b".into(),
                pane: Some("%99".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    networked: true,
                    ..Default::default()
                },
            })
            .await;

        let (status, body) =
            delete_pending_reply_inner(&state, "99".into(), "ghost-sender".into()).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(
            body["cleared"].as_u64(),
            Some(0),
            "no matching slot → cleared must be 0, got body: {body}"
        );
    }

    #[test]
    fn clear_pending_reply_from_returns_removed_count() {
        // daemon_protocol helper returns the number of entries actually
        // removed. 0 when nothing matches (no-op) so callers don't lie.
        use crate::daemon_protocol::{DaemonState, Event, SessionMeta};
        let mut state = DaemonState::new_for_model("d".into(), "h".into());
        state.apply(Event::Register {
            id: "sender".into(),
            pane: Some("%1".into()),
            metadata: SessionMeta {
                networked: true,
                ..Default::default()
            },
        });
        state.apply(Event::Register {
            id: "target".into(),
            pane: Some("%2".into()),
            metadata: SessionMeta {
                networked: true,
                ..Default::default()
            },
        });
        state.apply(Event::Send {
            from: "sender".into(),
            to: "target".into(),
            message: "x".into(),
            expects_reply: true,
            responds_to: None,
            done: false,
        });

        assert_eq!(state.clear_pending_reply_from("target", "sender"), 1);
        // Second call: nothing left to clear.
        assert_eq!(state.clear_pending_reply_from("target", "sender"), 0);
        // Unknown session: also 0.
        assert_eq!(state.clear_pending_reply_from("ghost", "sender"), 0);
    }

    /// End-to-end regression through a real axum Router and TCP listener.
    ///
    /// The core bug in #646 was a percent-decoding mismatch: axum decodes
    /// `%74` to `t` in path segments. The `resolve_pane_to_session` unit
    /// tests cover the handler's side of that; this test additionally proves
    /// that the CLI's `pane_wire_suffix` convention (send the suffix only)
    /// actually round-trips through axum's real Path extractor.
    ///
    /// What this adds over the inner-fn tests: if axum ever changes its
    /// percent-decoding behaviour (or if a refactor accidentally reroutes
    /// through a different extractor), the inner-fn tests keep passing but
    /// this test would fail. It is the ultimate guard for the bug chain.
    #[tokio::test]
    async fn delete_pending_reply_end_to_end_through_axum_router() {
        use axum::Router;
        use axum::routing::delete;
        use tokio::net::TcpListener;

        let state = crate::state::AppState::new_for_test();

        // Register sender (%74) and recipient (%99).
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "sender-a".into(),
                pane: Some("%74".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    networked: true,
                    ..Default::default()
                },
            })
            .await;
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "receiver-b".into(),
                pane: Some("%99".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    networked: true,
                    ..Default::default()
                },
            })
            .await;

        // Stage a pending-reply slot on the recipient.
        state
            .apply_and_execute(crate::daemon_protocol::Event::Send {
                from: "sender-a".into(),
                to: "receiver-b".into(),
                message: "do a thing".into(),
                expects_reply: true,
                responds_to: None,
                done: false,
            })
            .await;

        // Build a minimal router that mounts the real production route.
        let app = Router::new()
            .route(
                "/api/pane/{pane}/pending-replies/{from}",
                delete(delete_pending_reply),
            )
            .with_state(state.clone());

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });

        // Send the request the way the CLI now does: suffix, no leading `%`.
        let client = reqwest::Client::new();
        let url = format!("http://{addr}/api/pane/99/pending-replies/sender-a");
        let resp = client.delete(&url).send().await.unwrap();
        assert_eq!(
            resp.status().as_u16(),
            200,
            "DELETE on real pane must return 200, not silent 404"
        );

        // Slot must be gone.
        {
            let proto = state.protocol.read().await;
            let still_there = proto
                .pending_replies
                .get("receiver-b")
                .map(|v| v.iter().any(|e| e.from == "sender-a"))
                .unwrap_or(false);
            assert!(
                !still_there,
                "pending-reply slot must be cleared after the DELETE"
            );
        }

        // Bonus: a correctly-URL-encoded `%` (sent as `%2599`, extracted by
        // axum as literal `%99`) must also route to the right pane. This is
        // the defensive tolerance that `resolve_pane_to_session` provides
        // for future callers that percent-escape the `%` properly. The
        // clear is idempotent on the DaemonState side so we still get 200
        // even though the slot is already empty.
        let url2 = format!("http://{addr}/api/pane/%2599/pending-replies/sender-a");
        let resp2 = client.delete(&url2).send().await.unwrap();
        assert_eq!(
            resp2.status().as_u16(),
            200,
            "%25-encoded `%` form must also route to the right pane"
        );

        // And the *buggy* pre-fix URL form — raw `%74` in the path — must
        // not spuriously succeed. Axum decodes `%74` to `t`, the helper
        // gets a non-matching pane id, and the correct answer is 404. This
        // is the exact failure the CLI used to silently swallow.
        let url3 = format!("http://{addr}/api/pane/%74/pending-replies/sender-a");
        let resp3 = client.delete(&url3).send().await.unwrap();
        assert_eq!(
            resp3.status().as_u16(),
            404,
            "raw `%74` URL (the pre-fix CLI's bug) must 404, not silently match"
        );

        server.abort();
    }

    /// End-to-end regression for the sender_id = `feat/646-...` case raised in
    /// code review. ouija session ids can contain `/` (branch-name-style ids
    /// passed to `/api/sessions/start` without validation), so `sender_id`
    /// in the DELETE URL must be percent-encoded or axum's two-segment
    /// route matcher fails and we hit the same silent-404 class.
    ///
    /// This test proves the full chain works end-to-end: register a session
    /// whose id contains `/`, stage a pending-reply slot for it, DELETE with
    /// the id percent-encoded, assert 200 and the slot is cleared.
    #[tokio::test]
    async fn delete_pending_reply_handles_slash_containing_sender_id() {
        use axum::Router;
        use axum::routing::delete;
        use tokio::net::TcpListener;

        let state = crate::state::AppState::new_for_test();

        // Register a sender with a branch-name-style id (contains `/`).
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "feat/646-test".into(),
                pane: Some("%74".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    networked: true,
                    ..Default::default()
                },
            })
            .await;
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "receiver-b".into(),
                pane: Some("%99".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    networked: true,
                    ..Default::default()
                },
            })
            .await;

        // Stage a pending-reply slot from the slash-id sender.
        state
            .apply_and_execute(crate::daemon_protocol::Event::Send {
                from: "feat/646-test".into(),
                to: "receiver-b".into(),
                message: "do a thing".into(),
                expects_reply: true,
                responds_to: None,
                done: false,
            })
            .await;

        let app = Router::new()
            .route(
                "/api/pane/{pane}/pending-replies/{from}",
                delete(delete_pending_reply),
            )
            .with_state(state.clone());

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });
        let client = reqwest::Client::new();

        // First, prove the broken form — raw `/` in the path — does NOT
        // match the two-segment route. Axum must not accept it; we get 404
        // (route not found) rather than the DELETE handler being called.
        // This is the exact failure the review flagged.
        let buggy_url =
            format!("http://{addr}/api/pane/99/pending-replies/feat/646-test");
        let buggy_resp = client.delete(&buggy_url).send().await.unwrap();
        assert_eq!(
            buggy_resp.status().as_u16(),
            404,
            "raw `/` in sender_id must break route matching (not silently \
             succeed); the CLI fix is to percent-encode it"
        );

        // Slot must still be there — the buggy URL was a no-op.
        {
            let proto = state.protocol.read().await;
            let entries = proto
                .pending_replies
                .get("receiver-b")
                .expect("slot should still exist after a 404");
            assert!(entries.iter().any(|e| e.from == "feat/646-test"));
        }

        // Now the correctly-encoded form: `feat%2F646-test`. axum decodes it
        // back to `feat/646-test` on the handler side, the lookup matches,
        // and the slot is cleared.
        let encoded_url =
            format!("http://{addr}/api/pane/99/pending-replies/feat%2F646-test");
        let resp = client.delete(&encoded_url).send().await.unwrap();
        assert_eq!(
            resp.status().as_u16(),
            200,
            "percent-encoded sender_id must route to the handler and clear the slot"
        );

        let proto = state.protocol.read().await;
        let still_there = proto
            .pending_replies
            .get("receiver-b")
            .map(|v| v.iter().any(|e| e.from == "feat/646-test"))
            .unwrap_or(false);
        assert!(
            !still_there,
            "slot from sender `feat/646-test` must be cleared"
        );

        server.abort();
    }

    #[tokio::test]
    async fn delete_pending_reply_clears_stuck_slot_after_sender_renamed() {
        // Full regression for the hub2 symptom: sender was *renamed*, so the
        // recipient's pending_replies bucket still has an entry whose `from`
        // points at a session id that no longer exists in the registry. The
        // daemon's cascade-on-remove does NOT trigger (no Remove event ran),
        // so the slot stays stuck and the reminder loop keeps firing on it.
        // The recipient must be able to clear it by pane id without
        // restarting the daemon — that is exactly what the hub2 operator
        // couldn't do before this PR.
        let state = crate::state::AppState::new_for_test();

        // Register sender (A) and recipient (B).
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "sender-a".into(),
                pane: Some("%74".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    networked: true,
                    ..Default::default()
                },
            })
            .await;
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "receiver-b".into(),
                pane: Some("%99".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    networked: true,
                    ..Default::default()
                },
            })
            .await;

        // A sends B a message that expects a reply → B's pending_replies[B]
        // has an entry keyed by `from = "sender-a"`.
        state
            .apply_and_execute(crate::daemon_protocol::Event::Send {
                from: "sender-a".into(),
                to: "receiver-b".into(),
                message: "do a thing".into(),
                expects_reply: true,
                responds_to: None,
                done: false,
            })
            .await;

        // Sanity: slot exists.
        {
            let proto = state.protocol.read().await;
            let entries = proto
                .pending_replies
                .get("receiver-b")
                .expect("receiver should have a pending-reply bucket");
            assert!(
                entries.iter().any(|e| e.from == "sender-a"),
                "sender-a slot should exist before clear"
            );
        }

        // Model the real hub2 shape: the sender was *renamed*, not removed.
        // apply_rename migrates the sender's own pending_replies bucket key
        // but does NOT rewrite `from` values in other sessions' pending
        // buckets — so B's pending_replies[B] still has an entry whose
        // `from = "sender-a"` pointing at a name that no longer exists in
        // the registry. No Event::Remove has fired, so the auto-clean
        // cascade does NOT kick in. This is exactly the stuck slot the
        // recipient used to be unable to clear without restarting the
        // daemon.
        state
            .apply_and_execute(crate::daemon_protocol::Event::Rename {
                old_id: "sender-a".into(),
                new_id: "sender-renamed".into(),
            })
            .await;

        // Sanity: the stuck slot is still there post-rename.
        {
            let proto = state.protocol.read().await;
            let entries = proto
                .pending_replies
                .get("receiver-b")
                .expect("receiver bucket must survive rename of sender");
            assert!(
                entries.iter().any(|e| e.from == "sender-a"),
                "sender-a slot must still be there after rename — this is \
                 the bug shape we're proving we can clear"
            );
        }

        // B clears the stuck slot by hitting the pane route with the numeric
        // suffix (what the CLI now sends). This must succeed, report the
        // cleared count, and the slot must be gone.
        let (status, body) =
            delete_pending_reply_inner(&state, "99".into(), "sender-a".into()).await;
        assert_eq!(
            status,
            StatusCode::OK,
            "clear-reply on real pane + real pending slot must return 200"
        );
        assert_eq!(
            body["cleared"].as_u64(),
            Some(1),
            "cleared must report the removed slot count so the CLI is not lied to"
        );

        let proto = state.protocol.read().await;
        let still_there = proto
            .pending_replies
            .get("receiver-b")
            .map(|v| v.iter().any(|e| e.from == "sender-a"))
            .unwrap_or(false);
        assert!(
            !still_there,
            "sender-a slot must be cleared after DELETE /api/pane/99/pending-replies/sender-a"
);
    }

    #[tokio::test]
    async fn prune_stale_sessions_dry_run_lists_stale() {
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "stale-s1".into(),
                pane: Some("%1".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    project_dir: Some("/tmp/nonexistent".into()),
                    worktree_present: Some(false),
                    ..Default::default()
                },
            })
            .await;
        // Call handler directly
        let (status, body) = prune_stale_sessions(
            State(state.clone()),
            Json(PruneStaleBody { confirm: false }),
        )
        .await;
        assert_eq!(status, StatusCode::OK);
        let value = body.0;
        assert_eq!(value["dry_run"], true);
        assert_eq!(value["would_prune"], serde_json::json!(["stale-s1"]));
        // Session should still exist
        let proto = state.protocol.read().await;
        assert!(proto.sessions.contains_key("stale-s1"));
    }

    #[tokio::test]
    async fn prune_stale_sessions_confirm_removes_stale() {
        let state = crate::state::AppState::new_for_test();
        state
            .apply_and_execute(crate::daemon_protocol::Event::Register {
                id: "stale-s1".into(),
                pane: Some("%1".into()),
                metadata: crate::daemon_protocol::SessionMeta {
                    project_dir: Some("/tmp/nonexistent".into()),
                    worktree_present: Some(false),
                    ..Default::default()
                },
            })
            .await;
        let (status, body) = prune_stale_sessions(
            State(state.clone()),
            Json(PruneStaleBody { confirm: true }),
        )
        .await;
        assert_eq!(status, StatusCode::OK);
        let value = body.0;
        assert_eq!(value["dry_run"], false);
        assert_eq!(value["pruned"], serde_json::json!(["stale-s1"]));
        // Session should be removed
        let proto = state.protocol.read().await;
        assert!(!proto.sessions.contains_key("stale-s1"));
    }
}