supercode-harness 0.4.19

The optional native Supercode agent and tool harness
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
//! Versioned, language-neutral service over persisted harness sessions.
//!
//! The service is transport-agnostic: [`HarnessSessionService::handle`] accepts
//! one JSON-RPC value and [`HarnessSessionService::poll`] produces subscription
//! notifications. The CLI exposes those primitives as NDJSON over stdio.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tokio::sync::Notify;

use crate::runtime::generated_session_id;
#[cfg(feature = "adapter-api")]
use crate::runtime::{HostedHarnessConnection, HostedHarnessRuntime};
use crate::sdk::{
    discover_session_page, load_session, load_session_with_fidelity, SdkCapabilities, SdkError,
    SdkErrorCode, SdkEvent, SdkOperation, SdkRequest, SdkRuntimeEvent, SdkService,
};
use crate::watch::{bound_session_view, message_json, normalized_session_json};
use crate::Fidelity;
#[cfg(feature = "adapter-api")]
use crate::SupercodeHttpRuntimeBackend;
use crate::{
    discover_live_runtime, harness_support_registry, AcpRuntimeBackend, ClaudeCodeRuntimeBackend,
    CodexRuntimeBackend, DiscoveryQuery, HarnessCatalog, HarnessHomes, HarnessId,
    ImplementationKind, LiveRuntimeEndpoint, LiveRuntimeSource, OpenCodeRuntimeBackend,
    PiRuntimeBackend, Role, RuntimeAttachRequest, RuntimeBackend, RuntimeConnection, RuntimeInput,
    RuntimeLaunch, RuntimeStartRequest, Session, SessionDescriptor, SessionFollower, SessionFormat,
    SessionLocator, SessionSource,
};
use crate::{reduce, tokens};
#[cfg(feature = "adapter-api")]
use crate::{register_live_runtime, resolve_live_runtime, LiveRuntimeRegistration};

/// Every JSON-RPC method the harness service dispatches (`harness.v1.capabilities`
/// reports it; ORCH-4 registry tiers must cite entries of it).
pub const HARNESS_SERVICE_METHODS: &[&str] = &[
    "harness.v1.support.report",
    "harness.v1.harnesses.list",
    "harness.v1.harnesses.probe",
    "harness.v1.harnesses.settings",
    "harness.v1.harnesses.configure",
    "harness.v1.harnesses.auth.methods",
    "harness.v1.harnesses.auth.begin",
    "harness.v1.harnesses.auth.verify",
    "harness.v1.sessions.discover",
    "harness.v1.sessions.load",
    "harness.v1.sessions.follow",
    "harness.v1.sessions.unfollow",
    "harness.v1.sessions.activity.subscribe",
    "harness.v1.sessions.activity.unsubscribe",
    "harness.v1.sessions.index.subscribe",
    "harness.v1.sessions.index.unsubscribe",
    "harness.v1.sessions.message",
    "harness.v1.sessions.import",
    "harness.v1.sessions.export",
    "harness.v1.sessions.translate",
    "harness.v1.sessions.reduce",
    "harness.v1.sessions.branch",
    "harness.v1.sessions.handoff",
    "harness.v1.sessions.resume_instructions",
    "harness.v1.skills.list",
    "harness.v1.skills.install",
    "harness.v1.skills.remove",
    "harness.v1.memory.show",
    "harness.v1.memory.search",
    "harness.v1.jobs.list",
    "harness.v1.jobs.get",
    "harness.v1.jobs.create",
    "harness.v1.jobs.update",
    "harness.v1.jobs.pause",
    "harness.v1.jobs.resume",
    "harness.v1.jobs.run",
    "harness.v1.jobs.delete",
    "harness.v1.sessions.new",
    "harness.v1.sessions.reset",
    "harness.v1.sessions.archive",
    "harness.v1.sessions.delete",
    "harness.v1.runs.list",
    "harness.v1.runs.get",
    "harness.v1.approvals.list",
    "harness.v1.approvals.resolve",
    "harness.v1.runtimes.capabilities",
    "harness.v1.runtimes.start",
    "harness.v1.runtimes.resume",
    "harness.v1.runtimes.attach_existing",
    "harness.v1.runtimes.attach",
    "harness.v1.runtimes.send_input",
    "harness.v1.runtimes.interrupt",
    "harness.v1.runtimes.steer",
    "harness.v1.runtimes.respond",
    "harness.v1.runtimes.terminal_instructions",
    "harness.v1.runtimes.close",
    "harness.v1.profiles.list",
    "harness.v1.profiles.get",
    "harness.v1.profiles.create",
    "harness.v1.profiles.delete",
    "harness.v1.channels.list",
    "harness.v1.routes.list",
    "harness.v1.triggers.list",
    "harness.v1.channels.status",
    "harness.v1.orchestration.load",
    "harness.v1.orchestration.save",
    "harness.v1.orchestration.compile",
    "harness.v1.orchestration.decompile",
    "harness.v1.orchestration.import",
    "harness.v1.orchestration.export",
    "harness.v1.workflow.load",
];

/// Protocol namespace implemented by this service.
pub const HARNESS_SERVICE_VERSION: &str = "harness.v1";
/// Notification method emitted for followed-session changes.
pub const SESSION_EVENT_METHOD: &str = "harness.v1.sessions.event";
/// Notification method emitted for normalized session-activity transitions.
pub const SESSION_ACTIVITY_EVENT_METHOD: &str = "harness.v1.sessions.activity_event";
/// Notification method emitted for revisioned session-list changes.
pub const SESSION_INDEX_EVENT_METHOD: &str = "harness.v1.sessions.index_event";
/// Notification method emitted for live runtime events.
pub const RUNTIME_EVENT_METHOD: &str = "harness.v1.runtimes.event";

/// Stateful persisted-session service. Each instance owns its follow
/// subscriptions; discovery and loading remain read-only.
pub struct HarnessSessionService {
    catalog: HarnessCatalog,
    followers: BTreeMap<String, SessionFollower>,
    followed_sources: BTreeMap<String, FollowedSource>,
    activity_subscriptions: BTreeMap<String, ActivitySubscription>,
    index_subscriptions: BTreeMap<String, crate::session_index::SessionIndexSubscription>,
    index_notifier: Arc<Notify>,
    #[cfg(feature = "adapter-api")]
    activity_monitor: crate::session_activity::SessionActivityMonitor,
    next_subscription: u64,
    runtimes: BTreeMap<String, Box<dyn RuntimeConnection>>,
    terminal_launches: BTreeMap<String, StructuredLaunch>,
    runtime_sequences: BTreeMap<String, u64>,
    next_runtime: u64,
    reduction_store_root: Option<PathBuf>,
    /// ORCH-9: live permission/approval requests outstanding on the open
    /// runtime connections above, fed by the same event pump that publishes
    /// `harness.v1.runtimes.event`.
    approvals: crate::approvals::ApprovalRegistry,
    /// ORCH-9: supercode's own queued subagent approvals, when the host that
    /// owns this service publishes its parent queue here.
    subagent_approvals: Option<Arc<std::sync::Mutex<Vec<crate::subagents::QueuedApproval>>>>,
}

impl Default for HarnessSessionService {
    fn default() -> Self {
        Self::new()
    }
}

impl HarnessSessionService {
    /// Create an empty service instance.
    pub fn new() -> Self {
        Self {
            catalog: HarnessCatalog::new(),
            followers: BTreeMap::new(),
            followed_sources: BTreeMap::new(),
            activity_subscriptions: BTreeMap::new(),
            index_subscriptions: BTreeMap::new(),
            index_notifier: Arc::new(Notify::new()),
            #[cfg(feature = "adapter-api")]
            activity_monitor: Default::default(),
            next_subscription: 1,
            runtimes: BTreeMap::new(),
            terminal_launches: BTreeMap::new(),
            runtime_sequences: BTreeMap::new(),
            next_runtime: 1,
            reduction_store_root: None,
            approvals: crate::approvals::ApprovalRegistry::new(),
            subagent_approvals: None,
        }
    }

    /// Override the trusted, service-owned store used for durable reduction
    /// bundles. Embedders and tests use this to keep all writes inside an
    /// explicitly selected root; the CLI otherwise uses the normal
    /// `$SUPERCODE_HOME/sessions` location.
    pub fn with_reduction_store_root(mut self, root: impl Into<PathBuf>) -> Self {
        self.reduction_store_root = Some(root.into());
        self
    }

    /// ORCH-9: publish the parent's own subagent-approval queue into
    /// `harness.v1.approvals.list`.
    ///
    /// This is the SAME `Arc` an [`crate::Agent`] pushes into
    /// (`Agent::pending_child_approvals`), so a host that runs supercode's own
    /// loop beside this service surfaces those requests through the uniform
    /// door without copying them anywhere.
    pub fn observe_subagent_approvals(
        &mut self,
        queue: Arc<std::sync::Mutex<Vec<crate::subagents::QueuedApproval>>>,
    ) {
        self.subagent_approvals = Some(queue);
    }

    /// ORCH-9: every approval request this service can see, newest last.
    ///
    /// Two sources, both live: the requests outstanding on the open runtime
    /// connections, and supercode's own queued subagent approvals. There is
    /// no file or database source at the pinned harness versions (see
    /// [`crate::approvals`]), so a stored or proposal row is never produced.
    pub fn approvals(&self, query: &crate::approvals::ApprovalsQuery) -> Vec<crate::ApprovalRow> {
        let now = crate::approvals::now_ms();
        let mut rows = self.approvals.rows(now);
        if let Some(queue) = self.subagent_approvals.as_ref() {
            let queued = queue
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .clone();
            rows.extend(crate::approvals::subagent_rows(&queued, now));
        }
        rows.retain(|row| query.matches(row));
        rows.sort_by(|left, right| {
            left.requested_at_ms
                .cmp(&right.requested_at_ms)
                .then_with(|| left.id.cmp(&right.id))
        });
        rows
    }

    /// ORCH-20 (controlled tier): answer one listed approval request by its
    /// row id and one uniform decision.
    ///
    /// The decision is translated into the option token and reply envelope
    /// the door that raised the request already accepts
    /// ([`crate::approvals::plan_reply`]), and the answer is then sent by
    /// calling `harness.v1.runtimes.respond` itself — the same code path, the
    /// same adapter, the same bookkeeping that drops the row. This verb adds
    /// a translation and nothing else.
    async fn approvals_resolve(
        &mut self,
        params: Value,
    ) -> std::result::Result<Value, ServiceError> {
        let params = decode::<crate::approvals::ApprovalsResolveParams>(params)?;
        if params.id.trim().is_empty() {
            return Err(ServiceError::InvalidParams(
                "approvals resolve requires the `id` of a listed approval row".into(),
            ));
        }
        let choice = match (params.decision, params.option_id.as_deref()) {
            (Some(_), Some(_)) => {
                return Err(ServiceError::InvalidParams(
                    "approvals resolve takes either `decision` or `option_id`, not both".into(),
                ))
            }
            (Some(decision), None) => crate::approvals::ApprovalChoice::Decision(decision),
            (None, Some(option)) => crate::approvals::ApprovalChoice::Option(option.to_string()),
            (None, None) => {
                return Err(ServiceError::InvalidParams(format!(
                    "approvals resolve requires `decision` ({}) or an explicit `option_id`",
                    crate::approvals::ApprovalDecision::ALL
                        .map(|decision| decision.as_str())
                        .join(" | "),
                )))
            }
        };
        let resolution = self
            .approvals
            .resolution(&params.id, &choice)
            .map_err(|error| ServiceError::InvalidParams(error.to_string()))?;
        // The harness's own door, unchanged: this is the identical call
        // `harness.v1.runtimes.respond` performs for a caller who built the
        // envelope by hand, including dropping the answered row.
        self.runtime_call(
            "harness.v1.runtimes.respond",
            json!({
                "connection": resolution.connection,
                "request_id": resolution.request_id,
                "response": resolution.response,
            }),
        )
        .await?;
        Ok(json!({
            "id": params.id,
            "decision": params.decision.map(|decision| decision.as_str()),
            "option_id": resolution.option_id,
            "resolved": true,
        }))
    }

    /// Return the edge-triggered wakeup used by session-index filesystem
    /// subscriptions. Transports can await this instead of polling indexes.
    #[cfg(feature = "adapter-api")]
    pub fn session_index_notifier(&self) -> Arc<Notify> {
        Arc::clone(&self.index_notifier)
    }

    /// Handle one JSON-RPC 2.0 request and return one JSON-RPC response.
    #[cfg(feature = "adapter-api")]
    pub fn handle(&mut self, request: Value) -> Value {
        let id = request.get("id").cloned().unwrap_or(Value::Null);
        if request.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
            return rpc_error(id, -32600, "expected a JSON-RPC 2.0 request");
        }
        let Some(method) = request.get("method").and_then(Value::as_str) else {
            return rpc_error(id, -32600, "request is missing `method`");
        };
        let params = request.get("params").cloned().unwrap_or_else(|| json!({}));
        match self.call(method, params) {
            Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
            Err(ServiceError::InvalidParams(message)) => rpc_error(id, -32602, &message),
            Err(ServiceError::MethodNotFound) => rpc_error(id, -32601, "method not found"),
            Err(ServiceError::UnsupportedAction(message)) => rpc_error(id, -32020, &message),
            Err(ServiceError::Operation(message)) => rpc_error(id, -32000, &message),
            Err(ServiceError::Sdk(error)) => sdk_rpc_error(id, &error),
        }
    }

    /// Handle either a persisted-session request or an asynchronous live
    /// runtime request.
    #[cfg(feature = "adapter-api")]
    pub async fn handle_async(&mut self, request: Value) -> Value {
        let method = request
            .get("method")
            .and_then(Value::as_str)
            .unwrap_or_default();
        if matches!(
            method,
            "harness.v1.harnesses.list" | "harness.v1.harnesses.probe"
        ) {
            let id = request.get("id").cloned().unwrap_or(Value::Null);
            if request.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
                return rpc_error(id, -32600, "expected a JSON-RPC 2.0 request");
            }
            let params = request.get("params").cloned().unwrap_or_else(|| json!({}));
            return match self.inventory_call(method, params).await {
                Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
                Err(ServiceError::InvalidParams(message)) => rpc_error(id, -32602, &message),
                Err(ServiceError::MethodNotFound) => rpc_error(id, -32601, "method not found"),
                Err(ServiceError::UnsupportedAction(message)) => rpc_error(id, -32020, &message),
                Err(ServiceError::Operation(message)) => rpc_error(id, -32000, &message),
                Err(ServiceError::Sdk(error)) => sdk_rpc_error(id, &error),
            };
        }
        if matches!(
            method,
            "harness.v1.harnesses.auth.methods"
                | "harness.v1.harnesses.auth.begin"
                | "harness.v1.harnesses.auth.verify"
        ) {
            let id = request.get("id").cloned().unwrap_or(Value::Null);
            if request.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
                return rpc_error(id, -32600, "expected a JSON-RPC 2.0 request");
            }
            let params = request.get("params").cloned().unwrap_or_else(|| json!({}));
            return match self.harness_authentication_call(method, params).await {
                Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
                Err(ServiceError::InvalidParams(message)) => rpc_error(id, -32602, &message),
                Err(ServiceError::MethodNotFound) => rpc_error(id, -32601, "method not found"),
                Err(ServiceError::UnsupportedAction(message)) => rpc_error(id, -32020, &message),
                Err(ServiceError::Operation(message)) => rpc_error(id, -32000, &message),
                Err(ServiceError::Sdk(error)) => sdk_rpc_error(id, &error),
            };
        }
        // ORCH-19 controlled tier. Answered here rather than through the SDK
        // operation dispatch below so the harness's OWN refusal reaches the
        // caller: `sdk_error` collapses every `UnsupportedAction` to one
        // generic sentence, and the whole point of this tier is that a
        // refusal names which door the harness does have.
        if matches!(
            method,
            "harness.v1.sessions.new"
                | "harness.v1.sessions.reset"
                | "harness.v1.sessions.archive"
                | "harness.v1.sessions.delete"
        ) {
            let id = request.get("id").cloned().unwrap_or(Value::Null);
            if request.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
                return rpc_error(id, -32600, "expected a JSON-RPC 2.0 request");
            }
            let params = request.get("params").cloned().unwrap_or_else(|| json!({}));
            let verb = match method {
                "harness.v1.sessions.new" => crate::SessionVerb::New,
                "harness.v1.sessions.reset" => crate::SessionVerb::Reset,
                "harness.v1.sessions.archive" => crate::SessionVerb::Archive,
                _ => crate::SessionVerb::Delete,
            };
            return match self.mutate_session(verb, params).await {
                Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
                Err(ServiceError::InvalidParams(message)) => rpc_error(id, -32602, &message),
                Err(ServiceError::MethodNotFound) => rpc_error(id, -32601, "method not found"),
                Err(ServiceError::UnsupportedAction(message)) => rpc_error(id, -32020, &message),
                Err(ServiceError::Operation(message)) => rpc_error(id, -32000, &message),
                Err(ServiceError::Sdk(error)) => sdk_rpc_error(id, &error),
            };
        }
        if method == "harness.v1.sessions.message" {
            let id = request.get("id").cloned().unwrap_or(Value::Null);
            if request.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
                return rpc_error(id, -32600, "expected a JSON-RPC 2.0 request");
            }
            let params = request.get("params").cloned().unwrap_or_else(|| json!({}));
            return match self.message_call(params).await {
                Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
                Err(ServiceError::InvalidParams(message)) => rpc_error(id, -32602, &message),
                Err(ServiceError::MethodNotFound) => rpc_error(id, -32601, "method not found"),
                Err(ServiceError::UnsupportedAction(message)) => rpc_error(id, -32020, &message),
                Err(ServiceError::Operation(message)) => rpc_error(id, -32000, &message),
                Err(ServiceError::Sdk(error)) => sdk_rpc_error(id, &error),
            };
        }
        if matches!(
            method,
            "harness.v1.harnesses.settings" | "harness.v1.harnesses.configure"
        ) {
            let id = request.get("id").cloned().unwrap_or(Value::Null);
            if request.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
                return rpc_error(id, -32600, "expected a JSON-RPC 2.0 request");
            }
            let params = request.get("params").cloned().unwrap_or_else(|| json!({}));
            return match self.harness_settings_call(method, params) {
                Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
                Err(ServiceError::InvalidParams(message)) => rpc_error(id, -32602, &message),
                Err(ServiceError::MethodNotFound) => rpc_error(id, -32601, "method not found"),
                Err(ServiceError::UnsupportedAction(message)) => rpc_error(id, -32020, &message),
                Err(ServiceError::Operation(message)) => rpc_error(id, -32000, &message),
                Err(ServiceError::Sdk(error)) => sdk_rpc_error(id, &error),
            };
        }
        if method == "harness.v1.sessions.activity.subscribe" {
            let id = request.get("id").cloned().unwrap_or(Value::Null);
            if request.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
                return rpc_error(id, -32600, "expected a JSON-RPC 2.0 request");
            }
            let params = request.get("params").cloned().unwrap_or_else(|| json!({}));
            return match self.subscribe_session_activity(params).await {
                Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
                Err(ServiceError::InvalidParams(message)) => rpc_error(id, -32602, &message),
                Err(ServiceError::MethodNotFound) => rpc_error(id, -32601, "method not found"),
                Err(ServiceError::UnsupportedAction(message)) => rpc_error(id, -32020, &message),
                Err(ServiceError::Operation(message)) => rpc_error(id, -32000, &message),
                Err(ServiceError::Sdk(error)) => sdk_rpc_error(id, &error),
            };
        }
        if let Some(operation) = SdkOperation::from_method(method) {
            let id = request.get("id").cloned().unwrap_or(Value::Null);
            if request.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
                return rpc_error(id, -32600, "expected a JSON-RPC 2.0 request");
            }
            let params = request.get("params").cloned().unwrap_or_else(|| json!({}));
            return match self.execute(SdkRequest { operation, params }).await {
                Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
                Err(error) => sdk_rpc_error(id, &error),
            };
        }
        if !method.starts_with("harness.v1.runtimes.") {
            return self.handle(request);
        }
        let id = request.get("id").cloned().unwrap_or(Value::Null);
        if request.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
            return rpc_error(id, -32600, "expected a JSON-RPC 2.0 request");
        }
        let params = request.get("params").cloned().unwrap_or_else(|| json!({}));
        match self.runtime_call(method, params).await {
            Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
            Err(ServiceError::InvalidParams(message)) => rpc_error(id, -32602, &message),
            Err(ServiceError::MethodNotFound) => rpc_error(id, -32601, "method not found"),
            Err(ServiceError::UnsupportedAction(message)) => rpc_error(id, -32020, &message),
            Err(ServiceError::Operation(message)) => rpc_error(id, -32000, &message),
            Err(ServiceError::Sdk(error)) => sdk_rpc_error(id, &error),
        }
    }

    /// Poll all active subscriptions once and return zero or more JSON-RPC
    /// notifications. Recoverable follower errors are delivered as events.
    #[cfg(feature = "adapter-api")]
    pub fn poll(&mut self) -> Vec<Value> {
        let mut notifications = Vec::new();
        for (subscription, follower) in &mut self.followers {
            match follower.poll() {
                Ok(Some(event)) => notifications.push(json!({
                    "jsonrpc": "2.0",
                    "method": SESSION_EVENT_METHOD,
                    "params": {
                        "subscription": subscription,
                        "event": event.to_json(),
                    }
                })),
                Ok(None) => {}
                Err(error) => notifications.push(json!({
                    "jsonrpc": "2.0",
                    "method": SESSION_EVENT_METHOD,
                    "params": {
                        "subscription": subscription,
                        "event": {
                            "type": "watch_error",
                            "recoverable": true,
                            "message": error.to_string(),
                        },
                    }
                })),
            }
        }
        notifications
    }

    /// Report each followed session's live-runtime lifecycle state on that
    /// session's own subscription, emitting only when the state changes.
    ///
    /// A growing transcript is not evidence that an agent is working, so the
    /// state comes from the live-runtime registry and nowhere else. A followed
    /// session with no registered Supercode runtime — a harness running outside
    /// Supercode — reports `persisted`, which says plainly that its activity is
    /// unknown rather than guessing at it. These events carry no sequence
    /// number and no transcript content; they never interleave with the
    /// content follower's sequenced stream.
    #[cfg(feature = "adapter-api")]
    pub async fn poll_session_runtime_states(&mut self) -> Vec<Value> {
        let registry = crate::LocalRuntimeRegistry::new();
        let authorization = crate::RuntimeAuthorization::observer();
        let mut notifications = Vec::new();
        for (subscription, source) in &mut self.followed_sources {
            let state = match registry
                .source_state(&source.harness, &source.session_id, &authorization)
                .await
            {
                Ok(Some(state)) => state,
                Ok(None) => crate::RuntimeRegistryState::Persisted,
                // A failed registry read is not evidence of a state change.
                Err(_) => continue,
            };
            if source.reported.as_deref() == Some(state.as_str()) {
                continue;
            }
            source.reported = Some(state.as_str().to_string());
            notifications.push(json!({
                "jsonrpc": "2.0",
                "method": SESSION_EVENT_METHOD,
                "params": {
                    "subscription": subscription,
                    "event": {"type": "runtime_state", "state": state.as_str()},
                },
            }));
        }
        notifications
    }

    /// Poll normalized activity subscriptions, emitting only proven state
    /// transitions. Every subscription is bulk-sampled so stock-harness
    /// process and registry discovery happens once per UI, not once per row.
    #[cfg(feature = "adapter-api")]
    pub async fn poll_session_activities(&mut self) -> Vec<Value> {
        let subscriptions = self
            .activity_subscriptions
            .iter()
            .map(|(id, subscription)| {
                (
                    id.clone(),
                    subscription.locators.clone(),
                    subscription.homes.clone(),
                )
            })
            .collect::<Vec<_>>();
        let mut notifications = Vec::new();
        for (subscription_id, locators, homes) in subscriptions {
            let Ok(activities) = self.activity_monitor.resolve(&locators, &homes).await else {
                // A failed evidence read proves no transition. Retain the last
                // good state instead of flashing every row to persisted.
                continue;
            };
            let Some(subscription) = self.activity_subscriptions.get_mut(&subscription_id) else {
                continue;
            };
            let mut changed = Vec::new();
            for activity in activities {
                let key = activity.key();
                if subscription
                    .reported
                    .get(&key)
                    .is_some_and(|previous| previous.same_state(&activity))
                {
                    continue;
                }
                subscription.reported.insert(key, activity.clone());
                changed.push(activity);
            }
            if !changed.is_empty() {
                notifications.push(json!({
                    "jsonrpc": "2.0",
                    "method": SESSION_ACTIVITY_EVENT_METHOD,
                    "params": {
                        "subscription": subscription_id,
                        "activities": changed,
                    },
                }));
            }
        }
        notifications
    }

    /// Drain native-store invalidations and emit revisioned descriptor deltas.
    /// An idle subscription performs no catalog or transcript reads between
    /// its minute-scale recovery reconciliations.
    #[cfg(feature = "adapter-api")]
    pub fn poll_session_indexes(&mut self) -> Vec<Value> {
        let mut notifications = Vec::new();
        for (subscription, index) in &mut self.index_subscriptions {
            let homes = index.homes().clone();
            match index.poll() {
                Ok(Some(delta)) => match live_index_changes(delta.changes, &homes) {
                    Ok(changes) => notifications.push(json!({
                        "jsonrpc": "2.0",
                        "method": SESSION_INDEX_EVENT_METHOD,
                        "params": {
                            "subscription": subscription,
                            "revision": delta.revision,
                            "changes": changes,
                        },
                    })),
                    Err(error) => notifications.push(json!({
                        "jsonrpc": "2.0",
                        "method": SESSION_INDEX_EVENT_METHOD,
                        "params": {
                            "subscription": subscription,
                            "error": {"recoverable": true, "message": error_message(error)},
                        },
                    })),
                },
                Ok(None) => {}
                Err(error) => notifications.push(json!({
                    "jsonrpc": "2.0",
                    "method": SESSION_INDEX_EVENT_METHOD,
                    "params": {
                        "subscription": subscription,
                        "error": {"recoverable": true, "message": error},
                    },
                })),
            }
        }
        notifications
    }

    #[cfg(feature = "adapter-api")]
    async fn subscribe_session_activity(
        &mut self,
        params: Value,
    ) -> std::result::Result<Value, ServiceError> {
        let params = decode::<ActivitySubscribeParams>(params)?;
        if params.locators.is_empty() {
            return Err(ServiceError::InvalidParams(
                "sessions.activity.subscribe requires at least one locator".into(),
            ));
        }
        if params.locators.len() > 2_048 {
            return Err(ServiceError::InvalidParams(
                "sessions.activity.subscribe accepts at most 2048 locators".into(),
            ));
        }
        let initial = self
            .activity_monitor
            .resolve(&params.locators, &params.homes)
            .await
            .map_err(ServiceError::Sdk)?;
        let subscription = format!("activity-sub-{}", self.next_subscription);
        self.next_subscription += 1;
        let reported = initial
            .iter()
            .cloned()
            .map(|activity| (activity.key(), activity))
            .collect();
        self.activity_subscriptions.insert(
            subscription.clone(),
            ActivitySubscription {
                locators: params.locators,
                homes: params.homes,
                reported,
            },
        );
        Ok(json!({"subscription": subscription, "initial": initial}))
    }

    /// Non-blockingly sample one event from every connected live runtime.
    #[cfg(feature = "adapter-api")]
    pub async fn poll_runtimes(&mut self) -> Vec<Value> {
        self.poll_sdk_events()
            .await
            .into_iter()
            .map(|(connection, runtime_event)| {
                json!({
                    "jsonrpc": "2.0",
                    "method": RUNTIME_EVENT_METHOD,
                    "params": {
                        "connection": connection,
                        "session_id": runtime_event.session_id,
                        "sequence": runtime_event.event.sequence,
                        "event": {
                            "kind": runtime_event.event.kind,
                            "payload": runtime_event.event.payload,
                        },
                    },
                })
            })
            .collect()
    }

    async fn poll_sdk_events(&mut self) -> Vec<(String, SdkRuntimeEvent)> {
        let mut events = Vec::new();
        let mut closed = Vec::new();
        let now_ms = crate::approvals::now_ms();
        for (connection, runtime) in &mut self.runtimes {
            let session_id = runtime.handle().runtime_id.clone();
            let harness = runtime.handle().harness.clone();
            // Drain what the runtime already has: a turn is several events
            // (updates, then the protocol's completion), and delivering one
            // per poll would cost a poll interval each. A zero timeout takes
            // only what is ready — an idle runtime costs nothing.
            for _ in 0..256 {
                match tokio::time::timeout(Duration::ZERO, runtime.next_event()).await {
                    Ok(Ok(Some(event))) => {
                        let terminal = event.kind == "transport_closed";
                        // ORCH-9: a permission/approval request arrives as an
                        // ordinary event; it becomes listable here and stops
                        // being listable when `runtimes.respond` answers it.
                        self.approvals
                            .observe(connection, &harness, &session_id, &event, now_ms);
                        let next_sequence = self
                            .runtime_sequences
                            .entry(session_id.clone())
                            .or_insert(0);
                        let sequence = event.sequence.unwrap_or_else(|| {
                            *next_sequence = next_sequence.saturating_add(1);
                            *next_sequence
                        });
                        *next_sequence = (*next_sequence).max(sequence);
                        events.push((
                            connection.clone(),
                            SdkRuntimeEvent {
                                session_id: session_id.clone(),
                                event: SdkEvent {
                                    sequence,
                                    kind: event.kind,
                                    payload: event.payload,
                                },
                            },
                        ));
                        if terminal {
                            closed.push(connection.clone());
                            break;
                        }
                    }
                    Ok(Ok(None)) => {
                        let sequence = self
                            .runtime_sequences
                            .entry(session_id.clone())
                            .or_insert(0);
                        *sequence = sequence.saturating_add(1);
                        events.push((
                        connection.clone(),
                        SdkRuntimeEvent {
                            session_id,
                            event: SdkEvent {
                                sequence: *sequence,
                                kind: "transport_closed".into(),
                                payload: json!({"message": "Harness runtime transport closed."}),
                            },
                        },
                    ));
                        closed.push(connection.clone());
                        break;
                    }
                    Err(_) => break,
                    Ok(Err(error)) => {
                        let sequence = self
                            .runtime_sequences
                            .entry(session_id.clone())
                            .or_insert(0);
                        *sequence = sequence.saturating_add(1);
                        events.push((
                        connection.clone(),
                        SdkRuntimeEvent {
                            session_id,
                            event: SdkEvent {
                                sequence: *sequence,
                                kind: "transport_error".into(),
                                payload: json!({"message": error.to_string(), "terminal": true}),
                            },
                        },
                    ));
                        closed.push(connection.clone());
                        break;
                    }
                }
            }
        }
        for connection in closed {
            if let Some(runtime) = self.runtimes.remove(&connection) {
                self.runtime_sequences.remove(&runtime.handle().runtime_id);
            }
            self.terminal_launches.remove(&connection);
            // A connection that is gone cannot answer anything it was
            // holding; those requests stop being listable with it.
            self.approvals.forget(&connection);
        }
        events
    }

    fn call(&mut self, method: &str, params: Value) -> std::result::Result<Value, ServiceError> {
        match method {
            "harness.v1.capabilities" => Ok(json!({
                "version": HARNESS_SERVICE_VERSION,
                "sdk": self.capabilities(),
                "methods": HARNESS_SERVICE_METHODS,
                "notifications": [
                    SESSION_EVENT_METHOD,
                    SESSION_ACTIVITY_EVENT_METHOD,
                    SESSION_INDEX_EVENT_METHOD,
                    RUNTIME_EVENT_METHOD
                ],
                "harnesses": harness_support_registry()
                    .harnesses
                    .into_iter()
                    .map(|harness| harness.id)
                    .collect::<Vec<_>>(),
            })),
            "harness.v1.support.report" => serde_json::to_value(harness_support_registry())
                .map_err(|error| ServiceError::Operation(error.to_string())),
            "harness.v1.profiles.list" | "harness.v1.profiles.get" => profiles_call(method, params),
            // ORCH-21 controlled tier. Each verb translates to the HARNESS'S
            // OWN profile verb and runs it (`crate::profiles_control`);
            // supercode makes and removes nothing itself. The row returned is
            // re-read through the ORCH-10 loader afterwards, and `ran`
            // narrates the exact command.
            "harness.v1.profiles.create" => {
                mutate_profile(crate::profiles_control::ProfileVerb::Create, params)
            }
            "harness.v1.profiles.delete" => {
                mutate_profile(crate::profiles_control::ProfileVerb::Delete, params)
            }
            "harness.v1.channels.list" | "harness.v1.channels.status" => {
                channels_call(method, params)
            }
            // ORCH-15 observed tier: which profile / agent a surface tuple
            // resolves to, read from each gateway harness's own config.
            "harness.v1.routes.list" => routes_call(params),
            // ORCH-16 observed tier: inbound webhook routes / hook mappings.
            "harness.v1.triggers.list" => triggers_call(params),
            // ONT-4: the orchestration doors. One home folder in, one typed orchestration
            // value out (and back). Every one of the four is
            // `crate::orchestration_doors`, which the `supercode orchestration` verbs call
            // too — the RPC adds nothing but the envelope. A vault VALUE
            // never crosses this wire: a load or a compile answers with the
            // `.env` KEY NAMES, and a caller that needs a value reads the
            // home's own `.env`.
            // the workflow layer's read door: a harness's board as one typed value,
            // the same code the `supercode workflow load` verb calls
            "harness.v1.workflow.load" => {
                let params = decode::<WorkflowLoadParams>(params)?;
                let read =
                    crate::workflow_doors::load(params.from, &params.home).map_err(operation)?;
                serde_json::to_value(read)
                    .map_err(|error| ServiceError::Operation(error.to_string()))
            }
            "harness.v1.orchestration.load" => {
                let params = decode::<OrchestrationLoadParams>(params)?;
                let read = crate::orchestration_doors::load(&params.root, params.flavor)
                    .map_err(operation)?;
                serde_json::to_value(read)
                    .map_err(|error| ServiceError::Operation(error.to_string()))
            }
            "harness.v1.orchestration.save" => {
                let params = decode::<OrchestrationSaveParams>(params)?;
                let saved = crate::orchestration_doors::save(
                    &params.root,
                    params.orchestration,
                    params.vault,
                )
                .map_err(operation)?;
                serde_json::to_value(saved)
                    .map_err(|error| ServiceError::Operation(error.to_string()))
            }
            "harness.v1.orchestration.compile" => {
                let params = decode::<OrchestrationCompileParams>(params)?;
                let read = crate::orchestration_doors::compile(params.from, &params.home)
                    .map_err(operation)?;
                serde_json::to_value(read)
                    .map_err(|error| ServiceError::Operation(error.to_string()))
            }
            "harness.v1.orchestration.decompile" => {
                let params = decode::<OrchestrationDecompileParams>(params)?;
                let report = crate::orchestration_doors::decompile(
                    params.to,
                    params.orchestration,
                    &params.source,
                    params.source_flavor,
                    &params.dest,
                    params.vault,
                )
                .map_err(operation)?;
                serde_json::to_value(report)
                    .map_err(|error| ServiceError::Operation(error.to_string()))
            }
            // a migration keeps the credential in this process: a compile and
            // a save (import), a load and a decompile (export), composed here
            // because composed by a client the secret would have to cross
            // the wire
            "harness.v1.orchestration.import" => {
                let params = decode::<OrchestrationImportParams>(params)?;
                let imported =
                    crate::orchestration_doors::import(params.from, &params.home, &params.into)
                        .map_err(operation)?;
                serde_json::to_value(imported)
                    .map_err(|error| ServiceError::Operation(error.to_string()))
            }
            "harness.v1.orchestration.export" => {
                let params = decode::<OrchestrationExportParams>(params)?;
                let report =
                    crate::orchestration_doors::export(params.to, &params.root, &params.dest)
                        .map_err(operation)?;
                serde_json::to_value(report)
                    .map_err(|error| ServiceError::Operation(error.to_string()))
            }
            // ORCH-12 observed tier: read and search the persistent memory
            // documents a harness keeps on disk. Read-only — every write
            // (`hermes memory off`, `openclaw memory forget|reset`, Claude
            // Code's `/memory`) stays the harness's own verb. A harness with
            // no memory store is refused with UnsupportedAction.
            "harness.v1.memory.show" | "harness.v1.memory.search" => memory_call(method, params),
            // ORCH-11 observed tier: read-only enumeration of every harness's
            // installed skill packages. An unknown harness id is refused with
            // UnsupportedAction — every harness supports skills, so a filter
            // that matches nothing is a caller error, never an empty listing.
            "harness.v1.skills.list" => {
                let query = decode::<crate::skills::SkillsQuery>(params)?;
                if let Some(harness) = query.harness.as_deref() {
                    if !crate::skills::SKILL_HARNESSES.contains(&harness) {
                        return Err(ServiceError::UnsupportedAction(format!(
                            "`{harness}` has no skills root supercode reads"
                        )));
                    }
                }
                serde_json::to_value(crate::skills::list_skills(&query))
                    .map_err(|error| ServiceError::Operation(error.to_string()))
            }
            // ORCH-22 controlled tier: each verb goes through the door the
            // HARNESS publishes — `hermes skills install|uninstall`,
            // `openclaw skills install`, and for the core four the loader's
            // own directory, which is the only skills door those harnesses
            // have. supercode resolves no registry and unpacks no archive.
            // The row returned is re-read through the ORCH-11 loader
            // afterwards, and `ran` narrates exactly what was performed.
            "harness.v1.skills.install" => {
                mutate_skill(crate::skills_control::SkillVerb::Install, params)
            }
            "harness.v1.skills.remove" => {
                mutate_skill(crate::skills_control::SkillVerb::Remove, params)
            }
            // ORCH-9 observed tier: the approval requests waiting for an
            // answer. At the pinned harness versions the only uniform source
            // is a LIVE request held by an open runtime connection, plus
            // supercode's own queued subagent approvals — neither Hermes
            // 0.21.0 nor OpenClaw 2026.7.1-2 has an approvals door to read
            // (see `crate::approvals`). A harness whose runtime cannot carry
            // a protocol request at all is refused by name.
            "harness.v1.approvals.list" => {
                let query = decode::<crate::approvals::ApprovalsQuery>(params)?;
                if let Some(harness) = query.harness.as_deref() {
                    if !crate::approvals::lists_approvals(harness) {
                        return Err(ServiceError::UnsupportedAction(format!(
                            "`{harness}` has no runtime door that carries an approval request"
                        )));
                    }
                }
                serde_json::to_value(self.approvals(&query))
                    .map_err(|error| ServiceError::Operation(error.to_string()))
            }
            "harness.v1.sessions.discover" => {
                let query = decode::<DiscoveryQuery>(params)?;
                let page = discover_session_page(&query).map_err(operation)?;
                // Claude Code is the one harness that publishes its RUNNING
                // sessions. The registry is read once per discovery and joined
                // by session id; every record in it has already survived a
                // `kill(pid, 0)` liveness check inside `read_registry`.
                let peers = if page
                    .sessions
                    .iter()
                    .any(|session| session.locator.harness.as_str() == HarnessId::CLAUDE_CODE)
                {
                    crate::claude_peer::read_registry(&crate::claude_peer::registry_dir(
                        &query.homes,
                    ))
                } else {
                    Vec::new()
                };
                let activities = crate::session_activity::resolve_stock_session_activities(
                    &page
                        .sessions
                        .iter()
                        .map(|session| session.locator.clone())
                        .collect::<Vec<_>>(),
                    &query.homes,
                )
                .into_iter()
                .map(|activity| (activity.key(), activity))
                .collect::<BTreeMap<_, _>>();
                let sessions = page
                    .sessions
                    .into_iter()
                    .map(|session| {
                        let mut value = live_descriptor_value(&session, &peers)?;
                        let activity_key = (
                            session.locator.harness.as_str().to_string(),
                            session.locator.session_id.clone(),
                        );
                        if let Some(activity) = activities.get(&activity_key) {
                            value["activity"] = serde_json::to_value(activity)
                                .map_err(|error| ServiceError::Operation(error.to_string()))?;
                            if let Some(status) = legacy_live_status(activity) {
                                value["live_status"] = json!(status);
                            }
                        }
                        Ok(value)
                    })
                    .collect::<std::result::Result<Vec<_>, ServiceError>>()?;
                Ok(json!({"sessions": sessions, "next_cursor": page.next_cursor}))
            }
            "harness.v1.sessions.load" => {
                let params = decode::<LoadSessionParams>(params)?;
                if let Some(options) = &params.options {
                    options.validate()?;
                    return load_session(&params.read.locator)
                        .map(|session| projected_session_result(&session, options))
                        .map_err(operation);
                }
                let mut session = if params.read.display_history() {
                    self.catalog
                        .load_display_view(
                            &params.read.locator,
                            params.read.read_fidelity(),
                            params.read.tail_messages().unwrap_or(500),
                        )
                        .map_err(crate::Error::from)
                } else if params.read.include_subagents() {
                    load_session_with_fidelity(&params.read.locator, params.read.read_fidelity())
                } else {
                    self.catalog
                        .load_parent_with_fidelity(
                            &params.read.locator,
                            params.read.read_fidelity(),
                        )
                        .map_err(crate::Error::from)
                }
                .map_err(operation)?;
                params.read.bound_session(&mut session);
                Ok(json!({"session": normalized_session_json(&session)}))
            }
            "harness.v1.sessions.follow" => {
                let params = decode::<LocatorParams>(params)?;
                let mut follower = self
                    .catalog
                    .follow_read_view(
                        &params.locator,
                        params.read_fidelity(),
                        params.include_subagents(),
                        params.tail_messages(),
                        params.max_message_chars(),
                        params.display_history(),
                    )
                    .map_err(operation)?;
                let initial = follower
                    .poll()
                    .map_err(operation)?
                    .map(|event| event.to_json());
                let subscription = format!("sub-{}", self.next_subscription);
                self.next_subscription += 1;
                self.followers.insert(subscription.clone(), follower);
                self.followed_sources.insert(
                    subscription.clone(),
                    FollowedSource {
                        harness: params.locator.harness.as_str().to_string(),
                        session_id: params.locator.session_id.clone(),
                        reported: None,
                    },
                );
                Ok(json!({"subscription": subscription, "initial": initial}))
            }
            "harness.v1.sessions.unfollow" => {
                let params = decode::<UnfollowParams>(params)?;
                self.followed_sources.remove(&params.subscription);
                Ok(json!({
                    "removed": self.followers.remove(&params.subscription).is_some()
                }))
            }
            "harness.v1.sessions.activity.unsubscribe" => {
                let params = decode::<UnfollowParams>(params)?;
                Ok(json!({
                    "removed": self.activity_subscriptions.remove(&params.subscription).is_some()
                }))
            }
            "harness.v1.sessions.index.subscribe" => {
                let query = decode::<DiscoveryQuery>(params)?;
                crate::session_index::validate_query(&query)
                    .map_err(ServiceError::InvalidParams)?;
                let homes = query.homes.clone();
                let (index, initial) = crate::session_index::SessionIndexSubscription::open(
                    query,
                    Arc::clone(&self.index_notifier),
                )
                .map_err(ServiceError::Operation)?;
                let peers = peers_for_descriptors(&initial, &homes);
                let initial = initial
                    .iter()
                    .map(|descriptor| live_descriptor_value(descriptor, &peers))
                    .collect::<std::result::Result<Vec<_>, ServiceError>>()?;
                let subscription = format!("index-sub-{}", self.next_subscription);
                self.next_subscription += 1;
                self.index_subscriptions.insert(subscription.clone(), index);
                Ok(json!({
                    "subscription": subscription,
                    "revision": 1,
                    "initial": initial,
                }))
            }
            "harness.v1.sessions.index.unsubscribe" => {
                let params = decode::<UnfollowParams>(params)?;
                Ok(json!({
                    "removed": self.index_subscriptions.remove(&params.subscription).is_some()
                }))
            }
            "harness.v1.sessions.import" => {
                let params = decode::<ImportSessionParams>(params)?;
                let session = Session::load_str(&params.content, params.source_harness.into())
                    .map_err(operation)?;
                Ok(json!({"session": normalized_session_json(&session)}))
            }
            "harness.v1.sessions.export" | "harness.v1.sessions.translate" => {
                let params = decode::<ExportSessionParams>(params)?;
                let session = load_session(&params.locator).map_err(operation)?;
                let artifact = session_artifact(&params.locator, &session, params.target_harness)?;
                if method == "harness.v1.sessions.export"
                    && params.target_harness == TransferFormat::Hermes
                {
                    // UNI-18: write through Hermes's own door, never into its store
                    let imported = crate::hermes_import::import_into_hermes(&session, None)
                        .map_err(operation)?;
                    return Ok(json!({"artifact": artifact, "imported": imported}));
                }
                Ok(json!({"artifact": artifact}))
            }
            "harness.v1.sessions.reduce" => {
                let params = decode::<ReduceSessionParams>(params)?;
                self.reduce_session(params)
            }
            "harness.v1.sessions.branch" => {
                let params = decode::<BranchSessionParams>(params)?;
                let session = load_session(&params.locator).map_err(operation)?;
                let storage = params.locator.storage.path().display().to_string();
                let bootstrap_prompt = format!(
                    "Continue as a new branch from {} session {}. The frozen parent transcript is at {}. Read or load that parent for context, summarize the relevant state, then continue independently without mutating the parent session.",
                    params.locator.harness.as_str(), params.locator.session_id, storage
                );
                let artifact = params
                    .target_harness
                    .map(|target| session_artifact(&params.locator, &session, target))
                    .transpose()?;
                Ok(json!({
                    "parent": params.locator,
                    "session": normalized_session_json(&session),
                    "bootstrap_prompt": bootstrap_prompt,
                    "artifact": artifact,
                }))
            }
            "harness.v1.sessions.handoff" => {
                let params = decode::<HandoffSessionParams>(params)?;
                let session = load_session(&params.locator).map_err(operation)?;
                let cwd = params
                    .cwd
                    .or_else(|| session.meta.cwd.clone())
                    .unwrap_or_else(|| PathBuf::from("."));
                let artifact =
                    handoff_artifact(&params.locator, &session, params.target_harness, &cwd)?;
                let target_session_id = artifact.session_id.as_deref().ok_or_else(|| {
                    ServiceError::Operation(
                        "handoff artifact omitted target session identity".into(),
                    )
                })?;
                let instructions =
                    handoff_instructions(params.target_harness, target_session_id, &cwd);
                Ok(json!({
                    "artifact": artifact,
                    "launch": instructions.launch,
                    "materialize": instructions.materialize,
                    "requires_materialization": instructions.requires_materialization,
                    "note": instructions.note,
                }))
            }
            // ORCH-7 observed tier. Read-only: the handlers open the harness's
            // own job store (Claude Code's session JSONL, Hermes's and
            // OpenClaw's `cron/jobs.json`) and never write, fire, or schedule.
            "harness.v1.jobs.list" => {
                let query = decode::<crate::jobs::JobsQuery>(params)?;
                if let Some(harness) = query.harness.as_deref() {
                    refuse_harness_without_jobs(harness, "jobs.list")?;
                }
                let listing = crate::jobs::list_jobs(&query).map_err(operation)?;
                serde_json::to_value(listing)
                    .map_err(|error| ServiceError::Operation(error.to_string()))
            }
            "harness.v1.jobs.get" => {
                let params = decode::<JobsGetParams>(params)?;
                refuse_harness_without_jobs(&params.harness, "jobs.get")?;
                match crate::jobs::get_job(&params.harness, &params.id, &params.homes)
                    .map_err(operation)?
                {
                    Some((job, source)) => Ok(json!({"job": job, "source": source})),
                    None => Err(ServiceError::Operation(format!(
                        "`{}` has no scheduled job `{}`",
                        params.harness, params.id
                    ))),
                }
            }
            // ORCH-18 controlled tier. Each verb translates to the HARNESS'S
            // OWN cron verb and runs it (`crate::jobs_control`); supercode
            // schedules nothing. The row returned is re-read from the
            // harness's store afterwards, and `ran` narrates the exact command
            // with any credential redacted.
            "harness.v1.jobs.create" => mutate_job(crate::jobs_control::JobVerb::Create, params),
            "harness.v1.jobs.update" => mutate_job(crate::jobs_control::JobVerb::Update, params),
            "harness.v1.jobs.pause" => mutate_job(crate::jobs_control::JobVerb::Pause, params),
            "harness.v1.jobs.resume" => mutate_job(crate::jobs_control::JobVerb::Resume, params),
            "harness.v1.jobs.run" => mutate_job(crate::jobs_control::JobVerb::Run, params),
            "harness.v1.jobs.delete" => mutate_job(crate::jobs_control::JobVerb::Delete, params),
            // ORCH-8 observed tier. Read-only: the handlers open the harness's
            // own run store (Hermes's `cron/executions.db`, OpenClaw's
            // `cron_run_logs`) and never claim, retry, or prune a fire.
            "harness.v1.runs.list" => {
                let query = decode::<crate::runs::RunsQuery>(params)?;
                if let Some(harness) = query.harness.as_deref() {
                    refuse_harness_without_runs(harness, "runs.list")?;
                }
                let listing = crate::runs::list_runs(&query).map_err(operation)?;
                serde_json::to_value(listing)
                    .map_err(|error| ServiceError::Operation(error.to_string()))
            }
            "harness.v1.runs.get" => {
                let params = decode::<RunsGetParams>(params)?;
                refuse_harness_without_runs(&params.harness, "runs.get")?;
                match crate::runs::get_run(&params.harness, &params.id, &params.homes)
                    .map_err(operation)?
                {
                    Some((run, source)) => Ok(json!({"run": run, "source": source})),
                    None => Err(ServiceError::Operation(format!(
                        "`{}` has no run `{}`",
                        params.harness, params.id
                    ))),
                }
            }
            "harness.v1.sessions.resume_instructions" => {
                let params = decode::<ResumeInstructionsParams>(params)?;
                let session = load_session(&params.locator).map_err(operation)?;
                let cwd = params
                    .cwd
                    .or(session.meta.cwd)
                    .unwrap_or_else(|| PathBuf::from("."));
                let launch = resume_launch(
                    params.locator.harness.as_str(),
                    &params.locator.session_id,
                    &cwd,
                    params.policy,
                )?;
                Ok(json!({"launch": launch}))
            }
            _ => Err(ServiceError::MethodNotFound),
        }
    }

    fn reduce_session(
        &self,
        params: ReduceSessionParams,
    ) -> std::result::Result<Value, ServiceError> {
        let session = load_session(&params.locator).map_err(operation)?;
        if session.messages.is_empty() {
            return Err(ServiceError::InvalidParams(
                "cannot reduce an empty session".into(),
            ));
        }
        let keep_last = params.keep_last.clamp(1, 128);
        let policy = reduce::ReductionPolicy {
            clear_turns_older_than: Some(keep_last),
            ..Default::default()
        };
        let (view, log) =
            reduce::project_messages(&session.messages, &policy, &reduce::ReductionLog::default());
        if log.reductions.is_empty() {
            return Err(ServiceError::UnsupportedAction(format!(
                "session `{}` is already too small for a meaningful reversible reduction",
                params.locator.session_id
            )));
        }
        let source_tokens = tokens::estimate_view_tokens(&session.messages);
        let reduced_tokens = tokens::estimate_view_tokens(&view);
        if reduced_tokens >= source_tokens {
            return Err(ServiceError::UnsupportedAction(format!(
                "session `{}` has no token-reducing reversible projection",
                params.locator.session_id
            )));
        }

        let store_root = self
            .reduction_store_root
            .clone()
            .unwrap_or_else(default_reduction_store_root);
        let store = crate::SessionStore::open(&store_root).map_err(operation)?;
        let rescue_id = format!("rescue-{}", generated_session_id());
        let imported = session
            .imported_message_count
            .unwrap_or(session.messages.len())
            .min(session.messages.len());
        let sidecar_jsonl = session.to_native_jsonl_v2(&session.messages[imported..]);
        let view_jsonl = messages_jsonl(&view)?;
        let title = format!(
            "Reduced {} continuation from {}",
            params.target_harness.id(),
            params.locator.session_id
        );

        // Durability order is intentional: the full source of truth lands
        // before either object that can refer to it. A crash may leave an
        // unused sidecar, but can never leave a reduced view whose originals
        // were not durably written first.
        store
            .save_sidecar(&rescue_id, &sidecar_jsonl)
            .map_err(operation)?;
        store
            .save_reduction_log(&rescue_id, &log)
            .map_err(operation)?;
        store
            .save(&rescue_id, &title, &view_jsonl)
            .map_err(operation)?;

        let source_bytes = serde_json::to_vec(&session.messages)
            .map_err(|error| ServiceError::Operation(error.to_string()))?
            .len() as u64;
        let reduced_bytes = serde_json::to_vec(&view)
            .map_err(|error| ServiceError::Operation(error.to_string()))?
            .len() as u64;
        store
            .set_reduction_stats(
                &rescue_id,
                &title,
                source_bytes,
                reduced_bytes,
                log.reductions.len() as u32,
            )
            .map_err(operation)?;

        // The receipt is issued only after a real disk reload. This proves
        // the exact files another process will consume, not the convenient
        // in-memory values that produced them.
        let reloaded_sidecar = store
            .load_sidecar(&rescue_id)
            .map_err(operation)?
            .ok_or_else(|| ServiceError::Operation("reduction sidecar disappeared".into()))?;
        let reloaded_sidecar = Session::from_sidecar_str(&reloaded_sidecar).map_err(operation)?;
        let reloaded_log = store
            .load_reduction_log(&rescue_id)
            .map_err(operation)?
            .ok_or_else(|| ServiceError::Operation("reduction log disappeared".into()))?;
        let reloaded_view = parse_messages_jsonl(&store.load(&rescue_id).map_err(operation)?)?;
        reduce::verify_log(&reloaded_log, &reloaded_sidecar).map_err(operation)?;
        // `sc.reduction` is deliberately in-memory-only metadata: it must
        // never leak onto a provider-facing transcript. Reapplying the
        // durable log to the durable sidecar restores those ids. Comparing
        // its wire form with the transcript reloaded above proves that the
        // persisted view is exactly the deterministic projection before we
        // use the restamped form for inversion.
        let (restamped_view, restamped_log) =
            reduce::project_messages(&reloaded_sidecar.messages, &policy, &reloaded_log);
        if messages_jsonl(&restamped_view)? != messages_jsonl(&reloaded_view)? {
            return Err(ServiceError::Operation(
                "persisted reduction view does not match its durable log and sidecar".into(),
            ));
        }
        if restamped_log != reloaded_log {
            return Err(ServiceError::Operation(
                "reapplying the durable reduction log changed its identity".into(),
            ));
        }
        let inverted =
            reduce::invert(&restamped_view, &reloaded_log, &reloaded_sidecar).map_err(operation)?;
        if inverted != session.messages {
            return Err(ServiceError::Operation(
                "reduction inversion did not restore the source messages byte-exactly".into(),
            ));
        }

        let ratio = source_tokens as f64 / reduced_tokens.max(1) as f64;
        let sidecar_path = store.sidecar_path(&rescue_id);
        let reduction_log_path = store.reduction_log_path(&rescue_id).map_err(operation)?;
        let bootstrap_prompt = reduced_bootstrap_prompt(
            &params.locator,
            params.target_harness,
            &view_jsonl,
            &sidecar_path,
            &reduction_log_path,
        );
        let mut reduced_session = session.clone();
        reduced_session.meta.session_id = Some(rescue_id.clone());
        reduced_session.messages = view;

        Ok(json!({
            "session": normalized_session_json(&reduced_session),
            "bootstrap_prompt": bootstrap_prompt,
            "receipt": {
                "id": rescue_id,
                "sidecar_id": rescue_id,
                "source_harness": params.locator.harness,
                "target_harness": params.target_harness.id(),
                "source_tokens": source_tokens,
                "reduced_tokens": reduced_tokens,
                "ratio": ratio,
                "source_bytes": source_bytes,
                "reduced_bytes": reduced_bytes,
                "reductions": reloaded_log.reductions.len(),
                "sidecar_path": sidecar_path,
                "reduction_log_path": reduction_log_path,
                "verified": true,
                "reversible": true,
            }
        }))
    }

    async fn runtime_call(
        &mut self,
        method: &str,
        params: Value,
    ) -> std::result::Result<Value, ServiceError> {
        match method {
            "harness.v1.runtimes.capabilities" => {
                let params = decode::<RuntimeBackendParams>(params)?;
                let backend = runtime_backend(&params)?;
                Ok(json!({
                    "harness": backend.harness(),
                    "capabilities": backend.capabilities(),
                }))
            }
            "harness.v1.runtimes.start" => {
                let params = decode::<RuntimeStartParams>(params)?;
                let backend = runtime_backend(&params.backend)?;
                let capabilities = backend.capabilities();
                let workspace = params.cwd.clone();
                let runtime = backend
                    .start(RuntimeStartRequest {
                        cwd: params.cwd,
                        launch: runtime_launch(&params.backend),
                        mcp_servers: params.mcp_servers,
                    })
                    .await
                    .map_err(operation)?;
                self.insert_hosted_runtime(runtime, capabilities, workspace)
                    .await
            }
            "harness.v1.runtimes.resume" | "harness.v1.runtimes.attach" => {
                let params = decode::<RuntimeAttachParams>(params)?;
                let backend = runtime_backend(&params.backend)?;
                let capabilities = backend.capabilities();
                let workspace = params.cwd.clone().unwrap_or_else(|| {
                    std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
                });
                let runtime = backend
                    .attach(RuntimeAttachRequest {
                        runtime_id: params.runtime_id,
                        cwd: params.cwd,
                        launch: runtime_launch(&params.backend),
                    })
                    .await
                    .map_err(operation)?;
                self.insert_hosted_runtime(runtime, capabilities, workspace)
                    .await
            }
            "harness.v1.runtimes.attach_existing" => {
                let params = decode::<RuntimeAttachParams>(params)?;
                let backend: Box<dyn RuntimeBackend> = match params
                    .backend
                    .base_url
                    .as_deref()
                    .and_then(|value| LiveRuntimeEndpoint::parse(value).ok())
                {
                    Some(endpoint) => {
                        #[cfg(not(feature = "adapter-api"))]
                        {
                            let _ = endpoint;
                            return Err(ServiceError::UnsupportedAction(
                                "live HTTP attachment adapter is not compiled".into(),
                            ));
                        }
                        #[cfg(feature = "adapter-api")]
                        {
                            let workspace = params.cwd.clone().ok_or_else(|| {
                                ServiceError::InvalidParams(
                                    "Supercode live attach requires the project cwd".into(),
                                )
                            })?;
                            let source = LiveRuntimeSource {
                                harness: params.backend.harness.as_str().to_string(),
                                session_id: params.runtime_id.clone(),
                                workspace,
                            };
                            let receipt = resolve_live_runtime(&endpoint, &source)
                                .map_err(|error| ServiceError::Operation(error.to_string()))?;
                            Box::new(SupercodeHttpRuntimeBackend::new(receipt))
                        }
                    }
                    None => runtime_backend(&params.backend)?,
                };
                if !backend.capabilities().attach_existing_process {
                    return Err(ServiceError::Operation(format!(
                        "{} cannot attach to an already-running process; use runtimes.resume for a persisted session",
                        backend.harness().as_str()
                    )));
                }
                let runtime = backend
                    .attach_existing(RuntimeAttachRequest {
                        runtime_id: params.runtime_id,
                        cwd: params.cwd,
                        launch: runtime_launch(&params.backend),
                    })
                    .await
                    .map_err(operation)?;
                self.insert_runtime(runtime)
            }
            "harness.v1.runtimes.send_input" => {
                let params = decode::<RuntimeInputParams>(params)?;
                let image_urls = validate_runtime_image_urls(params.image_urls)?;
                let runtime = self.runtime_mut(&params.connection)?;
                let turn_id = runtime
                    .send_input(RuntimeInput {
                        text: params.text,
                        image_urls,
                    })
                    .await
                    .map_err(operation)?;
                Ok(json!({"turn_id": turn_id}))
            }
            "harness.v1.runtimes.interrupt" => {
                let params = decode::<RuntimeConnectionParams>(params)?;
                self.runtime_mut(&params.connection)?
                    .interrupt()
                    .await
                    .map_err(operation)?;
                Ok(json!({}))
            }
            "harness.v1.runtimes.steer" => {
                let params = decode::<RuntimeInputParams>(params)?;
                if !params.image_urls.is_empty() {
                    return Err(ServiceError::InvalidParams(
                        "runtime steering accepts text only".into(),
                    ));
                }
                let text = params.text.trim();
                if text.is_empty() || text.chars().count() > 50_000 {
                    return Err(ServiceError::InvalidParams(
                        "runtime steering requires 1 to 50,000 text characters".into(),
                    ));
                }
                self.runtime_mut(&params.connection)?
                    .steer(text.to_string())
                    .await
                    .map_err(operation)?;
                Ok(json!({}))
            }
            "harness.v1.runtimes.respond" => {
                let params = decode::<RuntimeRespondParams>(params)?;
                let request_id = params.request_id.clone();
                self.runtime_mut(&params.connection)?
                    .respond(params.request_id, params.response)
                    .await
                    .map_err(operation)?;
                // ORCH-9: an answered request is no longer waiting for one.
                self.approvals.answered(&params.connection, &request_id);
                Ok(json!({}))
            }
            "harness.v1.runtimes.terminal_instructions" => {
                let params = decode::<RuntimeConnectionParams>(params)?;
                let launch = self
                    .terminal_launches
                    .get(&params.connection)
                    .ok_or_else(|| {
                        ServiceError::Operation(
                            "this runtime is not hosted for terminal attachment".into(),
                        )
                    })?;
                Ok(json!({"launch":launch}))
            }
            "harness.v1.runtimes.close" => {
                let params = decode::<RuntimeConnectionParams>(params)?;
                let Some(mut runtime) = self.runtimes.remove(&params.connection) else {
                    return Err(ServiceError::InvalidParams(format!(
                        "unknown runtime connection `{}`",
                        params.connection
                    )));
                };
                self.terminal_launches.remove(&params.connection);
                self.runtime_sequences.remove(&runtime.handle().runtime_id);
                self.approvals.forget(&params.connection);
                runtime.close().await.map_err(operation)?;
                Ok(json!({"closed": true}))
            }
            _ => Err(ServiceError::MethodNotFound),
        }
    }

    /// Deliver one message into a session that is running right now.
    #[cfg(feature = "adapter-api")]
    async fn message_call(&self, params: Value) -> std::result::Result<Value, ServiceError> {
        let params = decode::<MessageSessionParams>(params)?;
        Ok(message_live_session(&params, &crate::claude_peer::ProcessCourierRunner).await)
    }

    #[cfg(feature = "adapter-api")]
    fn harness_settings_call(
        &self,
        method: &str,
        params: Value,
    ) -> std::result::Result<Value, ServiceError> {
        let homes = crate::HarnessHomes::default();
        match method {
            "harness.v1.harnesses.settings" => {
                let params = decode::<HarnessSettingsParams>(params)?;
                let report = crate::inspect_harness_interop_settings(&homes, &params.harness)
                    .map_err(|error| ServiceError::Operation(error.to_string()))?;
                serde_json::to_value(report)
                    .map_err(|error| ServiceError::Operation(error.to_string()))
            }
            "harness.v1.harnesses.configure" => {
                let params = decode::<ConfigureHarnessParams>(params)?;
                let report = crate::configure_harness_interop_settings(
                    &homes,
                    &params.harness,
                    &params.changes,
                    params.expected_revision.as_deref(),
                )
                .map_err(|error| ServiceError::Operation(error.to_string()))?;
                serde_json::to_value(report)
                    .map_err(|error| ServiceError::Operation(error.to_string()))
            }
            _ => Err(ServiceError::MethodNotFound),
        }
    }

    fn insert_runtime(
        &mut self,
        runtime: Box<dyn RuntimeConnection>,
    ) -> std::result::Result<Value, ServiceError> {
        let connection = format!("runtime-{}", self.next_runtime);
        self.next_runtime += 1;
        let handle = runtime.handle().clone();
        self.runtime_sequences
            .entry(handle.runtime_id.clone())
            .or_insert(0);
        self.runtimes.insert(connection.clone(), runtime);
        Ok(json!({"connection": connection, "handle": handle}))
    }

    #[cfg(feature = "adapter-api")]
    async fn insert_hosted_runtime(
        &mut self,
        runtime: Box<dyn RuntimeConnection>,
        capabilities: crate::RuntimeCapabilities,
        workspace: PathBuf,
    ) -> std::result::Result<Value, ServiceError> {
        let (host, connection) = HostedHarnessRuntime::spawn(runtime, capabilities);
        let token: std::sync::Arc<str> = crate::server::generate_token().into();
        let server = crate::server::run_frontend_http(
            host.clone(),
            host.frontend_sender(),
            "127.0.0.1:0",
            token.clone(),
        )
        .await
        .map_err(|error| ServiceError::Operation(error.to_string()))?;
        let source = LiveRuntimeSource {
            harness: connection.handle().harness.as_str().to_string(),
            session_id: connection.handle().runtime_id.clone(),
            workspace: workspace.clone(),
        };
        let registration = register_live_runtime(
            connection.handle().runtime_id.clone(),
            source.clone(),
            format!("http://{}", server.address()),
            token.to_string(),
        )
        .map_err(|error| ServiceError::Operation(error.to_string()))?;
        let endpoint = registration.endpoint().to_string();
        let launch = StructuredLaunch {
            cwd: workspace,
            // Pin attachment to the executable hosting this runtime. A bare
            // `supercode` could resolve to an older global install whose CLI
            // does not understand the receipt it is being asked to open.
            program: std::env::current_exe()
                .ok()
                .map(|path| path.to_string_lossy().into_owned())
                .unwrap_or_else(|| "supercode".into()),
            arguments: vec![
                "harness".into(),
                "attach".into(),
                "--endpoint".into(),
                endpoint,
                "--harness".into(),
                source.harness,
                "--session".into(),
                source.session_id,
            ],
            env: BTreeMap::new(),
        };
        let lease = HostedRuntimeLease {
            connection,
            _host: host,
            _registration: registration,
            _server: server,
        };
        let opened = self.insert_runtime(Box::new(lease))?;
        let connection_id = opened["connection"]
            .as_str()
            .expect("insert_runtime returns a connection id")
            .to_string();
        self.terminal_launches.insert(connection_id, launch);
        Ok(opened)
    }

    #[cfg(not(feature = "adapter-api"))]
    async fn insert_hosted_runtime(
        &mut self,
        runtime: Box<dyn RuntimeConnection>,
        _capabilities: crate::RuntimeCapabilities,
        _workspace: PathBuf,
    ) -> std::result::Result<Value, ServiceError> {
        self.insert_runtime(runtime)
    }

    fn runtime_mut(
        &mut self,
        connection: &str,
    ) -> std::result::Result<&mut Box<dyn RuntimeConnection>, ServiceError> {
        self.runtimes.get_mut(connection).ok_or_else(|| {
            ServiceError::InvalidParams(format!("unknown runtime connection `{connection}`"))
        })
    }

    /// ORCH-19: run one conversation-lifecycle verb through the harness's own
    /// door.
    ///
    /// Two doors, one shape. A CLI / HTTP / own-store door is self-contained
    /// in [`crate::sessions_control`]. A LIVE door (Hermes's and OpenClaw's
    /// `/new` and `/reset`, which are slash commands their gateway interprets
    /// INSIDE a session) is performed here, because only the service owns the
    /// open runtime connection — the command is typed through the very same
    /// `send_input` path a human's message takes, so supercode invents no
    /// private channel.
    async fn mutate_session(
        &mut self,
        verb: crate::SessionVerb,
        params: Value,
    ) -> std::result::Result<Value, ServiceError> {
        let mutation = decode::<crate::SessionMutation>(params)?;
        let door = crate::sessions_control::door(&mutation.harness, verb)
            .map_err(session_control_error)?;
        let outcome = match door {
            // The live door types the slash command through an open hosted
            // runtime, which only exists with the `adapter-api` feature; the
            // CLI / HTTP / own-store doors below need nothing extra.
            #[cfg(not(feature = "adapter-api"))]
            crate::SessionDoor::Live(command) => {
                return Err(ServiceError::Operation(format!(
                    "`{}` performs `sessions.{}` by typing `{command}` into a live driven \
                     session, which needs this build's `adapter-api` feature",
                    mutation.harness,
                    verb.as_str()
                )));
            }
            #[cfg(feature = "adapter-api")]
            crate::SessionDoor::Live(command) => {
                let connection = mutation
                    .connection
                    .clone()
                    .filter(|value| !value.trim().is_empty())
                    .ok_or_else(|| {
                        ServiceError::InvalidParams(format!(
                            "`{}` performs `sessions.{}` by typing `{command}` into a live \
                             driven session: pass the `connection` of an open runtime \
                             (`harness.v1.runtimes.start`)",
                            mutation.harness,
                            verb.as_str()
                        ))
                    })?;
                let runtime = self.runtime_mut(&connection)?;
                let session = mutation
                    .session
                    .clone()
                    .filter(|value| !value.trim().is_empty())
                    .unwrap_or_else(|| runtime.handle().runtime_id.clone());
                runtime
                    .send_input(RuntimeInput {
                        text: command.to_string(),
                        image_urls: Vec::new(),
                    })
                    .await
                    .map_err(operation)?;
                crate::sessions_control::live_outcome(verb, &mutation, command, session)
                    .map_err(session_control_error)?
            }
            _ => crate::sessions_control::mutate(verb, &mutation)
                .await
                .map_err(session_control_error)?,
        };
        serde_json::to_value(outcome).map_err(|error| ServiceError::Operation(error.to_string()))
    }

    async fn inventory_call(
        &self,
        method: &str,
        params: Value,
    ) -> std::result::Result<Value, ServiceError> {
        let mut params = decode::<HarnessInventoryParams>(params)?;
        if method == "harness.v1.harnesses.probe" {
            let harness = params.harness.take().ok_or_else(|| {
                ServiceError::InvalidParams("harnesses.probe requires `harness`".into())
            })?;
            params.harnesses = vec![harness];
        }
        let selected = params
            .harnesses
            .iter()
            .map(HarnessId::as_str)
            .collect::<std::collections::BTreeSet<_>>();
        let supported = harness_support_registry()
            .harnesses
            .into_iter()
            .filter(|descriptor| selected.is_empty() || selected.contains(descriptor.id.as_str()))
            .collect::<Vec<_>>();
        if !params.harnesses.is_empty() && supported.len() != selected.len() {
            let known = supported
                .iter()
                .map(|harness| harness.id.as_str())
                .collect::<std::collections::BTreeSet<_>>();
            let missing = params
                .harnesses
                .iter()
                .filter(|id| !known.contains(id.as_str()))
                .map(HarnessId::as_str)
                .collect::<Vec<_>>();
            return Err(ServiceError::InvalidParams(format!(
                "unknown harness(es): {}",
                missing.join(", ")
            )));
        }
        let global_counts = params
            .include_sessions
            .then(|| self.session_counts(None, &params.harnesses));
        let workspace_counts = params.include_sessions.then(|| {
            params
                .workspace
                .as_deref()
                .map(|workspace| self.session_counts(Some(workspace), &params.harnesses))
        });
        let probes = supported.into_iter().map(|descriptor| {
            let global = global_counts
                .as_ref()
                .map(|counts| counts.get(descriptor.id.as_str()).copied().unwrap_or(0));
            let workspace = workspace_counts
                .as_ref()
                .and_then(Option::as_ref)
                .map(|counts| counts.get(descriptor.id.as_str()).copied().unwrap_or(0));
            self.probe_harness(descriptor, &params, global, workspace)
        });
        let harnesses = futures::future::join_all(probes).await;
        serde_json::to_value(HarnessInventoryReport {
            probe: params.probe,
            workspace: params.workspace,
            harnesses,
        })
        .map_err(|error| ServiceError::Operation(error.to_string()))
    }

    #[cfg(feature = "adapter-api")]
    async fn harness_authentication_call(
        &self,
        method: &str,
        params: Value,
    ) -> std::result::Result<Value, ServiceError> {
        match method {
            "harness.v1.harnesses.auth.methods" | "harness.v1.harnesses.auth.verify" => {
                let params = decode::<HarnessAuthenticationParams>(params)?;
                serde_json::to_value(crate::inspect_harness_authentication(&params.harness).await)
                    .map_err(|error| ServiceError::Operation(error.to_string()))
            }
            "harness.v1.harnesses.auth.begin" => {
                let params = decode::<BeginHarnessAuthenticationParams>(params)?;
                let cwd = params
                    .cwd
                    .or_else(|| std::env::current_dir().ok())
                    .unwrap_or_else(|| PathBuf::from("."));
                let plan = crate::harness_authentication_plan(
                    &params.harness,
                    params.environment,
                    params.method,
                    &cwd,
                )
                .map_err(|error| ServiceError::UnsupportedAction(error.to_string()))?;
                serde_json::to_value(plan)
                    .map_err(|error| ServiceError::Operation(error.to_string()))
            }
            _ => Err(ServiceError::MethodNotFound),
        }
    }

    async fn probe_harness(
        &self,
        descriptor: crate::HarnessSupportDescriptor,
        params: &HarnessInventoryParams,
        global: Option<usize>,
        workspace: Option<usize>,
    ) -> LocalHarness {
        let launch = descriptor.runtime.default_launch.as_ref();
        // ORC-7: the orchestrator publishes no runtime launch — it is not an
        // adapter supercode connects a turn to. What "installed" means for it
        // is that its Node daemon entry is present, so the row answers from
        // that instead of from a PATH lookup it could never satisfy.
        let orchestrator_entry = (descriptor.id.as_str() == HarnessId::ORCHESTRATOR)
            .then(crate::orchestrator::daemon_entry)
            .and_then(Result::ok);
        let executable = match &orchestrator_entry {
            Some(entry) => Some(entry.clone()),
            None => launch.and_then(|launch| find_executable(&launch.program)),
        };
        let installed = executable.is_some();
        let version = if params.skip_versions || orchestrator_entry.is_some() {
            // The orchestrator's "executable" is a Node module, not a CLI
            // with a `--version` flag; running it to ask would start a daemon.
            None
        } else {
            match executable.as_deref() {
                Some(path) => executable_version(path).await,
                None => None,
            }
        };
        let configured = auth_evidence(descriptor.id.as_str());
        let mut auth = if configured {
            HarnessAuthState::Configured
        } else if matches!(
            descriptor.id.as_str(),
            HarnessId::CLAUDE_CODE | HarnessId::CODEX
        ) {
            // These two adapters have explicit native status/login contracts
            // and complete local evidence coverage (including Claude's macOS
            // Keychain-backed oauthAccount marker). Treating absent evidence
            // as unknown advertises a start that will only fail interactively.
            HarnessAuthState::Required
        } else {
            HarnessAuthState::Unknown
        };
        let mut runtime = if installed {
            HarnessRuntimeState::Degraded
        } else {
            HarnessRuntimeState::Unavailable
        };
        let is_orchestrator = descriptor.id.as_str() == HarnessId::ORCHESTRATOR;
        let mut reason = (!installed).then(|| {
            if is_orchestrator {
                format!(
                    "{} is supported but its daemon entry `{}` was not found",
                    descriptor.display_name,
                    crate::orchestrator::DAEMON_ENTRY
                )
            } else {
                format!(
                    "{} is supported but `{}` was not found on PATH",
                    descriptor.display_name,
                    launch
                        .map(|launch| launch.program.as_str())
                        .unwrap_or("executable")
                )
            }
        });
        let mut repair = (!installed).then(|| {
            if is_orchestrator {
                format!(
                    "Install the `supercode-orchestrator` package so `{}` resolves.",
                    crate::orchestrator::DAEMON_ENTRY
                )
            } else {
                format!(
                    "Install {} and ensure `{}` is on PATH.",
                    descriptor.display_name,
                    launch
                        .map(|launch| launch.program.as_str())
                        .unwrap_or("its executable")
                )
            }
        });

        if installed && params.probe == HarnessProbeLevel::Handshake {
            let backend_params = RuntimeBackendParams {
                harness: descriptor.id.clone(),
                protocol: None,
                launch: None,
                base_url: None,
                policy: RuntimePolicy::Default,
            };
            match runtime_backend(&backend_params) {
                Ok(backend) => {
                    let cwd = params
                        .workspace
                        .clone()
                        .or_else(|| std::env::current_dir().ok())
                        .unwrap_or_else(|| PathBuf::from("."));
                    let isolated = descriptor
                        .runtime
                        .default_launch
                        .clone()
                        .and_then(|launch| {
                            IsolatedProbeHome::new(descriptor.id.as_str(), launch).ok()
                        });
                    let Some(isolated) = isolated else {
                        reason = Some(
                            "No-prompt runtime handshake could not create its isolated harness home."
                                .into(),
                        );
                        repair = Some(
                            "Check temporary-directory permissions, then run the handshake probe again."
                                .into(),
                        );
                        let running = probe_running_instance(descriptor.id.as_str());
                        return LocalHarness {
                            gateway: gateway_health(
                                descriptor.id.as_str(),
                                installed,
                                running.as_ref(),
                                version.as_deref(),
                            ),
                            id: descriptor.id,
                            display_name: descriptor.display_name,
                            supported: true,
                            installed,
                            executable: executable.map(|path| path.to_string_lossy().into_owned()),
                            version,
                            auth,
                            runtime,
                            protocol: descriptor.runtime.protocol,
                            capabilities: descriptor.runtime.capabilities.clone(),
                            effective_capabilities: descriptor.runtime.capabilities,
                            sessions: HarnessSessionCounts { global, workspace },
                            running,
                            reason,
                            repair,
                        };
                    };
                    match tokio::time::timeout(
                        Duration::from_secs(30),
                        backend.start(RuntimeStartRequest {
                            cwd,
                            launch: Some(isolated.launch.clone()),
                            mcp_servers: Vec::new(),
                        }),
                    )
                    .await
                    {
                        Ok(Ok(mut connection)) => {
                            match stabilize_handshake(connection.as_mut()).await {
                                Ok(()) => {
                                    auth = HarnessAuthState::Ready;
                                    runtime = HarnessRuntimeState::Ready;
                                    reason = Some(
                                        "No-prompt runtime handshake remained healthy through the startup stabilization window; no model request was sent."
                                            .into(),
                                    );
                                    repair = None;
                                }
                                Err(message) => {
                                    auth = if looks_like_auth_error(&message) {
                                        HarnessAuthState::Required
                                    } else if configured {
                                        HarnessAuthState::Configured
                                    } else {
                                        HarnessAuthState::Unknown
                                    };
                                    reason = Some(format!(
                                        "No-prompt runtime handshake became unhealthy during startup: {message}"
                                    ));
                                    repair = Some(if auth == HarnessAuthState::Required {
                                        format!(
                                            "Run `{}` interactively once and complete sign-in, then probe again.",
                                            launch.map(|launch| launch.program.as_str()).unwrap_or("the harness")
                                        )
                                    } else {
                                        "Run the harness directly to inspect its startup failure, then probe again."
                                            .into()
                                    });
                                }
                            }
                            let _ =
                                tokio::time::timeout(Duration::from_secs(3), connection.close())
                                    .await;
                        }
                        Ok(Err(error)) => {
                            let message = truncate_text(&error.to_string(), 500);
                            auth = if looks_like_auth_error(&message) {
                                HarnessAuthState::Required
                            } else if configured {
                                HarnessAuthState::Configured
                            } else {
                                HarnessAuthState::Unknown
                            };
                            reason = Some(format!("No-prompt runtime handshake failed: {message}"));
                            repair = Some(if auth == HarnessAuthState::Required {
                                format!(
                                    "Run `{}` interactively once and complete sign-in, then probe again.",
                                    launch.map(|launch| launch.program.as_str()).unwrap_or("the harness")
                                )
                            } else {
                                "Check the harness installation and run the handshake probe again."
                                    .into()
                            });
                        }
                        Err(_) => {
                            reason = Some(
                                "No-prompt runtime handshake timed out after 30 seconds.".into(),
                            );
                            repair = Some("Run the harness directly to check startup or authentication, then probe again.".into());
                        }
                    }
                    // Keep the isolated home alive through process teardown.
                    // Otherwise the compiler may release the last meaningful
                    // use after cloning `launch`, and a still-starting CLI can
                    // recreate its state directory after Drop removed it.
                    // Some Node-based launchers finish a short asynchronous
                    // installation-id write just after their parent process
                    // is reaped. Remove once immediately, allow that bounded
                    // writer to settle, then perform the authoritative pass.
                    let _ = isolated.cleanup();
                    tokio::time::sleep(Duration::from_millis(250)).await;
                    if let Err(error) = isolated.cleanup() {
                        auth = if configured {
                            HarnessAuthState::Configured
                        } else {
                            HarnessAuthState::Unknown
                        };
                        runtime = HarnessRuntimeState::Degraded;
                        reason = Some(format!(
                            "No-prompt runtime handshake could not remove its isolated harness home: {error}"
                        ));
                        repair = Some(
                            "Check temporary-directory permissions, remove the reported disposable probe home, then run the handshake again."
                                .into(),
                        );
                    }
                }
                Err(error) => {
                    reason = Some(error_message(error));
                }
            }
        } else if installed && configured {
            reason = Some("Executable and local authentication evidence found; use a handshake probe to verify readiness.".into());
        } else if installed && auth == HarnessAuthState::Required {
            reason =
                Some("Executable found, but no native authentication evidence is present.".into());
            repair = Some(format!(
                "Run `supercode harness login {}` to use the harness-owned sign-in flow.",
                descriptor.id.as_str()
            ));
        } else if installed {
            reason = Some("Executable found; authentication readiness is unknown until a no-prompt handshake succeeds.".into());
            repair =
                Some(format!(
                "Run `{}` interactively once if sign-in is required, or use `--probe handshake`.",
                launch.map(|launch| launch.program.as_str()).unwrap_or("the harness")
            ));
        }

        let effective_capabilities = if installed {
            descriptor.runtime.capabilities.clone()
        } else {
            unavailable_capabilities()
        };
        let running = probe_running_instance(descriptor.id.as_str());
        LocalHarness {
            gateway: gateway_health(
                descriptor.id.as_str(),
                installed,
                running.as_ref(),
                version.as_deref(),
            ),
            id: descriptor.id,
            display_name: descriptor.display_name,
            supported: true,
            installed,
            executable: executable.map(|path| path.to_string_lossy().into_owned()),
            version,
            auth,
            runtime,
            protocol: descriptor.runtime.protocol,
            capabilities: descriptor.runtime.capabilities,
            effective_capabilities,
            sessions: HarnessSessionCounts { global, workspace },
            running,
            reason,
            repair,
        }
    }

    fn session_counts(
        &self,
        workspace: Option<&Path>,
        harnesses: &[HarnessId],
    ) -> BTreeMap<String, usize> {
        let mut counts = BTreeMap::new();
        for session in self
            .catalog
            .discover(&DiscoveryQuery {
                workspace: workspace.map(Path::to_path_buf),
                harnesses: harnesses.to_vec(),
                ..DiscoveryQuery::default()
            })
            .unwrap_or_default()
        {
            *counts
                .entry(session.locator.harness.as_str().to_string())
                .or_insert(0) += 1;
        }
        counts
    }
}

#[async_trait::async_trait]
impl SdkService for HarnessSessionService {
    fn capabilities(&self) -> SdkCapabilities {
        SdkCapabilities::default()
    }

    async fn execute(&mut self, request: SdkRequest) -> Result<Value, SdkError> {
        if request.operation == SdkOperation::Events {
            let events = self
                .poll_sdk_events()
                .await
                .into_iter()
                .map(|(_, event)| event)
                .collect::<Vec<_>>();
            return serde_json::to_value(events).map_err(|error| {
                SdkError::new(
                    SdkErrorCode::Execution,
                    request.operation,
                    error.to_string(),
                )
            });
        }
        if self.runtimes.is_empty()
            && matches!(
                request.operation,
                SdkOperation::Input
                    | SdkOperation::Interrupt
                    | SdkOperation::Steer
                    | SdkOperation::Respond
                    | SdkOperation::Close
            )
        {
            return Err(SdkError::unsupported(request.operation));
        }
        let method = request
            .operation
            .method()
            .ok_or_else(|| SdkError::unsupported(request.operation))?;
        let result = match request.operation {
            SdkOperation::Discover
            | SdkOperation::Load
            | SdkOperation::Export
            | SdkOperation::ProfilesList
            | SdkOperation::ProfilesGet
            | SdkOperation::ProfilesCreate
            | SdkOperation::ProfilesDelete
            | SdkOperation::SkillsList
            | SdkOperation::SkillsInstall
            | SdkOperation::SkillsRemove
            | SdkOperation::ChannelsList
            | SdkOperation::RoutesList
            | SdkOperation::TriggersList
            | SdkOperation::ChannelsStatus
            | SdkOperation::MemoryShow
            | SdkOperation::MemorySearch
            | SdkOperation::JobsList
            | SdkOperation::JobsGet
            | SdkOperation::JobsCreate
            | SdkOperation::JobsUpdate
            | SdkOperation::JobsPause
            | SdkOperation::JobsResume
            | SdkOperation::JobsRun
            | SdkOperation::JobsDelete
            | SdkOperation::RunsList
            | SdkOperation::RunsGet
            | SdkOperation::ApprovalsList
            | SdkOperation::OrchestrationLoad
            | SdkOperation::OrchestrationSave
            | SdkOperation::OrchestrationCompile
            | SdkOperation::OrchestrationDecompile
            | SdkOperation::OrchestrationImport
            | SdkOperation::OrchestrationExport
            | SdkOperation::WorkflowLoad => self.call(method, request.params),
            // ORCH-20: answering needs the live connection, so it takes the
            // async door and ends in `harness.v1.runtimes.respond`.
            SdkOperation::ApprovalsResolve => self.approvals_resolve(request.params).await,
            SdkOperation::Start
            | SdkOperation::Resume
            | SdkOperation::Input
            | SdkOperation::Interrupt
            | SdkOperation::Steer
            | SdkOperation::Respond
            | SdkOperation::Close => self.runtime_call(method, request.params).await,
            // ORCH-19 controlled tier. Every verb goes through the HARNESS'S
            // OWN door — its CLI, its HTTP API, or its slash command typed
            // into a live driven session — and returns the row re-read from
            // the harness's store afterwards.
            SdkOperation::SessionsNew => {
                self.mutate_session(crate::SessionVerb::New, request.params)
                    .await
            }
            SdkOperation::SessionsReset => {
                self.mutate_session(crate::SessionVerb::Reset, request.params)
                    .await
            }
            SdkOperation::SessionsArchive => {
                self.mutate_session(crate::SessionVerb::Archive, request.params)
                    .await
            }
            SdkOperation::SessionsDelete => {
                self.mutate_session(crate::SessionVerb::Delete, request.params)
                    .await
            }
            SdkOperation::Events => unreachable!("handled before method dispatch"),
        };
        result.map_err(|error| sdk_error(request.operation, error))
    }

    async fn events(&mut self) -> Result<Vec<SdkRuntimeEvent>, SdkError> {
        Ok(self
            .poll_sdk_events()
            .await
            .into_iter()
            .map(|(_, event)| event)
            .collect())
    }
}

#[cfg(feature = "adapter-api")]
struct HostedRuntimeLease {
    connection: HostedHarnessConnection,
    _host: std::sync::Arc<HostedHarnessRuntime>,
    _registration: LiveRuntimeRegistration,
    _server: crate::server::FrontendHttpServer,
}

#[async_trait::async_trait]
#[cfg(feature = "adapter-api")]
impl RuntimeConnection for HostedRuntimeLease {
    fn handle(&self) -> &crate::RuntimeHandle {
        self.connection.handle()
    }

    async fn send_input(&mut self, input: RuntimeInput) -> crate::Result<Option<String>> {
        self.connection.send_input(input).await
    }

    async fn next_event(&mut self) -> crate::Result<Option<crate::HarnessEvent>> {
        self.connection.next_event().await
    }

    async fn interrupt(&mut self) -> crate::Result<()> {
        self.connection.interrupt().await
    }

    async fn respond(&mut self, request_id: Value, response: Value) -> crate::Result<()> {
        self.connection.respond(request_id, response).await
    }

    async fn close(&mut self) -> crate::Result<()> {
        self.connection.close().await
    }
}

async fn stabilize_handshake(connection: &mut dyn RuntimeConnection) -> Result<(), String> {
    let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
    loop {
        let now = tokio::time::Instant::now();
        if now >= deadline {
            return Ok(());
        }
        match tokio::time::timeout(deadline - now, connection.next_event()).await {
            Err(_) => return Ok(()),
            Ok(Ok(Some(event))) => {
                if let Some(message) = handshake_event_failure(&event) {
                    return Err(truncate_text(&message, 500));
                }
            }
            Ok(Ok(None)) => return Err("runtime transport closed during startup".into()),
            Ok(Err(error)) => return Err(error.to_string()),
        }
    }
}

fn handshake_event_failure(event: &crate::HarnessEvent) -> Option<String> {
    let detail = event
        .payload
        .get("message")
        .or_else(|| event.payload.get("line"))
        .and_then(Value::as_str)
        .unwrap_or(event.kind.as_str());
    match event.kind.as_str() {
        "transport_closed" => Some("runtime transport closed during startup".into()),
        "transport_error" => Some(format!("runtime transport error: {detail}")),
        "malformed_output" => Some(format!("runtime emitted non-protocol output: {detail}")),
        // Stderr is retained as a runtime event, but is not transport health.
        // Grok, for example, can log an AuthorizationRequired error from an
        // optional background worker while its ACP session continues to send
        // updates and complete prompts normally.
        _ => None,
    }
}

fn projected_session_result(session: &Session, options: &SessionLoadOptions) -> Value {
    let total_messages = session.messages.len();
    let (offset, end) = projected_message_window(total_messages, options);
    json!({
        "session": projected_session_json(session, options),
        "summary": projected_session_summary(session, options),
        "window": {
            "has_more": offset > 0 || end < total_messages,
            "has_newer": end < total_messages,
            "has_older": offset > 0,
            "newer_items": normalized_item_count(&session.messages[end..]),
            "offset": offset,
            "older_items": normalized_item_count(&session.messages[..offset]),
            "returned": end.saturating_sub(offset),
            "total_messages": total_messages,
        }
    })
}

fn normalized_item_count(messages: &[crate::ChatMessage]) -> usize {
    messages
        .iter()
        .map(|message| {
            let conversation = usize::from(
                matches!(message.role, Role::Assistant | Role::User)
                    && message_has_content(message),
            );
            let tool_result =
                usize::from(message.role == Role::Tool && message_has_content(message));
            conversation + tool_result + message.tool_calls().len()
        })
        .sum()
}

fn projected_session_summary(session: &Session, options: &SessionLoadOptions) -> Value {
    let mut conversational = session.messages.iter().filter(|message| {
        matches!(message.role, Role::Assistant | Role::User) && message_has_content(message)
    });
    let first_message = conversational.clone().next();
    let last_message = conversational.next_back();
    let mut assistant = session
        .messages
        .iter()
        .filter(|message| message.role == Role::Assistant && message_has_content(message));
    let first_assistant_message = assistant.clone().next();
    let last_assistant_message = assistant.next_back();
    let end_of_turn = session
        .messages
        .iter()
        .rev()
        .find(|message| message.role != Role::System)
        .is_some_and(|message| {
            message.role == Role::Assistant
                && message_has_content(message)
                && message.tool_calls().is_empty()
        });
    let project = |message: Option<&crate::ChatMessage>| {
        message.map(|message| project_inline_media(message_json(message), options))
    };
    json!({
        "end_of_turn": end_of_turn,
        "first_assistant_message": project(first_assistant_message),
        "first_message": project(first_message),
        "last_assistant_message": project(last_assistant_message),
        "last_assistant_text": last_assistant_message.map(message_text).unwrap_or_default(),
        "last_message": project(last_message),
    })
}

fn message_has_content(message: &crate::ChatMessage) -> bool {
    message
        .content
        .as_deref()
        .is_some_and(|content| !content.trim().is_empty())
        || message
            .content_parts
            .as_ref()
            .is_some_and(|parts| !parts.is_empty())
}

fn message_text(message: &crate::ChatMessage) -> String {
    if let Some(content) = &message.content {
        return content.clone();
    }
    message
        .content_parts
        .as_ref()
        .into_iter()
        .flatten()
        .filter_map(|part| part.get("text").and_then(Value::as_str))
        .collect::<Vec<_>>()
        .join("\n")
}

fn projected_session_json(session: &Session, options: &SessionLoadOptions) -> Value {
    let (offset, end) = projected_message_window(session.messages.len(), options);
    let messages = session.messages[offset..end]
        .iter()
        .map(|message| project_inline_media(message_json(message), options))
        .collect::<Vec<_>>();
    let subagents = if options.include_subagents.unwrap_or(true) {
        // The reported window describes the top-level transcript. Applying it
        // recursively would silently truncate subagents without returning a
        // window for each child. Keep their histories complete while carrying
        // the caller's media policy through the tree.
        let subagent_options = SessionLoadOptions {
            message_limit: None,
            message_offset: None,
            message_tail: None,
            ..options.clone()
        };
        session
            .subagents
            .iter()
            .map(|subagent| projected_session_json(subagent, &subagent_options))
            .collect::<Vec<_>>()
    } else {
        Vec::new()
    };
    json!({
        "source": match session.meta.source {
            SessionSource::ClaudeCode => "claude_code",
            SessionSource::Codex => "codex",
            SessionSource::Gemini => "gemini",
            SessionSource::Goose => "goose",
            SessionSource::Grok => "grok",
            SessionSource::Native => "native",
            SessionSource::OpenClaw => "openclaw",
            SessionSource::Hermes => "hermes",
            SessionSource::OpenCode => "opencode",
            SessionSource::Pi => "pi",
        },
        "session_id": session.meta.session_id,
        "model": session.meta.model,
        "cwd": session.meta.cwd,
        "system_prompt": session.meta.system_prompt,
        "agent_id": session.meta.agent_id,
        "parent_tool_use_id": session.meta.parent_tool_use_id,
        "lineage": session.meta.lineage,
        "messages": messages,
        "subagents": subagents,
        "raw_record_count": session.raw.len(),
        "parse_error_lines": session.parse_error_lines,
    })
}

fn projected_message_window(total: usize, options: &SessionLoadOptions) -> (usize, usize) {
    if let Some(tail) = options.message_tail {
        return (total.saturating_sub(tail), total);
    }
    let offset = options.message_offset.unwrap_or(0).min(total);
    let end = options
        .message_limit
        .map(|limit| offset.saturating_add(limit).min(total))
        .unwrap_or(total);
    (offset, end)
}

fn project_inline_media(mut message: Value, options: &SessionLoadOptions) -> Value {
    let Some(parts) = message.get_mut("content").and_then(Value::as_array_mut) else {
        return message;
    };
    for part in parts {
        let Some(url) = part
            .get("image_url")
            .and_then(|image| image.get("url"))
            .and_then(Value::as_str)
        else {
            continue;
        };
        let Some(rest) = url.strip_prefix("data:") else {
            continue;
        };
        let Some((media_type, encoded)) = rest.split_once(";base64,") else {
            continue;
        };
        let padding = usize::from(encoded.ends_with('=')) + usize::from(encoded.ends_with("=="));
        let decoded_bytes = encoded.len().saturating_mul(3) / 4;
        let decoded_bytes = decoded_bytes.saturating_sub(padding);
        let should_elide = matches!(options.inline_media, InlineMediaMode::Metadata)
            || options
                .max_inline_media_bytes
                .is_some_and(|limit| decoded_bytes > limit);
        if should_elide {
            *part = json!({
                "type": "media_reference",
                "media_type": media_type,
                "encoding": "base64",
                "encoded_bytes": encoded.len(),
                "decoded_bytes": decoded_bytes,
                "omitted": true,
            });
        }
    }
    message
}

#[derive(Deserialize)]
struct LocatorParams {
    locator: SessionLocator,
    /// Optional fidelity for the READ surfaces (`sessions.load`,
    /// `sessions.follow`).
    ///
    /// Omitted means [`Fidelity::Semantic`]: these two methods only ever
    /// produce a read-only view, and a compacted or resumed-across-files
    /// transcript — the everyday shape of a long Claude Code session — has no
    /// losslessly reconstructable record graph, so refusing to render it made
    /// the mirror unusable rather than accurate. A caller that intends to
    /// CONTINUE from what it reads asks for a lossless level explicitly and
    /// gets the strict refusal back. Every other method (export, translate,
    /// branch, handoff, resume_instructions) is lossless-only and has no
    /// such knob.
    #[serde(default)]
    fidelity: Option<Fidelity>,
    /// Optional bounded frontend projection. Absent preserves the historical
    /// complete-session read contract.
    #[serde(default)]
    view: Option<SessionReadView>,
}

#[derive(Deserialize)]
struct SessionReadView {
    /// Number of trailing normalized messages to return. Zero is treated as
    /// one so a caller cannot accidentally request an unbounded empty mode.
    #[serde(default)]
    tail_messages: Option<usize>,
    /// Whether Claude Code child transcripts belong in this view. The
    /// frontend default is false; the legacy no-view path remains true.
    #[serde(default)]
    include_subagents: bool,
    /// Preserve human-visible native history across model-context compaction.
    #[serde(default)]
    display_history: bool,
    /// Bound each individual text field so a single tool result cannot turn a
    /// small message window into a hundred-megabyte RPC response.
    #[serde(default)]
    max_message_chars: Option<usize>,
}

impl LocatorParams {
    fn read_fidelity(&self) -> Fidelity {
        self.fidelity.unwrap_or(Fidelity::Semantic)
    }

    fn include_subagents(&self) -> bool {
        self.view
            .as_ref()
            .map(|view| view.include_subagents)
            .unwrap_or(true)
    }

    fn tail_messages(&self) -> Option<usize> {
        self.view
            .as_ref()
            .and_then(|view| view.tail_messages)
            .map(|limit| limit.clamp(1, 5_000))
    }

    fn display_history(&self) -> bool {
        self.view.as_ref().is_some_and(|view| view.display_history)
    }

    fn max_message_chars(&self) -> Option<usize> {
        self.view
            .as_ref()
            .and_then(|view| view.max_message_chars)
            .map(|limit| limit.clamp(256, 64_000))
    }

    fn bound_session(&self, session: &mut Session) {
        bound_session_view(session, self.tail_messages(), self.max_message_chars());
    }
}

#[derive(Debug, Clone, Copy, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
enum InlineMediaMode {
    #[default]
    Full,
    Metadata,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct SessionLoadOptions {
    include_subagents: Option<bool>,
    inline_media: InlineMediaMode,
    max_inline_media_bytes: Option<usize>,
    message_limit: Option<usize>,
    message_offset: Option<usize>,
    message_tail: Option<usize>,
}

impl SessionLoadOptions {
    fn validate(&self) -> std::result::Result<(), ServiceError> {
        if self.message_tail.is_some()
            && (self.message_limit.is_some() || self.message_offset.is_some())
        {
            return Err(ServiceError::InvalidParams(
                "sessions.load options.message_tail cannot be combined with message_limit or message_offset"
                    .into(),
            ));
        }
        Ok(())
    }
}

#[derive(Deserialize)]
struct LoadSessionParams {
    #[serde(flatten)]
    read: LocatorParams,
    #[serde(default)]
    options: Option<SessionLoadOptions>,
}

#[derive(Deserialize)]
struct UnfollowParams {
    subscription: String,
}

#[derive(Deserialize)]
struct ActivitySubscribeParams {
    locators: Vec<SessionLocator>,
    #[serde(default)]
    homes: crate::HarnessHomes,
}

#[derive(Deserialize)]
struct MessageSessionParams {
    locator: SessionLocator,
    text: String,
    /// Same storage roots discovery accepts, so a caller (and a test) can
    /// point the live-session registry somewhere other than `$HOME`.
    #[serde(default)]
    homes: crate::HarnessHomes,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct HarnessSettingsParams {
    harness: String,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ConfigureHarnessParams {
    harness: String,
    #[serde(default)]
    changes: Vec<crate::HarnessSettingChange>,
    #[serde(default)]
    expected_revision: Option<String>,
}

fn claude_inbound_controls_or_error(homes: &crate::HarnessHomes) -> (Value, Value) {
    match crate::inspect_harness_interop_settings(homes, HarnessId::CLAUDE_CODE) {
        Ok(report) => (
            serde_json::to_value(report).unwrap_or(Value::Null),
            Value::Null,
        ),
        Err(error) => (
            Value::Null,
            Value::String(format!(
                "Supercode could not inspect Claude Code inbound controls: {error}"
            )),
        ),
    }
}

/// Deliver `text` into a session that is running right now, or say why not.
///
/// A refusal is a RESULT, not a JSON-RPC error: "that session is persisted
/// only" is an answer about the session, which a mirror renders next to the
/// transcript, and this service's error envelope carries no structured data
/// field a machine-readable reason could survive in.
///
/// `delivered_to_bus` is the honest ceiling of what the courier proves. The
/// message reached the receiving session's inbox; whether that session ever
/// reads it is governed by ITS OWN inbound controls (`crossSessionInbound`,
/// approval dialogs), which Supercode neither sees nor overrides.
#[cfg(feature = "adapter-api")]
async fn message_live_session(
    params: &MessageSessionParams,
    runner: &dyn crate::claude_peer::CourierRunner,
) -> Value {
    if params.locator.harness.as_str() != HarnessId::CLAUDE_CODE {
        return json!({
            "delivered_to_bus": false,
            "refusal": {
                "reason": crate::claude_peer::ClaudePeerRefusal::HarnessUnsupported.as_str(),
                "message": format!(
                    "`{}` does not publish a live-session registry; only claude-code sessions can be messaged in place",
                    params.locator.harness.as_str()
                ),
            },
        });
    }
    let (inbound_controls, inbound_controls_error) =
        claude_inbound_controls_or_error(&params.homes);
    match crate::claude_peer::message_claude_peer(
        &params.homes,
        &params.locator.session_id,
        &params.text,
        runner,
    )
    .await
    {
        Ok(delivery) => json!({
            "delivered_to_bus": true,
            "target": {
                "session_id": delivery.target.session_id,
                "name": delivery.target.name,
                "pid": delivery.target.pid,
                "cwd": delivery.target.cwd,
                "status": delivery.target.status.map(|status| status.as_str()),
            },
            "courier": {
                "model": crate::claude_peer::COURIER_MODEL,
                "report": delivery.courier_report,
            },
            "inbound_controls": inbound_controls,
            "inbound_controls_error": inbound_controls_error,
        }),
        Err(refusal) => json!({
            "delivered_to_bus": false,
            "refusal": {"reason": refusal.reason.as_str(), "message": refusal.message},
            "inbound_controls": inbound_controls,
            "inbound_controls_error": inbound_controls_error,
        }),
    }
}

/// Source identity of one follow subscription, plus the last lifecycle state
/// already reported on it. The follower itself stays purely persistence-facing.
// Only the adapter-api poll reads these; the subscription bookkeeping itself is
// shared by both builds.
#[cfg_attr(not(feature = "adapter-api"), allow(dead_code))]
struct FollowedSource {
    harness: String,
    session_id: String,
    reported: Option<String>,
}

#[cfg_attr(not(feature = "adapter-api"), allow(dead_code))]
struct ActivitySubscription {
    locators: Vec<SessionLocator>,
    homes: crate::HarnessHomes,
    reported: BTreeMap<(String, String), crate::SessionActivity>,
}

fn peers_for_descriptors(
    descriptors: &[SessionDescriptor],
    homes: &HarnessHomes,
) -> Vec<crate::claude_peer::ClaudePeerSession> {
    if descriptors
        .iter()
        .any(|session| session.locator.harness.as_str() == HarnessId::CLAUDE_CODE)
    {
        crate::claude_peer::read_registry(&crate::claude_peer::registry_dir(homes))
    } else {
        Vec::new()
    }
}

/// Add the live address that makes an indexed row behaviorally equivalent to a discovered row.
///
/// The durable index owns only persistence metadata. Live endpoints remain projections: every
/// message/attach operation revalidates its authority, so publishing one here never trusts a stale
/// browser-held handle. Reading the Claude registry once per batch keeps this O(peers + rows).
fn live_descriptor_value(
    session: &SessionDescriptor,
    peers: &[crate::claude_peer::ClaudePeerSession],
) -> std::result::Result<Value, ServiceError> {
    let mut value = serde_json::to_value(session)
        .map_err(|error| ServiceError::Operation(error.to_string()))?;
    if let Some(workspace) = &session.cwd {
        let source = LiveRuntimeSource {
            harness: session.locator.harness.as_str().to_string(),
            session_id: session.locator.session_id.clone(),
            workspace: workspace.clone(),
        };
        if let Some(endpoint) = discover_live_runtime(&source)
            .map_err(|error| ServiceError::Operation(error.to_string()))?
        {
            value["live_endpoint"] = json!(endpoint.as_str());
        }
    }
    if value.get("live_endpoint").is_none() {
        if let Some(peer) = peers.iter().find(|peer| {
            session.locator.harness.as_str() == HarnessId::CLAUDE_CODE
                && peer.session_id == session.locator.session_id
        }) {
            value["live_endpoint"] = json!(peer.endpoint().as_str());
        }
    }
    Ok(value)
}

fn live_index_changes(
    changes: Vec<crate::session_index::SessionIndexChange>,
    homes: &HarnessHomes,
) -> std::result::Result<Vec<Value>, ServiceError> {
    use crate::session_index::SessionIndexChange;
    let has_claude = changes.iter().any(|change| match change {
        SessionIndexChange::Added { descriptor } | SessionIndexChange::Updated { descriptor } => {
            descriptor.locator.harness.as_str() == HarnessId::CLAUDE_CODE
        }
        SessionIndexChange::Removed { .. } => false,
    });
    let peers = if has_claude {
        crate::claude_peer::read_registry(&crate::claude_peer::registry_dir(homes))
    } else {
        Vec::new()
    };
    changes
        .into_iter()
        .map(|change| match change {
            SessionIndexChange::Added { descriptor } => Ok(json!({
                "kind": "added",
                "descriptor": live_descriptor_value(&descriptor, &peers)?,
            })),
            SessionIndexChange::Updated { descriptor } => Ok(json!({
                "kind": "updated",
                "descriptor": live_descriptor_value(&descriptor, &peers)?,
            })),
            SessionIndexChange::Removed { key } => Ok(json!({
                "kind": "removed",
                "key": key,
            })),
        })
        .collect()
}

fn legacy_live_status(activity: &crate::SessionActivity) -> Option<&'static str> {
    use crate::{SessionPresence, SessionTurnState};
    match (activity.presence, activity.turn) {
        (SessionPresence::Persisted, _) => None,
        (SessionPresence::Running, SessionTurnState::Working) => Some("busy"),
        (SessionPresence::Running, SessionTurnState::Idle) => Some("idle"),
        // The normalized activity object can honestly report a live owner even
        // when the stock harness never published a turn status. Preserve the
        // older field's stricter contract instead of guessing `running`.
        (SessionPresence::Running, SessionTurnState::Unknown)
            if activity.evidence.native_state.is_none() =>
        {
            None
        }
        (SessionPresence::Running, _) | (SessionPresence::ShuttingDown, _) => Some("running"),
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case")]
enum TransferFormat {
    ClaudeCode,
    Codex,
    #[serde(rename = "opencode", alias = "open-code")]
    OpenCode,
    Pi,
    Grok,
    Gemini,
    Goose,
    /// UNI-18: a Hermes target. Its artifact is the Codex rollout that
    /// `hermes sessions import --from codex` reads; `sessions.export` performs
    /// that import into the Hermes home.
    Hermes,
}

impl TransferFormat {
    fn id(self) -> &'static str {
        match self {
            Self::ClaudeCode => HarnessId::CLAUDE_CODE,
            Self::Codex => HarnessId::CODEX,
            Self::OpenCode => HarnessId::OPENCODE,
            Self::Pi => HarnessId::PI,
            Self::Grok => HarnessId::GROK,
            Self::Gemini => HarnessId::GEMINI,
            Self::Goose => HarnessId::GOOSE,
            Self::Hermes => HarnessId::HERMES,
        }
    }
}

impl From<TransferFormat> for SessionFormat {
    fn from(value: TransferFormat) -> Self {
        match value {
            TransferFormat::ClaudeCode => Self::ClaudeCode,
            TransferFormat::Codex => Self::Codex,
            TransferFormat::OpenCode => Self::OpenCode,
            TransferFormat::Pi => Self::Pi,
            TransferFormat::Grok => Self::Grok,
            TransferFormat::Gemini => Self::Gemini,
            TransferFormat::Goose => Self::Goose,
            // a Hermes artifact is the Codex rollout Hermes imports
            TransferFormat::Hermes => Self::Codex,
        }
    }
}

#[derive(Deserialize)]
struct ImportSessionParams {
    source_harness: TransferFormat,
    content: String,
}

#[derive(Deserialize)]
struct ExportSessionParams {
    locator: SessionLocator,
    target_harness: TransferFormat,
}

#[derive(Deserialize)]
struct ReduceSessionParams {
    locator: SessionLocator,
    target_harness: TransferFormat,
    #[serde(default = "default_keep_last")]
    keep_last: usize,
}

fn default_keep_last() -> usize {
    6
}

#[derive(Deserialize)]
struct BranchSessionParams {
    locator: SessionLocator,
    #[serde(default)]
    target_harness: Option<TransferFormat>,
}

#[derive(Deserialize)]
struct HandoffSessionParams {
    locator: SessionLocator,
    target_harness: TransferFormat,
    #[serde(default)]
    cwd: Option<PathBuf>,
}

#[derive(Debug, Clone, Copy, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
enum ResumePolicy {
    #[default]
    Default,
    Yolo,
}

#[derive(Deserialize)]
struct ResumeInstructionsParams {
    locator: SessionLocator,
    #[serde(default)]
    cwd: Option<PathBuf>,
    #[serde(default)]
    policy: ResumePolicy,
}

/// `harness.v1.workflow.load` parameters: which harness's board, and its home.
#[derive(Deserialize)]
struct WorkflowLoadParams {
    from: crate::workflow_doors::WorkflowHarness,
    home: PathBuf,
}

/// ONT-4 `harness.v1.orchestration.load` parameters. `flavor` says which layout the
/// folder is read as; our own is the default.
#[derive(Deserialize)]
struct OrchestrationLoadParams {
    root: PathBuf,
    #[serde(default)]
    flavor: crate::orchestration_doors::HomeFlavor,
}

/// ONT-4 `harness.v1.orchestration.save` parameters. `vault` is merged into the
/// home's own secrets; a caller that sends none keeps what is on disk.
#[derive(Deserialize)]
struct OrchestrationSaveParams {
    root: PathBuf,
    orchestration: crate::orchestration::Orchestration,
    #[serde(default)]
    vault: BTreeMap<String, String>,
}

/// ONT-4 `harness.v1.orchestration.compile` parameters.
#[derive(Deserialize)]
struct OrchestrationCompileParams {
    from: crate::orchestration_doors::OrchestrationHarness,
    home: PathBuf,
}

/// ONT-4 `harness.v1.orchestration.decompile` parameters. `source` is the home the
/// orchestration was compiled from: it is re-compiled to recover the io bookkeeping
/// that byte reuse and the live-store refusal (UNI-18) are decided from.
#[derive(Deserialize)]
struct OrchestrationDecompileParams {
    to: crate::orchestration_doors::OrchestrationHarness,
    orchestration: crate::orchestration::Orchestration,
    source: PathBuf,
    #[serde(default)]
    source_flavor: crate::orchestration_doors::SourceFlavor,
    dest: PathBuf,
    #[serde(default)]
    vault: BTreeMap<String, String>,
}

/// `harness.v1.orchestration.import` parameters: another harness's home, and the
/// folder of ours it becomes.
#[derive(Deserialize)]
struct OrchestrationImportParams {
    from: crate::orchestration_doors::OrchestrationHarness,
    home: PathBuf,
    into: PathBuf,
}

/// `harness.v1.orchestration.export` parameters: a folder of ours, and the home of
/// another harness it becomes.
#[derive(Deserialize)]
struct OrchestrationExportParams {
    to: crate::orchestration_doors::OrchestrationHarness,
    root: PathBuf,
    dest: PathBuf,
}

/// `harness.v1.jobs.get` parameters.
#[derive(Deserialize)]
struct JobsGetParams {
    harness: String,
    id: String,
    #[serde(default)]
    homes: crate::HarnessHomes,
}

/// ORCH-18: run one mutating job verb through the harness's own CLI.
///
/// The refusal ladder is deliberate: a harness with no scheduled-job concept
/// at all answers with the SAME sentence `jobs.list` gives it, and a harness
/// that has jobs but publishes no client-callable verb (Claude Code, whose
/// jobs are created by the model inside a session) answers with its own
/// reason. Neither is ever a silent no-op.
fn mutate_job(
    verb: crate::jobs_control::JobVerb,
    params: Value,
) -> std::result::Result<Value, ServiceError> {
    let mutation = decode::<crate::jobs_control::JobMutation>(params)?;
    refuse_harness_without_jobs(&mutation.harness, &format!("jobs.{}", verb.as_str()))?;
    let outcome = crate::jobs_control::mutate(verb, &mutation).map_err(job_control_error)?;
    serde_json::to_value(outcome).map_err(|error| ServiceError::Operation(error.to_string()))
}

/// ORCH-22: run one mutating skills verb through the harness's own door.
///
/// The refusal ladder mirrors `jobs.*`: a harness with no skills root at all
/// answers with the same sentence `skills.list` gives it, and a harness whose
/// door does not publish this verb (OpenClaw has no `skills remove` at the
/// pin) answers with its own reason. Neither is ever a silent no-op.
fn mutate_skill(
    verb: crate::skills_control::SkillVerb,
    params: Value,
) -> std::result::Result<Value, ServiceError> {
    let mutation = decode::<crate::skills_control::SkillMutation>(params)?;
    if !crate::skills_control::supports_skill_control(&mutation.harness) {
        return Err(ServiceError::UnsupportedAction(format!(
            "`{}` has no skills root supercode reads; `skills.{}` is supported for: {}",
            mutation.harness,
            verb.as_str(),
            crate::skills_control::CONTROLLED_SKILL_HARNESSES.join(", ")
        )));
    }
    let outcome =
        crate::skills_control::mutate_skill(verb, &mutation).map_err(skill_control_error)?;
    serde_json::to_value(outcome).map_err(|error| ServiceError::Operation(error.to_string()))
}

/// The skills twin of [`job_control_error`], with the same mapping rule.
fn skill_control_error(error: crate::skills_control::SkillControlError) -> ServiceError {
    match error {
        crate::skills_control::SkillControlError::Unsupported(message) => {
            ServiceError::UnsupportedAction(message)
        }
        crate::skills_control::SkillControlError::Invalid(message) => {
            ServiceError::InvalidParams(message)
        }
        crate::skills_control::SkillControlError::Failed(message) => {
            ServiceError::Operation(message)
        }
    }
}

/// ORCH-21: run one mutating profile verb through the harness's own CLI.
///
/// The refusal ladder mirrors `mutate_job`'s: a harness with no profile
/// concept at all answers with the SAME sentence `profiles.list` gives it, and
/// a harness that HAS profiles but publishes no client-callable verb (Codex's
/// file-authored `[profiles.<name>]` tables, supercode's compiled-in presets)
/// answers with its own reason. Neither is ever a silent no-op.
fn mutate_profile(
    verb: crate::profiles_control::ProfileVerb,
    params: Value,
) -> std::result::Result<Value, ServiceError> {
    let mutation = decode::<crate::profiles_control::ProfileMutation>(params)?;
    let outcome =
        crate::profiles_control::mutate(verb, &mutation).map_err(profile_control_error)?;
    serde_json::to_value(outcome).map_err(|error| ServiceError::Operation(error.to_string()))
}

/// The same mapping `job_control_error` applies, for the profile noun.
fn profile_control_error(error: crate::profiles_control::ProfileControlError) -> ServiceError {
    match error {
        crate::profiles_control::ProfileControlError::Unsupported(message) => {
            ServiceError::UnsupportedAction(message)
        }
        crate::profiles_control::ProfileControlError::Invalid(message) => {
            ServiceError::InvalidParams(message)
        }
        crate::profiles_control::ProfileControlError::Failed(message) => {
            ServiceError::Operation(message)
        }
    }
}

/// Map a controlled-tier failure onto the service's error vocabulary. A verb
/// the harness lacks is `UnsupportedAction`; a harness verb that RAN and
/// failed carries its own stderr through as the operation error.
fn job_control_error(error: crate::jobs_control::JobControlError) -> ServiceError {
    match error {
        crate::jobs_control::JobControlError::Unsupported(message) => {
            ServiceError::UnsupportedAction(message)
        }
        crate::jobs_control::JobControlError::Invalid(message) => {
            ServiceError::InvalidParams(message)
        }
        crate::jobs_control::JobControlError::Failed(message) => ServiceError::Operation(message),
    }
}

/// Map an ORCH-19 controlled-tier failure onto the service's error
/// vocabulary. A verb the harness has no door for is `UnsupportedAction`; a
/// door that RAN and failed carries the harness's own stderr / HTTP body
/// through as the operation error.
fn session_control_error(error: crate::SessionControlError) -> ServiceError {
    match error {
        crate::SessionControlError::Unsupported(message) => {
            ServiceError::UnsupportedAction(message)
        }
        crate::SessionControlError::Invalid(message) => ServiceError::InvalidParams(message),
        crate::SessionControlError::Failed(message) => ServiceError::Operation(message),
    }
}

/// A harness without a scheduled-job concept refuses the verb rather than
/// answering with an empty list — an absent capability and an empty inventory
/// are different answers (the same rule `runtimes.capabilities` applies to
/// `steer`).
fn refuse_harness_without_jobs(harness: &str, verb: &str) -> std::result::Result<(), ServiceError> {
    if crate::jobs::supports_jobs(harness) {
        return Ok(());
    }
    Err(ServiceError::UnsupportedAction(format!(
        "`{harness}` has no scheduled jobs; `{verb}` is supported for: {}",
        crate::jobs::JOB_HARNESSES.join(", ")
    )))
}

/// `harness.v1.runs.get` parameters.
#[derive(Deserialize)]
struct RunsGetParams {
    harness: String,
    id: String,
    #[serde(default)]
    homes: crate::HarnessHomes,
}

/// A harness with no run store refuses the verb rather than answering with an
/// empty history — the same rule `jobs.list` applies. Claude Code lands here
/// on purpose: its cron fires are ordinary turns inside the session that
/// created the job, so there is no fire record to list.
fn refuse_harness_without_runs(harness: &str, verb: &str) -> std::result::Result<(), ServiceError> {
    if crate::runs::supports_runs(harness) {
        return Ok(());
    }
    Err(ServiceError::UnsupportedAction(format!(
        "`{harness}` keeps no run store; `{verb}` is supported for: {}",
        crate::runs::RUN_HARNESSES.join(", ")
    )))
}

#[derive(Serialize)]
struct SessionArtifact {
    source_harness: HarnessId,
    target_harness: &'static str,
    session_id: Option<String>,
    content: String,
    suggested_filename: String,
    files: Vec<SessionArtifactFile>,
    fidelity: Fidelity,
    residue: Vec<String>,
}

#[derive(Serialize)]
struct SessionArtifactFile {
    path: String,
    content: String,
    role: ArtifactFileRole,
}

#[derive(Serialize)]
#[serde(rename_all = "snake_case")]
enum ArtifactFileRole {
    Primary,
    Subagent,
    Bundle,
    SourceRecovery,
}

#[derive(Serialize)]
struct StructuredLaunch {
    cwd: PathBuf,
    program: String,
    arguments: Vec<String>,
    env: BTreeMap<String, String>,
}

struct HandoffInstructions {
    launch: StructuredLaunch,
    materialize: Option<StructuredLaunch>,
    requires_materialization: bool,
    note: String,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum HarnessProbeLevel {
    #[default]
    Passive,
    Handshake,
}

#[derive(Default, Deserialize)]
#[serde(default)]
struct HarnessInventoryParams {
    harness: Option<HarnessId>,
    harnesses: Vec<HarnessId>,
    workspace: Option<PathBuf>,
    probe: HarnessProbeLevel,
    include_sessions: bool,
    /// Omit subprocess-based `--version` calls when a latency-sensitive UI only needs readiness.
    skip_versions: bool,
}

#[derive(Deserialize)]
struct HarnessAuthenticationParams {
    harness: HarnessId,
}

#[derive(Deserialize)]
struct BeginHarnessAuthenticationParams {
    harness: HarnessId,
    #[serde(default = "local_browser_authentication_environment")]
    environment: crate::HarnessAuthenticationEnvironment,
    #[serde(default)]
    method: Option<crate::HarnessAuthenticationMethodId>,
    #[serde(default)]
    cwd: Option<PathBuf>,
}

fn local_browser_authentication_environment() -> crate::HarnessAuthenticationEnvironment {
    crate::HarnessAuthenticationEnvironment::LocalBrowser
}

#[derive(Serialize)]
struct HarnessInventoryReport {
    probe: HarnessProbeLevel,
    workspace: Option<PathBuf>,
    harnesses: Vec<LocalHarness>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
enum HarnessAuthState {
    Ready,
    Configured,
    Required,
    Unknown,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
enum HarnessRuntimeState {
    Ready,
    Degraded,
    Unavailable,
}

#[derive(Serialize)]
struct HarnessSessionCounts {
    global: Option<usize>,
    workspace: Option<usize>,
}

/// Receipt-backed evidence that a harness has a RUNNING instance right now,
/// distinct from being merely installed (UNI-7). Detection is passive and
/// default-on: a gateway liveness connect for daemon harnesses, a fresh
/// SQLite WAL stamp for store-writer harnesses (precedent: the opencode
/// follower's -wal/-shm freshness). Control stays behind per-connection
/// grants — this reports observations only.
/// ORCH-17: the gateway-health noun on an inventory row. Derived from the
/// UNI-7 running-instance probe (Hermes: `state.db-wal` freshness; OpenClaw:
/// a TCP connect to the gateway endpoint resolved from its OWN config) plus
/// the executable version — never by starting anything.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GatewayState {
    Up,
    Down,
    Unknown,
}

/// ORCH-17: `gateway` on a `harness.v1.harnesses.list` row.
#[derive(Debug, Clone, Serialize)]
pub struct GatewayHealth {
    pub state: GatewayState,
    /// The endpoint supercode would connect to (OpenClaw: the gateway
    /// WebSocket resolved from `openclaw.json`; core harnesses: their
    /// declared connect address when one exists). `None` when the harness
    /// has no single endpoint (Hermes multiplexes platforms).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub endpoint: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    /// What the verdict rests on, or why it is `unknown`.
    pub evidence: String,
    pub checked_at_ms: u64,
}

/// OpenClaw's gateway WebSocket endpoint, resolved from its own config the
/// way the registry's connect descriptor prescribes (`gateway.url`, else
/// `gateway.port`, else the documented default).
fn openclaw_gateway_endpoint(home: &Path) -> String {
    let config_path = home.join(".openclaw/openclaw.json");
    let gateway = std::fs::read_to_string(&config_path)
        .ok()
        .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
        .and_then(|config| config.get("gateway").cloned());
    if let Some(url) = gateway
        .as_ref()
        .and_then(|gateway| gateway.get("url"))
        .and_then(serde_json::Value::as_str)
    {
        return url.to_string();
    }
    let port = gateway
        .as_ref()
        .and_then(|gateway| gateway.get("port"))
        .and_then(serde_json::Value::as_u64)
        .unwrap_or(18789);
    format!("ws://127.0.0.1:{port}")
}

/// Ask Hermes itself (`hermes gateway status`, read-only, ~1 s) whether its
/// gateway is up. The command is per-host launchd/systemd text without a JSON
/// form at 0.19–0.21; the verdict is read from the lines it prints:
/// "supervised by launchd (PID …)" / "is running" → up, "not running" /
/// "not installed" → down, anything else → no verdict. `SUPERCODE_HERMES_BIN`
/// overrides the executable so a fake can stand in under test.
fn hermes_gateway_status() -> Option<(GatewayState, String)> {
    let program = crate::harness_command::harness_program(HarnessId::HERMES).ok()?;
    let output = std::process::Command::new(&program)
        .args(["gateway", "status"])
        .stdin(std::process::Stdio::null())
        .output()
        .ok()?;
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let verdict = text.lines().find_map(|line| {
        let l = line.trim();
        if l.contains("supervised by launchd (PID")
            || l.contains("supervised by systemd (PID")
            || l.contains("Gateway is running")
            || l.contains("process is running")
        {
            Some((GatewayState::Up, format!("`hermes gateway status`: {l}")))
        } else if l.contains("not running") || l.contains("not installed") {
            Some((GatewayState::Down, format!("`hermes gateway status`: {l}")))
        } else {
            None
        }
    });
    verdict
}

fn gateway_health(
    id: &str,
    installed: bool,
    running: Option<&RunningInstance>,
    version: Option<&str>,
) -> GatewayHealth {
    let checked_at_ms = now_epoch_ms();
    let home = std::env::var_os("HOME").map(PathBuf::from);
    match id {
        HarnessId::HERMES | HarnessId::OPENCLAW => {
            let endpoint = (id == HarnessId::OPENCLAW)
                .then(|| home.as_deref().map(openclaw_gateway_endpoint))
                .flatten();
            let (state, evidence) = match running {
                Some(instance) => (GatewayState::Up, instance.evidence.clone()),
                None if !installed => (
                    GatewayState::Unknown,
                    format!("`{id}` is not installed; no gateway to probe"),
                ),
                None if id == HarnessId::HERMES => match hermes_gateway_status() {
                    // The harness's own door outranks the WAL heuristic: an idle
                    // gateway writes nothing for minutes yet is up.
                    Some((state, evidence)) => (state, evidence),
                    None => (
                        GatewayState::Down,
                        "no fresh state.db-wal activity under ~/.hermes and `hermes gateway status` gave no verdict".to_string(),
                    ),
                },
                None => (
                    GatewayState::Down,
                    format!(
                        "no TCP listener at {}",
                        endpoint.as_deref().unwrap_or("the gateway endpoint")
                    ),
                ),
            };
            GatewayHealth {
                state,
                endpoint,
                version: version.map(str::to_string),
                evidence,
                checked_at_ms,
            }
        }
        // ORC-7: the orchestrator's gateway IS its daemon, and the daemon's
        // own lease file is the record of it. A lease naming a live pid is
        // up; a lease whose process is gone is down and says so as a STALE
        // lease, never as "no lease"; no lease at all is down. Nothing is
        // started, and no port is guessed — the daemon multiplexes adapters
        // the way Hermes does, so it has no single endpoint either.
        HarnessId::ORCHESTRATOR => {
            let root = crate::HarnessHomes::default().orchestrator;
            let (state, evidence) = match crate::orchestrator::read_lease(&root) {
                Some(lease) if crate::orchestrator::pid_is_live(lease.pid) => (
                    GatewayState::Up,
                    format!(
                        "`{}` names pid {} (started {}), which is live",
                        crate::orchestrator::lock_path(&root).display(),
                        lease.pid,
                        lease.started_at
                    ),
                ),
                Some(lease) => (
                    GatewayState::Down,
                    format!(
                        "stale lease `{}`: pid {} is gone",
                        crate::orchestrator::lock_path(&root).display(),
                        lease.pid
                    ),
                ),
                None => (
                    GatewayState::Down,
                    format!(
                        "no lease at `{}`; `supercode orchestrator start` writes one",
                        crate::orchestrator::lock_path(&root).display()
                    ),
                ),
            };
            GatewayHealth {
                state,
                endpoint: None,
                version: version.map(str::to_string),
                evidence,
                checked_at_ms,
            }
        }
        _ => GatewayHealth {
            state: GatewayState::Unknown,
            endpoint: None,
            version: version.map(str::to_string),
            evidence: format!("`{id}` runs per session, not as a gateway"),
            checked_at_ms,
        },
    }
}

#[derive(Debug, Clone, Serialize)]
struct RunningInstance {
    /// How the instance was detected.
    method: RunningInstanceMethod,
    /// The evidence the verdict rests on (endpoint reached / WAL path+age).
    evidence: String,
    /// Epoch-ms instant the probe executed.
    checked_at_ms: u64,
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
enum RunningInstanceMethod {
    /// A TCP connect to the harness's own configured gateway endpoint
    /// succeeded.
    GatewayConnect,
    /// The harness's session store has an active SQLite WAL (a live writer
    /// holds the store open and stamped it recently).
    StoreWalActivity,
}

fn now_epoch_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|elapsed| elapsed.as_millis() as u64)
        .unwrap_or(0)
}

/// OpenClaw: the gateway endpoint comes from the harness's OWN config
/// (`<home>/.openclaw/openclaw.json` — `gateway.url` or `gateway.port`,
/// default port 18789); a successful TCP connect is the running signal.
fn probe_openclaw_running(home: &Path) -> Option<RunningInstance> {
    let config_path = home.join(".openclaw/openclaw.json");
    let text = std::fs::read_to_string(&config_path).ok();
    let gateway = text
        .as_deref()
        .and_then(|raw| serde_json::from_str::<serde_json::Value>(raw).ok())
        .and_then(|config| config.get("gateway").cloned());
    let address = gateway
        .as_ref()
        .and_then(|gateway| gateway.get("url"))
        .and_then(serde_json::Value::as_str)
        .and_then(|url| {
            url.split("://").nth(1).map(|rest| {
                rest.trim_end_matches('/')
                    .split('/')
                    .next()
                    .unwrap_or(rest)
                    .to_string()
            })
        })
        .unwrap_or_else(|| {
            let port = gateway
                .as_ref()
                .and_then(|gateway| gateway.get("port"))
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(18789);
            format!("127.0.0.1:{port}")
        });
    let reachable = std::net::TcpStream::connect_timeout(
        &address.parse().ok()?,
        std::time::Duration::from_millis(400),
    )
    .is_ok();
    reachable.then(|| RunningInstance {
        method: RunningInstanceMethod::GatewayConnect,
        evidence: format!(
            "gateway endpoint {address} accepted a TCP connect (from {})",
            config_path.display()
        ),
        checked_at_ms: now_epoch_ms(),
    })
}

/// Hermes: `<home>/.hermes/state.db-wal` freshly modified means a live writer
/// holds the store open (SQLite WAL exists only while a connection is open;
/// a recent stamp distinguishes an active instance from a stale crash
/// leftover).
fn probe_hermes_running(home: &Path, max_wal_age_ms: u64) -> Option<RunningInstance> {
    let wal = home.join(".hermes/state.db-wal");
    let modified = std::fs::metadata(&wal).ok()?.modified().ok()?;
    let age_ms = std::time::SystemTime::now()
        .duration_since(modified)
        .map(|age| age.as_millis() as u64)
        .unwrap_or(u64::MAX);
    (age_ms <= max_wal_age_ms).then(|| RunningInstance {
        method: RunningInstanceMethod::StoreWalActivity,
        evidence: format!(
            "{} stamped {age_ms}ms ago (threshold {max_wal_age_ms}ms)",
            wal.display()
        ),
        checked_at_ms: now_epoch_ms(),
    })
}

/// Default-on running-instance detection for the harnesses that have one.
fn probe_running_instance(id: &str) -> Option<RunningInstance> {
    let home = std::env::var_os("HOME").map(PathBuf::from)?;
    match id {
        HarnessId::OPENCLAW => probe_openclaw_running(&home),
        HarnessId::HERMES => probe_hermes_running(&home, 300_000),
        _ => None,
    }
}

#[derive(Serialize)]
struct LocalHarness {
    id: HarnessId,
    display_name: String,
    supported: bool,
    installed: bool,
    executable: Option<String>,
    version: Option<String>,
    auth: HarnessAuthState,
    runtime: HarnessRuntimeState,
    protocol: String,
    capabilities: crate::RuntimeCapabilities,
    effective_capabilities: crate::RuntimeCapabilities,
    sessions: HarnessSessionCounts,
    /// Receipt-backed running-instance detection (None = not detected or the
    /// harness has no running-instance concept). Distinct from `installed`.
    #[serde(skip_serializing_if = "Option::is_none")]
    running: Option<RunningInstance>,
    /// ORCH-17: gateway health derived from `running` + the harness's own config.
    gateway: GatewayHealth,
    reason: Option<String>,
    repair: Option<String>,
}

#[derive(Clone, Deserialize)]
struct RuntimeBackendParams {
    harness: HarnessId,
    #[serde(default)]
    protocol: Option<String>,
    #[serde(default)]
    launch: Option<RuntimeLaunch>,
    #[serde(default)]
    base_url: Option<String>,
    #[serde(default)]
    policy: RuntimePolicy,
}

#[derive(Debug, Clone, Copy, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
enum RuntimePolicy {
    #[default]
    Default,
    Yolo,
}

#[derive(Deserialize)]
struct RuntimeStartParams {
    #[serde(flatten)]
    backend: RuntimeBackendParams,
    cwd: PathBuf,
    /// MCP servers to mount into the new session through the harness's own
    /// start door (ORC-6). Backends without such a door ignore them.
    #[serde(default)]
    mcp_servers: Vec<crate::McpServerLaunch>,
}

#[derive(Deserialize)]
struct RuntimeAttachParams {
    #[serde(flatten)]
    backend: RuntimeBackendParams,
    runtime_id: String,
    #[serde(default)]
    cwd: Option<PathBuf>,
}

#[derive(Deserialize)]
struct RuntimeConnectionParams {
    connection: String,
}

#[derive(Deserialize)]
struct RuntimeInputParams {
    connection: String,
    text: String,
    #[serde(default)]
    image_urls: Vec<String>,
}

const MAX_RUNTIME_IMAGES: usize = 4;
const MAX_RUNTIME_IMAGE_URL_BYTES: usize = 12 * 1024 * 1024;
const MAX_RUNTIME_IMAGE_URL_BYTES_TOTAL: usize = 32 * 1024 * 1024;

fn validate_runtime_image_urls(image_urls: Vec<String>) -> Result<Vec<String>, ServiceError> {
    if image_urls.len() > MAX_RUNTIME_IMAGES {
        return Err(ServiceError::InvalidParams(format!(
            "a runtime prompt accepts at most {MAX_RUNTIME_IMAGES} images"
        )));
    }
    let mut total = 0usize;
    for url in &image_urls {
        if !(url.starts_with("data:image/")
            || url.starts_with("https://")
            || url.starts_with("http://"))
        {
            return Err(ServiceError::InvalidParams(
                "runtime images must be image data URLs or HTTP(S) URLs".into(),
            ));
        }
        if url.len() > MAX_RUNTIME_IMAGE_URL_BYTES {
            return Err(ServiceError::InvalidParams(format!(
                "one runtime image exceeds the {MAX_RUNTIME_IMAGE_URL_BYTES}-byte encoded limit"
            )));
        }
        total = total.saturating_add(url.len());
    }
    if total > MAX_RUNTIME_IMAGE_URL_BYTES_TOTAL {
        return Err(ServiceError::InvalidParams(format!(
            "runtime images exceed the {MAX_RUNTIME_IMAGE_URL_BYTES_TOTAL}-byte encoded total limit"
        )));
    }
    Ok(image_urls)
}

#[derive(Deserialize)]
struct RuntimeRespondParams {
    connection: String,
    request_id: Value,
    response: Value,
}

fn default_reduction_store_root() -> PathBuf {
    if let Some(root) = std::env::var_os("SUPERCODE_HOME") {
        return PathBuf::from(root).join("sessions");
    }
    if let Some(home) = std::env::var_os("HOME") {
        return PathBuf::from(home).join(".supercode").join("sessions");
    }
    PathBuf::from(".supercode").join("sessions")
}

fn messages_jsonl(messages: &[crate::ChatMessage]) -> std::result::Result<String, ServiceError> {
    let mut output = String::new();
    for message in messages {
        output.push_str(
            &serde_json::to_string(message)
                .map_err(|error| ServiceError::Operation(error.to_string()))?,
        );
        output.push('\n');
    }
    Ok(output)
}

fn parse_messages_jsonl(
    content: &str,
) -> std::result::Result<Vec<crate::ChatMessage>, ServiceError> {
    content
        .lines()
        .enumerate()
        .filter(|(_, line)| !line.trim().is_empty())
        .map(|(index, line)| {
            serde_json::from_str::<crate::ChatMessage>(line).map_err(|error| {
                ServiceError::Operation(format!(
                    "reduced transcript line {} is invalid: {error}",
                    index + 1
                ))
            })
        })
        .collect()
}

fn reduced_bootstrap_prompt(
    source: &SessionLocator,
    target: TransferFormat,
    view_jsonl: &str,
    sidecar_path: &Path,
    reduction_log_path: &Path,
) -> String {
    format!(
        "Continue the work from this losslessly reduced {source_harness} session in {target_harness}.\n\
         \n\
         The bounded working transcript is below. Treat reduction markers as transparent placeholders, not missing work. If a detail behind a marker is needed, use ordinary file-reading/search tools against the full Supercode sidecar at `{sidecar}` and its reduction index at `{log}`. Do not guess hidden content. Both files were reloaded and verified before this continuation was issued.\n\
         \n\
         <supercode-reduced-session source-session=\"{source_id}\">\n\
         {view_jsonl}\
         </supercode-reduced-session>\n\
         \n\
         Resume from the latest unresolved user request and preserve the source session's decisions and constraints.",
        source_harness = source.harness.as_str(),
        target_harness = target.id(),
        sidecar = sidecar_path.display(),
        log = reduction_log_path.display(),
        source_id = source.session_id,
    )
}

fn session_artifact(
    locator: &SessionLocator,
    session: &Session,
    target: TransferFormat,
) -> std::result::Result<SessionArtifact, ServiceError> {
    session_artifact_with_id(locator, session, target, None)
}

fn session_artifact_with_id(
    locator: &SessionLocator,
    session: &Session,
    target: TransferFormat,
    target_session_id: Option<&str>,
) -> std::result::Result<SessionArtifact, ServiceError> {
    let format: SessionFormat = target.into();
    let diagonal = format.source() == session.meta.source;
    let has_appended_turns = session
        .imported_message_count
        .is_some_and(|imported| imported < session.messages.len());
    let content = if let Some(id) = target_session_id {
        if diagonal && format != SessionFormat::OpenCode {
            session
                .to_jsonl_spliced(format, Some(id))
                .map_err(operation)?
        } else {
            let mut rewritten = session.clone();
            rewritten.meta.session_id = Some(id.to_string());
            rewritten.to_jsonl(format).map_err(operation)?
        }
    } else if diagonal && session.raw_is_verbatim && !has_appended_turns {
        session.raw_verbatim()
    } else if diagonal {
        session.to_jsonl_spliced(format, None).map_err(operation)?
    } else {
        session.to_jsonl(format).map_err(operation)?
    };
    let stem = sanitize_filename(
        target_session_id
            .or(session.meta.session_id.as_deref())
            .unwrap_or(&locator.session_id),
    );
    let suggested_filename = if diagonal && target == TransferFormat::Grok {
        "chat_history.jsonl".to_string()
    } else if target == TransferFormat::Goose {
        format!("{stem}.goose.json")
    } else {
        format!("{stem}.{}.jsonl", target.id())
    };
    let mut files = vec![SessionArtifactFile {
        path: suggested_filename.clone(),
        content: content.clone(),
        role: ArtifactFileRole::Primary,
    }];
    if target == TransferFormat::ClaudeCode {
        let bundle_stem = Path::new(&suggested_filename)
            .file_stem()
            .and_then(|stem| stem.to_str())
            .unwrap_or(&stem);
        let mut child_paths = BTreeSet::new();
        for (index, subagent) in session.subagents.iter().enumerate() {
            let agent_id = subagent
                .meta
                .agent_id
                .as_deref()
                .map(|id| id.strip_prefix("agent-").unwrap_or(id))
                .map(sanitize_filename)
                .filter(|id| !id.is_empty())
                .unwrap_or_else(|| format!("subagent-{}", index + 1));
            let child_has_appended_turns = subagent
                .imported_message_count
                .is_some_and(|imported| imported < subagent.messages.len());
            let child_content = if target_session_id.is_none()
                && subagent.meta.source == SessionSource::ClaudeCode
                && subagent.raw_is_verbatim
                && !child_has_appended_turns
            {
                subagent.raw_verbatim()
            } else if subagent.meta.source == SessionSource::ClaudeCode {
                subagent
                    .to_jsonl_spliced(SessionFormat::ClaudeCode, target_session_id)
                    .map_err(operation)?
            } else {
                let mut child = subagent.clone();
                if let Some(id) = target_session_id {
                    child.meta.session_id = Some(id.to_string());
                }
                child
                    .to_jsonl(SessionFormat::ClaudeCode)
                    .map_err(operation)?
            };
            let path = format!("{bundle_stem}/subagents/agent-{agent_id}.jsonl");
            if !child_paths.insert(path.clone()) {
                return Err(ServiceError::Operation(format!(
                    "Claude subagent ids collide at artifact path `{path}`"
                )));
            }
            files.push(SessionArtifactFile {
                path,
                content: child_content,
                role: ArtifactFileRole::Subagent,
            });
        }
    }
    if diagonal && target == TransferFormat::Grok {
        append_grok_bundle_files(locator, "", ArtifactFileRole::Bundle, &mut files)?;
    }
    if !diagonal || !session.raw_is_verbatim {
        files.push(SessionArtifactFile {
            path: "recovery/source.supercode.jsonl".into(),
            content: session.to_native_jsonl(),
            role: ArtifactFileRole::SourceRecovery,
        });
        for (index, subagent) in session.subagents.iter().enumerate() {
            let id = subagent
                .meta
                .agent_id
                .as_deref()
                .map(sanitize_filename)
                .unwrap_or_else(|| format!("subagent-{}", index + 1));
            files.push(SessionArtifactFile {
                path: format!("recovery/subagents/{id}.supercode.jsonl"),
                content: subagent.to_native_jsonl(),
                role: ArtifactFileRole::SourceRecovery,
            });
        }
    }
    if !diagonal && session.meta.source == SessionSource::Grok {
        append_grok_bundle_files(
            locator,
            "recovery/grok/",
            ArtifactFileRole::SourceRecovery,
            &mut files,
        )?;
    }
    let (fidelity, residue) = if diagonal
        && target_session_id.is_none()
        && session.raw_is_verbatim
        && !has_appended_turns
    {
        (Fidelity::ByteLossless, Vec::new())
    } else if diagonal && !(target_session_id.is_some() && target == TransferFormat::OpenCode) {
        (
            Fidelity::ValueLossless,
            vec![if target_session_id.is_some() {
                "target identity was rewritten, so the artifact intentionally differs from source bytes".into()
            } else {
                "source storage was reconstructed as a native-value-equivalent export; original container bytes were not captured".into()
            }],
        )
    } else {
        (
            Fidelity::Semantic,
            vec!["target schema has no portable slot for every source-native record and metadata field".into()],
        )
    };
    Ok(SessionArtifact {
        source_harness: locator.harness.clone(),
        target_harness: target.id(),
        session_id: target_session_id
            .map(str::to_string)
            .or_else(|| session.meta.session_id.clone()),
        content,
        suggested_filename,
        files,
        fidelity,
        residue,
    })
}

fn append_grok_bundle_files(
    locator: &SessionLocator,
    prefix: &str,
    role: ArtifactFileRole,
    files: &mut Vec<SessionArtifactFile>,
) -> std::result::Result<(), ServiceError> {
    let primary = locator.storage.path();
    if primary.file_name().and_then(|name| name.to_str()) != Some("chat_history.jsonl") {
        return Err(ServiceError::Operation(format!(
            "Grok bundle locator must name chat_history.jsonl, got {}",
            primary.display()
        )));
    }
    let parent = primary.parent().ok_or_else(|| {
        ServiceError::Operation("Grok chat_history.jsonl has no session directory".into())
    })?;
    for name in ["summary.json", "updates.jsonl"] {
        let path = parent.join(name);
        let metadata = match std::fs::symlink_metadata(&path) {
            Ok(metadata) => metadata,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
            Err(error) => return Err(ServiceError::Operation(error.to_string())),
        };
        if metadata.file_type().is_symlink() || !metadata.is_file() {
            return Err(ServiceError::Operation(format!(
                "refusing non-regular Grok bundle member {}",
                path.display()
            )));
        }
        let content = std::fs::read_to_string(&path).map_err(|error| {
            ServiceError::Operation(format!(
                "Grok bundle member {} is not representable as UTF-8: {error}",
                path.display()
            ))
        })?;
        files.push(SessionArtifactFile {
            path: format!("{prefix}{name}"),
            content,
            role: match role {
                ArtifactFileRole::Bundle => ArtifactFileRole::Bundle,
                _ => ArtifactFileRole::SourceRecovery,
            },
        });
    }
    Ok(())
}

fn handoff_artifact(
    locator: &SessionLocator,
    session: &Session,
    target: TransferFormat,
    cwd: &Path,
) -> std::result::Result<SessionArtifact, ServiceError> {
    if target != TransferFormat::Grok {
        let target_session_id = target_session_id(target);
        return session_artifact_with_id(locator, session, target, Some(&target_session_id));
    }

    // Stock Grok's importer accepts Claude/Codex transcripts and materializes its own
    // multi-file session bundle. A synthesized Grok chat_history.jsonl alone is not a
    // resumable handoff because updates.jsonl is the authoritative restore log.
    let mut importable = session.clone();
    // The Claude importer validates sessionId as a UUID. Source harness identities
    // are not portable (OpenCode, for example, uses `ses_...`), and a handoff must
    // not overwrite an existing target session when the source already uses UUIDs.
    // Mint a distinct target identity and still bind the importer-returned ID at
    // launch time because the importer remains the authority on materialization.
    importable.meta.session_id = Some(target_session_id(TransferFormat::ClaudeCode));
    importable.meta.cwd = Some(if cwd.is_absolute() {
        cwd.to_path_buf()
    } else {
        std::env::current_dir()
            .map_err(|error| ServiceError::Operation(error.to_string()))?
            .join(cwd)
    });
    let content = importable
        .to_jsonl(SessionFormat::ClaudeCode)
        .map_err(operation)?;
    let stem = sanitize_filename(
        importable
            .meta
            .session_id
            .as_deref()
            .unwrap_or(&locator.session_id),
    );
    let suggested_filename = format!("{stem}.grok-import.claude-code.jsonl");
    Ok(SessionArtifact {
        source_harness: locator.harness.clone(),
        // This names the artifact's actual wire format. The requested handoff target
        // remains Grok; its official importer is the materialization boundary.
        target_harness: TransferFormat::ClaudeCode.id(),
        session_id: importable.meta.session_id.clone(),
        content: content.clone(),
        suggested_filename: suggested_filename.clone(),
        files: vec![SessionArtifactFile {
            path: suggested_filename,
            content,
            role: ArtifactFileRole::Primary,
        }],
        fidelity: Fidelity::Semantic,
        residue: vec!["Grok's stock importer accepts a Claude Code transcript, not a complete Grok updates/session bundle".into()],
    })
}

fn target_session_id(target: TransferFormat) -> String {
    let uuid = generated_session_id();
    match target {
        TransferFormat::OpenCode => format!("ses_{}", uuid.replace('-', "")),
        TransferFormat::ClaudeCode
        | TransferFormat::Codex
        | TransferFormat::Pi
        | TransferFormat::Grok
        | TransferFormat::Gemini
        | TransferFormat::Goose
        | TransferFormat::Hermes => uuid,
    }
}

fn sanitize_filename(value: &str) -> String {
    let value = value
        .chars()
        .map(|character| {
            if character.is_ascii_alphanumeric() || matches!(character, '-' | '_') {
                character
            } else {
                '-'
            }
        })
        .collect::<String>();
    let value = value.trim_matches('-');
    if value.is_empty() {
        "session".into()
    } else {
        value.chars().take(100).collect()
    }
}

fn handoff_instructions(
    target: TransferFormat,
    session_id: &str,
    cwd: &Path,
) -> HandoffInstructions {
    let launch = |program: &str, arguments: Vec<String>| StructuredLaunch {
        cwd: cwd.to_path_buf(),
        program: program.into(),
        arguments,
        env: BTreeMap::new(),
    };
    match target {
        TransferFormat::ClaudeCode => HandoffInstructions {
            launch: launch("claude", vec!["--resume".into(), session_id.into()]),
            materialize: None,
            requires_materialization: true,
            note: "Write the artifact into Claude Code's native project session store before running the resume launch; Claude Code has no general transcript-import command.".into(),
        },
        TransferFormat::Hermes => HandoffInstructions {
            launch: launch("hermes", vec!["--resume".into(), session_id.into()]),
            materialize: None,
            requires_materialization: true,
            note: "Hand the artifact (a Codex rollout) to `hermes sessions import --from codex <file>` — `sessions.export --to hermes` does exactly that — and resume the id Hermes prints: Hermes mints its own id and writes its own store.".into(),
        },
        TransferFormat::Codex => HandoffInstructions {
            launch: launch("codex", vec!["resume".into(), session_id.into()]),
            materialize: None,
            requires_materialization: true,
            note: "Write the artifact into Codex's native rollout store before running the resume launch; Codex has no general transcript-import command.".into(),
        },
        TransferFormat::OpenCode => HandoffInstructions {
            launch: launch("opencode", vec!["--session".into(), session_id.into()]),
            materialize: Some(launch(
                "opencode",
                vec!["import".into(), "{artifact_path}".into()],
            )),
            requires_materialization: true,
            note: "Write the artifact to a file, run the materialize command with its path, then launch the imported session.".into(),
        },
        TransferFormat::Pi => HandoffInstructions {
            launch: launch("pi", vec!["--session".into(), "{artifact_path}".into()]),
            materialize: None,
            requires_materialization: true,
            note: "Write the artifact to a file and replace {artifact_path} in the launch arguments; Pi can resume that file directly.".into(),
        },
        TransferFormat::Grok => HandoffInstructions {
            launch: launch(
                "grok",
                vec![
                    "--resume".into(),
                    "{imported_session_id}".into(),
                    "--fork-session".into(),
                ],
            ),
            materialize: Some(launch(
                "grok",
                vec!["import".into(), "--json".into(), "{artifact_path}".into()],
            )),
            requires_materialization: true,
            note: "The artifact is Claude Code JSONL for Grok's official importer. Write it to a file, run the materialize command, read sessionId from its NDJSON outcome=imported record, replace {imported_session_id} in the launch arguments, then launch a writable fork of the imported session.".into(),
        },
        TransferFormat::Gemini => HandoffInstructions {
            launch: launch(
                "gemini",
                vec!["--session-file".into(), "{artifact_path}".into()],
            ),
            materialize: None,
            requires_materialization: true,
            note: "Write the Gemini JSONL artifact to a file and replace {artifact_path}; Gemini imports it into the current project's chat store before opening the continuation.".into(),
        },
        TransferFormat::Goose => HandoffInstructions {
            launch: launch(
                "goose",
                vec![
                    "session".into(),
                    "--resume".into(),
                    "--session-id".into(),
                    "{imported_session_id}".into(),
                ],
            ),
            materialize: Some(launch(
                "goose",
                vec!["session".into(), "import".into(), "{artifact_path}".into()],
            )),
            requires_materialization: true,
            note: "Write the Goose JSON artifact to a file, run the materialize command, read the imported session id from its output, replace {imported_session_id}, then resume that native Goose session.".into(),
        },
    }
}

fn resume_launch(
    harness: &str,
    session_id: &str,
    cwd: &Path,
    policy: ResumePolicy,
) -> std::result::Result<StructuredLaunch, ServiceError> {
    let mut arguments = Vec::new();
    let program = match harness {
        HarnessId::GROK => {
            if matches!(policy, ResumePolicy::Yolo) {
                if crate::support::self_sandbox_supported() {
                    arguments.extend(["--sandbox".into(), "workspace".into()]);
                }
                arguments.push("--always-approve".into());
            }
            arguments.extend(["--resume".into(), session_id.into()]);
            "grok"
        }
        HarnessId::CODEX => {
            let cwd_key = serde_json::to_string(cwd.to_string_lossy().as_ref())
                .expect("a filesystem path always serializes as JSON text");
            arguments.extend([
                "-c".into(),
                "check_for_update_on_startup=false".into(),
                "-c".into(),
                format!("projects.{cwd_key}.trust_level=\"trusted\""),
            ]);
            if matches!(policy, ResumePolicy::Yolo) {
                arguments.extend([
                    "--dangerously-bypass-approvals-and-sandbox".into(),
                    "--dangerously-bypass-hook-trust".into(),
                ]);
            }
            arguments.extend(["resume".into(), session_id.into()]);
            "codex"
        }
        HarnessId::CLAUDE_CODE => {
            if matches!(policy, ResumePolicy::Yolo) {
                arguments.push("--dangerously-skip-permissions".into());
            }
            arguments.extend(["--resume".into(), session_id.into()]);
            "claude"
        }
        HarnessId::GEMINI => {
            if matches!(policy, ResumePolicy::Yolo) {
                arguments.push("--yolo".into());
            }
            arguments.extend(["--resume".into(), session_id.into()]);
            "gemini"
        }
        HarnessId::GOOSE => {
            arguments.extend([
                "session".into(),
                "--resume".into(),
                "--session-id".into(),
                session_id.into(),
            ]);
            "goose"
        }
        HarnessId::PI => {
            if matches!(policy, ResumePolicy::Yolo) {
                arguments.push("--approve".into());
            }
            arguments.extend(["--session".into(), session_id.into()]);
            "pi"
        }
        HarnessId::OPENCODE => {
            arguments.extend(["--session".into(), session_id.into()]);
            "opencode"
        }
        HarnessId::SUPERCODE => {
            if matches!(policy, ResumePolicy::Yolo) {
                arguments.push("--dangerous".into());
            }
            arguments.extend(["resume".into(), session_id.into()]);
            "supercode"
        }
        other => {
            return Err(ServiceError::InvalidParams(format!(
                "no structured resume launch is registered for harness `{other}`"
            )))
        }
    };
    Ok(StructuredLaunch {
        cwd: cwd.to_path_buf(),
        program: program.into(),
        arguments,
        env: BTreeMap::new(),
    })
}

/// Stage the resolved gateway credential in a private (0600) file so the
/// bridge can read it via `--token-file` — the delivery the real `openclaw
/// acp` accepts. One stable file per endpoint (keyed by an address digest,
/// no secret material in the name), overwritten on every connect so files
/// never accumulate and a rotated token never goes stale on disk.
fn openclaw_gateway_token_file(address: &str, secret: &str) -> std::io::Result<PathBuf> {
    let digest = blake3::hash(address.as_bytes()).to_hex();
    let path = std::env::temp_dir().join(format!(
        "supercode-openclaw-gateway-token-{}",
        &digest.as_str()[..16]
    ));
    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(&path)?;
        file.write_all(secret.as_bytes())?;
    }
    #[cfg(not(unix))]
    std::fs::write(&path, secret)?;
    Ok(path)
}

/// Open a connect-mode descriptor: resolve the endpoint address and
/// credential from the harness's own config file and build the backend that
/// joins the already-running endpoint. Fails closed with a specific
/// diagnostic when the config cannot be resolved or the declared protocol has
/// no connect-capable client yet.
fn open_connect_descriptor(
    descriptor: &crate::HarnessSupportDescriptor,
    home: &Path,
) -> std::result::Result<Box<dyn RuntimeBackend>, ServiceError> {
    let Some(connect) = &descriptor.runtime.connect_launch else {
        return Err(ServiceError::InvalidParams(format!(
            "harness `{}` has no registered connect-mode launch",
            descriptor.id.as_str()
        )));
    };
    let resolved = connect
        .resolve(home)
        .map_err(|error| ServiceError::UnsupportedAction(error.to_string()))?;
    match (descriptor.id.as_str(), connect.protocol.as_str()) {
        (HarnessId::OPENCODE, protocol) if protocol.starts_with("opencode-http") => {
            let mut backend = OpenCodeRuntimeBackend::connect(&resolved.address);
            if let Some(token) = resolved.auth {
                backend = backend.with_bearer(token);
            }
            Ok(Box::new(backend))
        }
        (HarnessId::OPENCLAW, protocol) if protocol.starts_with("acp") => {
            // OpenClaw's own `openclaw acp` binary is the gateway client: a
            // stdio ACP bridge that joins the RUNNING gateway at the resolved
            // endpoint. Blind-walk finding 2026-08-31: the real bridge does
            // NOT honor OPENCLAW_GATEWAY_TOKEN from the environment — the
            // credential must arrive via `--token-file` (never bare `--token`
            // on argv, where process listings could read it). The env var is
            // still set for older bridges that did read it. Requires openclaw
            // >= 2026.7: the 2026.2 bridge drops its gateway socket
            // mid-prompt and advertises no session resume (executed finding,
            // docs/interop/research/openclaw-acp-dialect-2026-08-30.json).
            let mut env = BTreeMap::new();
            let mut arguments = vec!["acp".into(), "--url".into(), resolved.address.clone()];
            if let Some(token) = resolved.auth {
                let token_path = openclaw_gateway_token_file(&resolved.address, token.secret())
                    .map_err(|error| {
                        ServiceError::UnsupportedAction(format!(
                            "could not stage the gateway credential for the bridge: {error}"
                        ))
                    })?;
                arguments.push("--token-file".into());
                arguments.push(token_path.to_string_lossy().into_owned());
                env.insert("OPENCLAW_GATEWAY_TOKEN".to_string(), token.secret().to_string());
            }
            // The bridge program comes from the descriptor's own default
            // launch (the compiled registry pins `openclaw`), so tests can
            // substitute an absolute mock-bridge path without touching
            // process-global state.
            let program = descriptor
                .runtime
                .default_launch
                .as_ref()
                .map(|launch| launch.program.clone())
                .unwrap_or_else(|| "openclaw".into());
            let launch = RuntimeLaunch {
                program,
                arguments,
                env,
            };
            Ok(Box::new(
                crate::AcpRuntimeBackend::new(descriptor.id.clone(), launch)
                    .with_resume_support(descriptor.runtime.capabilities.resume_session),
            ))
        }
        _ => Err(ServiceError::UnsupportedAction(format!(
            "connect-mode endpoint for `{}` speaks `{}`; joining it needs that protocol's gateway client",
            descriptor.id.as_str(),
            connect.protocol
        ))),
    }
}

/// The registry's connect-mode launch for this harness, honored only when the
/// caller supplied neither an explicit launch nor a base URL.
fn registry_connect_descriptor(
    params: &RuntimeBackendParams,
) -> Option<crate::HarnessSupportDescriptor> {
    if params.launch.is_some() || params.base_url.is_some() {
        return None;
    }
    harness_support_registry()
        .harnesses
        .into_iter()
        .find(|descriptor| descriptor.id == params.harness)
        .filter(|descriptor| descriptor.runtime.connect_launch.is_some())
}

fn service_home() -> std::result::Result<PathBuf, ServiceError> {
    std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| {
        ServiceError::UnsupportedAction(
            "connect-mode launches need HOME to locate the harness config".into(),
        )
    })
}

fn runtime_backend(
    params: &RuntimeBackendParams,
) -> std::result::Result<Box<dyn RuntimeBackend>, ServiceError> {
    if let Some(descriptor) = registry_connect_descriptor(params) {
        return open_connect_descriptor(&descriptor, &service_home()?);
    }
    if params.protocol.as_deref() == Some("acp") {
        let launch = params
            .launch
            .clone()
            .or_else(|| {
                harness_support_registry()
                    .harnesses
                    .into_iter()
                    .find(|harness| harness.id == params.harness)
                    .filter(|harness| {
                        harness.runtime.implementation == ImplementationKind::GenericProtocol
                            && harness.runtime.protocol.starts_with("acp")
                    })
                    .and_then(|harness| harness.runtime.default_launch)
            })
            .ok_or_else(|| {
                ServiceError::InvalidParams(
                    "an ACP runtime requires `launch` unless the harness has a registered default"
                        .into(),
                )
            })?;
        let resume_session = harness_support_registry()
            .harnesses
            .into_iter()
            .find(|harness| harness.id == params.harness)
            .is_some_and(|harness| harness.runtime.capabilities.resume_session);
        return Ok(Box::new(
            AcpRuntimeBackend::new(params.harness.clone(), launch)
                .with_resume_support(resume_session),
        ));
    }
    let backend: Box<dyn RuntimeBackend> = match params.harness.as_str() {
        HarnessId::CODEX => Box::new(CodexRuntimeBackend::new()),
        HarnessId::CLAUDE_CODE => Box::new(ClaudeCodeRuntimeBackend::new()),
        HarnessId::PI => Box::new(PiRuntimeBackend::new()),
        HarnessId::OPENCODE => match &params.base_url {
            Some(url) => Box::new(OpenCodeRuntimeBackend::connect(url)),
            None => Box::new(OpenCodeRuntimeBackend::new()),
        },
        harness => {
            let descriptor = harness_support_registry()
                .harnesses
                .into_iter()
                .find(|descriptor| descriptor.id.as_str() == harness)
                .filter(|descriptor| {
                    descriptor.runtime.implementation == ImplementationKind::GenericProtocol
                        && descriptor.runtime.protocol.starts_with("acp")
                });
            let Some(descriptor) = descriptor else {
                return Err(ServiceError::InvalidParams(format!(
                    "no runtime adapter for harness `{harness}`; use protocol `acp` with a launch command"
                )));
            };
            let resume = descriptor.runtime.capabilities.resume_session;
            Box::new(
                AcpRuntimeBackend::new(
                    descriptor.id,
                    descriptor
                        .runtime
                        .default_launch
                        .expect("generic ACP registry entry includes its launch"),
                )
                .with_resume_support(resume),
            )
        }
    };
    Ok(backend)
}

fn runtime_launch(params: &RuntimeBackendParams) -> Option<RuntimeLaunch> {
    if let Some(launch) = &params.launch {
        return Some(launch.clone());
    }
    if !matches!(params.policy, RuntimePolicy::Yolo) {
        return None;
    }
    let launch = match params.harness.as_str() {
        HarnessId::GROK => RuntimeLaunch {
            program: "grok".into(),
            arguments: {
                let mut arguments: Vec<String> = Vec::new();
                if crate::support::self_sandbox_supported() {
                    arguments.extend(["--sandbox".into(), "workspace".into()]);
                }
                arguments.extend([
                    "--always-approve".into(),
                    "agent".into(),
                    "--no-leader".into(),
                    "stdio".into(),
                ]);
                arguments
            },
            env: BTreeMap::from([("GROK_AGENT_DASHBOARD".into(), "0".into())]),
        },
        HarnessId::CODEX => RuntimeLaunch {
            program: "codex".into(),
            arguments: vec![
                "--dangerously-bypass-approvals-and-sandbox".into(),
                "--dangerously-bypass-hook-trust".into(),
                "app-server".into(),
            ],
            env: BTreeMap::new(),
        },
        HarnessId::CLAUDE_CODE => RuntimeLaunch {
            program: "claude".into(),
            arguments: vec![
                "--dangerously-skip-permissions".into(),
                "--print".into(),
                "--input-format".into(),
                "stream-json".into(),
                "--output-format".into(),
                "stream-json".into(),
                "--verbose".into(),
            ],
            env: BTreeMap::new(),
        },
        HarnessId::PI => RuntimeLaunch {
            program: "pi".into(),
            arguments: vec!["--approve".into(), "--mode".into(), "rpc".into()],
            env: BTreeMap::new(),
        },
        HarnessId::OPENCODE => RuntimeLaunch {
            program: "opencode".into(),
            arguments: vec!["serve".into()],
            env: BTreeMap::new(),
        },
        HarnessId::GEMINI => RuntimeLaunch {
            program: "gemini".into(),
            arguments: vec!["--acp".into(), "--yolo".into()],
            env: BTreeMap::new(),
        },
        HarnessId::GOOSE => RuntimeLaunch {
            program: "goose".into(),
            arguments: vec!["acp".into()],
            env: BTreeMap::new(),
        },
        HarnessId::SUPERCODE => RuntimeLaunch {
            program: "supercode".into(),
            arguments: vec!["acp".into(), "--dangerous".into()],
            env: BTreeMap::new(),
        },
        _ => return None,
    };
    Some(launch)
}

/// Disposable harness state for a no-prompt readiness probe. Merely opening
/// several stock CLIs writes a session header or migrates configuration, so a
/// handshake must never point at the user's real home. Authentication files
/// are copied into the private temporary home; all writes disappear with the
/// guard after the connection closes.
struct IsolatedProbeHome {
    launch: RuntimeLaunch,
    root: PathBuf,
}

impl IsolatedProbeHome {
    fn new(harness: &str, mut launch: RuntimeLaunch) -> std::io::Result<Self> {
        let root = std::env::temp_dir().join(format!(
            "supercode-harness-probe-{harness}-{}",
            generated_session_id()
        ));
        std::fs::create_dir_all(&root)?;
        set_private_dir_permissions(&root)?;

        if let Some(source_home) = std::env::var_os("HOME").map(PathBuf::from) {
            for relative in probe_auth_files(harness) {
                copy_probe_file(&source_home, &root, relative)?;
            }
        }
        configure_isolated_probe_auth(harness, &root)?;

        let root_text = root.to_string_lossy().into_owned();
        for (key, value) in [
            ("HOME", root_text.clone()),
            (
                "XDG_CACHE_HOME",
                root.join(".cache").to_string_lossy().into_owned(),
            ),
            (
                "XDG_CONFIG_HOME",
                root.join(".config").to_string_lossy().into_owned(),
            ),
            (
                "XDG_DATA_HOME",
                root.join(".local/share").to_string_lossy().into_owned(),
            ),
        ] {
            launch.env.insert(key.into(), value);
        }
        let scoped = match harness {
            HarnessId::CLAUDE_CODE => Some(("CLAUDE_CONFIG_DIR", root.join(".claude"))),
            HarnessId::CODEX => Some(("CODEX_HOME", root.join(".codex"))),
            HarnessId::GEMINI => Some(("GEMINI_CLI_HOME", root.clone())),
            HarnessId::GROK => Some(("GROK_HOME", root.join(".grok"))),
            HarnessId::PI => Some(("PI_CODING_AGENT_DIR", root.join(".pi/agent"))),
            HarnessId::SUPERCODE => Some(("SUPERCODE_HOME", root.join(".config/supercode"))),
            _ => None,
        };
        if let Some((key, value)) = scoped {
            launch
                .env
                .insert(key.into(), value.to_string_lossy().into_owned());
        }
        Ok(Self { launch, root })
    }

    fn cleanup(&self) -> std::io::Result<()> {
        match std::fs::remove_dir_all(&self.root) {
            Ok(()) => Ok(()),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(error) => Err(error),
        }
    }
}

impl Drop for IsolatedProbeHome {
    fn drop(&mut self) {
        let _ = self.cleanup();
    }
}

fn probe_auth_files(harness: &str) -> &'static [&'static str] {
    match harness {
        HarnessId::CLAUDE_CODE => &[".claude/.credentials.json", ".claude.json"],
        // The gateway endpoint + token live in openclaw's own config; without
        // it the isolated probe dials the default endpoint unauthenticated
        // (PARITY-24 finding 2026-08-31).
        HarnessId::OPENCLAW => &[".openclaw/openclaw.json"],
        HarnessId::CODEX => &[".codex/auth.json"],
        HarnessId::GEMINI => &[
            ".gemini/google_accounts.json",
            ".gemini/oauth_creds.json",
            ".gemini/settings.json",
        ],
        HarnessId::GROK => &[".grok/auth.json", ".grok/config.toml"],
        HarnessId::OPENCODE => &[
            ".config/opencode/auth.json",
            ".local/share/opencode/auth.json",
        ],
        HarnessId::PI => &[".pi/agent/auth.json"],
        HarnessId::SUPERCODE => &[
            ".config/supercode/config.toml",
            ".config/supercode/credentials.toml",
        ],
        _ => &[],
    }
}

fn copy_probe_file(source_home: &Path, probe_home: &Path, relative: &str) -> std::io::Result<()> {
    let source = source_home.join(relative);
    if !source.is_file() {
        return Ok(());
    }
    let destination = probe_home.join(relative);
    if let Some(parent) = destination.parent() {
        std::fs::create_dir_all(parent)?;
        set_private_dir_permissions(parent)?;
    }
    std::fs::copy(source, &destination)?;
    set_private_file_permissions(&destination)
}

fn configure_isolated_probe_auth(harness: &str, probe_home: &Path) -> std::io::Result<()> {
    if harness != HarnessId::GEMINI {
        return Ok(());
    }
    let oauth = probe_home.join(".gemini/oauth_creds.json");
    if !oauth.is_file() {
        return Ok(());
    }
    let settings_path = probe_home.join(".gemini/settings.json");
    let mut settings = std::fs::read_to_string(&settings_path)
        .ok()
        .and_then(|raw| serde_json::from_str::<Value>(&raw).ok())
        .unwrap_or_else(|| json!({}));
    settings["security"]["auth"]["selectedType"] = Value::String("oauth-personal".into());
    std::fs::write(
        &settings_path,
        serde_json::to_vec_pretty(&settings).map_err(std::io::Error::other)?,
    )?;
    set_private_file_permissions(&settings_path)
}

#[cfg(unix)]
fn set_private_dir_permissions(path: &Path) -> std::io::Result<()> {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))
}

#[cfg(not(unix))]
fn set_private_dir_permissions(_path: &Path) -> std::io::Result<()> {
    Ok(())
}

#[cfg(unix)]
fn set_private_file_permissions(path: &Path) -> std::io::Result<()> {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
}

#[cfg(not(unix))]
fn set_private_file_permissions(_path: &Path) -> std::io::Result<()> {
    Ok(())
}

fn find_executable(program: &str) -> Option<PathBuf> {
    let candidate = PathBuf::from(program);
    if candidate.components().count() > 1 {
        return candidate.is_file().then_some(candidate);
    }
    let path = std::env::var_os("PATH")?;
    for directory in std::env::split_paths(&path) {
        let candidate = directory.join(program);
        if candidate.is_file() {
            return std::fs::canonicalize(&candidate).ok().or(Some(candidate));
        }
        #[cfg(windows)]
        {
            for extension in ["exe", "cmd", "bat"] {
                let candidate = directory.join(format!("{program}.{extension}"));
                if candidate.is_file() {
                    return std::fs::canonicalize(&candidate).ok().or(Some(candidate));
                }
            }
        }
    }
    None
}

async fn executable_version(executable: &Path) -> Option<String> {
    let mut command = tokio::process::Command::new(executable);
    command
        .arg("--version")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .kill_on_drop(true);
    let output = tokio::time::timeout(Duration::from_secs(3), command.output())
        .await
        .ok()?
        .ok()?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    stdout
        .lines()
        .chain(stderr.lines())
        .map(str::trim)
        .find(|line| !line.is_empty())
        .map(|line| truncate_text(line, 200))
}

pub(crate) fn auth_evidence(harness: &str) -> bool {
    let env_names: &[&str] = match harness {
        HarnessId::CLAUDE_CODE => &["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"],
        HarnessId::CODEX => &["OPENAI_API_KEY"],
        HarnessId::OPENCODE => &["ANTHROPIC_API_KEY", "OPENAI_API_KEY", "OPENROUTER_API_KEY"],
        HarnessId::PI => &["ANTHROPIC_API_KEY", "OPENAI_API_KEY", "OPENROUTER_API_KEY"],
        HarnessId::GROK => &["XAI_API_KEY", "GROK_API_KEY"],
        HarnessId::GEMINI => &["GEMINI_API_KEY", "GOOGLE_API_KEY"],
        HarnessId::SUPERCODE => &["OPENROUTER_API_KEY"],
        _ => &[],
    };
    if env_names
        .iter()
        .any(|name| std::env::var_os(name).is_some_and(|value| !value.is_empty()))
    {
        return true;
    }
    let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else {
        return false;
    };
    let files: Vec<PathBuf> = match harness {
        HarnessId::CLAUDE_CODE => vec![home.join(".claude/.credentials.json")],
        HarnessId::CODEX => vec![home.join(".codex/auth.json")],
        HarnessId::OPENCODE => vec![
            home.join(".local/share/opencode/auth.json"),
            home.join(".config/opencode/auth.json"),
        ],
        HarnessId::PI => vec![home.join(".pi/agent/auth.json")],
        HarnessId::GROK => vec![home.join(".grok/auth.json")],
        HarnessId::GEMINI => vec![
            home.join(".gemini/oauth_creds.json"),
            home.join(".gemini/google_accounts.json"),
        ],
        HarnessId::SUPERCODE => vec![home.join(".config/supercode/credentials.toml")],
        _ => Vec::new(),
    };
    if files.into_iter().any(|path| {
        std::fs::metadata(path)
            .map(|metadata| metadata.is_file() && metadata.len() > 2)
            .unwrap_or(false)
    }) {
        return true;
    }
    // macOS keeps Claude Code's OAuth login in the Keychain, so
    // `.claude/.credentials.json` never exists there and the file probe above
    // reports a signed-in install as unauthenticated forever. A completed
    // login also writes an `oauthAccount` record into `~/.claude.json` on
    // every platform — file-based, prompt-free evidence (querying the
    // Keychain itself from an unsigned daemon can raise a UI prompt).
    if harness == HarnessId::CLAUDE_CODE {
        return std::fs::read_to_string(home.join(".claude.json"))
            .map(|text| text.contains("\"oauthAccount\""))
            .unwrap_or(false);
    }
    false
}

fn looks_like_auth_error(message: &str) -> bool {
    let message = message.to_ascii_lowercase();
    [
        "auth",
        "login",
        "sign in",
        "sign-in",
        "credential",
        "unauthorized",
        "forbidden",
        "token",
    ]
    .iter()
    .any(|needle| message.contains(needle))
}

fn unavailable_capabilities() -> crate::RuntimeCapabilities {
    crate::RuntimeCapabilities {
        start_session: false,
        resume_session: false,
        attach_existing_process: false,
        send_input: false,
        stream_events: false,
        interrupt: false,
        steer: false,
        respond_to_requests: false,
    }
}

fn truncate_text(text: &str, max_chars: usize) -> String {
    let mut chars = text.chars();
    let truncated = chars.by_ref().take(max_chars).collect::<String>();
    if chars.next().is_some() {
        format!("{truncated}…")
    } else {
        truncated
    }
}

fn error_message(error: ServiceError) -> String {
    match error {
        ServiceError::InvalidParams(message)
        | ServiceError::Operation(message)
        | ServiceError::UnsupportedAction(message) => message,
        ServiceError::MethodNotFound => "runtime adapter is not available".into(),
        ServiceError::Sdk(error) => error.to_string(),
    }
}

#[derive(Debug)]
enum ServiceError {
    InvalidParams(String),
    MethodNotFound,
    UnsupportedAction(String),
    Operation(String),
    Sdk(SdkError),
}

fn sdk_error(operation: SdkOperation, error: ServiceError) -> SdkError {
    match error {
        ServiceError::InvalidParams(message) => {
            SdkError::new(SdkErrorCode::InvalidArgument, operation, message)
        }
        ServiceError::MethodNotFound | ServiceError::UnsupportedAction(_) => {
            SdkError::unsupported(operation)
        }
        ServiceError::Operation(message) => {
            let code = if message.contains("already in progress") {
                SdkErrorCode::Busy
            } else if message.contains("not supported by this runtime") {
                SdkErrorCode::UnsupportedAction
            } else if message.contains("unknown runtime connection") {
                SdkErrorCode::NotFound
            } else {
                SdkErrorCode::Execution
            };
            SdkError::new(code, operation, message)
        }
        ServiceError::Sdk(error) => error,
    }
}

fn sdk_rpc_error(id: Value, error: &SdkError) -> Value {
    let error_code = error.code();
    let code = match error_code {
        SdkErrorCode::Unauthenticated => -32030,
        SdkErrorCode::Unauthorized => -32031,
        SdkErrorCode::ControllerRequired => -32032,
        SdkErrorCode::LeaseExpired => -32033,
        SdkErrorCode::InvalidArgument => -32602,
        SdkErrorCode::NotFound => -32004,
        SdkErrorCode::Busy => -32000,
        SdkErrorCode::UnsupportedAction => -32020,
        SdkErrorCode::Execution => -32002,
        SdkErrorCode::Transport => -32003,
    };
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "error": {
            "code": code,
            "name": error_code,
            "operation": error.operation(),
            "message": error.to_string(),
        },
    })
}

fn decode<T: for<'de> Deserialize<'de>>(value: Value) -> std::result::Result<T, ServiceError> {
    serde_json::from_value(value).map_err(|error| ServiceError::InvalidParams(error.to_string()))
}

fn operation(error: impl Into<crate::Error>) -> ServiceError {
    let error = error.into();
    match error {
        crate::Error::Sdk(error) => ServiceError::Sdk(error),
        error => ServiceError::Operation(error.to_string()),
    }
}

/// ORCH-12 `harness.v1.memory.show|search` params. `homes` is the same
/// storage-root override every read-only method accepts, so a caller can
/// point the read at a fixture home without touching the real ones.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(default)]
struct MemoryRequest {
    /// Harness whose store is read. Required.
    harness: Option<String>,
    /// The needle, required by `search`.
    query: Option<String>,
    /// Hermes profile, OpenClaw agent, or Claude Code project.
    profile: Option<String>,
    /// Claude Code session id selecting a project store (`show` only).
    session: Option<String>,
    /// Include each document's whole text (`show` only).
    full: bool,
    /// Treat `query` as a regular expression (`search` only).
    regex: bool,
    /// Working tree whose project store is read.
    cwd: Option<std::path::PathBuf>,
    /// Storage roots to read.
    homes: crate::HarnessHomes,
}

/// Read the memory noun. A harness with no memory store fails with
/// `UnsupportedAction` (RPC `-32020`), never an empty list.
fn memory_call(method: &str, params: Value) -> std::result::Result<Value, ServiceError> {
    let request = decode::<MemoryRequest>(params)?;
    let harness = request
        .harness
        .clone()
        .ok_or_else(|| ServiceError::InvalidParams("`harness` is required".into()))?;
    let to_service = |error: crate::memory::MemoryError| match error {
        crate::memory::MemoryError::UnsupportedHarness { .. }
        | crate::memory::MemoryError::SessionNotScoped { .. } => {
            ServiceError::UnsupportedAction(error.to_string())
        }
        other => ServiceError::InvalidParams(other.to_string()),
    };
    match method {
        "harness.v1.memory.show" => {
            let documents = crate::memory::show_memory(&crate::memory::MemoryQuery {
                harness,
                profile: request.profile,
                session: request.session,
                full: request.full,
                cwd: request.cwd,
                homes: request.homes,
            })
            .map_err(to_service)?;
            Ok(json!({
                "schema": crate::memory::MEMORY_SCHEMA,
                "documents": documents,
            }))
        }
        "harness.v1.memory.search" => {
            let query = request
                .query
                .ok_or_else(|| ServiceError::InvalidParams("`query` is required".into()))?;
            let matches = crate::memory::search_memory(&crate::memory::MemorySearchQuery {
                harness,
                query,
                profile: request.profile,
                regex: request.regex,
                cwd: request.cwd,
                homes: request.homes,
            })
            .map_err(to_service)?;
            Ok(json!({
                "schema": crate::memory::MEMORY_SCHEMA,
                "matches": matches,
            }))
        }
        _ => Err(ServiceError::MethodNotFound),
    }
}

/// ORCH-10 `harness.v1.profiles.list|get` params. `homes` is the same
/// storage-root override every read-only method accepts, so a caller can
/// point the read at a fixture home without touching the real ones.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
struct ProfilesQuery {
    /// Restrict the listing to one harness. `get` requires it.
    harness: Option<String>,
    /// Profile name, required by `get`.
    name: Option<String>,
    /// Storage roots to read.
    homes: crate::HarnessHomes,
}

impl Default for ProfilesQuery {
    fn default() -> Self {
        Self {
            harness: None,
            name: None,
            homes: crate::HarnessHomes::default(),
        }
    }
}

/// Read the profile noun. A harness with no profile concept fails with
/// `UnsupportedAction` (RPC `-32020`), never an empty list.
fn profiles_call(method: &str, params: Value) -> std::result::Result<Value, ServiceError> {
    let query = decode::<ProfilesQuery>(params)?;
    let to_service = |error: crate::profiles::ProfileError| match error {
        crate::profiles::ProfileError::UnsupportedHarness { .. } => {
            ServiceError::UnsupportedAction(error.to_string())
        }
        crate::profiles::ProfileError::NotFound { .. } => {
            ServiceError::InvalidParams(error.to_string())
        }
    };
    match method {
        "harness.v1.profiles.list" => {
            let profiles = crate::profiles::list_profiles(&query.homes, query.harness.as_deref())
                .map_err(to_service)?;
            Ok(json!({
                "schema": crate::profiles::PROFILES_SCHEMA,
                "profiles": profiles,
            }))
        }
        "harness.v1.profiles.get" => {
            let harness = query
                .harness
                .ok_or_else(|| ServiceError::InvalidParams("`harness` is required".into()))?;
            let name = query
                .name
                .ok_or_else(|| ServiceError::InvalidParams("`name` is required".into()))?;
            let profile =
                crate::profiles::get_profile(&query.homes, &harness, &name).map_err(to_service)?;
            Ok(json!({
                "schema": crate::profiles::PROFILES_SCHEMA,
                "profile": profile,
            }))
        }
        _ => Err(ServiceError::MethodNotFound),
    }
}

/// ORCH-14 `harness.v1.channels.list|status` params, the same storage-root
/// override every read-only method accepts so a caller can point the read at
/// a fixture home without touching the real ones.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
struct ChannelsQuery {
    /// Restrict the listing to one harness. `status` requires it.
    harness: Option<String>,
    /// Channel name, required by `status`.
    name: Option<String>,
    /// Storage roots to read.
    homes: crate::HarnessHomes,
}

impl Default for ChannelsQuery {
    fn default() -> Self {
        Self {
            harness: None,
            name: None,
            homes: crate::HarnessHomes::default(),
        }
    }
}

/// Read the channel noun. A harness with no channel concept fails with
/// `UnsupportedAction` (RPC `-32020`), never an empty list. No row carries a
/// token, key or secret — see `crate::channels` "Secrecy".
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
struct RoutesQuery {
    harness: Option<String>,
    /// Restrict to routes targeting one profile / agent.
    profile: Option<String>,
    homes: crate::HarnessHomes,
}

impl Default for RoutesQuery {
    fn default() -> Self {
        Self {
            harness: None,
            profile: None,
            homes: crate::HarnessHomes::default(),
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
struct TriggersQuery {
    harness: Option<String>,
    homes: crate::HarnessHomes,
}

impl Default for TriggersQuery {
    fn default() -> Self {
        Self {
            harness: None,
            homes: crate::HarnessHomes::default(),
        }
    }
}

fn triggers_call(params: Value) -> std::result::Result<Value, ServiceError> {
    let query = decode::<TriggersQuery>(params)?;
    let triggers = crate::triggers::list_triggers(&query.homes, query.harness.as_deref())
        .map_err(|error| ServiceError::UnsupportedAction(error.to_string()))?;
    Ok(json!({
        "schema": crate::triggers::TRIGGERS_SCHEMA,
        "triggers": triggers,
    }))
}

fn routes_call(params: Value) -> std::result::Result<Value, ServiceError> {
    let query = decode::<RoutesQuery>(params)?;
    let routes = crate::routes::list_routes(
        &query.homes,
        query.harness.as_deref(),
        query.profile.as_deref(),
    )
    .map_err(|error| ServiceError::UnsupportedAction(error.to_string()))?;
    Ok(json!({
        "schema": crate::routes::ROUTES_SCHEMA,
        "routes": routes,
    }))
}

fn channels_call(method: &str, params: Value) -> std::result::Result<Value, ServiceError> {
    let query = decode::<ChannelsQuery>(params)?;
    let to_service = |error: crate::channels::ChannelError| match error {
        crate::channels::ChannelError::UnsupportedHarness { .. } => {
            ServiceError::UnsupportedAction(error.to_string())
        }
        crate::channels::ChannelError::NotFound { .. } => {
            ServiceError::InvalidParams(error.to_string())
        }
    };
    match method {
        "harness.v1.channels.list" => {
            let channels = crate::channels::list_channels(&query.homes, query.harness.as_deref())
                .map_err(to_service)?;
            Ok(json!({
                "schema": crate::channels::CHANNELS_SCHEMA,
                "channels": channels,
            }))
        }
        "harness.v1.channels.status" => {
            let harness = query
                .harness
                .ok_or_else(|| ServiceError::InvalidParams("`harness` is required".into()))?;
            let name = query
                .name
                .ok_or_else(|| ServiceError::InvalidParams("`name` is required".into()))?;
            let channel = crate::channels::channel_status(&query.homes, &harness, &name)
                .map_err(to_service)?;
            Ok(json!({
                "schema": crate::channels::CHANNELS_SCHEMA,
                "channel": channel,
            }))
        }
        _ => Err(ServiceError::MethodNotFound),
    }
}

fn rpc_error(id: Value, code: i64, message: &str) -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "error": {"code": code, "message": message},
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{HarnessEvent, HarnessId, RuntimeEndpoint, RuntimeHandle, StorageLocator};
    use async_trait::async_trait;
    use std::io::Write;
    use std::path::PathBuf;
    use std::time::Instant;

    #[test]
    fn indexed_claude_descriptor_keeps_the_live_peer_address() {
        let descriptor = SessionDescriptor {
            locator: SessionLocator {
                harness: HarnessId::new(HarnessId::CLAUDE_CODE),
                session_id: "live-session".into(),
                storage: StorageLocator::File {
                    path: PathBuf::from("/tmp/live-session.jsonl"),
                },
            },
            cwd: Some(PathBuf::from("/project")),
            title: None,
            preview_candidates: Vec::new(),
            latest_message_candidates: Vec::new(),
            updated_at_ms: Some(1),
            message_count: None,
            model: None,
            parent_session_id: None,
            child_session_count: 0,
            nouns: Default::default(),
        };
        let peer = crate::claude_peer::ClaudePeerSession {
            pid: 42,
            session_id: "live-session".into(),
            cwd: Some(PathBuf::from("/project")),
            name: "peer".into(),
            socket_path: PathBuf::from("/tmp/peer.sock"),
            status: Some(crate::claude_peer::ClaudePeerStatus::Busy),
            updated_at_ms: Some(1),
            version: Some("test".into()),
        };

        let value = live_descriptor_value(&descriptor, &[peer]).unwrap();
        assert!(value["live_endpoint"]
            .as_str()
            .is_some_and(|endpoint| endpoint.starts_with("cc-peer:v1:42:peer:")));
    }

    struct EndingRuntime {
        handle: RuntimeHandle,
        event: Option<HarnessEvent>,
    }

    #[async_trait]
    impl RuntimeConnection for EndingRuntime {
        fn handle(&self) -> &RuntimeHandle {
            &self.handle
        }

        async fn send_input(&mut self, _input: RuntimeInput) -> crate::Result<Option<String>> {
            unreachable!("ending runtime does not accept input")
        }

        async fn next_event(&mut self) -> crate::Result<Option<HarnessEvent>> {
            Ok(self.event.take())
        }

        async fn interrupt(&mut self) -> crate::Result<()> {
            Ok(())
        }

        async fn respond(&mut self, _request_id: Value, _response: Value) -> crate::Result<()> {
            Ok(())
        }

        async fn close(&mut self) -> crate::Result<()> {
            Ok(())
        }
    }

    fn ending_runtime(event: Option<HarnessEvent>) -> Box<dyn RuntimeConnection> {
        Box::new(EndingRuntime {
            handle: RuntimeHandle {
                harness: HarnessId::from(HarnessId::CLAUDE_CODE),
                runtime_id: "ending-session".into(),
                endpoint: RuntimeEndpoint::LocalProcess {
                    pid: None,
                    command: vec!["ending-runtime".into()],
                    protocol: "test".into(),
                },
            },
            event,
        })
    }

    fn request(id: u64, method: &str, params: Value) -> Value {
        json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})
    }

    // ---- ORCH-6: conversation nouns on `sessions.*` ----------------------

    fn hermes_store() -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hermes_home/state.db")
    }

    /// The discovery response for the Hermes fixture home, with the one
    /// machine-specific value (the absolute store path) replaced so the exact
    /// same JSON can be committed and replayed by the UI story.
    fn hermes_discovery(params: Value) -> Value {
        let mut response =
            HarnessSessionService::new().handle(request(1, "harness.v1.sessions.discover", params));
        let store = hermes_store().display().to_string();
        for session in response["result"]["sessions"]
            .as_array_mut()
            .expect("sessions array")
        {
            if session["locator"]["storage"]["path"] == json!(store) {
                session["locator"]["storage"]["path"] = json!("<fixtures>/hermes_home/state.db");
            }
            // `activity` reports a wall-clock observation instant, not a fact
            // about the session; it would make this response differ on every
            // call. The nouns under test are all session facts.
            session.as_object_mut().unwrap().remove("activity");
        }
        response["result"].take()
    }

    fn hermes_query() -> Value {
        json!({
            "harnesses": ["hermes"],
            "homes": {"hermes": hermes_store()},
        })
    }

    fn row<'a>(result: &'a Value, id: &str) -> &'a Value {
        result["sessions"]
            .as_array()
            .expect("sessions array")
            .iter()
            .find(|session| session["locator"]["session_id"] == json!(id))
            .unwrap_or_else(|| panic!("no discovered row for `{id}` in {result:#}"))
    }

    #[test]
    fn orch6_discover_rows_carry_the_conversation_nouns() {
        let result = hermes_discovery(hermes_query());

        // A Telegram DM: reached on a channel, no repo — the workspace IS the
        // channel (D2 precedence), and `main` is not a profile.
        let dm = row(&result, "tg-dm-1");
        assert_eq!(dm["trigger"], json!("channel"));
        assert_eq!(dm["surface"]["platform"], json!("telegram"));
        assert_eq!(dm["surface"]["kind"], json!("dm"));
        assert_eq!(dm["surface"]["chat_id"], json!("123456"));
        assert_eq!(dm["surface"]["participant_id"], json!("u1"));
        assert_eq!(
            dm["workspace"],
            json!({"kind": "channel", "value": "telegram:123456"})
        );
        assert!(dm.get("profile").is_none(), "{dm:#}");

        // A cron fire: recurring, with the job recovered from the minted id.
        let fire = row(&result, "cron_job42_20260902_120000");
        assert_eq!(fire["trigger"], json!("cron"));
        assert_eq!(
            fire["recurrence"],
            json!({"job_id": "job42", "kind": "cron"})
        );
        assert_eq!(fire["workspace"]["kind"], json!("repo"));

        // A profiled group session with a pending handoff: repo workspace
        // wins over the channel, and the chat stays on the surface key.
        let coder = row(&result, "tg-coder-1");
        assert_eq!(coder["trigger"], json!("channel"));
        assert_eq!(coder["profile"], json!("coder"));
        assert_eq!(coder["surface"]["thread_id"], json!("55"));
        assert_eq!(
            coder["surface"]["key"],
            json!("agent:coder:telegram:group:-100777:55")
        );
        assert_eq!(
            coder["workspace"],
            json!({"kind": "repo", "value": "/workspace/project"})
        );
        assert_eq!(
            coder["cross_surface"],
            json!({"state": "pending", "platform": "discord"})
        );

        // A plain ACP session stays human-triggered with no surface at all.
        let acp = row(&result, "cef97234-e8e8-428a-99ab-e8fff4e7e613");
        assert_eq!(acp["trigger"], json!("human"));
        assert!(acp.get("surface").is_none(), "{acp:#}");
        assert_eq!(acp["workspace"], json!({"kind": "none"}));
    }

    #[test]
    fn orch6_discover_filters_by_harness_and_profile() {
        let mut params = hermes_query();
        params["profile"] = json!("coder");
        let result = hermes_discovery(params);
        let ids: Vec<&str> = result["sessions"]
            .as_array()
            .expect("sessions array")
            .iter()
            .map(|session| session["locator"]["session_id"].as_str().unwrap())
            .collect();
        assert_eq!(ids, vec!["tg-coder-1"]);

        // A profile no session is routed through returns nothing rather than
        // silently ignoring the filter.
        let mut missing = hermes_query();
        missing["profile"] = json!("nobody");
        assert_eq!(hermes_discovery(missing)["sessions"], json!([]));

        // The harness filter is `harnesses`; an id no harness answers to is
        // an empty page, never every store on the box.
        let elsewhere = json!({"harnesses": ["codex"], "homes": {"codex": hermes_store()}});
        assert_eq!(hermes_discovery(elsewhere)["sessions"], json!([]));
    }

    #[test]
    fn orch6_load_reports_the_same_nouns_as_discovery() {
        let mut service = HarnessSessionService::new();
        let loaded = service.handle(request(
            1,
            "harness.v1.sessions.load",
            json!({"locator": {
                "harness": "hermes",
                "session_id": "tg-coder-1",
                "storage": {"kind": "file", "path": hermes_store()},
            }}),
        ));
        let session = &loaded["result"]["session"];
        let discovered = hermes_discovery(hermes_query());
        let row = row(&discovered, "tg-coder-1");
        for noun in [
            "trigger",
            "surface",
            "profile",
            "recurrence",
            "cross_surface",
            "workspace",
        ] {
            assert_eq!(
                session[noun],
                row.get(noun).cloned().unwrap_or(Value::Null),
                "`{noun}` disagrees between sessions.load and sessions.discover"
            );
        }
    }

    /// ORCH-10: the fixture homes, as the RPC's `homes` override. Hermes's
    /// home is named by its `state.db`; OpenClaw's is the state directory.
    fn profile_fixture_homes() -> Value {
        let fixtures = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
        json!({
            "hermes": fixtures.join("hermes_home/state.db"),
            "openclaw": fixtures.join("openclaw_home"),
        })
    }

    fn profile_row<'a>(response: &'a Value, harness: &str, name: &str) -> &'a Value {
        response["result"]["profiles"]
            .as_array()
            .unwrap_or_else(|| panic!("no profiles array in {response}"))
            .iter()
            .find(|row| row["harness"] == harness && row["name"] == name)
            .unwrap_or_else(|| panic!("no `{harness}` profile `{name}` in {response}"))
    }

    /// dev/01: every source answers in one row shape, over the committed
    /// fixture homes — the Hermes profile directory and its `state.db`
    /// partition, the OpenClaw agent directories and `openclaw.json`, and
    /// supercode's own presets.
    #[test]
    fn profiles_list_reads_every_source_uniformly() {
        let mut service = HarnessSessionService::new();
        let response = service.handle(request(
            1,
            "harness.v1.profiles.list",
            json!({"homes": profile_fixture_homes()}),
        ));
        assert_eq!(
            response["result"]["schema"],
            crate::profiles::PROFILES_SCHEMA
        );

        let default = profile_row(&response, "hermes", "default");
        assert_eq!(default["kind"], "hermes_profile");
        assert_eq!(default["default"], true);
        assert_eq!(default["routes"], 0);
        assert_eq!(default["sessions"], 11);
        assert_eq!(default["model"], "anthropic/claude-sonnet-4-5");

        let coder = profile_row(&response, "hermes", "coder");
        assert_eq!(coder["kind"], "hermes_profile");
        assert_eq!(coder["default"], false);
        assert_eq!(coder["routes"], 1, "gateway.profile_routes targets coder");
        assert_eq!(coder["sessions"], 1, "state.db profile_name = 'coder'");
        assert_eq!(coder["model"], "anthropic/claude-opus-4-8");
        assert!(coder["home"]
            .as_str()
            .unwrap()
            .ends_with("hermes_home/profiles/coder"));

        let main = profile_row(&response, "openclaw", "main");
        assert_eq!(main["kind"], "openclaw_agent");
        // No entry declares `default: true` (real configs do not), so `main`
        // wins on OpenClaw's own convention rather than alphabetically.
        assert_eq!(main["default"], true);
        assert_eq!(main["routes"], 0);
        assert_eq!(main["sessions"], 4);
        assert_eq!(
            main["model"],
            Value::Null,
            "`agents.defaults.model` is an install default, not this agent's pin"
        );

        let design = profile_row(&response, "openclaw", "design");
        assert_eq!(design["default"], false);
        assert_eq!(design["routes"], 1, "one binding names agentId `design`");
        assert_eq!(design["sessions"], 0);
        assert_eq!(design["model"], "anthropic/claude-opus-4-8");

        let preset = profile_row(&response, "supercode", "supercode-default");
        assert_eq!(preset["kind"], "preset");
        assert_eq!(preset["default"], true);
        assert_eq!(preset["home"], Value::Null);
        assert_eq!(preset["routes"], Value::Null);
    }

    /// Codex's own profiles are `[profiles.<name>]` tables, with the
    /// top-level `profile` key naming the default.
    #[test]
    fn profiles_list_reads_codex_profile_tables() {
        let codex_home = std::env::temp_dir().join(format!(
            "supercode-orch10-codex-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(codex_home.join("sessions")).unwrap();
        std::fs::write(
            codex_home.join("config.toml"),
            "profile = \"review\"\n\n[profiles.review]\nmodel = \"gpt-5.1-codex\"\n\n[profiles.fast]\nmodel = \"gpt-5.1-codex-mini\"\n",
        )
        .unwrap();

        let mut service = HarnessSessionService::new();
        let response = service.handle(request(
            1,
            "harness.v1.profiles.list",
            json!({"harness": "codex", "homes": {"codex": codex_home.join("sessions")}}),
        ));
        let rows = response["result"]["profiles"].as_array().unwrap();
        assert_eq!(rows.len(), 2, "{response}");
        let review = profile_row(&response, "codex", "review");
        assert_eq!(review["kind"], "codex_profile");
        assert_eq!(review["default"], true);
        assert_eq!(review["model"], "gpt-5.1-codex");
        assert_eq!(review["home"], Value::Null);
        assert_eq!(profile_row(&response, "codex", "fast")["default"], false);

        let got = service.handle(request(
            2,
            "harness.v1.profiles.get",
            json!({
                "harness": "codex",
                "name": "fast",
                "homes": {"codex": codex_home.join("sessions")},
            }),
        ));
        assert_eq!(got["result"]["profile"]["model"], "gpt-5.1-codex-mini");
        std::fs::remove_dir_all(&codex_home).ok();
    }

    /// A verb a harness lacks fails with `UnsupportedAction`, never a silent
    /// empty list; an unknown name is an invalid argument, not an empty row.
    #[test]
    fn profiles_refuse_harnesses_without_the_concept() {
        let mut service = HarnessSessionService::new();
        let response = service.handle(request(
            1,
            "harness.v1.profiles.list",
            json!({"harness": "claude-code"}),
        ));
        assert_eq!(response["error"]["code"], -32020, "{response}");

        let missing = service.handle(request(
            2,
            "harness.v1.profiles.get",
            json!({
                "harness": "hermes",
                "name": "no-such-profile",
                "homes": profile_fixture_homes(),
            }),
        ));
        assert_eq!(missing["error"]["code"], -32602, "{missing}");
    }

    /// The two methods are advertised, so a client discovers them from
    /// `harness.v1.capabilities` rather than from documentation.
    #[test]
    fn profiles_methods_are_advertised() {
        let mut service = HarnessSessionService::new();
        let response = service.handle(request(1, "harness.v1.capabilities", json!({})));
        let methods = response["result"]["methods"].as_array().unwrap();
        for method in ["harness.v1.profiles.list", "harness.v1.profiles.get"] {
            assert!(
                methods.iter().any(|entry| entry == method),
                "{method} is not advertised"
            );
        }
    }

    // -----------------------------------------------------------------
    // ORCH-14 — channels
    // -----------------------------------------------------------------

    fn channel_row<'a>(response: &'a Value, harness: &str, name: &str) -> &'a Value {
        response["result"]["channels"]
            .as_array()
            .unwrap_or_else(|| panic!("no channels array in {response}"))
            .iter()
            .find(|row| row["harness"] == harness && row["name"] == name)
            .unwrap_or_else(|| panic!("no `{harness}` channel `{name}` in {response}"))
    }

    fn channels_list(harness: Option<&str>) -> Value {
        let mut params = json!({"homes": profile_fixture_homes()});
        if let Some(harness) = harness {
            params["harness"] = json!(harness);
        }
        HarnessSessionService::new().handle(request(1, "harness.v1.channels.list", params))
    }

    /// dev/01: both sources answer in one row shape over the committed
    /// fixture homes — Hermes's `platforms:` blocks with their `extra` maps,
    /// and OpenClaw's `channels.<name>` entries split per account.
    #[test]
    fn channels_list_reads_both_gateway_harnesses_uniformly() {
        let response = channels_list(None);
        assert_eq!(
            response["result"]["schema"],
            crate::channels::CHANNELS_SCHEMA
        );

        // Hermes: a credentialed platform, a bridged `extra.key` platform,
        // and one the config explicitly disables.
        let telegram = channel_row(&response, "hermes", "telegram");
        assert_eq!(telegram["kind"], "telegram");
        assert_eq!(telegram["enabled"], true);
        assert_eq!(telegram["configured"], true);
        // The `sessions` count is the discovery rows whose surface platform
        // is telegram: the fixture's `agent:main:telegram:…` DM and the
        // `agent:coder:telegram:…` group.
        assert_eq!(telegram["sessions"], 2);
        let api = channel_row(&response, "hermes", "api_server");
        assert_eq!(api["configured"], true, "extra.key is a credential key");
        assert_eq!(api["sessions"], 0);
        let webhook = channel_row(&response, "hermes", "webhook");
        assert_eq!(webhook["enabled"], false);
        // Hermes lists no credential for `webhook`: declaring it is all it
        // needs, so a credential-less entry is still `configured`.
        assert_eq!(webhook["configured"], true);

        // OpenClaw: one row per account, named `<channel>/<accountId>`.
        let linked = channel_row(&response, "openclaw", "slack/T0FIXTURE");
        assert_eq!(linked["kind"], "slack");
        assert_eq!(linked["account"], "T0FIXTURE");
        assert_eq!(linked["enabled"], true);
        assert_eq!(linked["configured"], true);
        let unlinked = channel_row(&response, "openclaw", "slack/T1FIXTURE");
        assert_eq!(unlinked["enabled"], false);
        assert_eq!(
            unlinked["configured"], false,
            "an account with no credential key is not configured"
        );
        // A single-account channel keeps its own name and names its account
        // inline.
        let telegram = channel_row(&response, "openclaw", "telegram");
        assert_eq!(telegram["account"], "hermes-fixture-bot");
        assert_eq!(telegram["configured"], true);

        // `status` is never claimed from a config file.
        for row in response["result"]["channels"].as_array().unwrap() {
            assert_eq!(row["status"], "unknown", "{row}");
        }
    }

    /// dev/01: no field of any emitted row carries a credential. The fixture
    /// homes hold four FAKE credential strings; a row that leaked one — as a
    /// value, an account label, or a name — fails here.
    #[test]
    fn channels_rows_never_carry_a_fixture_secret() {
        let secrets = [
            "FAKE-TOKEN-DO-NOT-EMIT",
            "FAKE-API-SERVER-KEY-DO-NOT-EMIT",
            "FAKE-SLACK-BOT-TOKEN-DO-NOT-EMIT",
            "FAKE-SLACK-APP-TOKEN-DO-NOT-EMIT",
            "FAKE-TELEGRAM-TOKEN-DO-NOT-EMIT",
        ];
        // The strings really are in the fixtures, so this test can fail.
        let fixtures = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
        let raw = format!(
            "{}{}",
            std::fs::read_to_string(fixtures.join("hermes_home/config.yaml")).unwrap(),
            std::fs::read_to_string(fixtures.join("openclaw_home/openclaw.json")).unwrap(),
        );
        for secret in secrets {
            assert!(raw.contains(secret), "fixture no longer holds `{secret}`");
        }

        let emitted = serde_json::to_string(&channels_list(None)["result"]).unwrap();
        for secret in secrets {
            assert!(
                !emitted.contains(secret),
                "`{secret}` leaked into a channel row: {emitted}"
            );
        }
        // Belt and braces: no row FIELD is credential-shaped either, so a
        // future field cannot smuggle one past the literal scan.
        for row in channels_list(None)["result"]["channels"]
            .as_array()
            .unwrap()
        {
            for key in row.as_object().unwrap().keys() {
                let key = key.to_ascii_lowercase();
                assert!(
                    !["token", "key", "secret", "password", "credential"]
                        .iter()
                        .any(|marker| key.ends_with(marker)),
                    "`{key}` is a credential-shaped field on a channel row"
                );
            }
        }
    }

    /// `status` answers one row by name, and refuses an unknown one.
    #[test]
    fn channels_status_reads_one_row_by_name() {
        let mut service = HarnessSessionService::new();
        let got = service.handle(request(
            1,
            "harness.v1.channels.status",
            json!({
                "harness": "openclaw",
                "name": "slack/T0FIXTURE",
                "homes": profile_fixture_homes(),
            }),
        ));
        assert_eq!(got["result"]["channel"]["kind"], "slack");
        assert_eq!(got["result"]["channel"]["account"], "T0FIXTURE");
        assert_eq!(got["result"]["channel"]["status"], "unknown");

        let missing = service.handle(request(
            2,
            "harness.v1.channels.status",
            json!({
                "harness": "openclaw",
                "name": "no-such-channel",
                "homes": profile_fixture_homes(),
            }),
        ));
        assert_eq!(missing["error"]["code"], -32602, "{missing}");
    }

    /// A harness with no channel concept fails with `UnsupportedAction`,
    /// never a silent empty list — Claude Code included, because its channels
    /// are MCP-protocol declarations no config file names.
    #[test]
    fn channels_refuse_harnesses_without_the_concept() {
        let response = channels_list(Some("claude-code"));
        assert_eq!(response["error"]["code"], -32020, "{response}");
        let codex = channels_list(Some("codex"));
        assert_eq!(codex["error"]["code"], -32020, "{codex}");
    }

    /// The harness filter restricts the rows rather than being ignored.
    #[test]
    fn channels_list_filters_by_harness() {
        let response = channels_list(Some("openclaw"));
        let rows = response["result"]["channels"].as_array().unwrap();
        assert!(!rows.is_empty(), "{response}");
        assert!(
            rows.iter().all(|row| row["harness"] == "openclaw"),
            "harness filter leaked: {response}"
        );
    }

    /// Both methods are advertised, so a client discovers them from
    /// `harness.v1.capabilities` rather than from documentation.
    #[test]
    fn channels_methods_are_advertised() {
        let mut service = HarnessSessionService::new();
        let response = service.handle(request(1, "harness.v1.capabilities", json!({})));
        let methods = response["result"]["methods"].as_array().unwrap();
        for method in ["harness.v1.channels.list", "harness.v1.channels.status"] {
            assert!(
                methods.iter().any(|entry| entry == method),
                "{method} is not advertised"
            );
        }
    }

    /// The UI story renders REAL rows: this writes the discovery response the
    /// two assertions above pin into the fixture the Storybook
    /// `Compositions/Universal nouns` stories import, and fails when the
    /// committed copy has drifted from what the service now answers.
    #[test]
    fn orch6_story_fixture_matches_the_live_discovery_response() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../../sdk/ui/stories/fixtures/hermes-discovery.json");
        let mut result = hermes_discovery(hermes_query());
        // `updated_at_ms` is derived from the fixture's own stored timestamps,
        // so the whole response is deterministic; drop only the cursor, which
        // is pagination state rather than a session fact.
        result.as_object_mut().unwrap().remove("next_cursor");
        let rendered = format!("{}\n", serde_json::to_string_pretty(&result).unwrap());
        if std::env::var_os("SUPERCODE_UPDATE_FIXTURES").is_some() {
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(&path, &rendered).unwrap();
        }
        let committed = std::fs::read_to_string(&path).unwrap_or_default();
        assert_eq!(
            committed, rendered,
            "sdk/ui/stories/fixtures/hermes-discovery.json is stale — \
             re-run with SUPERCODE_UPDATE_FIXTURES=1"
        );
    }

    fn pi_locator() -> SessionLocator {
        SessionLocator {
            harness: HarnessId::from(HarnessId::PI),
            session_id: "1e6f2a3b-0000-4000-8000-000000000001".into(),
            storage: StorageLocator::File {
                path: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                    .join("tests/fixtures/pi_session.jsonl"),
            },
        }
    }

    fn opencode_locator() -> SessionLocator {
        let session_id = "ses_fixtureAAAAAAAAAAAAAAA1";
        SessionLocator {
            harness: HarnessId::from(HarnessId::OPENCODE),
            session_id: session_id.into(),
            storage: StorageLocator::Sqlite {
                path: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                    .join("tests/fixtures/opencode_fixture/opencode.db"),
                selector: session_id.into(),
            },
        }
    }

    fn grok_locator() -> SessionLocator {
        SessionLocator {
            harness: HarnessId::from(HarnessId::GROK),
            session_id: "73c09283-4b33-41fa-90f1-0bcb0f7be523".into(),
            storage: StorageLocator::File {
                path: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                    .join("tests/fixtures/grok_session/chat_history.jsonl"),
            },
        }
    }

    // ---- ORCH-11: `harness.v1.skills.list` -------------------------------

    fn fixture_homes() -> Value {
        let fixtures = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
        json!({
            "claude_code": fixtures.join("__absent__"),
            "codex": fixtures.join("__absent__"),
            "opencode": fixtures.join("__absent__"),
            "pi": fixtures.join("__absent__"),
            "agents": fixtures.join("__absent__"),
            "hermes": fixtures.join("hermes_home"),
            "openclaw": fixtures.join("openclaw_home"),
        })
    }

    fn skills_rows(params: Value) -> Vec<Value> {
        let response =
            HarnessSessionService::new().handle(request(1, "harness.v1.skills.list", params));
        assert!(response.get("error").is_none(), "{response:#}");
        response["result"].as_array().cloned().unwrap_or_default()
    }

    /// The uniform row over two harnesses at once, from the harnesses' own
    /// skill roots: name, harness, scope, location, description, version.
    #[test]
    fn skills_list_reads_the_hermes_and_openclaw_roots() {
        let fixtures = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
        let rows = skills_rows(json!({
            "homes": fixture_homes(),
            "cwd": fixtures.join("hermes_home"),
        }));
        let arxiv = rows
            .iter()
            .find(|row| row["name"] == json!("arxiv-search"))
            .unwrap_or_else(|| panic!("no arxiv row in {rows:#?}"));
        assert_eq!(arxiv["harness"], json!(HarnessId::HERMES));
        assert_eq!(arxiv["scope"], json!("user"));
        assert_eq!(arxiv["version"], json!("1.4.0"));
        assert!(arxiv["location"]
            .as_str()
            .unwrap()
            .ends_with("hermes_home/skills/research/arxiv"));

        // A directory with no SKILL.md still lists, by directory name.
        let bare = rows
            .iter()
            .find(|row| row["name"] == json!("bare-skill"))
            .unwrap_or_else(|| panic!("no bare-skill row in {rows:#?}"));
        assert_eq!(bare["enabled"], json!(null));
        assert!(bare.get("description").is_none());

        let demo = rows
            .iter()
            .find(|row| row["name"] == json!("clawhub-demo"))
            .unwrap_or_else(|| panic!("no clawhub-demo row in {rows:#?}"));
        assert_eq!(demo["harness"], json!(HarnessId::OPENCLAW));
        assert_eq!(demo["scope"], json!("managed"));
        assert_eq!(demo["enabled"], json!(false));
    }

    /// Both filters select against the same rows.
    #[test]
    fn skills_list_filters_by_harness_and_scope() {
        let fixtures = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
        let hermes = skills_rows(json!({
            "homes": fixture_homes(),
            "cwd": fixtures.join("hermes_home"),
            "harness": HarnessId::HERMES,
        }));
        assert!(!hermes.is_empty());
        assert!(hermes
            .iter()
            .all(|row| row["harness"] == json!(HarnessId::HERMES)));

        let managed = skills_rows(json!({
            "homes": fixture_homes(),
            "cwd": fixtures.join("openclaw_home"),
            "harness": HarnessId::OPENCLAW,
            "scope": "managed",
        }));
        assert_eq!(managed.len(), 1, "{managed:#?}");
        assert_eq!(managed[0]["name"], json!("clawhub-demo"));

        let bundled = skills_rows(json!({
            "homes": fixture_homes(),
            "cwd": fixtures.join("openclaw_home"),
            "harness": HarnessId::OPENCLAW,
            "scope": "bundled",
        }));
        assert!(bundled.is_empty(), "{bundled:#?}");
    }

    /// A harness supercode has no skills root for is refused by name, not
    /// answered with an empty list.
    #[test]
    fn skills_list_refuses_an_unknown_harness() {
        let response = HarnessSessionService::new().handle(request(
            1,
            "harness.v1.skills.list",
            json!({"harness": "not-a-harness", "homes": fixture_homes()}),
        ));
        assert_eq!(response["error"]["code"], json!(-32020), "{response:#}");
        assert!(response["error"]["message"]
            .as_str()
            .unwrap()
            .contains("not-a-harness"));
    }

    /// The method is advertised, and its SDK operation resolves it.
    #[test]
    fn skills_list_is_an_advertised_method_and_sdk_operation() {
        assert!(HARNESS_SERVICE_METHODS.contains(&"harness.v1.skills.list"));
        assert_eq!(
            SdkOperation::from_method("harness.v1.skills.list"),
            Some(SdkOperation::SkillsList)
        );
    }

    // ---- ORCH-22: `harness.v1.skills.install|remove` ----------------------

    /// Both controlled verbs are advertised and resolve to their operation.
    #[test]
    fn skills_install_and_remove_are_advertised_methods_and_sdk_operations() {
        assert!(HARNESS_SERVICE_METHODS.contains(&"harness.v1.skills.install"));
        assert!(HARNESS_SERVICE_METHODS.contains(&"harness.v1.skills.remove"));
        assert_eq!(
            SdkOperation::from_method("harness.v1.skills.install"),
            Some(SdkOperation::SkillsInstall)
        );
        assert_eq!(
            SdkOperation::from_method("harness.v1.skills.remove"),
            Some(SdkOperation::SkillsRemove)
        );
    }

    /// The directory door, end to end over the RPC: a local package lands in
    /// Claude Code's own user root and the outcome carries the operation and
    /// the row the ORCH-11 loader reads back.
    #[test]
    fn skills_install_and_remove_drive_the_directory_door() {
        let root = std::env::temp_dir().join(format!(
            "supercode-orch22-rpc-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let source = root.join("probe-src");
        std::fs::create_dir_all(&source).unwrap();
        std::fs::write(
            source.join("SKILL.md"),
            "---\nname: orch22-rpc\ndescription: a probe\n---\nbody\n",
        )
        .unwrap();
        let homes = json!({
            "claude_code": root.join("claude_home"),
            "codex": root.join("__absent__"),
            "opencode": root.join("__absent__"),
            "pi": root.join("__absent__"),
            "hermes": root.join("__absent__"),
            "openclaw": root.join("__absent__"),
            "agents": root.join("__absent__"),
        });

        let mut service = HarnessSessionService::new();
        let installed = service.handle(request(
            1,
            "harness.v1.skills.install",
            json!({
                "harness": HarnessId::CLAUDE_CODE,
                "source": source,
                "scope": "user",
                "cwd": root,
                "homes": homes,
            }),
        ));
        let result = &installed["result"];
        assert_eq!(result["name"], json!("orch22-rpc"), "{installed:#}");
        assert_eq!(result["verb"], json!("install"));
        assert!(result["ran"]
            .as_str()
            .is_some_and(|ran| ran.starts_with("cp -R ")));
        assert_eq!(result["skill"]["scope"], json!("user"));

        let removed = service.handle(request(
            2,
            "harness.v1.skills.remove",
            json!({
                "harness": HarnessId::CLAUDE_CODE,
                "name": "orch22-rpc",
                "scope": "user",
                "cwd": root,
                "homes": homes,
            }),
        ));
        assert_eq!(removed["result"]["removed"], json!(true), "{removed:#}");
        assert!(!root.join("claude_home/skills/orch22-rpc").exists());
        std::fs::remove_dir_all(&root).ok();
    }

    /// OpenClaw publishes no `skills remove` at the pin, so the uniform verb
    /// refuses with UnsupportedAction instead of deleting files itself.
    #[test]
    fn skills_remove_refuses_openclaw_at_the_pin() {
        let response = HarnessSessionService::new().handle(request(
            1,
            "harness.v1.skills.remove",
            json!({"harness": HarnessId::OPENCLAW, "name": "clawhub-demo"}),
        ));
        assert_eq!(response["error"]["code"], json!(-32020), "{response:#}");
        assert!(response["error"]["message"]
            .as_str()
            .unwrap()
            .contains("no `skills remove` verb"));
    }

    /// A harness with no skills root at all is refused by name, with the
    /// same sentence `skills.list` gives it.
    #[test]
    fn skills_install_refuses_a_harness_without_a_skills_root() {
        let response = HarnessSessionService::new().handle(request(
            1,
            "harness.v1.skills.install",
            json!({"harness": "not-a-harness", "source": "/tmp/x"}),
        ));
        assert_eq!(response["error"]["code"], json!(-32020), "{response:#}");
        assert!(response["error"]["message"]
            .as_str()
            .unwrap()
            .contains("not-a-harness"));
    }

    // ---- ORCH-12: `harness.v1.memory.show|search` ------------------------

    /// `HarnessHomes` for the committed fixture homes. Every root a test does
    /// not name is pinned at an absent path, so a read can never fall through
    /// to this machine's real harness homes. Note `hermes` is the `state.db`
    /// PATH (its parent is HERMES_HOME) and `claude_code` is the `projects`
    /// directory — the same contract discovery uses.
    fn memory_homes() -> Value {
        let fixtures = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
        json!({
            "claude_code": fixtures.join("__absent__"),
            "codex": fixtures.join("__absent__"),
            "opencode": fixtures.join("__absent__"),
            "pi": fixtures.join("__absent__"),
            "grok": fixtures.join("__absent__"),
            "gemini": fixtures.join("__absent__"),
            "goose": fixtures.join("__absent__"),
            "supercode": fixtures.join("__absent__"),
            "hermes": fixtures.join("hermes_home/state.db"),
            "openclaw": fixtures.join("openclaw_home"),
        })
    }

    fn memory_call_ok(method: &str, params: Value, key: &str) -> Vec<Value> {
        let response = HarnessSessionService::new().handle(request(1, method, params));
        assert!(response.get("error").is_none(), "{response:#}");
        assert_eq!(response["result"]["schema"], json!("supercode.memory.v1"));
        response["result"][key]
            .as_array()
            .cloned()
            .unwrap_or_default()
    }

    fn memory_documents(params: Value) -> Vec<Value> {
        memory_call_ok("harness.v1.memory.show", params, "documents")
    }

    fn memory_matches(params: Value) -> Vec<Value> {
        memory_call_ok("harness.v1.memory.search", params, "matches")
    }

    fn find_document<'a>(rows: &'a [Value], profile: &str, name: &str) -> &'a Value {
        rows.iter()
            .find(|row| row["profile"] == profile && row["name"] == name)
            .unwrap_or_else(|| panic!("no `{profile}` document `{name}` in {rows:#?}"))
    }

    /// Hermes: the built-in `MEMORY.md`/`USER.md` pair and the `memories/`
    /// topic files, for HERMES_HOME itself and for every profile home.
    #[test]
    fn memory_show_reads_the_hermes_profile_homes() {
        let rows = memory_documents(json!({"harness": "hermes", "homes": memory_homes()}));

        let notes = find_document(&rows, "default", "MEMORY.md");
        assert_eq!(notes["harness"], "hermes");
        assert_eq!(notes["scope"], "user");
        assert!(notes["size"].as_u64().unwrap() > 0);
        assert!(notes["updated_at"].is_string(), "{notes:#?}");
        // The default answer previews the head and never the whole body.
        assert!(notes.get("content").is_none(), "{notes:#?}");
        assert_eq!(notes["truncated"], true);
        assert_eq!(notes["preview"].as_array().unwrap().len(), 5);

        let user = find_document(&rows, "default", "USER.md");
        assert_eq!(user["scope"], "user");
        assert!(user["preview"]
            .as_array()
            .unwrap()
            .iter()
            .any(|line| line.as_str().unwrap().contains("neovim")));

        let topic = find_document(&rows, "default", "memories/2026-09-01-notes.md");
        assert!(topic["path"]
            .as_str()
            .unwrap()
            .ends_with("hermes_home/memories/2026-09-01-notes.md"));

        // Profile mode points HERMES_HOME at `<root>/profiles/<name>`.
        let coder = find_document(&rows, "coder", "MEMORY.md");
        assert_eq!(coder["scope"], "profile");
        assert!(coder["path"]
            .as_str()
            .unwrap()
            .ends_with("hermes_home/profiles/coder/MEMORY.md"));
    }

    /// `full` is the only way a body crosses the wire, and `profile` narrows
    /// the read to one home.
    #[test]
    fn memory_show_returns_bodies_only_under_full_and_narrows_by_profile() {
        let rows = memory_documents(json!({
            "harness": "hermes",
            "profile": "coder",
            "full": true,
            "homes": memory_homes(),
        }));
        assert!(
            rows.iter().all(|row| row["profile"] == "coder"),
            "{rows:#?}"
        );
        let coder = find_document(&rows, "coder", "MEMORY.md");
        assert!(coder["content"]
            .as_str()
            .expect("full returns the body")
            .contains("anthropic/claude-opus-4-8"));
    }

    /// OpenClaw: memory-core's files under each agent's workspace —
    /// `<state>/workspace` for the default agent, `<state>/workspace-<id>`
    /// for any other.
    #[test]
    fn memory_show_reads_the_openclaw_agent_workspaces() {
        let rows = memory_documents(json!({"harness": "openclaw", "homes": memory_homes()}));

        let main = find_document(&rows, "main", "MEMORY.md");
        assert_eq!(main["scope"], "agent");
        assert!(main["path"]
            .as_str()
            .unwrap()
            .ends_with("openclaw_home/workspace/MEMORY.md"));

        let topic = find_document(&rows, "main", "memory/2026-09-01-standup.md");
        assert!(topic["path"]
            .as_str()
            .unwrap()
            .ends_with("openclaw_home/workspace/memory/2026-09-01-standup.md"));

        let design = find_document(&rows, "design", "MEMORY.md");
        assert!(design["path"]
            .as_str()
            .unwrap()
            .ends_with("openclaw_home/workspace-design/MEMORY.md"));
    }

    /// Claude Code: the auto-memory directory of the project the working tree
    /// belongs to, keyed by the enclosing git repository.
    #[test]
    fn memory_show_reads_a_claude_code_project_auto_memory_directory() {
        let scratch = std::env::temp_dir().join(format!(
            "supercode-orch12-cc-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let project = scratch.join("repo");
        std::fs::create_dir_all(project.join(".git")).unwrap();
        // Auto-memory is shared across a repo's worktrees, so a nested
        // working directory must resolve to the repo's own project dir.
        let worktree = project.join("crates/harness");
        std::fs::create_dir_all(&worktree).unwrap();
        let slug: String = project
            .to_string_lossy()
            .chars()
            .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
            .collect();
        let projects = scratch.join("claude/projects");
        let memory = projects.join(&slug).join("memory");
        std::fs::create_dir_all(&memory).unwrap();
        std::fs::write(
            memory.join("MEMORY.md"),
            "# index\n- [build box](build-box.md) — the pinned harnesses\n",
        )
        .unwrap();
        std::fs::write(
            memory.join("build-box.md"),
            "hermes 0.21.0 and openclaw 2026.7.1-2 are the pins\n",
        )
        .unwrap();

        let mut homes = memory_homes();
        homes["claude_code"] = json!(projects);
        let rows = memory_documents(json!({
            "harness": "claude-code",
            "cwd": worktree,
            "homes": homes,
        }));
        let index = find_document(&rows, &slug, "MEMORY.md");
        assert_eq!(index["harness"], "claude-code");
        assert_eq!(index["scope"], "project");
        let topic = find_document(&rows, &slug, "build-box.md");
        assert!(topic["preview"]
            .as_array()
            .unwrap()
            .iter()
            .any(|line| line.as_str().unwrap().contains("2026.7.1-2")));

        let hits = memory_matches(json!({
            "harness": "claude-code",
            "query": "pinned harnesses",
            "cwd": worktree,
            "homes": homes,
        }));
        assert_eq!(hits.len(), 1, "{hits:#?}");
        assert_eq!(hits[0]["name"], "MEMORY.md");
        assert_eq!(hits[0]["line"], 2);

        let _ = std::fs::remove_dir_all(&scratch);
    }

    /// A config-less OpenClaw install declares no default agent, but
    /// memory-core still resolves ONE agent to the default `workspace`
    /// directory — the same `main`-then-first convention the profile rows
    /// use. Measured against `openclaw memory status` on the pinned CLI
    /// (`docs/interop/research/orch12-memory-receipt-2026-09-03.json`).
    #[test]
    fn memory_show_resolves_the_default_workspace_without_an_openclaw_config() {
        let state = std::env::temp_dir().join(format!(
            "supercode-orch12-oc-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        // No `openclaw.json`: only the agent home the gateway creates.
        std::fs::create_dir_all(state.join("agents/main/agent")).unwrap();
        std::fs::create_dir_all(state.join("workspace")).unwrap();
        std::fs::write(
            state.join("workspace/MEMORY.md"),
            "the gateway websocket needs credentials\n",
        )
        .unwrap();

        let mut homes = memory_homes();
        homes["openclaw"] = json!(state);
        let rows = memory_documents(json!({"harness": "openclaw", "homes": homes}));
        assert_eq!(rows.len(), 1, "{rows:#?}");
        let row = find_document(&rows, "main", "MEMORY.md");
        assert_eq!(row["scope"], "agent");
        assert!(row["path"]
            .as_str()
            .unwrap()
            .ends_with("workspace/MEMORY.md"));

        let _ = std::fs::remove_dir_all(&state);
    }

    /// Search is a plain scan over the same documents: a hit carries the
    /// path, line and excerpt; a miss is an empty list, not an error.
    #[test]
    fn memory_search_reports_hits_by_line_and_misses_as_empty() {
        let hit = memory_matches(json!({
            "harness": "hermes",
            "query": "NEOVIM",
            "homes": memory_homes(),
        }));
        assert_eq!(hit.len(), 1, "{hit:#?}");
        assert_eq!(hit[0]["harness"], "hermes");
        assert_eq!(hit[0]["name"], "USER.md");
        assert_eq!(hit[0]["scope"], "user");
        assert_eq!(hit[0]["line"], 5);
        assert!(hit[0]["excerpt"].as_str().unwrap().contains("neovim"));

        // A regular expression reaches the same lines.
        let regex = memory_matches(json!({
            "harness": "hermes",
            "query": "neo(vim|vi)",
            "regex": true,
            "homes": memory_homes(),
        }));
        assert_eq!(regex.len(), 1, "{regex:#?}");

        let miss = memory_matches(json!({
            "harness": "hermes",
            "query": "no-memory-line-says-this",
            "homes": memory_homes(),
        }));
        assert!(miss.is_empty(), "{miss:#?}");
    }

    /// The uniform-verb contract: a harness with no memory store at the pin
    /// is refused by name, and `session` only selects a Claude Code project.
    #[test]
    fn memory_refuses_harnesses_without_a_store_and_misplaced_session_scoping() {
        for method in ["harness.v1.memory.show", "harness.v1.memory.search"] {
            let response = HarnessSessionService::new().handle(request(
                1,
                method,
                json!({"harness": "codex", "query": "anything", "homes": memory_homes()}),
            ));
            assert_eq!(response["error"]["code"], json!(-32020), "{response:#}");
            assert!(response["error"]["message"]
                .as_str()
                .unwrap()
                .contains("codex"));
        }

        let response = HarnessSessionService::new().handle(request(
            1,
            "harness.v1.memory.show",
            json!({"harness": "hermes", "session": "abc", "homes": memory_homes()}),
        ));
        assert_eq!(response["error"]["code"], json!(-32020), "{response:#}");

        // `harness` is not optional: memory documents are the user's prose.
        let response = HarnessSessionService::new().handle(request(
            1,
            "harness.v1.memory.show",
            json!({"homes": memory_homes()}),
        ));
        assert_eq!(response["error"]["code"], json!(-32602), "{response:#}");
    }

    /// Both methods are advertised, and their SDK operations resolve them.
    #[test]
    fn memory_methods_are_advertised_and_map_to_sdk_operations() {
        assert!(HARNESS_SERVICE_METHODS.contains(&"harness.v1.memory.show"));
        assert!(HARNESS_SERVICE_METHODS.contains(&"harness.v1.memory.search"));
        assert_eq!(
            SdkOperation::from_method("harness.v1.memory.show"),
            Some(SdkOperation::MemoryShow)
        );
        assert_eq!(
            SdkOperation::from_method("harness.v1.memory.search"),
            Some(SdkOperation::MemorySearch)
        );
    }

    // ---- ORCH-9: `harness.v1.approvals.list` -----------------------------

    /// A runtime that raises one protocol request and then goes quiet, so a
    /// single poll delivers the request without closing the connection.
    struct RequestingRuntime {
        handle: RuntimeHandle,
        events: std::collections::VecDeque<HarnessEvent>,
        answered: std::sync::Arc<std::sync::Mutex<Vec<Value>>>,
    }

    #[async_trait]
    impl RuntimeConnection for RequestingRuntime {
        fn handle(&self) -> &RuntimeHandle {
            &self.handle
        }

        async fn send_input(&mut self, _input: RuntimeInput) -> crate::Result<Option<String>> {
            unreachable!("this runtime only raises requests")
        }

        async fn next_event(&mut self) -> crate::Result<Option<HarnessEvent>> {
            match self.events.pop_front() {
                Some(event) => Ok(Some(event)),
                // Quiet, not closed: `poll_sdk_events` times out and leaves
                // the connection open, the way a runtime blocked on a
                // permission request behaves.
                None => std::future::pending().await,
            }
        }

        async fn interrupt(&mut self) -> crate::Result<()> {
            Ok(())
        }

        async fn respond(&mut self, request_id: Value, response: Value) -> crate::Result<()> {
            // Both halves are recorded: ORCH-20 has to prove not just that the
            // right request was answered but that the door received its own
            // reply envelope.
            self.answered
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(json!({"request_id": request_id, "response": response}));
            Ok(())
        }

        async fn close(&mut self) -> crate::Result<()> {
            Ok(())
        }
    }

    fn requesting_runtime(
        harness: &str,
        events: Vec<HarnessEvent>,
        answered: std::sync::Arc<std::sync::Mutex<Vec<Value>>>,
    ) -> Box<dyn RuntimeConnection> {
        requesting_runtime_named(harness, "hermes-live-session", events, answered)
    }

    fn requesting_runtime_named(
        harness: &str,
        runtime_id: &str,
        events: Vec<HarnessEvent>,
        answered: std::sync::Arc<std::sync::Mutex<Vec<Value>>>,
    ) -> Box<dyn RuntimeConnection> {
        Box::new(RequestingRuntime {
            handle: RuntimeHandle {
                harness: HarnessId::from(harness),
                runtime_id: runtime_id.into(),
                endpoint: RuntimeEndpoint::LocalProcess {
                    pid: None,
                    command: vec!["hermes-acp".into()],
                    protocol: "acp".into(),
                },
            },
            events: events.into(),
            answered,
        })
    }

    fn permission_event(id: u64, title: &str) -> HarnessEvent {
        HarnessEvent {
            sequence: None,
            kind: "session/request_permission".into(),
            payload: json!({
                "jsonrpc": "2.0",
                "id": id,
                "method": "session/request_permission",
                "params": {
                    "sessionId": "hermes-live-session",
                    "toolCall": {"toolCallId": "call-1", "title": title, "kind": "execute"},
                    "options": [
                        {"optionId": "allow_once", "name": "Allow once", "kind": "allow_once"},
                        {"optionId": "allow_for_session", "name": "Allow for session", "kind": "allow_always"},
                        {"optionId": "deny", "name": "Deny", "kind": "reject_once"},
                    ],
                },
            }),
        }
    }

    fn approvals(service: &mut HarnessSessionService, params: Value) -> Value {
        let response = service.handle(request(1, "harness.v1.approvals.list", params));
        assert!(response.get("error").is_none(), "{response:#}");
        response["result"].clone()
    }

    /// ORC-2 dev/01: the same uniform loop over the CLAUDE CODE door. The
    /// `can_use_tool` control request the CLI raises to its registered
    /// permission handler lists as one pending row, `approvals.resolve <id>
    /// allow_once` sends the `{behavior}` result the CLI accepts through
    /// `runtimes.respond`, and the row is gone. The frame is the one claude
    /// 2.1.258 wrote, transcribed from
    /// `docs/interop/research/orc2-claude-respond-receipt-2026-09-04.json`.
    #[tokio::test]
    async fn a_claude_code_permission_request_lists_and_resolves_on_the_uniform_door() {
        let answered = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let mut service = HarnessSessionService::new();
        service.runtimes.insert(
            "runtime-cc".into(),
            requesting_runtime_named(
                HarnessId::CLAUDE_CODE,
                "claude-live-session",
                vec![HarnessEvent {
                    sequence: None,
                    kind: "control_request".into(),
                    payload: json!({
                        "type": "control_request",
                        "request_id": "053f8a2d-3445-4011-a259-4261b31c7326",
                        "request": {
                            "subtype": "can_use_tool",
                            "tool_name": "Bash",
                            "display_name": "Bash",
                            "input": {"command": "touch probe-artifact.txt"},
                            "tool_use_id": "toolu_mock_1",
                        },
                    }),
                }],
                answered.clone(),
            ),
        );

        let notifications = service.poll_runtimes().await;
        assert_eq!(notifications.len(), 1, "{notifications:#?}");

        let rows = approvals(&mut service, json!({"harness": HarnessId::CLAUDE_CODE}));
        assert_eq!(rows.as_array().map(Vec::len), Some(1), "{rows:#}");
        let row = &rows[0];
        assert_eq!(row["id"], "runtime-cc/053f8a2d-3445-4011-a259-4261b31c7326");
        assert_eq!(row["harness"], HarnessId::CLAUDE_CODE);
        assert_eq!(row["status"], "pending");
        assert_eq!(row["subject"], "Bash touch probe-artifact.txt");
        assert_eq!(row["runtime_id"], "claude-live-session");
        assert_eq!(
            row["options"]
                .as_array()
                .unwrap()
                .iter()
                .map(|option| option["id"].as_str().unwrap())
                .collect::<Vec<_>>(),
            vec!["allow", "deny"],
        );

        let response = resolve(
            &mut service,
            json!({"id": row["id"], "decision": "allow_once"}),
        )
        .await;
        assert!(response.get("error").is_none(), "{response:#}");
        assert_eq!(response["result"]["option_id"], "allow");
        assert_eq!(
            answered
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .as_slice(),
            &[json!({
                "request_id": "053f8a2d-3445-4011-a259-4261b31c7326",
                "response": {"behavior": "allow"},
            })],
        );
        assert_eq!(
            approvals(&mut service, json!({"harness": HarnessId::CLAUDE_CODE}))
                .as_array()
                .map(Vec::len),
            Some(0),
        );
    }

    /// dev/01: a live ACP permission request raised on a driven runtime is
    /// listable while the turn is blocked on it, and stops being listable
    /// the moment `runtimes.respond` answers it.
    #[tokio::test]
    async fn a_live_permission_request_lists_until_it_is_answered() {
        let answered = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let mut service = HarnessSessionService::new();
        service.runtimes.insert(
            "runtime-1".into(),
            requesting_runtime(
                HarnessId::HERMES,
                vec![permission_event(7, "rm -rf build")],
                answered.clone(),
            ),
        );

        let notifications = service.poll_runtimes().await;
        assert_eq!(notifications.len(), 1, "{notifications:#?}");

        let rows = approvals(&mut service, json!({}));
        assert_eq!(rows.as_array().map(Vec::len), Some(1), "{rows:#}");
        let row = &rows[0];
        assert_eq!(row["id"], "runtime-1/7");
        assert_eq!(row["harness"], HarnessId::HERMES);
        assert_eq!(row["kind"], "live");
        assert_eq!(row["status"], "pending");
        assert_eq!(row["subject"], "rm -rf build");
        assert_eq!(row["session_id"], "hermes-live-session");
        assert_eq!(row["runtime_id"], "hermes-live-session");
        assert!(row["requested_at_ms"].as_i64().is_some(), "{row:#}");
        assert!(
            row["age_ms"].as_i64().is_some_and(|age| age >= 0),
            "{row:#}"
        );
        assert_eq!(
            row["options"]
                .as_array()
                .unwrap()
                .iter()
                .map(|option| option["id"].as_str().unwrap())
                .collect::<Vec<_>>(),
            vec!["allow_once", "allow_for_session", "deny"],
        );

        // The filters select against the same rows.
        assert_eq!(
            approvals(&mut service, json!({"harness": HarnessId::HERMES}))
                .as_array()
                .map(Vec::len),
            Some(1),
        );
        assert_eq!(
            approvals(&mut service, json!({"session": "some-other-session"}))
                .as_array()
                .map(Vec::len),
            Some(0),
        );

        let response = service
            .handle_async(request(
                2,
                "harness.v1.runtimes.respond",
                json!({
                    "connection": "runtime-1",
                    "request_id": 7,
                    "response": {"outcome": {"outcome": "selected", "optionId": "allow_once"}},
                }),
            ))
            .await;
        assert!(response.get("error").is_none(), "{response:#}");
        assert_eq!(
            answered
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .as_slice(),
            &[json!({
                "request_id": 7,
                "response": {"outcome": {"outcome": "selected", "optionId": "allow_once"}},
            })],
        );

        let rows = approvals(&mut service, json!({}));
        assert_eq!(rows.as_array().map(Vec::len), Some(0), "{rows:#}");
    }

    /// dev/01: supercode's own queued subagent approvals list through the
    /// same door, carrying the outcome the record holds.
    #[test]
    fn queued_subagent_approvals_list_through_the_same_door() {
        let queue = std::sync::Arc::new(std::sync::Mutex::new(vec![
            crate::subagents::QueuedApproval {
                child_agent_id: "child-7".into(),
                tool: "shell".into(),
                subject: Some("cargo publish --dry-run".into()),
                queued_at_ms: 1,
                outcome: None,
            },
            crate::subagents::QueuedApproval {
                child_agent_id: "child-8".into(),
                tool: "write_file".into(),
                subject: None,
                queued_at_ms: 2,
                outcome: Some(crate::subagents::QueuedApprovalOutcome::Denied),
            },
        ]));
        let mut service = HarnessSessionService::new();
        service.observe_subagent_approvals(queue);

        let rows = approvals(&mut service, json!({}));
        assert_eq!(rows.as_array().map(Vec::len), Some(2), "{rows:#}");
        assert_eq!(rows[0]["id"], "supercode/subagent/child-7/1/0");
        assert_eq!(rows[0]["harness"], HarnessId::SUPERCODE);
        assert_eq!(rows[0]["status"], "pending");
        assert_eq!(rows[0]["subject"], "shell cargo publish --dry-run");
        assert_eq!(rows[1]["status"], "denied");
        assert!(rows[1]["options"].as_array().unwrap().is_empty());

        // `--session` addresses a subagent row by its child agent id.
        let only = approvals(&mut service, json!({"session": "child-8"}));
        assert_eq!(only.as_array().map(Vec::len), Some(1), "{only:#}");
        assert_eq!(only[0]["id"], "supercode/subagent/child-8/2/1");
    }

    /// The uniform-verb contract: an id whose runtime door cannot carry a
    /// protocol request is refused BY NAME rather than answered with an empty
    /// list. Since ORC-2 gave Claude Code a permission-response primitive
    /// every registered harness can carry one, so the refusal is exercised on
    /// an unknown id — and the registered ids are asserted to be accepted.
    #[test]
    fn approvals_list_refuses_a_harness_that_cannot_carry_a_request() {
        let response = HarnessSessionService::new().handle(request(
            1,
            "harness.v1.approvals.list",
            json!({"harness": "not-a-harness"}),
        ));
        assert_eq!(response["error"]["code"], json!(-32020), "{response:#}");
        assert!(response["error"]["message"]
            .as_str()
            .unwrap()
            .contains("not-a-harness"));
        for harness in [HarnessId::CLAUDE_CODE, HarnessId::CODEX] {
            let response = HarnessSessionService::new().handle(request(
                1,
                "harness.v1.approvals.list",
                json!({"harness": harness}),
            ));
            assert!(response.get("error").is_none(), "{harness}: {response:#}");
        }
    }

    /// The method is advertised, its SDK operation resolves it, and the
    /// registry reports the concept as observed for every harness whose
    /// runtime door can carry a request.
    #[test]
    fn approvals_list_is_an_advertised_method_and_an_observed_tier() {
        assert!(HARNESS_SERVICE_METHODS.contains(&"harness.v1.approvals.list"));
        assert_eq!(
            SdkOperation::from_method("harness.v1.approvals.list"),
            Some(SdkOperation::ApprovalsList)
        );
        let registry = harness_support_registry();
        for id in [
            HarnessId::HERMES,
            HarnessId::OPENCLAW,
            HarnessId::CODEX,
            // ORC-2: the Claude Code door answers `can_use_tool`, so its
            // pending_request concept joins the other driven doors.
            HarnessId::CLAUDE_CODE,
        ] {
            let concept = registry
                .harnesses
                .iter()
                .find(|harness| harness.id.as_str() == id)
                .unwrap()
                .orchestration
                .concepts
                .iter()
                .find(|concept| concept.concept == "pending_request")
                .unwrap();
            assert_eq!(concept.observed, crate::ImplementationKind::BuiltIn, "{id}");
            assert!(concept
                .methods
                .iter()
                .any(|method| method == "harness.v1.approvals.list"));
        }
    }

    // ---- ORCH-20: `harness.v1.approvals.resolve` -------------------------

    async fn resolve(service: &mut HarnessSessionService, params: Value) -> Value {
        service
            .handle_async(request(3, "harness.v1.approvals.resolve", params))
            .await
    }

    /// dev/01: the whole loop on a driven runtime — list one pending row,
    /// answer it by ROW ID with one uniform decision, and see it gone. The
    /// door receives its own ACP envelope carrying the option it enumerated.
    #[tokio::test]
    async fn a_listed_row_resolves_with_one_uniform_decision_and_then_is_gone() {
        let answered = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let mut service = HarnessSessionService::new();
        service.runtimes.insert(
            "runtime-1".into(),
            requesting_runtime(
                HarnessId::HERMES,
                vec![permission_event(7, "rm -rf build")],
                answered.clone(),
            ),
        );
        service.poll_runtimes().await;

        let rows = approvals(&mut service, json!({}));
        assert_eq!(rows[0]["id"], "runtime-1/7");

        let response = resolve(
            &mut service,
            json!({"id": "runtime-1/7", "decision": "allow_once"}),
        )
        .await;
        assert!(response.get("error").is_none(), "{response:#}");
        assert_eq!(
            response["result"],
            json!({
                "id": "runtime-1/7",
                "decision": "allow_once",
                "option_id": "allow_once",
                "resolved": true,
            }),
        );
        // The harness's own door was called with its own envelope.
        assert_eq!(
            answered
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .as_slice(),
            &[json!({
                "request_id": 7,
                "response": {"outcome": {"outcome": "selected", "optionId": "allow_once"}},
            })],
        );
        // And the row is gone, the same way `runtimes.respond` drops it.
        assert_eq!(
            approvals(&mut service, json!({})).as_array().map(Vec::len),
            Some(0),
        );
        // Answering it twice is an honest miss, not a silent success.
        let response = resolve(
            &mut service,
            json!({"id": "runtime-1/7", "decision": "allow_once"}),
        )
        .await;
        assert_eq!(response["error"]["code"], json!(-32602), "{response:#}");
    }

    /// dev/01: deny travels the same path and picks the option the request
    /// itself classified as a refusal.
    #[tokio::test]
    async fn deny_selects_the_requests_own_reject_option() {
        let answered = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let mut service = HarnessSessionService::new();
        service.runtimes.insert(
            "runtime-1".into(),
            requesting_runtime(
                HarnessId::HERMES,
                vec![permission_event(11, "git push --force")],
                answered.clone(),
            ),
        );
        service.poll_runtimes().await;

        let response = resolve(
            &mut service,
            json!({"id": "runtime-1/11", "decision": "deny"}),
        )
        .await;
        assert!(response.get("error").is_none(), "{response:#}");
        // `deny` is the optionId whose ACP `kind` is `reject_once`.
        assert_eq!(response["result"]["option_id"], "deny");
        assert_eq!(
            answered
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)[0]["response"],
            json!({"outcome": {"outcome": "selected", "optionId": "deny"}}),
        );
        assert_eq!(
            approvals(&mut service, json!({})).as_array().map(Vec::len),
            Some(0),
        );
    }

    /// dev/01: a decision this request does not offer is refused by name,
    /// listing the ones it does — never silently downgraded to a neighbour.
    #[tokio::test]
    async fn a_decision_the_request_does_not_offer_is_refused_with_the_offered_ones() {
        let answered = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let mut service = HarnessSessionService::new();
        let mut event = permission_event(3, "rm -rf build");
        // A request offering only allow-once and deny, as hermes 0.21.0's
        // edit-approval layer raises one.
        event.payload["params"]["options"] = json!([
            {"optionId": "allow_once", "name": "Allow edit", "kind": "allow_once"},
            {"optionId": "deny", "name": "Deny", "kind": "reject_once"},
        ]);
        service.runtimes.insert(
            "runtime-1".into(),
            requesting_runtime(HarnessId::HERMES, vec![event], answered.clone()),
        );
        service.poll_runtimes().await;

        let response = resolve(
            &mut service,
            json!({"id": "runtime-1/3", "decision": "allow_always"}),
        )
        .await;
        assert_eq!(response["error"]["code"], json!(-32602), "{response:#}");
        let message = response["error"]["message"].as_str().unwrap();
        assert!(message.contains("allow_always"), "{message}");
        assert!(message.contains("allow_once, deny"), "{message}");
        // Nothing was sent, and the request is still waiting for an answer.
        assert!(answered
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .is_empty());
        assert_eq!(
            approvals(&mut service, json!({})).as_array().map(Vec::len),
            Some(1),
        );
    }

    /// dev/01: supercode's own queued subagent row is addressable but not
    /// answerable through this door — it is the parent's audit copy of a
    /// request its own handler answers. Refused by name, never a no-op.
    #[tokio::test]
    async fn a_queued_subagent_row_is_refused_by_name_rather_than_silently_answered() {
        let queue = std::sync::Arc::new(std::sync::Mutex::new(vec![
            crate::subagents::QueuedApproval {
                child_agent_id: "child-7".into(),
                tool: "shell".into(),
                subject: Some("cargo publish --dry-run".into()),
                queued_at_ms: 1,
                outcome: None,
            },
        ]));
        let mut service = HarnessSessionService::new();
        service.observe_subagent_approvals(queue.clone());
        let row = approvals(&mut service, json!({}))[0]["id"]
            .as_str()
            .unwrap()
            .to_string();
        assert_eq!(row, "supercode/subagent/child-7/1/0");

        let response = resolve(&mut service, json!({"id": row, "decision": "allow_once"})).await;
        assert_eq!(response["error"]["code"], json!(-32602), "{response:#}");
        let message = response["error"]["message"].as_str().unwrap();
        assert!(message.contains("queued subagent record"), "{message}");
        assert!(message.contains("request"), "{message}");
        // The audit record is untouched: nothing pretended to answer it.
        assert!(queue
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)[0]
            .outcome
            .is_none());
    }

    /// An id nobody is holding, and a call that names no decision at all,
    /// both fail with a message that says why.
    #[tokio::test]
    async fn an_unknown_row_and_a_missing_decision_are_both_named() {
        let mut service = HarnessSessionService::new();
        let response = resolve(
            &mut service,
            json!({"id": "runtime-9/4", "decision": "deny"}),
        )
        .await;
        assert_eq!(response["error"]["code"], json!(-32602), "{response:#}");
        assert!(response["error"]["message"]
            .as_str()
            .unwrap()
            .contains("runtime-9/4"));

        let response = resolve(&mut service, json!({"id": "runtime-9/4"})).await;
        let message = response["error"]["message"].as_str().unwrap();
        assert!(
            message.contains("allow_once | allow_always | deny"),
            "{message}"
        );

        let response = resolve(
            &mut service,
            json!({"id": "runtime-9/4", "decision": "deny", "option_id": "deny"}),
        )
        .await;
        assert!(response["error"]["message"]
            .as_str()
            .unwrap()
            .contains("not both"));
    }

    /// The method is advertised, its SDK operation resolves it, and every
    /// harness whose runtime door can carry a request reports it on the
    /// CONTROLLED tier beside `runtimes.respond`.
    #[test]
    fn approvals_resolve_is_an_advertised_method_and_a_controlled_tier() {
        assert!(HARNESS_SERVICE_METHODS.contains(&"harness.v1.approvals.resolve"));
        assert_eq!(
            SdkOperation::from_method("harness.v1.approvals.resolve"),
            Some(SdkOperation::ApprovalsResolve)
        );
        assert_eq!(
            SdkOperation::ApprovalsResolve.action_name(),
            "approvals_resolve"
        );
        let registry = harness_support_registry();
        for id in [
            HarnessId::HERMES,
            HarnessId::OPENCLAW,
            HarnessId::CODEX,
            // ORC-2: the Claude Code door answers `can_use_tool`, so its
            // pending_request concept joins the other driven doors.
            HarnessId::CLAUDE_CODE,
        ] {
            let concept = registry
                .harnesses
                .iter()
                .find(|harness| harness.id.as_str() == id)
                .unwrap()
                .orchestration
                .concepts
                .iter()
                .find(|concept| concept.concept == "pending_request")
                .unwrap();
            assert_eq!(
                concept.controlled,
                crate::ImplementationKind::BuiltIn,
                "{id}"
            );
            assert!(
                concept
                    .methods
                    .iter()
                    .any(|method| method == "harness.v1.approvals.resolve"),
                "{id}"
            );
        }
    }

    #[test]
    fn capabilities_are_explicit_and_versioned() {
        let mut service = HarnessSessionService::new();
        let response = service.handle(request(1, "harness.v1.capabilities", json!({})));
        assert_eq!(response["result"]["version"], HARNESS_SERVICE_VERSION);
        assert_eq!(
            response["result"]["sdk"]["schema_version"],
            crate::SDK_SCHEMA_VERSION
        );
        assert_eq!(
            response["result"]["sdk"]["operations"]
                .as_array()
                .unwrap()
                .len(),
            SdkOperation::ALL.len()
        );
        assert_eq!(
            response["result"]["harnesses"].as_array().unwrap().len(),
            11
        );
        assert!(response["result"]["harnesses"]
            .as_array()
            .unwrap()
            .iter()
            .any(|harness| harness == HarnessId::GROK));
        assert!(response["result"]["harnesses"]
            .as_array()
            .unwrap()
            .iter()
            .any(|harness| harness == HarnessId::GOOSE));
    }

    #[test]
    fn handshake_health_uses_protocol_liveness_not_stderr_severity() {
        let noisy_stderr = crate::HarnessEvent {
            sequence: None,
            kind: "transport_stderr".into(),
            payload: json!({"line": "ERROR optional worker AuthorizationRequired"}),
        };
        assert_eq!(handshake_event_failure(&noisy_stderr), None);

        let closed = crate::HarnessEvent {
            sequence: None,
            kind: "transport_closed".into(),
            payload: json!({}),
        };
        assert!(handshake_event_failure(&closed).is_some());
    }

    #[tokio::test]
    async fn runtime_eof_is_notified_and_removed_for_raw_and_explicit_close() {
        let mut service = HarnessSessionService::new();
        service
            .runtimes
            .insert("raw-eof".into(), ending_runtime(None));
        service.runtimes.insert(
            "explicit-close".into(),
            ending_runtime(Some(HarnessEvent {
                sequence: None,
                kind: "transport_closed".into(),
                payload: json!({"message": "native transport exited"}),
            })),
        );

        let notifications = service.poll_runtimes().await;

        assert_eq!(notifications.len(), 2);
        assert!(notifications
            .iter()
            .all(|notification| { notification["params"]["event"]["kind"] == "transport_closed" }));
        assert!(notifications.iter().all(|notification| {
            notification["params"]["session_id"] == "ending-session"
                && notification["params"]["connection"].is_string()
        }));
        let mut sequences = notifications
            .iter()
            .filter_map(|notification| notification["params"]["sequence"].as_u64())
            .collect::<Vec<_>>();
        sequences.sort_unstable();
        assert_eq!(sequences, vec![1, 2]);
        assert!(service.runtimes.is_empty());
    }

    #[test]
    fn support_report_and_grok_default_binding_share_the_registry() {
        let mut service = HarnessSessionService::new();
        let response = service.handle(request(1, "harness.v1.support.report", json!({})));
        assert_eq!(response["result"]["schema"], crate::SUPPORT_REGISTRY_SCHEMA);
        let params = RuntimeBackendParams {
            harness: HarnessId::from(HarnessId::GROK),
            protocol: None,
            launch: None,
            base_url: None,
            policy: RuntimePolicy::Default,
        };
        let backend = match runtime_backend(&params) {
            Ok(backend) => backend,
            Err(_) => panic!("Grok should bind through its registered ACP launch"),
        };
        assert_eq!(backend.harness().as_str(), HarnessId::GROK);
        assert!(backend.capabilities().start_session);
        let registered = harness_support_registry()
            .harnesses
            .into_iter()
            .find(|harness| harness.id.as_str() == HarnessId::GROK)
            .and_then(|harness| harness.runtime.default_launch)
            .unwrap();
        assert!(!registered
            .arguments
            .iter()
            .any(|argument| argument == "--always-approve"));
        assert!(runtime_launch(&params).is_none());

        let yolo = RuntimeBackendParams {
            policy: RuntimePolicy::Yolo,
            ..params
        };
        assert!(runtime_launch(&yolo)
            .unwrap()
            .arguments
            .iter()
            .any(|argument| argument == "--always-approve"));

        let mismatched_protocol = RuntimeBackendParams {
            harness: HarnessId::from(HarnessId::CLAUDE_CODE),
            protocol: Some("acp".into()),
            launch: None,
            base_url: None,
            policy: RuntimePolicy::Default,
        };
        assert!(runtime_backend(&mismatched_protocol).is_err());
    }

    #[test]
    fn load_follow_and_unfollow_share_the_same_locator() {
        let mut service = HarnessSessionService::new();
        let locator = pi_locator();
        let loaded = service.handle(request(
            1,
            "harness.v1.sessions.load",
            json!({"locator": locator}),
        ));
        assert_eq!(
            loaded["result"]["session"]["session_id"],
            locator.session_id
        );

        let followed = service.handle(request(
            2,
            "harness.v1.sessions.follow",
            json!({"locator": locator}),
        ));
        assert_eq!(followed["result"]["subscription"], "sub-1");
        assert_eq!(followed["result"]["initial"]["type"], "session_snapshot");
        assert!(service.poll().is_empty());

        let unfollowed = service.handle(request(
            3,
            "harness.v1.sessions.unfollow",
            json!({"subscription": "sub-1"}),
        ));
        assert_eq!(unfollowed["result"]["removed"], true);
    }

    #[test]
    fn bounded_read_view_excludes_subagents_and_keeps_only_the_tail() {
        let temp = std::env::temp_dir().join(format!(
            "supercode-bounded-view-{}-{}",
            std::process::id(),
            generated_session_id()
        ));
        let path = temp.join("parent.jsonl");
        let subagents = temp.join("parent/subagents");
        std::fs::create_dir_all(&subagents).unwrap();
        let long_last = "x".repeat(300);
        let parent_records = [
            json!({"type":"user","uuid":"u1","parentUuid":null,"message":{"role":"user","content":"first"}}),
            json!({"type":"assistant","uuid":"a1","parentUuid":"u1","message":{"role":"assistant","content":[{"type":"text","text":"middle"}]}}),
            json!({"type":"user","uuid":"u2","parentUuid":"a1","message":{"role":"user","content":long_last}}),
        ];
        std::fs::write(
            &path,
            format!(
                "{}\n",
                parent_records
                    .iter()
                    .map(Value::to_string)
                    .collect::<Vec<_>>()
                    .join("\n")
            ),
        )
        .unwrap();
        std::fs::write(
            subagents.join("agent-child.jsonl"),
            concat!(
                r#"{"type":"user","uuid":"cu","parentUuid":null,"agentId":"child","message":{"role":"user","content":"child work"}}"#,
                "\n",
            ),
        )
        .unwrap();
        let locator = SessionLocator {
            harness: HarnessId::from(HarnessId::CLAUDE_CODE),
            session_id: "parent".into(),
            storage: StorageLocator::File { path },
        };
        let mut service = HarnessSessionService::new();

        let complete = service.handle(request(
            1,
            "harness.v1.sessions.load",
            json!({"locator": locator}),
        ));
        assert_eq!(
            complete["result"]["session"]["subagents"]
                .as_array()
                .unwrap()
                .len(),
            1
        );

        let bounded = service.handle(request(
            2,
            "harness.v1.sessions.load",
            json!({
                "locator": locator,
                "view": {
                    "tail_messages": 1,
                    "max_message_chars": 256,
                    "include_subagents": false
                },
            }),
        ));
        let session = &bounded["result"]["session"];
        assert!(session["subagents"].as_array().unwrap().is_empty());
        assert_eq!(session["messages"].as_array().unwrap().len(), 1);
        assert_eq!(
            session["messages"][0]["content"],
            format!("{}\n…", "x".repeat(256))
        );

        let followed = service.handle(request(
            3,
            "harness.v1.sessions.follow",
            json!({
                "locator": locator,
                "view": {
                    "tail_messages": 1,
                    "max_message_chars": 256,
                    "include_subagents": false
                },
            }),
        ));
        let initial = &followed["result"]["initial"]["session"];
        assert!(initial["subagents"].as_array().unwrap().is_empty());
        assert_eq!(initial["messages"].as_array().unwrap().len(), 1);

        let _ = std::fs::remove_dir_all(&temp);
    }

    #[test]
    fn forty_megabyte_display_load_is_bounded_and_prompt() {
        let temp = std::env::temp_dir().join(format!(
            "supercode-large-display-view-{}-{}",
            std::process::id(),
            generated_session_id()
        ));
        std::fs::create_dir_all(&temp).unwrap();
        let path = temp.join("rollout.jsonl");
        let mut file = std::io::BufWriter::new(std::fs::File::create(&path).unwrap());
        writeln!(
            file,
            r#"{{"timestamp":"2026-01-01T00:00:00Z","type":"session_meta","payload":{{"id":"large-display","cwd":"/tmp"}}}}"#
        )
        .unwrap();
        let padding = "x".repeat(80 * 1024);
        for index in 0..512 {
            let marker = if index == 0 {
                "OLDEST-SHOULD-NOT-LOAD"
            } else if index == 511 {
                "LATEST-MUST-LOAD"
            } else {
                "bulk"
            };
            writeln!(
                file,
                "{}",
                json!({
                    "timestamp": "2026-01-01T00:00:01Z",
                    "type": "response_item",
                    "payload": {
                        "type": "message",
                        "role": "assistant",
                        "content": [{"type": "output_text", "text": format!("{marker}:{padding}")}],
                    },
                })
            )
            .unwrap();
        }
        file.flush().unwrap();
        drop(file);
        assert!(std::fs::metadata(&path).unwrap().len() >= 40 * 1024 * 1024);

        let locator = SessionLocator {
            harness: HarnessId::from(HarnessId::CODEX),
            session_id: "large-display".into(),
            storage: StorageLocator::File { path },
        };
        let started = Instant::now();
        let response = HarnessSessionService::new().handle(request(
            1,
            "harness.v1.sessions.load",
            json!({
                "locator": locator,
                "view": {
                    "tail_messages": 500,
                    "max_message_chars": 1024,
                    "include_subagents": false,
                    "display_history": true,
                },
            }),
        ));
        let elapsed = started.elapsed();
        let wire = response.to_string();
        eprintln!(
            "bounded 40 MiB display load: {elapsed:?}, {} response bytes",
            wire.len()
        );
        assert!(response.get("error").is_none(), "{response:#}");
        assert!(wire.contains("LATEST-MUST-LOAD"));
        assert!(!wire.contains("OLDEST-SHOULD-NOT-LOAD"));
        assert!(
            wire.len() < 2 * 1024 * 1024,
            "bounded wire was {} bytes",
            wire.len()
        );
        assert!(
            elapsed.as_secs_f64() < 3.0,
            "bounded 40 MiB load took {elapsed:?}"
        );

        let _ = std::fs::remove_dir_all(&temp);
    }

    #[test]
    fn forty_megabyte_goose_store_display_load_reads_only_the_tail() {
        let temp = std::env::temp_dir().join(format!(
            "supercode-large-goose-view-{}-{}",
            std::process::id(),
            generated_session_id()
        ));
        std::fs::create_dir_all(&temp).unwrap();
        let path = temp.join("sessions.db");
        let connection = rusqlite::Connection::open(&path).unwrap();
        connection
            .execute_batch(
                "CREATE TABLE sessions (
                    id TEXT PRIMARY KEY, name TEXT NOT NULL, working_dir TEXT NOT NULL,
                    created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
                    session_type TEXT NOT NULL, extension_data TEXT,
                    goose_mode TEXT NOT NULL, provider_name TEXT, model_config_json TEXT,
                    archived_at TEXT
                 );
                 CREATE TABLE messages (
                    id INTEGER PRIMARY KEY, session_id TEXT NOT NULL, message_id TEXT,
                    role TEXT NOT NULL, content_json TEXT NOT NULL,
                    created_timestamp INTEGER NOT NULL, metadata_json TEXT
                 );",
            )
            .unwrap();
        connection
            .execute(
                "INSERT INTO sessions VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, NULL)",
                rusqlite::params![
                    "goose-large",
                    "Large Goose session",
                    "/tmp",
                    "2026-01-01 00:00:00",
                    "2026-01-01 00:00:02",
                    "user",
                    "{}",
                    "auto",
                    "anthropic",
                    r#"{"model_name":"claude-sonnet"}"#,
                ],
            )
            .unwrap();
        let old_content = serde_json::to_string(&vec![json!({
            "type": "text",
            "text": format!("OLDEST-SHOULD-NOT-LOAD:{}", "x".repeat(40 * 1024 * 1024)),
        })])
        .unwrap();
        connection
            .execute(
                "INSERT INTO messages VALUES (1, ?1, 'old', 'user', ?2, 1, '{}')",
                rusqlite::params!["goose-large", old_content],
            )
            .unwrap();
        connection
            .execute(
                "INSERT INTO messages VALUES (2, ?1, 'new', 'assistant', ?2, 2, '{}')",
                rusqlite::params![
                    "goose-large",
                    r#"[{"type":"text","text":"LATEST-MUST-LOAD"}]"#
                ],
            )
            .unwrap();
        drop(connection);
        assert!(std::fs::metadata(&path).unwrap().len() >= 40 * 1024 * 1024);

        let locator = SessionLocator {
            harness: HarnessId::from(HarnessId::GOOSE),
            session_id: "goose-large".into(),
            storage: StorageLocator::Sqlite {
                path,
                selector: "goose-large".into(),
            },
        };
        let started = Instant::now();
        let response = HarnessSessionService::new().handle(request(
            1,
            "harness.v1.sessions.load",
            json!({
                "locator": locator,
                "view": {
                    "tail_messages": 1,
                    "max_message_chars": 1024,
                    "include_subagents": false,
                    "display_history": true,
                },
            }),
        ));
        let elapsed = started.elapsed();
        let wire = response.to_string();
        eprintln!(
            "bounded 40 MiB Goose display load: {elapsed:?}, {} response bytes",
            wire.len()
        );
        assert!(response.get("error").is_none(), "{response:#}");
        assert!(wire.contains("LATEST-MUST-LOAD"));
        assert!(!wire.contains("OLDEST-SHOULD-NOT-LOAD"));
        assert!(
            wire.len() < 64 * 1024,
            "bounded wire was {} bytes",
            wire.len()
        );
        assert!(
            elapsed.as_secs_f64() < 1.0,
            "bounded Goose load took {elapsed:?}"
        );

        let _ = std::fs::remove_dir_all(&temp);
    }

    #[test]
    fn display_view_keeps_codex_assistant_history_across_compaction() {
        let temp = std::env::temp_dir().join(format!(
            "supercode-codex-display-view-{}-{}",
            std::process::id(),
            generated_session_id()
        ));
        std::fs::create_dir_all(&temp).unwrap();
        let path = temp.join("rollout.jsonl");
        std::fs::write(
            &path,
            concat!(
                r#"{"timestamp":"2026-01-01T00:00:00Z","type":"session_meta","payload":{"id":"codex-display","cwd":"/tmp"}}"#,
                "\n",
                r#"{"timestamp":"2026-01-01T00:00:01Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"old prompt"}]}}"#,
                "\n",
                r#"{"timestamp":"2026-01-01T00:00:02Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"old answer"}]}}"#,
                "\n",
                r#"{"timestamp":"2026-01-01T00:00:03Z","type":"compacted","payload":{"replacement_history":[{"type":"message","role":"user","content":[{"type":"input_text","text":"old prompt"}]},{"type":"compaction","encrypted_content":"opaque"}]}}"#,
                "\n",
                r#"{"timestamp":"2026-01-01T00:00:04Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"new prompt"}]}}"#,
                "\n",
                r#"{"timestamp":"2026-01-01T00:00:05Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"new answer"}]}}"#,
                "\n",
            ),
        )
        .unwrap();
        let locator = SessionLocator {
            harness: HarnessId::from(HarnessId::CODEX),
            session_id: "codex-display".into(),
            storage: StorageLocator::File { path },
        };
        let mut service = HarnessSessionService::new();

        let continuation = service.handle(request(
            1,
            "harness.v1.sessions.load",
            json!({"locator": locator}),
        ));
        let continuation_text = continuation["result"]["session"]["messages"].to_string();
        assert!(!continuation_text.contains("old answer"));

        let display = service.handle(request(
            2,
            "harness.v1.sessions.load",
            json!({
                "locator": locator,
                "view": {
                    "tail_messages": 10,
                    "include_subagents": false,
                    "display_history": true,
                },
            }),
        ));
        let display_text = display["result"]["session"]["messages"].to_string();
        assert!(display_text.contains("old prompt"));
        assert!(display_text.contains("old answer"));
        assert!(display_text.contains("new prompt"));
        assert!(display_text.contains("new answer"));

        let _ = std::fs::remove_dir_all(&temp);
    }

    #[test]
    fn load_supports_bounded_windows_and_media_metadata() {
        let mut service = HarnessSessionService::new();
        let locator = pi_locator();
        let bounded = service.handle(request(
            1,
            "harness.v1.sessions.load",
            json!({
                "locator": locator,
                "options": {
                    "include_subagents": false,
                    "message_limit": 2,
                    "message_offset": 1
                }
            }),
        ));
        assert_eq!(bounded["result"]["window"]["offset"], 1);
        assert_eq!(bounded["result"]["window"]["returned"], 2);
        assert!(bounded["result"]["summary"]["first_message"].is_object());
        assert!(bounded["result"]["summary"]["last_message"].is_object());
        assert_eq!(
            bounded["result"]["session"]["messages"]
                .as_array()
                .unwrap()
                .len(),
            2
        );
        assert!(bounded["result"]["session"]["subagents"]
            .as_array()
            .unwrap()
            .is_empty());

        let tail = service.handle(request(
            2,
            "harness.v1.sessions.load",
            json!({"locator": locator, "options": {"message_tail": 1}}),
        ));
        assert_eq!(tail["result"]["window"]["returned"], 1);
        assert_eq!(tail["result"]["window"]["has_more"], true);
        assert_eq!(tail["result"]["window"]["has_older"], true);
        assert!(tail["result"]["window"]["older_items"].as_u64().unwrap() > 0);
        assert!(tail["result"]["summary"]["first_message"].is_object());

        let metadata_only = service.handle(request(
            3,
            "harness.v1.sessions.load",
            json!({"locator": locator, "options": {"inline_media": "metadata"}}),
        ));
        assert!(metadata_only["result"]["session"]
            .to_string()
            .contains("media_reference"));
        assert!(!metadata_only["result"]["session"]
            .to_string()
            .contains("data:image/"));
    }

    #[test]
    fn import_translate_branch_and_handoff_use_typed_artifacts() {
        let mut service = HarnessSessionService::new();
        let locator = pi_locator();
        let translated = service.handle(request(
            1,
            "harness.v1.sessions.translate",
            json!({"locator": locator, "target_harness": "grok"}),
        ));
        assert_eq!(translated["result"]["artifact"]["source_harness"], "pi");
        assert_eq!(translated["result"]["artifact"]["target_harness"], "grok");
        assert!(translated["result"]["artifact"]["content"]
            .as_str()
            .is_some_and(|content| !content.is_empty()));

        for target in ["opencode", "open-code"] {
            let opencode = service.handle(request(
                6,
                "harness.v1.sessions.translate",
                json!({"locator": locator, "target_harness": target}),
            ));
            assert_eq!(opencode["result"]["artifact"]["target_harness"], "opencode");
        }
        let goose = service.handle(request(
            7,
            "harness.v1.sessions.translate",
            json!({"locator": locator, "target_harness": "goose"}),
        ));
        assert_eq!(goose["result"]["artifact"]["target_harness"], "goose");
        assert!(serde_json::from_str::<Value>(
            goose["result"]["artifact"]["content"].as_str().unwrap()
        )
        .unwrap()["conversation"]
            .is_array());

        let imported = service.handle(request(
            2,
            "harness.v1.sessions.import",
            json!({
                "source_harness": "grok",
                "content": translated["result"]["artifact"]["content"],
            }),
        ));
        assert_eq!(imported["result"]["session"]["source"], "grok");

        let branched = service.handle(request(
            3,
            "harness.v1.sessions.branch",
            json!({"locator": locator, "target_harness": "codex"}),
        ));
        assert_eq!(branched["result"]["parent"]["harness"], "pi");
        assert!(branched["result"]["bootstrap_prompt"]
            .as_str()
            .unwrap()
            .contains("frozen parent transcript"));
        assert_eq!(branched["result"]["artifact"]["target_harness"], "codex");

        let handoff = service.handle(request(
            4,
            "harness.v1.sessions.handoff",
            json!({"locator": locator, "target_harness": "pi", "cwd": "/tmp/project"}),
        ));
        assert_eq!(handoff["result"]["launch"]["program"], "pi");
        assert_eq!(handoff["result"]["launch"]["cwd"], "/tmp/project");
        assert_eq!(handoff["result"]["requires_materialization"], true);

        let goose_handoff = service.handle(request(
            8,
            "harness.v1.sessions.handoff",
            json!({"locator": locator, "target_harness": "goose", "cwd": "/tmp/project"}),
        ));
        assert_eq!(goose_handoff["result"]["launch"]["program"], "goose");
        assert_eq!(
            goose_handoff["result"]["materialize"]["arguments"],
            json!(["session", "import", "{artifact_path}"])
        );

        let resumed = service.handle(request(
            5,
            "harness.v1.sessions.resume_instructions",
            json!({"locator": locator, "cwd": "/tmp/project", "policy": "yolo"}),
        ));
        assert_eq!(resumed["result"]["launch"]["program"], "pi");
        assert_eq!(resumed["result"]["launch"]["arguments"][0], "--approve");
    }

    #[test]
    fn reduce_persists_and_reloads_a_byte_exact_reversible_bundle() {
        let temp = std::env::temp_dir().join(format!(
            "supercode-service-reduce-{}-{}",
            std::process::id(),
            generated_session_id()
        ));
        let source_path = temp.join("source.jsonl");
        let store_root = temp.join("store");
        std::fs::create_dir_all(&temp).unwrap();

        let mut records = vec![json!({
            "timestamp": "2026-01-01T00:00:00Z",
            "type": "session_meta",
            "payload": {"id": "codex-reduce", "cwd": "/tmp/project"},
        })];
        for turn in 0..16 {
            records.push(json!({
                "timestamp": format!("2026-01-01T00:00:{:02}Z", turn * 2 + 1),
                "type": "response_item",
                "payload": {
                    "type": "message",
                    "role": "user",
                    "content": [{
                        "type": "input_text",
                        "text": format!("request {turn}: {}", "context ".repeat(80)),
                    }],
                },
            }));
            records.push(json!({
                "timestamp": format!("2026-01-01T00:00:{:02}Z", turn * 2 + 2),
                "type": "response_item",
                "payload": {
                    "type": "message",
                    "role": "assistant",
                    "content": [{
                        "type": "output_text",
                        "text": format!("answer {turn}: {}", "implementation detail ".repeat(80)),
                    }],
                },
            }));
        }
        let source = format!(
            "{}\n",
            records
                .iter()
                .map(Value::to_string)
                .collect::<Vec<_>>()
                .join("\n")
        );
        std::fs::write(&source_path, &source).unwrap();
        let locator = SessionLocator {
            harness: HarnessId::from(HarnessId::CODEX),
            session_id: "codex-reduce".into(),
            storage: StorageLocator::File {
                path: source_path.clone(),
            },
        };
        let original = load_session(&locator).unwrap();
        let mut service =
            HarnessSessionService::new().with_reduction_store_root(store_root.clone());

        let response = service.handle(request(
            1,
            "harness.v1.sessions.reduce",
            json!({
                "locator": locator,
                "target_harness": "claude-code",
                "keep_last": 4,
            }),
        ));
        assert!(response.get("error").is_none(), "{response:#}");
        let receipt = &response["result"]["receipt"];
        assert_eq!(receipt["source_harness"], "codex");
        assert_eq!(receipt["target_harness"], "claude-code");
        assert_eq!(receipt["verified"], true);
        assert_eq!(receipt["reversible"], true);
        assert!(receipt["reductions"].as_u64().unwrap() > 0);
        assert!(
            receipt["source_tokens"].as_u64().unwrap()
                > receipt["reduced_tokens"].as_u64().unwrap()
        );
        assert!(receipt["ratio"].as_f64().unwrap() > 1.0);
        assert!(response["result"]["bootstrap_prompt"]
            .as_str()
            .unwrap()
            .contains("Do not guess hidden content"));

        let rescue_id = receipt["id"].as_str().unwrap();
        let store = crate::SessionStore::open(&store_root).unwrap();
        let sidecar =
            Session::from_sidecar_str(&store.load_sidecar(rescue_id).unwrap().unwrap()).unwrap();
        let log = store.load_reduction_log(rescue_id).unwrap().unwrap();
        let persisted_view = parse_messages_jsonl(&store.load(rescue_id).unwrap()).unwrap();
        let policy = reduce::ReductionPolicy {
            clear_turns_older_than: Some(4),
            ..Default::default()
        };
        let (restamped_view, reapplied_log) =
            reduce::project_messages(&sidecar.messages, &policy, &log);
        assert_eq!(
            messages_jsonl(&persisted_view).unwrap(),
            messages_jsonl(&restamped_view).unwrap()
        );
        assert_eq!(reapplied_log, log);
        reduce::verify_log(&log, &sidecar).unwrap();
        assert_eq!(
            reduce::invert(&restamped_view, &log, &sidecar).unwrap(),
            original.messages
        );
        assert_eq!(std::fs::read_to_string(&source_path).unwrap(), source);

        std::fs::remove_dir_all(temp).ok();
    }

    #[test]
    fn read_surfaces_view_a_severed_claude_graph_while_transfer_still_refuses_it() {
        let temp = std::env::temp_dir().join(format!(
            "supercode-severed-view-{}-{}",
            std::process::id(),
            generated_session_id()
        ));
        std::fs::create_dir_all(&temp).unwrap();
        let path = temp.join("severed.jsonl");
        // A live record whose parent was pruned — what a compacted or
        // resumed-across-files Claude Code session looks like on disk.
        std::fs::write(
            &path,
            concat!(
                r#"{"type":"user","uuid":"orphan-u","parentUuid":null,"message":{"role":"user","content":"stranded prompt"}}"#,
                "\n",
                r#"{"type":"assistant","uuid":"live-a","parentUuid":"pruned","message":{"id":"m","role":"assistant","content":[{"type":"text","text":"live answer"}]}}"#,
                "\n",
            ),
        )
        .unwrap();
        let locator = SessionLocator {
            harness: HarnessId::from(HarnessId::CLAUDE_CODE),
            session_id: "severed".into(),
            storage: StorageLocator::File { path },
        };
        let mut service = HarnessSessionService::new();

        let viewed = service.handle(request(
            1,
            "harness.v1.sessions.load",
            json!({"locator": locator}),
        ));
        let session = &viewed["result"]["session"];
        assert_eq!(session["fidelity"], "semantic");
        assert_eq!(session["messages"].as_array().unwrap().len(), 2);
        assert!(session["residue"].as_array().unwrap().iter().any(|entry| {
            entry
                .as_str()
                .is_some_and(|entry| entry.contains("live-a") && entry.contains("pruned"))
        }));

        // Asking a READ surface for a lossless reconstruction gets the strict
        // refusal back, unchanged.
        let strict = service.handle(request(
            2,
            "harness.v1.sessions.load",
            json!({"locator": locator, "fidelity": "byte_lossless"}),
        ));
        assert!(strict["error"]["message"]
            .as_str()
            .unwrap()
            .contains("cannot reconstruct lossless Claude continuation"));

        // Transfer/continuation surfaces have no view mode at all.
        let translated = service.handle(request(
            3,
            "harness.v1.sessions.translate",
            json!({"locator": locator, "target_harness": "codex"}),
        ));
        assert!(translated["error"]["message"]
            .as_str()
            .unwrap()
            .contains("cannot reconstruct lossless Claude continuation"));
        let resumed = service.handle(request(
            4,
            "harness.v1.sessions.resume_instructions",
            json!({"locator": locator}),
        ));
        assert!(resumed["error"]["message"]
            .as_str()
            .unwrap()
            .contains("cannot reconstruct lossless Claude continuation"));

        let _ = std::fs::remove_dir_all(&temp);
    }

    #[test]
    fn structured_resume_launches_cover_gemini_goose_and_supercode() {
        let codex = resume_launch(
            HarnessId::CODEX,
            "codex-session",
            Path::new("/tmp/project"),
            ResumePolicy::Yolo,
        )
        .unwrap_or_else(|_| panic!("Codex resume launch must be registered"));
        assert_eq!(codex.program, "codex");
        assert_eq!(
            codex.arguments,
            [
                "-c",
                "check_for_update_on_startup=false",
                "-c",
                "projects.\"/tmp/project\".trust_level=\"trusted\"",
                "--dangerously-bypass-approvals-and-sandbox",
                "--dangerously-bypass-hook-trust",
                "resume",
                "codex-session",
            ]
        );

        let gemini = resume_launch(
            HarnessId::GEMINI,
            "gemini-session",
            Path::new("/tmp/project"),
            ResumePolicy::Yolo,
        )
        .unwrap_or_else(|_| panic!("Gemini resume launch must be registered"));
        assert_eq!(gemini.program, "gemini");
        assert_eq!(gemini.arguments, ["--yolo", "--resume", "gemini-session"]);

        let goose = resume_launch(
            HarnessId::GOOSE,
            "goose-session",
            Path::new("/tmp/project"),
            ResumePolicy::Yolo,
        )
        .unwrap_or_else(|_| panic!("Goose resume launch must be registered"));
        assert_eq!(goose.program, "goose");
        assert_eq!(
            goose.arguments,
            ["session", "--resume", "--session-id", "goose-session"]
        );

        let supercode = resume_launch(
            HarnessId::SUPERCODE,
            "supercode-session",
            Path::new("/tmp/project"),
            ResumePolicy::Yolo,
        )
        .unwrap_or_else(|_| panic!("Supercode resume launch must be registered"));
        assert_eq!(supercode.program, "supercode");
        assert_eq!(
            supercode.arguments,
            ["--dangerous", "resume", "supercode-session"]
        );
    }

    #[test]
    fn diagonal_artifacts_preserve_claude_subagents_and_grok_bundle_members() {
        let temp = std::env::temp_dir().join(format!(
            "supercode-harness-artifact-{}-{}",
            std::process::id(),
            generated_session_id()
        ));
        let main_path = temp.join("parent.jsonl");
        let subagent_path = temp.join("parent/subagents/agent-child.jsonl");
        std::fs::create_dir_all(subagent_path.parent().unwrap()).unwrap();
        let fixture = std::fs::read_to_string(
            PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("tests/fixtures/claude_code_session.jsonl"),
        )
        .unwrap();
        let parent = fixture.trim_end_matches('\n');
        let child = fixture.trim_end_matches('\n');
        std::fs::write(&main_path, parent).unwrap();
        std::fs::write(&subagent_path, child).unwrap();
        let locator = SessionLocator {
            harness: HarnessId::from(HarnessId::CLAUDE_CODE),
            session_id: "213bb148-51ea-453f-9206-f8b4b1168547".into(),
            storage: StorageLocator::File {
                path: main_path.clone(),
            },
        };
        let mut service = HarnessSessionService::new();
        let claude = service.handle(request(
            1,
            "harness.v1.sessions.translate",
            json!({"locator": locator, "target_harness": "claude-code"}),
        ));
        let artifact = &claude["result"]["artifact"];
        assert_eq!(artifact["fidelity"], "byte_lossless");
        assert_eq!(artifact["content"], parent);
        let files = artifact["files"].as_array().unwrap();
        assert!(files.iter().any(|file| {
            file["role"] == "subagent"
                && file["path"]
                    .as_str()
                    .is_some_and(|path| path.ends_with("/subagents/agent-child.jsonl"))
                && file["content"] == child
        }));
        assert!(!artifact["content"].as_str().unwrap().ends_with('\n'));

        let grok = service.handle(request(
            2,
            "harness.v1.sessions.translate",
            json!({"locator": grok_locator(), "target_harness": "grok"}),
        ));
        let files = grok["result"]["artifact"]["files"].as_array().unwrap();
        for name in ["summary.json", "updates.jsonl"] {
            let expected = std::fs::read_to_string(
                PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                    .join("tests/fixtures/grok_session")
                    .join(name),
            )
            .unwrap();
            assert!(files.iter().any(|file| {
                file["path"] == name && file["role"] == "bundle" && file["content"] == expected
            }));
        }
        std::fs::remove_dir_all(temp).ok();
    }

    #[test]
    fn every_non_grok_handoff_mints_and_uses_a_fresh_target_identity() {
        let mut service = HarnessSessionService::new();
        let source = pi_locator();
        for (target, format) in [
            ("claude-code", SessionFormat::ClaudeCode),
            ("codex", SessionFormat::Codex),
            ("opencode", SessionFormat::OpenCode),
            ("pi", SessionFormat::Pi),
        ] {
            let result = service.handle(request(
                1,
                "harness.v1.sessions.handoff",
                json!({"locator": source, "target_harness": target, "cwd": "/tmp/project"}),
            ));
            let artifact = &result["result"]["artifact"];
            let target_id = artifact["session_id"].as_str().unwrap();
            assert_ne!(target_id, source.session_id, "{target}");
            let parsed = Session::load_str(artifact["content"].as_str().unwrap(), format).unwrap();
            assert_eq!(
                parsed.meta.session_id.as_deref(),
                Some(target_id),
                "{target}"
            );
            if target != "pi" {
                assert!(result["result"]["launch"]["arguments"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .any(|argument| argument == target_id));
            }
            if target == "opencode" {
                assert!(target_id.starts_with("ses_"));
                fn assert_session_ids(value: &Value, target_id: &str) {
                    match value {
                        Value::Object(fields) => {
                            if let Some(session_id) = fields.get("sessionID") {
                                assert_eq!(session_id, target_id);
                            }
                            for child in fields.values() {
                                assert_session_ids(child, target_id);
                            }
                        }
                        Value::Array(values) => {
                            for child in values {
                                assert_session_ids(child, target_id);
                            }
                        }
                        _ => {}
                    }
                }
                let document: Value =
                    serde_json::from_str(artifact["content"].as_str().unwrap()).unwrap();
                assert_session_ids(&document, target_id);
            }
        }

        let first = service.handle(request(
            2,
            "harness.v1.sessions.handoff",
            json!({"locator": source, "target_harness": "codex"}),
        ));
        let second = service.handle(request(
            3,
            "harness.v1.sessions.handoff",
            json!({"locator": source, "target_harness": "codex"}),
        ));
        assert_ne!(
            first["result"]["artifact"]["session_id"],
            second["result"]["artifact"]["session_id"]
        );
    }

    #[test]
    fn grok_handoff_uses_the_official_importer_contract() {
        let mut service = HarnessSessionService::new();
        let source = opencode_locator();
        let response = service.handle(request(
            1,
            "harness.v1.sessions.handoff",
            json!({
                "locator": source,
                "target_harness": "grok",
                "cwd": "/tmp/grok-handoff-project",
            }),
        ));
        let result = &response["result"];

        // The target is Grok, but the artifact truthfully names the Claude Code wire
        // format accepted by Grok's official importer. Raw Grok chat_history JSONL is
        // not a complete stock-resumable bundle.
        assert_eq!(result["artifact"]["target_harness"], "claude-code");
        assert!(result["artifact"]["suggested_filename"]
            .as_str()
            .unwrap()
            .ends_with(".grok-import.claude-code.jsonl"));
        let artifact = Session::load_str(
            result["artifact"]["content"].as_str().unwrap(),
            SessionFormat::ClaudeCode,
        )
        .unwrap();
        assert_eq!(
            artifact.meta.cwd.as_deref(),
            Some(Path::new("/tmp/grok-handoff-project"))
        );
        let target_session_id = artifact.meta.session_id.as_deref().unwrap();
        assert_eq!(target_session_id.len(), 36);
        assert_eq!(target_session_id.as_bytes()[14], b'4');
        assert_ne!(target_session_id, opencode_locator().session_id);
        assert_eq!(
            result["artifact"]["session_id"],
            artifact.meta.session_id.as_deref().unwrap()
        );

        assert_eq!(
            result["materialize"]["arguments"],
            json!(["import", "--json", "{artifact_path}"])
        );
        assert_eq!(
            result["launch"]["arguments"],
            json!(["--resume", "{imported_session_id}", "--fork-session"])
        );
        assert!(result["note"]
            .as_str()
            .unwrap()
            .contains("outcome=imported"));
        assert!(!result["launch"]["arguments"]
            .as_array()
            .unwrap()
            .iter()
            .any(|argument| argument == &opencode_locator().session_id));
    }

    #[tokio::test]
    async fn inventory_rejects_unknown_harnesses_and_runtime_attach_is_honest() {
        let mut service = HarnessSessionService::new();
        let inventory = service
            .handle_async(request(
                1,
                "harness.v1.harnesses.list",
                json!({"harnesses": ["missing"]}),
            ))
            .await;
        assert_eq!(inventory["error"]["code"], -32602);

        let attached = service
            .handle_async(request(
                2,
                "harness.v1.runtimes.attach_existing",
                json!({"harness": "codex", "runtime_id": "thread-1"}),
            ))
            .await;
        assert_eq!(attached["error"]["code"], -32000);
        assert!(attached["error"]["message"]
            .as_str()
            .unwrap()
            .contains("runtimes.resume"));
    }

    #[test]
    fn invalid_params_and_unknown_methods_use_json_rpc_errors() {
        let mut service = HarnessSessionService::new();
        let invalid = service.handle(request(1, "harness.v1.sessions.load", json!({})));
        assert_eq!(invalid["error"]["code"], -32602);
        let unknown = service.handle(request(2, "harness.v1.unknown", json!({})));
        assert_eq!(unknown["error"]["code"], -32601);
    }

    #[cfg(unix)]
    #[tokio::test]
    // The test mutates process-wide harness environment and deliberately
    // holds the global test lock until every async runtime operation ends.
    #[allow(clippy::await_holding_lock)]
    async fn async_service_drives_a_generic_acp_runtime() {
        let _environment_guard = crate::live_runtime::test_environment_lock();
        let script = r#"
            i=0
            while IFS= read -r line; do
              i=$((i + 1))
              case "$i" in
                1) printf '%s\n' '{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentCapabilities":{},"authMethods":[]}}' ;;
                2) printf '%s\n' '{"jsonrpc":"2.0","id":2,"result":{"sessionId":"svc_acp"}}' ;;
                3)
                  printf '%s\n' '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"svc_acp","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ok"}}}}'
                  printf '%s\n' '{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}}'
                  ;;
                4)
                  printf '%s\n' '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"svc_acp","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"from terminal"}}}}'
                  printf '%s\n' '{"jsonrpc":"2.0","id":4,"result":{"stopReason":"end_turn"}}'
                  ;;
              esac
            done
        "#;
        let mut service = HarnessSessionService::new();
        let started = service
            .handle_async(request(
                1,
                "harness.v1.runtimes.start",
                json!({
                    "harness": "codex",
                    "protocol": "acp",
                    "cwd": std::env::current_dir().unwrap(),
                    "launch": {"program": "/bin/sh", "arguments": ["-c", script], "env": {}},
                }),
            ))
            .await;
        assert_eq!(started["result"]["connection"], "runtime-1");
        assert_eq!(started["result"]["handle"]["runtime_id"], "svc_acp");

        let terminal = service
            .handle_async(request(
                9,
                "harness.v1.runtimes.terminal_instructions",
                json!({"connection":"runtime-1"}),
            ))
            .await;
        let arguments = terminal["result"]["launch"]["arguments"]
            .as_array()
            .expect("hosted runtime should return terminal arguments");
        let endpoint_index = arguments
            .iter()
            .position(|value| value == "--endpoint")
            .expect("terminal command should use an opaque endpoint");
        let endpoint = LiveRuntimeEndpoint::parse(
            arguments[endpoint_index + 1]
                .as_str()
                .expect("endpoint argument should be text"),
        )
        .unwrap();
        assert!(!terminal.to_string().contains("Bearer"));
        let workspace = std::env::current_dir().unwrap();
        let receipt = resolve_live_runtime(
            &endpoint,
            &LiveRuntimeSource {
                harness: "codex".into(),
                session_id: "svc_acp".into(),
                workspace,
            },
        )
        .unwrap();
        let remote = crate::HttpFrontendRuntime::connect(receipt.base_url, receipt.token)
            .await
            .unwrap();
        let mut attachment = crate::FrontendRuntime::attach(remote.as_ref(), 100)
            .await
            .unwrap();

        let sent = service
            .handle_async(request(
                2,
                "harness.v1.runtimes.send_input",
                json!({"connection": "runtime-1", "text": "hi"}),
            ))
            .await;
        assert_eq!(sent["result"]["turn_id"], "3");

        let mut events = Vec::new();
        for _ in 0..20 {
            events.extend(service.poll_runtimes().await);
            if events.len() >= 2 {
                break;
            }
            tokio::time::sleep(Duration::from_millis(2)).await;
        }
        assert!(events
            .iter()
            .any(|event| { event["params"]["event"]["kind"] == "session/update" }));
        assert!(events.iter().any(|event| {
            event["params"]["event"]["kind"] == "supercode/acp_request_completed"
        }));

        let saw_editor_reply = tokio::time::timeout(Duration::from_secs(2), async {
            loop {
                let event = attachment.next_event().await.unwrap();
                if event.kind == "text_delta" && event.payload["text"] == "ok" {
                    break;
                }
            }
        })
        .await;
        assert!(
            saw_editor_reply.is_ok(),
            "terminal should observe the editor-driven turn"
        );

        crate::FrontendRuntime::submit(remote.as_ref(), "DRIVE FROM TERMINAL".into())
            .await
            .unwrap();
        let saw_terminal_reply = tokio::time::timeout(Duration::from_secs(2), async {
            loop {
                let event = attachment.next_event().await.unwrap();
                if event.kind == "text_delta" && event.payload["text"] == "from terminal" {
                    break;
                }
            }
        })
        .await;
        assert!(
            saw_terminal_reply.is_ok(),
            "terminal should drive the same runtime"
        );

        let closed = service
            .handle_async(request(
                3,
                "harness.v1.runtimes.close",
                json!({"connection": "runtime-1"}),
            ))
            .await;
        assert_eq!(closed["result"]["closed"], true);
    }

    /// UNI-7 dev/02: a RUNNING mock gateway is detected through the real
    /// openclaw probe (config-declared endpoint, TCP connect), and an ACTIVE
    /// hermes WAL is detected through the real WAL-freshness probe; the
    /// negative sides (no listener, stale WAL, no config) stay undetected.
    #[test]
    fn running_instances_are_detected_from_mock_gateway_and_active_wal() {
        let home = connect_scratch_home("uni7-running");

        // No config at all: hermes has no default endpoint, so no detection.
        // (openclaw's no-config behavior now probes its DOCUMENTED default
        // endpoint ws://127.0.0.1:18789 — see the connect launch's
        // `default_address` — which is real box state a hermetic test must
        // not assert either way; the closed-port negative below covers the
        // no-listener side deterministically.)
        assert!(probe_hermes_running(&home, 300_000).is_none());

        // Mock gateway: a real TCP listener on an ephemeral port, declared in
        // the harness's own config file.
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        std::fs::create_dir_all(home.join(".openclaw")).unwrap();
        std::fs::write(
            home.join(".openclaw/openclaw.json"),
            format!(r#"{{"gateway": {{"mode": "local", "port": {port}, "auth": {{"mode": "token", "token": "t"}}}}}}"#),
        )
        .unwrap();
        let running = probe_openclaw_running(&home).expect("listening gateway must be detected");
        assert!(matches!(
            running.method,
            RunningInstanceMethod::GatewayConnect
        ));
        assert!(running.evidence.contains(&format!("127.0.0.1:{port}")));
        drop(listener);
        // Parallel tests also bind ephemeral loopback ports, so a just-freed
        // port can be re-bound by a NEIGHBORING test between drop and probe.
        // Detection on a closed port must fail — retry on a fresh port when
        // the freed one was recycled by someone else.
        let mut closed_detected = probe_openclaw_running(&home).is_some();
        for _ in 0..3 {
            if !closed_detected {
                break;
            }
            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
            let port = listener.local_addr().unwrap().port();
            drop(listener);
            std::fs::write(
                home.join(".openclaw/openclaw.json"),
                format!(r#"{{"gateway": {{"mode": "local", "port": {port}, "auth": {{"mode": "token", "token": "t"}}}}}}"#),
            )
            .unwrap();
            closed_detected = probe_openclaw_running(&home).is_some();
        }
        assert!(
            !closed_detected,
            "a closed gateway must not read as running"
        );

        // gateway.url form takes precedence over port.
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        std::fs::write(
            home.join(".openclaw/openclaw.json"),
            format!(r#"{{"gateway": {{"url": "ws://127.0.0.1:{port}", "auth": {{"mode": "token", "token": "t"}}}}}}"#),
        )
        .unwrap();
        assert!(probe_openclaw_running(&home).is_some());
        drop(listener);

        // Hermes: an ACTIVE WAL (fresh stamp) is detected; a stale one is not.
        std::fs::create_dir_all(home.join(".hermes")).unwrap();
        let wal = home.join(".hermes/state.db-wal");
        std::fs::write(&wal, b"wal").unwrap();
        let running = probe_hermes_running(&home, 300_000).expect("fresh WAL must be detected");
        assert!(matches!(
            running.method,
            RunningInstanceMethod::StoreWalActivity
        ));
        assert!(running.evidence.contains("state.db-wal"));
        let stale = std::time::SystemTime::now() - std::time::Duration::from_secs(3_600);
        std::fs::File::options()
            .append(true)
            .open(&wal)
            .unwrap()
            .set_modified(stale)
            .unwrap();
        assert!(
            probe_hermes_running(&home, 300_000).is_none(),
            "a stale WAL (crash leftover) must not read as running"
        );
    }

    fn connect_scratch_home(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "supercode-connect-service-{tag}-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// Minimal HTTP responder that speaks just enough OpenCode server to
    /// accept a health check, create a session, and hold an SSE stream open,
    /// while recording each request line with its Authorization header.
    async fn mock_opencode_endpoint() -> (String, tokio::sync::mpsc::UnboundedReceiver<String>) {
        use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (request_sender, request_receiver) = tokio::sync::mpsc::unbounded_channel();
        tokio::spawn(async move {
            loop {
                let Ok((mut stream, _)) = listener.accept().await else {
                    break;
                };
                let request_sender = request_sender.clone();
                tokio::spawn(async move {
                    let (reader, mut writer) = stream.split();
                    let mut reader = BufReader::new(reader);
                    let mut request_line = String::new();
                    if reader.read_line(&mut request_line).await.unwrap_or(0) == 0 {
                        return;
                    }
                    let request_line = request_line.trim_end().to_string();
                    let mut authorization = String::new();
                    let mut content_length = 0usize;
                    loop {
                        let mut line = String::new();
                        if reader.read_line(&mut line).await.unwrap_or(0) == 0 {
                            return;
                        }
                        let line = line.trim_end();
                        if line.is_empty() {
                            break;
                        }
                        let lower = line.to_ascii_lowercase();
                        if let Some(value) = lower.strip_prefix("authorization:") {
                            authorization = value.trim().to_string();
                        }
                        if let Some(value) = lower.strip_prefix("content-length:") {
                            content_length = value.trim().parse().unwrap_or(0);
                        }
                    }
                    if content_length > 0 {
                        let mut body = vec![0u8; content_length];
                        let _ = reader.read_exact(&mut body).await;
                    }
                    let _ = request_sender.send(format!("{request_line} :: {authorization}"));
                    if request_line.starts_with("GET /event") {
                        let _ = writer
                            .write_all(
                                b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\r\n",
                            )
                            .await;
                        tokio::time::sleep(std::time::Duration::from_secs(5)).await;
                        return;
                    }
                    let body = if request_line.starts_with("POST /session") {
                        r#"{"id":"mock-session"}"#
                    } else {
                        r#"{"status":"ok"}"#
                    };
                    let response = format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                        body.len(),
                        body
                    );
                    let _ = writer.write_all(response.as_bytes()).await;
                });
            }
        });
        (format!("http://{address}"), request_receiver)
    }

    fn connect_descriptor(protocol: &str) -> crate::HarnessSupportDescriptor {
        crate::HarnessSupportDescriptor {
            orchestration: Default::default(),
            id: HarnessId::from(HarnessId::OPENCODE),
            display_name: "OpenCode".into(),
            native: crate::NativeSupport {
                discover: crate::ImplementationKind::Absent,
                load: crate::ImplementationKind::Absent,
                follow: crate::ImplementationKind::Absent,
                import: crate::ImplementationKind::Absent,
                export: crate::ImplementationKind::Absent,
            },
            runtime: crate::RuntimeSupport {
                implementation: crate::ImplementationKind::BuiltIn,
                protocol: protocol.into(),
                default_launch: None,
                connect_launch: Some(crate::RuntimeConnectLaunch {
                    config_path: "~/opencode-tui.json".into(),
                    address_pointer: "/server/url".into(),
                    port_pointer: None,
                    default_address: None,
                    auth_pointer: Some("/server/token".into()),
                    protocol: protocol.into(),
                }),
                capabilities: crate::RuntimeCapabilities {
                    start_session: true,
                    resume_session: true,
                    attach_existing_process: true,
                    send_input: true,
                    stream_events: true,
                    interrupt: true,
                    steer: false,
                    respond_to_requests: true,
                },
            },
        }
    }

    #[tokio::test]
    async fn connect_mode_descriptor_opens_a_running_endpoint_with_config_sourced_auth() {
        let (base_url, mut requests) = mock_opencode_endpoint().await;
        let home = connect_scratch_home("open");
        std::fs::write(
            home.join("opencode-tui.json"),
            format!(r#"{{"server": {{"url": "{base_url}", "token": "connect-secret"}}}}"#),
        )
        .unwrap();

        let descriptor = connect_descriptor("opencode-http-sse");
        let backend = open_connect_descriptor(&descriptor, &home).unwrap();
        assert!(backend.capabilities().attach_existing_process);

        let connection = backend
            .start(crate::RuntimeStartRequest {
                cwd: home.clone(),
                launch: None,
                mcp_servers: Vec::new(),
            })
            .await
            .unwrap();
        let handle = connection.handle();
        assert_eq!(handle.runtime_id, "mock-session");
        match &handle.endpoint {
            crate::RuntimeEndpoint::Http {
                base_url: endpoint, ..
            } => assert_eq!(endpoint, &base_url),
            other => panic!("connect mode must join the running endpoint, got {other:?}"),
        }

        let mut seen = Vec::new();
        while let Ok(line) = requests.try_recv() {
            seen.push(line);
        }
        assert!(seen
            .iter()
            .any(|line| line.starts_with("GET /global/health")
                && line.contains("bearer connect-secret")));
        assert!(seen.iter().any(
            |line| line.starts_with("POST /session") && line.contains("bearer connect-secret")
        ));
    }

    /// UNI-5 dev/02, contract corrected by the 2026-08-31 blind walk: the
    /// full connect-mode attach path against a MOCK gateway bridge — no live
    /// gateway, no model spend. A scripted fake `openclaw` binary (a)
    /// asserts the REAL bridge contract — the resolved --url on argv and the
    /// credential via --token-file (the real bridge ignores the env var; the
    /// endpoint comes from openclaw-native `gateway.remote.url`, never the
    /// schema-invalid `gateway.url`) — then (b) speaks scripted ACP:
    /// initialize advertising sessionCapabilities.{list,resume},
    /// session/resume rebinding the requested session (join), and a
    /// prompted turn.
    #[tokio::test]
    async fn openclaw_connect_mode_attaches_lists_and_resumes_via_a_mock_bridge() {
        let home = connect_scratch_home("openclaw");
        std::fs::create_dir_all(home.join(".openclaw")).unwrap();
        std::fs::write(
            home.join(".openclaw/openclaw.json"),
            r#"{"gateway": {"remote": {"url": "ws://127.0.0.1:19789"}, "auth": {"mode": "token", "token": "mock-gateway-token"}}}"#,
        )
        .unwrap();
        let script = home.join("openclaw");
        std::fs::write(
            &script,
            r#"#!/bin/sh
# Fake `openclaw acp` bridge: verify the connect-mode contract, then speak ACP.
[ "$1" = "acp" ] || { echo "unexpected argv: $*" >&2; exit 9; }
[ "$2" = "--url" ] && [ "$3" = "ws://127.0.0.1:19789" ] || { echo "missing --url: $*" >&2; exit 9; }
[ "$4" = "--token-file" ] || { echo "missing --token-file: $*" >&2; exit 9; }
[ "$(cat "$5")" = "mock-gateway-token" ] || { echo "token file wrong" >&2; exit 9; }
while IFS= read -r line; do
  case "$line" in
    *'"initialize"'*)
      printf '%s
' '{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{},"resume":{}}},"agentInfo":{"name":"openclaw-acp","version":"2026.7.1-2"},"authMethods":[]}}' ;;
    *'"session/resume"'*)
      printf '%s
' '{"jsonrpc":"2.0","id":2,"result":{"sessionId":"agent:main:main"}}' ;;
    *'"session/new"'*)
      printf '%s
' '{"jsonrpc":"2.0","id":2,"result":{"sessionId":"agent:main:fresh"}}' ;;
    *'"session/prompt"'*)
      printf '%s
' '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"agent:main:main","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"joined"}}}}'
      printf '%s
' '{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}}' ;;
  esac
done
"#,
        )
        .unwrap();
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();

        let mut descriptor = crate::harness_support_registry()
            .harnesses
            .into_iter()
            .find(|harness| harness.id.as_str() == HarnessId::OPENCLAW)
            .expect("openclaw must be registered");
        descriptor
            .runtime
            .connect_launch
            .as_mut()
            .unwrap()
            .config_path = "~/.openclaw/openclaw.json".into();
        descriptor.runtime.default_launch.as_mut().unwrap().program =
            script.to_string_lossy().into_owned();
        let backend = open_connect_descriptor(&descriptor, &home).unwrap();
        assert!(backend.capabilities().resume_session);

        let joined = backend
            .attach(crate::RuntimeAttachRequest {
                runtime_id: "agent:main:main".into(),
                cwd: Some(home.clone()),
                launch: None,
            })
            .await;
        let mut connection = joined.expect("mock bridge attach must succeed");
        assert_eq!(connection.handle().runtime_id, "agent:main:main");
        let turn = connection
            .send_input(crate::RuntimeInput {
                text: "hello".into(),
                image_urls: Vec::new(),
            })
            .await;
        assert!(turn.is_ok(), "prompt through the mock bridge: {turn:?}");
        connection.close().await.unwrap();
    }

    #[tokio::test]
    async fn connect_mode_fails_closed_without_a_protocol_client_or_config() {
        let home = connect_scratch_home("fail");
        std::fs::write(
            home.join("opencode-tui.json"),
            r#"{"server": {"url": "http://127.0.0.1:1", "token": "connect-secret"}}"#,
        )
        .unwrap();

        let gateway_only = connect_descriptor("acp-v1-jsonrpc");
        let Err(error) = open_connect_descriptor(&gateway_only, &home) else {
            panic!("an ACP connect endpoint has no gateway client yet");
        };
        let message = format!("{error:?}");
        assert!(message.contains("acp-v1-jsonrpc"));
        assert!(!message.contains("connect-secret"));

        let unreadable = connect_descriptor("opencode-http-sse");
        let missing_home = connect_scratch_home("missing");
        let Err(error) = open_connect_descriptor(&unreadable, &missing_home) else {
            panic!("an unreadable connect config must fail closed");
        };
        let message = format!("{error:?}");
        assert!(message.contains("opencode-tui.json"));
        assert!(!message.contains("connect-secret"));
    }

    // ---------------------------------------------------------------------
    // ORCH-7 — `harness.v1.jobs.list` / `jobs.get` over the committed fixtures
    // ---------------------------------------------------------------------

    fn jobs_fixture_root() -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures")
    }

    /// Point only the three job-bearing homes at the fixtures. Nothing else is
    /// read, so the host machine's own harness homes cannot leak into a row.
    fn jobs_fixture_homes() -> Value {
        let root = jobs_fixture_root();
        json!({
            "claude_code": root.join("claude_jobs_home/projects"),
            "hermes": root.join("hermes_home/state.db"),
            "openclaw": root.join("openclaw_home"),
        })
    }

    fn jobs_list(params: Value) -> Value {
        let mut service = HarnessSessionService::new();
        service.handle(request(1, "harness.v1.jobs.list", params))
    }

    fn job_row<'a>(result: &'a Value, id: &str) -> &'a Value {
        result["jobs"]
            .as_array()
            .expect("jobs is an array")
            .iter()
            .find(|job| job["id"] == id)
            .unwrap_or_else(|| panic!("no job `{id}` in {result}"))
    }

    #[test]
    fn gateway_health_derives_from_running_probe_and_install_state() {
        let running = RunningInstance {
            method: RunningInstanceMethod::GatewayConnect,
            evidence: "gateway endpoint 127.0.0.1:18789 accepted a TCP connect".into(),
            checked_at_ms: 1,
        };
        let up = gateway_health(
            HarnessId::OPENCLAW,
            true,
            Some(&running),
            Some("2026.7.1-2"),
        );
        assert_eq!(up.state, GatewayState::Up);
        assert!(up.endpoint.as_deref().unwrap().starts_with("ws://"));
        assert_eq!(up.version.as_deref(), Some("2026.7.1-2"));
        // Hermes consults its own `gateway status` when the WAL heuristic says
        // nothing; a fake binary decides the verdict (the env var is global, so
        // the up/down cases run inside this one test, never in parallel).
        let dir = std::env::temp_dir().join(format!("supercode-orch17-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let fake = dir.join("hermes");
        let write_fake = |body: &str| {
            std::fs::write(&fake, format!("#!/bin/sh\n{body}\n")).unwrap();
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
            }
        };
        write_fake("echo '✗ Gateway service is not installed'");
        crate::harness_command::TEST_PROGRAM_OVERRIDE.with(|slot| {
            *slot.borrow_mut() = Some((
                HarnessId::HERMES.to_string(),
                fake.to_string_lossy().into_owned(),
            ))
        });
        let down = gateway_health(HarnessId::HERMES, true, None, None);
        assert_eq!(down.state, GatewayState::Down, "{down:?}");
        assert!(down.endpoint.is_none());
        assert!(down.evidence.contains("not installed"));
        write_fake("echo 'Launchd plist: /x/ai.hermes.gateway.plist'; echo '✓ Gateway is supervised by launchd (PID 4242)'");
        let idle_but_up = gateway_health(HarnessId::HERMES, true, None, Some("0.21.0"));
        assert_eq!(idle_but_up.state, GatewayState::Up, "{idle_but_up:?}");
        assert!(idle_but_up.evidence.contains("PID 4242"));
        write_fake("echo 'something unparseable'");
        let no_verdict = gateway_health(HarnessId::HERMES, true, None, None);
        assert_eq!(no_verdict.state, GatewayState::Down);
        assert!(no_verdict.evidence.contains("no verdict"));
        crate::harness_command::TEST_PROGRAM_OVERRIDE.with(|slot| *slot.borrow_mut() = None);
        let absent = gateway_health(HarnessId::HERMES, false, None, None);
        assert_eq!(absent.state, GatewayState::Unknown);
        let core = gateway_health(HarnessId::CODEX, true, None, Some("0.144.4"));
        assert_eq!(core.state, GatewayState::Unknown);
        assert!(core.evidence.contains("per session"));
    }

    #[test]
    fn triggers_list_reads_both_stores_and_never_emits_secrets() {
        let response = triggers_list(json!({"homes": jobs_fixture_homes()}));
        let rows = response["result"]["triggers"]
            .as_array()
            .expect("triggers")
            .clone();
        let hermes: Vec<&Value> = rows.iter().filter(|r| r["harness"] == "hermes").collect();
        assert!(
            hermes.iter().any(|r| r["name"] == "deploys"
                && r["route"] == "/webhooks/deploys"
                && r["kind"] == "webhook"),
            "{rows:#?}"
        );
        let openclaw: Vec<&Value> = rows.iter().filter(|r| r["harness"] == "openclaw").collect();
        assert!(openclaw
            .iter()
            .any(|r| r["name"] == "wake" && r["kind"] == "builtin_wake"));
        assert!(openclaw.iter().any(|r| r["name"] == "gmail"
            && r["kind"] == "hook_mapping"
            && r["target"]["action"] == "agent"));
        let rendered = response.to_string();
        for secret in [
            "FAKE-WEBHOOK-HMAC-DO-NOT-EMIT",
            "FAKE-HOOK-TOKEN-DO-NOT-EMIT",
        ] {
            assert!(!rendered.contains(secret), "{rendered}");
        }
        let refused =
            triggers_list(json!({"harness": "claude-code", "homes": jobs_fixture_homes()}));
        assert_eq!(refused["error"]["code"], -32020, "{refused}");
    }

    fn triggers_list(params: Value) -> Value {
        let mut service = HarnessSessionService::new();
        service.handle(request(1, "harness.v1.triggers.list", params))
    }

    #[test]
    fn routes_list_reads_both_gateway_configs_and_flags_the_defaults() {
        let response = routes_list(json!({"homes": jobs_fixture_homes()}));
        let rows = response["result"]["routes"]
            .as_array()
            .expect("routes")
            .clone();
        let hermes: Vec<&Value> = rows.iter().filter(|r| r["harness"] == "hermes").collect();
        assert_eq!(hermes.len(), 2, "{rows:#?}");
        assert_eq!(hermes[0]["target"], "coder");
        assert_eq!(hermes[0]["match"]["platform"], "slack");
        assert_eq!(hermes[0]["match"]["chat_id"], "C0FIXTURE");
        assert_eq!(hermes[0]["specificity"], 4);
        assert_eq!(hermes[1]["default"], true);
        let openclaw: Vec<&Value> = rows.iter().filter(|r| r["harness"] == "openclaw").collect();
        assert!(
            openclaw.iter().any(|r| r["target"] == "design"
                && r["match"]["platform"] == "slack"
                && r["specificity"] == 1),
            "{openclaw:#?}"
        );
        assert!(openclaw.iter().any(|r| r["default"] == true));
        // A core harness has no routing concept and is refused, never an empty list.
        let refused = routes_list(json!({"harness": "codex", "homes": jobs_fixture_homes()}));
        assert_eq!(refused["error"]["code"], -32020, "{refused}");
    }

    fn routes_list(params: Value) -> Value {
        let mut service = HarnessSessionService::new();
        service.handle(request(1, "harness.v1.routes.list", params))
    }

    #[test]
    fn jobs_list_projects_every_fixture_store_onto_the_uniform_row() {
        let response = jobs_list(json!({"homes": jobs_fixture_homes()}));
        let result = &response["result"];
        let ids: Vec<&str> = result["jobs"]
            .as_array()
            .unwrap()
            .iter()
            .map(|job| job["id"].as_str().unwrap())
            .collect();
        assert_eq!(
            ids,
            vec![
                "release-watch",
                "toolu_wake_recheck",
                "digest-15m",
                "nightly-audit",
                "coder-standup",
                "ops-once-boot",
                "85ad7832-896f-42be-af31-3e1ed2fbdc4b",
                "8bb7d938-ca46-4a6d-90eb-c92331155566",
                "cron_standup",
                "cron_reindex",
            ],
            "{result}"
        );

        // OpenClaw, pinned shape: rows come from `state/openclaw.sqlite`
        // (`cron_jobs.job_json` + runtime columns), captured from a real
        // 2026.7.1-2 gateway.
        let health = job_row(result, "85ad7832-896f-42be-af31-3e1ed2fbdc4b");
        assert_eq!(health["harness"], "openclaw");
        assert_eq!(health["schedule"]["kind"], "interval");
        assert_eq!(health["schedule"]["minutes"], 10.0);
        assert_eq!(health["session_target"], "isolated");
        assert_eq!(health["payload"]["kind"], "prompt");
        assert_eq!(health["payload"]["text"], "nightly health check");
        // ORCH-13: the mode word (`announce`) and the channel it announces on
        // (`last`) are separate facts, and the store keeps both — in
        // `job_json.delivery` and in the `delivery_*` columns beside it.
        assert_eq!(health["deliver"]["mode"], "announce");
        assert_eq!(health["deliver"]["target"], "last");
        assert_eq!(health["next_run_at"], "2026-09-03T06:52:26Z");
        let digest = job_row(result, "8bb7d938-ca46-4a6d-90eb-c92331155566");
        assert_eq!(digest["schedule"]["kind"], "cron");
        assert_eq!(digest["schedule"]["expr"], "0 9 * * 1");
        assert_eq!(digest["session_target"], "main");
        assert_eq!(digest["payload"]["kind"], "system_event");

        // Claude Code: session-scoped, one recurring cron and one one-shot wakeup.
        let cron = job_row(result, "release-watch");
        assert_eq!(cron["harness"], "claude-code");
        assert_eq!(cron["scope"], "session");
        assert_eq!(cron["session_id"], "7c1d2e3f-4a5b-6c7d-8e9f-0a1b2c3d4e5f");
        assert_eq!(cron["schedule"]["kind"], "cron");
        assert_eq!(cron["schedule"]["expr"], "*/10 * * * *");
        assert_eq!(cron["schedule"]["display"], "*/10 * * * *");
        assert_eq!(cron["payload"]["kind"], "prompt");
        assert_eq!(cron["recurring"], true);
        assert_eq!(cron["deliver"]["target"], "session");
        let wakeup = job_row(result, "toolu_wake_recheck");
        assert_eq!(wakeup["payload"]["kind"], "wakeup");
        assert_eq!(wakeup["schedule"]["kind"], "once");
        assert_eq!(wakeup["recurring"], false);
        assert_eq!(wakeup["state"], "pending");

        // Hermes: install-scoped, interval + origin delivery, and a paused cron.
        let interval = job_row(result, "digest-15m");
        assert_eq!(interval["harness"], "hermes");
        assert_eq!(interval["scope"], "install");
        assert_eq!(interval["profile"], Value::Null);
        assert_eq!(interval["schedule"]["kind"], "interval");
        assert_eq!(interval["schedule"]["minutes"], 15.0);
        assert_eq!(interval["schedule"]["display"], "every 15 min");
        assert_eq!(interval["deliver"]["target"], "origin");
        assert_eq!(interval["deliver"]["chat_id"], "-1002233445566");
        assert_eq!(interval["next_run_at"], "2026-09-02T11:15:00Z");
        assert_eq!(interval["last_status"], "ok");
        let nightly = job_row(result, "nightly-audit");
        assert_eq!(nightly["schedule"]["expr"], "0 3 * * *");
        assert_eq!(nightly["deliver"]["target"], "local");
        assert_eq!(nightly["enabled"], false);
        assert_eq!(nightly["state"], "paused");
        // The per-profile store carries the profile name from its own path.
        let profiled = job_row(result, "ops-once-boot");
        assert_eq!(profiled["profile"], "ops");
        assert_eq!(profiled["schedule"]["kind"], "once");
        assert_eq!(profiled["schedule"]["run_at"], "2026-09-03T06:00:00Z");
        assert_eq!(profiled["payload"]["kind"], "script");
        // An explicit `<platform>:<chat>` target carries the chat itself.
        assert_eq!(profiled["deliver"]["target"], "slack:C0429ABCD");
        assert_eq!(profiled["deliver"]["chat_id"], "C0429ABCD");
        assert_eq!(profiled["recurring"], false);

        // ORCH-13: a job delivering to its creating conversation carries that
        // conversation's whole surface — platform word, chat AND thread.
        let standup_to_group = job_row(result, "coder-standup");
        assert_eq!(standup_to_group["deliver"]["target"], "origin");
        assert_eq!(standup_to_group["deliver"]["chat_id"], "-100777");
        assert_eq!(standup_to_group["deliver"]["thread_id"], "55");
        // Hermes has no mode word and routes by adapter profile, not account.
        assert!(standup_to_group["deliver"]["mode"].is_null());
        assert!(standup_to_group["deliver"]["account"].is_null());

        // OpenClaw: the session target and the delivery mode are the row's own
        // columns, not a footnote.
        let standup = job_row(result, "cron_standup");
        assert_eq!(standup["harness"], "openclaw");
        assert_eq!(standup["session_target"], "isolated");
        assert_eq!(standup["deliver"]["mode"], "announce");
        assert_eq!(standup["deliver"]["target"], "slack");
        assert_eq!(standup["deliver"]["chat_id"], "C0429ABCD");
        assert_eq!(standup["payload"]["kind"], "prompt");
        assert_eq!(standup["profile"], "main");
        let reindex = job_row(result, "cron_reindex");
        assert_eq!(reindex["session_target"], "main");
        assert_eq!(reindex["payload"]["kind"], "system_event");
        assert_eq!(reindex["schedule"]["kind"], "interval");
        assert_eq!(reindex["schedule"]["display"], "every 240 min");
        assert_eq!(reindex["enabled"], false);

        // Every store consulted is named, so an empty answer is never silent.
        let states: Vec<(&str, &str)> = result["sources"]
            .as_array()
            .unwrap()
            .iter()
            .map(|source| {
                (
                    source["harness"].as_str().unwrap(),
                    source["state"].as_str().unwrap(),
                )
            })
            .collect();
        // The `coder` profile home has no cron store at all: it is named as
        // `absent_store`, not skipped, so "this profile schedules nothing" and
        // "this profile was never looked at" stay distinguishable.
        assert_eq!(
            states,
            vec![
                ("claude-code", "scanned"),
                ("hermes", "read"),
                ("hermes", "absent_store"),
                ("hermes", "read"),
                ("openclaw", "read"),
                ("openclaw", "read"),
            ],
            "{result}"
        );
    }

    #[test]
    fn jobs_list_filters_by_harness_session_and_profile() {
        let by_harness = jobs_list(json!({"harness": "openclaw", "homes": jobs_fixture_homes()}));
        let ids: Vec<&str> = by_harness["result"]["jobs"]
            .as_array()
            .unwrap()
            .iter()
            .map(|job| job["id"].as_str().unwrap())
            .collect();
        assert_eq!(
            ids,
            vec![
                "85ad7832-896f-42be-af31-3e1ed2fbdc4b",
                "8bb7d938-ca46-4a6d-90eb-c92331155566",
                "cron_standup",
                "cron_reindex",
            ]
        );

        let by_session = jobs_list(json!({
            "session": "7c1d2e3f-4a5b-6c7d-8e9f-0a1b2c3d4e5f",
            "homes": jobs_fixture_homes(),
        }));
        let jobs = by_session["result"]["jobs"].as_array().unwrap();
        assert_eq!(jobs.len(), 2, "{by_session}");
        assert!(jobs
            .iter()
            .all(|job| job["harness"] == "claude-code" && job["scope"] == "session"));

        let by_profile = jobs_list(json!({
            "harness": "hermes",
            "profile": "ops",
            "homes": jobs_fixture_homes(),
        }));
        let jobs = by_profile["result"]["jobs"].as_array().unwrap();
        assert_eq!(jobs.len(), 1, "{by_profile}");
        assert_eq!(jobs[0]["id"], "ops-once-boot");
    }

    #[test]
    fn jobs_get_answers_with_the_row_and_the_verbatim_native_record() {
        let mut service = HarnessSessionService::new();
        let hermes = service.handle(request(
            1,
            "harness.v1.jobs.get",
            json!({"harness": "hermes", "id": "digest-15m", "homes": jobs_fixture_homes()}),
        ));
        assert_eq!(hermes["result"]["job"]["schedule"]["kind"], "interval");
        // Native fields the uniform row does not carry survive on `source`.
        assert_eq!(hermes["result"]["source"]["provider"], "nous");
        assert_eq!(hermes["result"]["source"]["failure_deliver"], "local");

        let claude = service.handle(request(
            2,
            "harness.v1.jobs.get",
            json!({"harness": "claude-code", "id": "release-watch", "homes": jobs_fixture_homes()}),
        ));
        assert_eq!(claude["result"]["job"]["payload"]["kind"], "prompt");
        assert_eq!(
            claude["result"]["source"]["tool_use_id"],
            "toolu_cron_release_watch"
        );

        let missing = service.handle(request(
            3,
            "harness.v1.jobs.get",
            json!({"harness": "hermes", "id": "no-such-job", "homes": jobs_fixture_homes()}),
        ));
        assert!(missing["error"]["message"]
            .as_str()
            .is_some_and(|message| message.contains("no scheduled job `no-such-job`")));
    }

    #[test]
    fn jobs_refuse_a_harness_without_a_scheduled_job_concept() {
        let mut service = HarnessSessionService::new();
        for (id, method, params) in [
            (
                1,
                "harness.v1.jobs.list",
                json!({"harness": "codex", "homes": jobs_fixture_homes()}),
            ),
            (
                2,
                "harness.v1.jobs.get",
                json!({"harness": "codex", "id": "anything"}),
            ),
        ] {
            let response = service.handle(request(id, method, params));
            assert_eq!(response["error"]["code"], -32020, "{response}");
            assert!(response["error"]["message"]
                .as_str()
                .is_some_and(|message| message.contains("has no scheduled jobs")));
            assert!(response.get("result").is_none());
        }
    }

    #[test]
    fn jobs_list_reports_a_migrated_openclaw_store_as_absent_instead_of_failing() {
        let scratch = std::env::temp_dir().join(format!(
            "supercode-jobs-migrated-{}-{}",
            std::process::id(),
            generated_session_id()
        ));
        std::fs::create_dir_all(&scratch).unwrap();
        let response = jobs_list(json!({
            "harness": "openclaw",
            "homes": {"openclaw": scratch.clone()},
        }));
        let result = &response["result"];
        assert_eq!(result["jobs"].as_array().unwrap().len(), 0, "{result}");
        assert_eq!(result["sources"][0]["state"], "absent_store");
        assert_eq!(result["sources"][0]["harness"], "openclaw");
        std::fs::remove_dir_all(&scratch).ok();
    }

    // ---------------------------------------------------------------------
    // ORCH-8 — `harness.v1.runs.list` / `runs.get` over the committed fire
    // stores: Hermes's `cron/executions.db` (root home + profile home) and
    // OpenClaw's `cron_run_logs`. Every fixture row is written by
    // `tests/fixtures/gen_runs_fixtures.py` against the harnesses' own DDL.
    // ---------------------------------------------------------------------

    /// The health job in the committed OpenClaw fixture, which fired twice.
    const OPENCLAW_HEALTH_JOB: &str = "85ad7832-896f-42be-af31-3e1ed2fbdc4b";
    /// The digest job, whose single fire predates run ids.
    const OPENCLAW_DIGEST_JOB: &str = "8bb7d938-ca46-4a6d-90eb-c92331155566";

    fn runs_list(params: Value) -> Value {
        let mut service = HarnessSessionService::new();
        service.handle(request(1, "harness.v1.runs.list", params))
    }

    fn run_row<'a>(result: &'a Value, id: &str) -> &'a Value {
        result["runs"]
            .as_array()
            .expect("runs is an array")
            .iter()
            .find(|run| run["id"] == id)
            .unwrap_or_else(|| panic!("no run `{id}` in {result}"))
    }

    #[test]
    fn runs_list_projects_both_fixture_stores_onto_the_uniform_row() {
        let response = runs_list(json!({"homes": jobs_fixture_homes()}));
        let result = &response["result"];
        let ids: Vec<&str> = result["runs"]
            .as_array()
            .expect("runs is an array")
            .iter()
            .map(|run| run["id"].as_str().unwrap())
            .collect();
        let digest_fire = format!("{OPENCLAW_DIGEST_JOB}#1");
        assert_eq!(
            ids,
            vec![
                // Hermes, newest claim first, root ledger then profile ledger.
                "b2c3d4e5f60718293a4b5c6d7e8f9012",
                "a1b2c3d4e5f60718293a4b5c6d7e8f90",
                "c3d4e5f60718293a4b5c6d7e8f901234",
                "f60718293a4b5c6d7e8f901234567890",
                "e5f60718293a4b5c6d7e8f9012345678",
                "d4e5f60718293a4b5c6d7e8f90123456",
                // OpenClaw, newest `ts` first.
                "run_health_0002",
                digest_fire.as_str(),
                "run_health_0001",
            ],
            "{result}"
        );

        // The harness's OWN outcome word survives; nothing is renamed onto a
        // shared vocabulary.
        let failed = run_row(result, "b2c3d4e5f60718293a4b5c6d7e8f9012");
        assert_eq!(failed["harness"], "hermes");
        assert_eq!(failed["job_id"], "job42");
        assert_eq!(failed["status"], "failed");
        assert_eq!(failed["error"], "provider returned 500 after 3 attempts");
        assert_eq!(failed["claimed_at"], "2026-09-02T13:05:00.100442");

        // Hermes's `unknown` — an attempt whose owner died before writing a
        // terminal state — is a fourth status, not folded into `failed`.
        let abandoned = run_row(result, "d4e5f60718293a4b5c6d7e8f90123456");
        assert_eq!(abandoned["status"], "unknown");
        assert_eq!(abandoned["job_id"], "ops-once-boot");

        // An unterminated fire has no finish, and no session is invented.
        let running = run_row(result, "c3d4e5f60718293a4b5c6d7e8f901234");
        assert_eq!(running["status"], "running");
        assert!(running["finished_at"].is_null(), "{running}");
        assert!(running["session_id"].is_null(), "{running}");

        // OpenClaw records the session on the row itself, and epoch-ms
        // timestamps are rendered as RFC 3339.
        let ok = run_row(result, "run_health_0001");
        assert_eq!(ok["harness"], "openclaw");
        assert_eq!(ok["job_id"], OPENCLAW_HEALTH_JOB);
        assert_eq!(ok["status"], "ok");
        assert_eq!(ok["started_at"], "2026-09-02T08:30:00.000Z");
        assert_eq!(ok["finished_at"], "2026-09-02T08:30:30.000Z");
        assert_eq!(ok["session_id"], "3dd577ae-a0a3-4b5b-8063-f402be4f5fd4");
        // OpenClaw's run log is written once, at finish: there is no claim.
        assert!(ok["claimed_at"].is_null(), "{ok}");

        // A run-log row with no `run_id` falls back to the store's own
        // `(job_id, seq)` key rather than being dropped.
        assert_eq!(run_row(result, &digest_fire)["status"], "skipped");

        // ORCH-13: a fire whose delivery nothing recorded says so, rather than
        // borrowing a neighbouring fire's outcome. Both of these ran on jobs
        // that deliver `local` (or have no job record at all), so no
        // obligation is addressed to a surface they could match.
        for id in [
            "b2c3d4e5f60718293a4b5c6d7e8f9012",
            "d4e5f60718293a4b5c6d7e8f90123456",
        ] {
            assert!(run_row(result, id)["delivery"].is_null(), "{id}");
        }

        // Every store consulted is named, including the profile home that has
        // no ledger — an empty history and an absent store are different.
        let sources = result["sources"].as_array().unwrap();
        let states: Vec<(&str, &str)> = sources
            .iter()
            .map(|source| {
                (
                    source["harness"].as_str().unwrap(),
                    source["state"].as_str().unwrap(),
                )
            })
            .collect();
        assert_eq!(
            states,
            vec![
                ("hermes", "read"),
                ("hermes", "absent_store"),
                ("hermes", "read"),
                ("openclaw", "read"),
            ],
            "{result}"
        );
        assert_eq!(sources[2]["profile"], "ops");
        assert!(sources[3]["path"]
            .as_str()
            .is_some_and(|path| path.ends_with("state/openclaw.sqlite")));
    }

    #[test]
    fn runs_list_joins_a_hermes_fire_to_the_session_it_opened() {
        let response = runs_list(json!({
            "harness": "hermes",
            "job": "job42",
            "homes": jobs_fixture_homes(),
        }));
        let result = &response["result"];
        assert_eq!(result["runs"].as_array().unwrap().len(), 2, "{result}");

        // Hermes writes NO link from an execution to its session. The fire
        // that ran the agent is joined to `cron_job42_<stamp>` because that
        // id's instant falls inside its [claimed_at, finished_at] window.
        let ran = run_row(result, "a1b2c3d4e5f60718293a4b5c6d7e8f90");
        assert_eq!(ran["session_id"], "cron_job42_20260902_120000");

        // The later fire failed before opening one. Its window holds no
        // session, so the row says so instead of re-using the earlier fire's
        // — the join is per-FIRE, not per-job.
        let failed = run_row(result, "b2c3d4e5f60718293a4b5c6d7e8f9012");
        assert!(failed["session_id"].is_null(), "{failed}");
    }

    /// ORCH-13: where a fire's output went, read from each harness's own
    /// delivery record — Hermes's `delivery_obligations` ledger inside
    /// `state.db`, OpenClaw's `delivery_*` run-log columns.
    #[test]
    fn runs_list_reads_the_delivery_each_harness_recorded_for_a_fire() {
        let response = runs_list(json!({"homes": jobs_fixture_homes()}));
        let result = &response["result"];

        // Hermes: the ledger is the GATEWAY's, keyed by conversation and
        // surface, so the fire's own [claimed_at, finished_at] window picks
        // the obligation. The fire succeeded and so did the send.
        let delivered = run_row(result, "e5f60718293a4b5c6d7e8f9012345678");
        assert_eq!(delivered["status"], "completed");
        assert_eq!(delivered["delivery"]["state"], "delivered");
        assert_eq!(delivered["delivery"]["target"], "telegram:-100777:55");
        assert_eq!(delivered["delivery"]["attempts"], 1);
        assert!(delivered["delivery"]["last_error"].is_null(), "{delivered}");
        assert_eq!(
            delivered["delivery"]["delivered_at"],
            "2026-09-02T09:00:30.400Z"
        );

        // The next fire of the same job ALSO succeeded — and its output never
        // arrived. That is the fact `status` alone cannot carry.
        let undelivered = run_row(result, "f60718293a4b5c6d7e8f901234567890");
        assert_eq!(undelivered["status"], "completed");
        assert_eq!(undelivered["delivery"]["state"], "failed");
        assert_eq!(undelivered["delivery"]["attempts"], 3);
        assert_eq!(
            undelivered["delivery"]["last_error"],
            "telegram send failed: Bad Request: chat not found"
        );
        // Only a delivered obligation carries an instant of delivery; the
        // ledger's `updated_at` on a failed row dates the failure.
        assert!(
            undelivered["delivery"]["delivered_at"].is_null(),
            "{undelivered}"
        );

        // OpenClaw writes the outcome onto the run-log row and declares the
        // address on the job, so the row's target is joined from `cron_jobs`.
        let announced = run_row(result, "run_health_0001");
        assert_eq!(announced["delivery"]["state"], "delivered");
        assert_eq!(announced["delivery"]["target"], "last");
        // Its run log counts no attempts and stamps no delivered-at.
        assert!(announced["delivery"]["attempts"].is_null(), "{announced}");
        assert!(
            announced["delivery"]["delivered_at"].is_null(),
            "{announced}"
        );
        let refused = run_row(result, "run_health_0002");
        assert_eq!(refused["delivery"]["state"], "not-delivered");
        assert_eq!(refused["delivery"]["last_error"], "channel_not_found");

        // A run-log row with no delivery columns at all recorded no delivery:
        // the job's declared target is not evidence that anything was sent.
        let skipped = run_row(result, &format!("{OPENCLAW_DIGEST_JOB}#1"));
        assert!(skipped["delivery"].is_null(), "{skipped}");
    }

    /// A Hermes fire whose session carries a `session_key` is matched on that
    /// key FIRST — the most specific question the ledger can answer. Proven by
    /// moving the obligations off the job's surface on a COPY of the fixture,
    /// so only the session-key question can still find them.
    #[test]
    fn runs_list_matches_a_hermes_obligation_by_the_session_key_first() {
        let scratch = std::env::temp_dir().join(format!(
            "supercode-runs-delivery-{}-{}",
            std::process::id(),
            generated_session_id()
        ));
        std::fs::create_dir_all(scratch.join("cron")).unwrap();
        let fixture = jobs_fixture_root().join("hermes_home");
        std::fs::copy(fixture.join("state.db"), scratch.join("state.db")).unwrap();
        for name in ["cron/executions.db", "cron/jobs.json"] {
            std::fs::copy(fixture.join(name), scratch.join(name)).unwrap();
        }
        {
            let connection = rusqlite::Connection::open(scratch.join("state.db")).unwrap();
            // The obligations now sit on a surface no job in this store
            // delivers to, so the surface question cannot match them.
            connection
                .execute(
                    "UPDATE delivery_obligations SET platform = 'slack', chat_id = 'C0FALLBACK'",
                    [],
                )
                .unwrap();
            // A cron fire that ran inside a keyed conversation: the session
            // the window recovers carries `tg-coder-1`'s key.
            connection
                .execute(
                    "INSERT INTO sessions (id, source, session_key, started_at) VALUES \
                     ('cron_coder-standup_20260902_090010', 'cron', \
                      'agent:coder:telegram:group:-100777:55', 1788339610.0)",
                    [],
                )
                .unwrap();
        }
        let response = runs_list(json!({
            "harness": "hermes",
            "job": "coder-standup",
            "homes": {"hermes": scratch.join("state.db")},
        }));
        let result = &response["result"];
        let matched = run_row(result, "e5f60718293a4b5c6d7e8f9012345678");
        assert_eq!(
            matched["session_id"], "cron_coder-standup_20260902_090010",
            "{result}"
        );
        assert_eq!(matched["delivery"]["state"], "delivered", "{result}");
        assert_eq!(
            matched["delivery"]["target"], "slack:C0FALLBACK:55",
            "{result}"
        );
        std::fs::remove_dir_all(&scratch).ok();
    }

    #[test]
    fn runs_list_follows_a_compression_chain_to_the_readable_tip() {
        // A fire whose session was compressed mid-run is only readable at the
        // continuation, so that is what the row must report. Built on a COPY
        // of the committed fixture: no test writes to a fixture or to a real
        // harness home.
        let scratch = std::env::temp_dir().join(format!(
            "supercode-runs-compressed-{}-{}",
            std::process::id(),
            generated_session_id()
        ));
        std::fs::create_dir_all(scratch.join("cron")).unwrap();
        let fixture = jobs_fixture_root().join("hermes_home");
        std::fs::copy(fixture.join("state.db"), scratch.join("state.db")).unwrap();
        std::fs::copy(
            fixture.join("cron/executions.db"),
            scratch.join("cron/executions.db"),
        )
        .unwrap();
        {
            let connection = rusqlite::Connection::open(scratch.join("state.db")).unwrap();
            connection
                .execute(
                    "UPDATE sessions SET end_reason = 'compression' WHERE id = ?1",
                    ["cron_job42_20260902_120000"],
                )
                .unwrap();
            connection
                .execute(
                    "INSERT INTO sessions (id, source, parent_session_id, started_at) \
                     VALUES ('job42-after-compaction', 'cron', \
                             'cron_job42_20260902_120000', 1788350000.0)",
                    [],
                )
                .unwrap();
        }
        let response = runs_list(json!({
            "harness": "hermes",
            "job": "job42",
            "homes": {"hermes": scratch.join("state.db")},
        }));
        let result = &response["result"];
        assert_eq!(
            run_row(result, "a1b2c3d4e5f60718293a4b5c6d7e8f90")["session_id"],
            "job42-after-compaction",
            "{result}"
        );
        std::fs::remove_dir_all(&scratch).ok();
    }

    #[test]
    fn runs_list_filters_by_job_and_caps_by_limit() {
        let by_job = runs_list(json!({
            "harness": "openclaw",
            "job": OPENCLAW_HEALTH_JOB,
            "homes": jobs_fixture_homes(),
        }));
        let ids: Vec<&str> = by_job["result"]["runs"]
            .as_array()
            .unwrap()
            .iter()
            .map(|run| run["id"].as_str().unwrap())
            .collect();
        assert_eq!(ids, vec!["run_health_0002", "run_health_0001"], "{by_job}");

        let capped = runs_list(json!({
            "harness": "openclaw",
            "limit": 1,
            "homes": jobs_fixture_homes(),
        }));
        let runs = capped["result"]["runs"].as_array().unwrap();
        assert_eq!(runs.len(), 1, "{capped}");
        // Newest first, so the cap keeps the recent fire.
        assert_eq!(runs[0]["id"], "run_health_0002");
    }

    #[test]
    fn runs_get_answers_with_the_row_and_the_verbatim_native_record() {
        let mut service = HarnessSessionService::new();
        let hermes = service.handle(request(
            1,
            "harness.v1.runs.get",
            json!({
                "harness": "hermes",
                "id": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
                "homes": jobs_fixture_homes(),
            }),
        ));
        assert_eq!(hermes["result"]["run"]["status"], "completed");
        assert_eq!(
            hermes["result"]["run"]["session_id"],
            "cron_job42_20260902_120000"
        );
        // Ledger columns the uniform row does not carry survive on `source`.
        assert_eq!(hermes["result"]["source"]["source"], "scheduler");
        assert_eq!(hermes["result"]["source"]["pid"], 4242);
        assert_eq!(hermes["result"]["source"]["process_id"], "9f1c2d");

        let openclaw = service.handle(request(
            2,
            "harness.v1.runs.get",
            json!({
                "harness": "openclaw",
                "id": "run_health_0002",
                "homes": jobs_fixture_homes(),
            }),
        ));
        assert_eq!(openclaw["result"]["run"]["status"], "error");
        // ORCH-13: the run's delivery is projected AND the store's own columns
        // stay verbatim on `source`, so nothing about the fire is lost.
        assert_eq!(
            openclaw["result"]["source"]["delivery_status"],
            "not-delivered"
        );
        assert_eq!(
            openclaw["result"]["source"]["delivery_error"],
            "channel_not_found"
        );
        assert_eq!(openclaw["result"]["source"]["delivered"], 0);
        assert_eq!(
            openclaw["result"]["run"]["delivery"]["state"],
            "not-delivered"
        );
        assert_eq!(
            openclaw["result"]["run"]["delivery"]["last_error"],
            "channel_not_found"
        );

        let missing = service.handle(request(
            3,
            "harness.v1.runs.get",
            json!({"harness": "hermes", "id": "no-such-run", "homes": jobs_fixture_homes()}),
        ));
        assert!(missing["error"]["message"]
            .as_str()
            .is_some_and(|message| message.contains("no run `no-such-run`")));
    }

    #[test]
    fn runs_refuse_a_harness_that_keeps_no_run_store() {
        let mut service = HarnessSessionService::new();
        for (id, method, params) in [
            // Claude Code HAS scheduled jobs but no fire store: its fires are
            // ordinary turns. It must refuse, not answer with an empty list.
            (
                1,
                "harness.v1.runs.list",
                json!({"harness": "claude-code", "homes": jobs_fixture_homes()}),
            ),
            (
                2,
                "harness.v1.runs.get",
                json!({"harness": "claude-code", "id": "anything"}),
            ),
            (
                3,
                "harness.v1.runs.list",
                json!({"harness": "codex", "homes": jobs_fixture_homes()}),
            ),
        ] {
            let response = service.handle(request(id, method, params));
            assert_eq!(response["error"]["code"], -32020, "{response}");
            assert!(response["error"]["message"]
                .as_str()
                .is_some_and(|message| message.contains("keeps no run store")));
            assert!(response.get("result").is_none());
        }
    }

    #[test]
    fn runs_list_reports_an_install_with_no_run_store_as_absent() {
        let scratch = std::env::temp_dir().join(format!(
            "supercode-runs-empty-{}-{}",
            std::process::id(),
            generated_session_id()
        ));
        std::fs::create_dir_all(&scratch).unwrap();
        let response = runs_list(json!({
            "harness": "openclaw",
            "homes": {"openclaw": scratch.clone()},
        }));
        let result = &response["result"];
        assert_eq!(result["runs"].as_array().unwrap().len(), 0, "{result}");
        assert_eq!(result["sources"][0]["state"], "absent_store");
        assert!(result["sources"][0]["path"]
            .as_str()
            .is_some_and(|path| path.ends_with("state/openclaw.sqlite")));
        std::fs::remove_dir_all(&scratch).ok();
    }
}