croft-software 0.2.132

VSCode-style TUI written in Rust
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
//! `croft pair`: the AI pilot that streams a Claude conversation's tokens
//! straight into the collab seat, so a co-editing session sees the edit
//! arrive token by token instead of as one bulk insert (docs/MULTIPLAYER.md,
//! "croft pair").
//!
//! This module's pure core is the fence machine: the model is taught (via
//! the pair system prompt) to wrap edits in a fenced protocol inside its
//! streamed TEXT output:
//!
//! ```text
//! <<<EDIT file:START_ROW:START_COL-END_ROW:END_COL>>>
//! <replacement text>
//! <<<END>>>
//! ```
//!
//! Coordinates are 0-based CHARACTER positions against the buffer text the
//! pilot injected into the turn; byte offsets only ever come from
//! [`crate::collab::byte_offset`] (never treat a column as bytes). The
//! machine is fed raw `text_delta` fragments split at arbitrary points and
//! emits events; everything outside a well-formed fence is commentary and is
//! never applied to a buffer.

pub(crate) mod local;
pub(crate) mod proactive;

use std::io::{BufRead, Read as _, Write as _};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use anyhow::{Context, Result};
use serde_json::{Value, json};

use crate::collab::{
    CollabChannel, CollabEvent, CollabRole, CollabSession, ResolvedSpan, position,
};

/// Start of an edit-fence header line.
const EDIT_MARKER: &str = "<<<EDIT ";
/// Start of a note-fence header line (anchored commentary, never applied).
const NOTE_MARKER: &str = "<<<NOTE ";
/// The whole terminator line.
const END_MARKER: &str = "<<<END>>>";

/// What the fence machine resolved from a run of streamed text deltas, in
/// stream order. Only text between a well-formed `EditStart` and its
/// `EditEnd` ever touches a buffer.
#[derive(Debug)]
pub enum FenceEvent {
    /// Model prose outside any fence (including malformed fences): printed
    /// to the pilot's terminal, never applied.
    Commentary(String),
    /// A well-formed header opened an edit: replace the 0-based char range
    /// `start..end` of `file` with the body that streams next.
    EditStart {
        file: String,
        start: (usize, usize),
        end: (usize, usize),
    },
    /// The next fragment of the current fence's body, in stream order.
    EditBody(String),
    /// The fence closed cleanly; the streamed body is the whole replacement.
    EditEnd,
    /// The turn ended mid-fence (risk R2): the pilot reverts whatever body
    /// already streamed in.
    EditAbort,
    /// A well-formed header opened a note anchored to the 0-based `row` of
    /// `file`: commentary tied to a line, accumulated and surfaced whole at
    /// `NoteEnd`, never applied to any buffer.
    NoteStart { file: String, row: usize },
    /// The next fragment of the current note's body, in stream order.
    NoteBody(String),
    /// The note closed cleanly; its accumulated body may anchor.
    NoteEnd,
    /// The turn ended mid-note: nothing anchors.
    NoteAbort,
}

/// Where the machine is between pushes.
enum FenceState {
    /// Outside a fence: complete lines classify as header or commentary.
    Outside,
    /// Inside a fence body. `held_newline`: a body '\n' was consumed but not
    /// emitted (it may turn out to be the newline that separates the body
    /// from `<<<END>>>`, which is stripped). `at_line_start`: the unprocessed
    /// tail starts a fresh line, so it could still become the END marker.
    /// `is_note`: the fence opened with NOTE, so body/end/abort events use
    /// the note variants (same scanner, different consumer semantics).
    Body {
        held_newline: bool,
        at_line_start: bool,
        is_note: bool,
    },
}

/// Incremental parser for the fenced edit protocol. Fed `text_delta`
/// fragments split at arbitrary points; emits [`FenceEvent`]s as soon as
/// they are unambiguous, so a fence body streams token by token (the whole
/// point of `croft pair`). Call [`finish`](Self::finish) at end of turn.
pub struct FenceMachine {
    buf: String,
    state: FenceState,
}

impl FenceMachine {
    pub fn new() -> Self {
        Self {
            buf: String::new(),
            state: FenceState::Outside,
        }
    }

    /// Feed one streamed fragment; returns every event it completed.
    pub fn push(&mut self, delta: &str) -> Vec<FenceEvent> {
        self.buf.push_str(delta);
        let mut events = Vec::new();
        loop {
            match self.state {
                FenceState::Outside => {
                    let Some(nl) = self.buf.find('\n') else {
                        break;
                    };
                    let line: String = self.buf.drain(..=nl).collect();
                    let trimmed = &line[..line.len() - 1];
                    if let Some(start) = parse_header(trimmed) {
                        events.push(start);
                        self.state = FenceState::Body {
                            held_newline: false,
                            at_line_start: true,
                            is_note: false,
                        };
                    } else if let Some(start) = parse_note_header(trimmed) {
                        events.push(start);
                        self.state = FenceState::Body {
                            held_newline: false,
                            at_line_start: true,
                            is_note: true,
                        };
                    } else {
                        events.push(FenceEvent::Commentary(line));
                    }
                }
                FenceState::Body {
                    ref mut held_newline,
                    ref mut at_line_start,
                    is_note,
                } => {
                    let body_event = if is_note {
                        FenceEvent::NoteBody
                    } else {
                        FenceEvent::EditBody
                    };
                    if *at_line_start {
                        match self.buf.find('\n') {
                            Some(nl) => {
                                if &self.buf[..nl] == END_MARKER {
                                    // The held newline separated body from
                                    // the marker: stripped, not body.
                                    self.buf.drain(..=nl);
                                    events.push(if is_note {
                                        FenceEvent::NoteEnd
                                    } else {
                                        FenceEvent::EditEnd
                                    });
                                    self.state = FenceState::Outside;
                                } else {
                                    // A complete body line: the held newline
                                    // is confirmed body, the line's own
                                    // newline is held in its place.
                                    let mut body = String::new();
                                    if *held_newline {
                                        body.push('\n');
                                    }
                                    body.push_str(&self.buf[..nl]);
                                    self.buf.drain(..=nl);
                                    events.push(body_event(body));
                                    *held_newline = true;
                                }
                            }
                            None => {
                                if END_MARKER.starts_with(self.buf.as_str()) {
                                    // Could still become the terminator (or
                                    // is it, pending its newline): wait.
                                    break;
                                }
                                // Provably not the marker: stream it now.
                                let mut body = String::new();
                                if *held_newline {
                                    body.push('\n');
                                    *held_newline = false;
                                }
                                body.push_str(&self.buf);
                                self.buf.clear();
                                events.push(body_event(body));
                                *at_line_start = false;
                                break;
                            }
                        }
                    } else {
                        match self.buf.find('\n') {
                            Some(nl) => {
                                if nl > 0 {
                                    events.push(body_event(self.buf[..nl].to_string()));
                                }
                                self.buf.drain(..=nl);
                                *held_newline = true;
                                *at_line_start = true;
                            }
                            None => {
                                if !self.buf.is_empty() {
                                    events.push(body_event(std::mem::take(&mut self.buf)));
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }
        events
    }

    /// End of turn: flush leftovers. Outside a fence the tail is commentary;
    /// a bare END marker with no trailing newline still closes the fence;
    /// anything else mid-fence aborts it (the pilot reverts). The machine is
    /// reset for the next turn either way.
    pub fn finish(&mut self) -> Vec<FenceEvent> {
        let mut events = Vec::new();
        match self.state {
            FenceState::Outside => {
                if !self.buf.is_empty() {
                    let mut tail = std::mem::take(&mut self.buf);
                    // Only the unterminated LAST line can be a fence header.
                    // A VALID one is protocol residue (a fence the turn cut
                    // off before its newline) and is dropped like an
                    // unterminated body; malformed ones stay commentary,
                    // the malformed-header rule.
                    let last_start = tail.rfind('\n').map_or(0, |i| i + 1);
                    let line = tail[last_start..].trim_end_matches('\r');
                    if parse_header(line).is_some() || parse_note_header(line).is_some() {
                        tail.truncate(last_start);
                    }
                    if !tail.is_empty() {
                        events.push(FenceEvent::Commentary(tail));
                    }
                }
            }
            FenceState::Body {
                at_line_start,
                is_note,
                ..
            } => {
                if at_line_start && self.buf == END_MARKER {
                    events.push(if is_note {
                        FenceEvent::NoteEnd
                    } else {
                        FenceEvent::EditEnd
                    });
                } else if is_note {
                    events.push(FenceEvent::NoteAbort);
                } else {
                    events.push(FenceEvent::EditAbort);
                }
                self.buf.clear();
            }
        }
        self.state = FenceState::Outside;
        events
    }
}

/// Parse an EDIT header into its [`FenceEvent::EditStart`]. Two forms:
/// four integers `<file>:SR:SC-ER:EC` (character range), or two integers
/// `<file>:SR-ER` (whole rows, inclusive — start column 0, end column
/// `usize::MAX`, which [`crate::collab::byte_offset`] clamps to the end of
/// row ER). Coordinates bind rightmost so the file name may itself contain
/// ':' or '-'. None = not a well-formed header (the line degrades to
/// commentary).
fn parse_header(line: &str) -> Option<FenceEvent> {
    let inner = line.strip_prefix(EDIT_MARKER)?.strip_suffix(">>>")?;
    parse_char_range_header(inner).or_else(|| parse_whole_line_header(inner))
}

/// The four-int form: `<file>:SR:SC-ER:EC`.
fn parse_char_range_header(inner: &str) -> Option<FenceEvent> {
    let (rest, ec) = inner.rsplit_once(':')?;
    let (rest, mid) = rest.rsplit_once(':')?;
    let (sc, er) = mid.split_once('-')?;
    let (file, sr) = rest.rsplit_once(':')?;
    if file.is_empty() {
        return None;
    }
    Some(FenceEvent::EditStart {
        file: file.to_string(),
        start: (sr.parse().ok()?, sc.parse().ok()?),
        end: (er.parse().ok()?, ec.parse().ok()?),
    })
}

/// The two-int whole-line form: `<file>:SR-ER`, both rows inclusive. A file
/// part that itself ends in `:<digits>` is a TRUNCATED four-int header
/// (`file:SR:SC-ER` missing its end column), not a path — rejected so it
/// degrades to commentary instead of editing a bogus file.
fn parse_whole_line_header(inner: &str) -> Option<FenceEvent> {
    let (file, range) = inner.rsplit_once(':')?;
    let (sr, er) = range.split_once('-')?;
    if file.is_empty() {
        return None;
    }
    if let Some((_, tail)) = file.rsplit_once(':')
        && !tail.is_empty()
        && tail.chars().all(|c| c.is_ascii_digit())
    {
        return None;
    }
    Some(FenceEvent::EditStart {
        file: file.to_string(),
        start: (sr.parse().ok()?, 0),
        end: (er.parse().ok()?, usize::MAX),
    })
}

/// Parse `<<<NOTE <file>:<row>>>>` into its [`FenceEvent::NoteStart`]. The
/// row binds rightmost so the file name may itself contain ':'. None = not
/// a well-formed header (the line degrades to commentary).
fn parse_note_header(line: &str) -> Option<FenceEvent> {
    let inner = line.strip_prefix(NOTE_MARKER)?.strip_suffix(">>>")?;
    let (file, row) = inner.rsplit_once(':')?;
    if file.is_empty() {
        return None;
    }
    Some(FenceEvent::NoteStart {
        file: file.to_string(),
        row: row.parse().ok()?,
    })
}

/// A fence range as byte offsets into the joined ('\n'-separated) text of
/// `lines`, via the shared char-coordinate bridge (risk R6: columns are
/// chars, offsets are bytes; this is the only conversion path).
pub fn range_bytes(lines: &[String], start: (usize, usize), end: (usize, usize)) -> (usize, usize) {
    (
        crate::collab::byte_offset(lines, start.0, start.1),
        crate::collab::byte_offset(lines, end.0, end.1),
    )
}

/// Byte offset of the start of `row` in `lines`, clamped to the last line
/// (models sometimes cite a row just past EOF).
fn note_offset(lines: &[String], row: usize) -> usize {
    let row = row.min(lines.len().saturating_sub(1));
    crate::collab::byte_offset(lines, row, 0)
}

/// Replay remote-edit spans over every note anchored in `file`, keeping
/// their offsets true while other participants type.
fn shift_notes(notes: &mut [Note], file: &str, spans: &[ResolvedSpan]) {
    for n in notes.iter_mut().filter(|n| n.file == file) {
        for span in spans {
            n.offset = shift_offset(n.offset, span);
        }
    }
}

/// Transform a tracked byte offset through one remote edit span, the same
/// sequential replay the buffers do: a span entirely before the offset
/// shifts it by the size delta (an insert exactly at the offset counts as
/// before, pushing it right); a span straddling it clamps to the span's new
/// end; a span after it leaves it alone.
pub fn shift_offset(x: usize, span: &ResolvedSpan) -> usize {
    if span.at + span.deleted <= x {
        // No underflow: span.deleted <= x on this branch.
        x + span.inserted.len() - span.deleted
    } else if span.at < x {
        span.at + span.inserted.len()
    } else {
        x
    }
}

// ---------------------------------------------------------------------------
// Pilot runtime: spawn the claude CLI in stream-json mode, parse its token
// stream through the fence machine, and apply fences live through a collab
// guest seat. Cancel rides the relay (CollabMsg::StreamCancel) and lands as
// a control_request interrupt on claude's stdin.
// ---------------------------------------------------------------------------

/// The tools the pilot's claude may call without a prompt (approved product
/// decision: read-only plus the stream; the ONLY write path is the fence).
/// The `croft-collab` MCP server here is a second, read-only seat riding
/// along for live buffer queries; the pilot itself owns the writing seat.
/// `Read`, `Grep` and `Glob` are deliberately not listed: a bare rule
/// matches every path (`~/.ssh`, `~/.aws`), while with no rule `dontAsk`
/// runs them inside the workspace and denies them outside it (#1926).
const ALLOWED_TOOLS: &str = "mcp__croft-collab__collab_open,mcp__croft-collab__collab_read,\
     mcp__croft-collab__collab_status";

/// The built-in tools the pilot's claude has at all: no settings file can
/// allow a tool outside this set, so there is no shell and no write tool
/// whatever the user's or the workspace's settings say (#1926).
const BUILTIN_TOOLS: &str = "Read,Grep,Glob";

/// The settings the pilot's claude loads: the user's own (sign-in, model,
/// their own hooks). The workspace's `.claude/settings.json` belongs to
/// whoever committed it, and its hooks would run the moment the navigator
/// starts, before anyone asked it anything (#1926).
const SETTING_SOURCES: &str = "user";

/// How long an EditStart waits for its file to bootstrap, a hair past the
/// session's own 3s deadline (same reasoning as the collab agent's).
const LIVE_TIMEOUT: Duration = Duration::from_secs(4);

/// Taught to the model via --append-system-prompt: the fence protocol whose
/// streamed body croft applies token by token.
const PAIR_SYSTEM_PROMPT: &str = r#"You are pair-programming INSIDE the croft editor: your streamed text is parsed live and fenced edits are applied to the shared buffer token by token, so your human partner watches the edit appear as you write it.

To edit a file, emit an edit fence directly in your text output:

<<<EDIT <file>:<start_row>:<start_col>-<end_row>:<end_col>>>>
<replacement text>
<<<END>>>

Rules:
- The header carries the file plus EXACTLY FOUR integers: START_ROW:START_COL-END_ROW:END_COL. Never omit the rows — for a single-line edit on row N the header reads <file>:N:C1-N:C2 (e.g. replacing columns 15..19 of row 0 of demo.txt, your partner's gutter line 1, is `<<<EDIT demo.txt:0:15-0:19>>>`, NOT `demo.txt:15:19`). A header without all four numbers is ignored as plain text and your edit does not happen.
- <file> is the workspace-relative path. Coordinates are 0-based CHARACTER positions (not bytes) into the file's CURRENT text: the range start..end (start inclusive, end exclusive) is deleted and the fence body replaces it. To insert without deleting, use a zero-width range (start == end).
- Compute coordinates against the buffer text in the latest user message (the --- CURRENT BUFFER --- block) or from the mcp__croft-collab__collab_read tool. If you emit several fences in one reply, later fences must use coordinates that account for your earlier fences' changes.
- The header and <<<END>>> each sit alone on their own line. The body between them is applied verbatim: real code only, no markdown fences, no commentary.
- Everything outside a fence is commentary shown to your partner in the terminal; it is never applied to any buffer.
- Start the fence as soon as you know the edit; stream the body naturally rather than planning silently.

Example (replace rows 3-4 of src/lib.rs, gutter lines 4-5, where row 4 is 12 chars long):
<<<EDIT src/lib.rs:3:0-4:12>>>
fn renamed() -> u32 {
    41 + 1
}
<<<END>>>

To pin a remark to a specific line WITHOUT editing anything, emit a note fence:

<<<NOTE <file>:<row>>>>
<what you want to say about that line>
<<<END>>>

Note rules:
- The header carries the file plus EXACTLY ONE integer, the 0-based row the note speaks about (e.g. `<<<NOTE demo.txt:4>>>` pins a remark to row 4 of demo.txt, gutter line 5). Your partner sees it attached to that line in their editor.
- Notes never change any buffer. Use them for review remarks, questions, and change proposals.

Some user messages number the buffer: each line arrives prefixed with `N|` where N is its 0-based row. The prefix is a label, not content — character columns still count from the first character AFTER the first `|`, and NOTE/EDIT rows use exactly those N values.
Your partner's gutter numbers lines from 1, so row N is line N+1 to them. Whenever you mention a line in words they read (a note body or your commentary), use that 1-based gutter number. Fence headers and `N|` prefixes stay 0-based.

Turn kinds:
- An ask turn names a task and where you were invoked: you may edit with EDIT fences and remark with NOTE fences.
- A yielded turn says it is COMMENT-ONLY: your partner handed you the floor to review, not to type. EDIT fences on such a turn are DISCARDED by the editor. Speak in NOTE fences anchored to the lines you mean, propose changes there, and wait to be asked before editing.
- A reply turn answers one of your notes with your partner's own words. If the reply asks for a change ("correct this", "do it"), that is the ask: make the change with EDIT fences. If it asks a question or disagrees, answer with NOTE fences.

A participant can cancel your stream mid-edit; the streamed text is then reverted and your next user message starts with a note saying so. When that happens, stop that approach and ask what they want instead."#;

/// Appended to [`PAIR_SYSTEM_PROMPT`] for local models only: character
/// columns trip weaker models (the spike's under-covered range), so they are
/// steered to the whole-line header form instead.
const LOCAL_MODEL_PROMPT_SUFFIX: &str = r#"Local-model addendum:
- PREFER the whole-line EDIT header form: <<<EDIT <file>:<start_row>-<end_row>>>> with exactly TWO integers. It replaces those entire lines — both rows 0-based, both INCLUSIVE — with the fence body, so you never count characters. Replacing row 1 (gutter line 2) whole is `<<<EDIT greet.py:1-1>>>`.
- Rewrite whole lines instead of splicing inside a line; use the four-integer form only when you must keep part of a line.
- You have no tools: everything you need is in the message. Keep replies short — the fences plus at most a couple of commentary lines."#;

/// Which conversation transport seats the navigator: the claude CLI child
/// (the full agent) or a direct Anthropic-compatible `/v1/messages` endpoint
/// (Ollama, LM Studio, llama.cpp, vLLM — the minimal payload those can
/// actually serve; see docs/MULTIPLAYER.md).
#[derive(Clone, Debug, PartialEq)]
pub enum Provider {
    Claude,
    Local { base_url: String },
}

impl Provider {
    /// Map a pair record's stringly provider to the transport it names.
    /// Absent or unrecognized = Claude (every 0.1.635 record is claude).
    pub fn from_record(provider: Option<&str>, base_url: Option<&str>) -> Self {
        match provider {
            Some("ollama") => Provider::Local {
                base_url: base_url.unwrap_or("http://localhost:11434").to_string(),
            },
            _ => Provider::Claude,
        }
    }
}

/// The system prompt a provider's model is taught: the shared fence
/// protocol, plus the whole-line guidance for local models.
pub(crate) fn system_prompt(provider: &Provider) -> std::borrow::Cow<'static, str> {
    match provider {
        Provider::Claude => std::borrow::Cow::Borrowed(PAIR_SYSTEM_PROMPT),
        Provider::Local { .. } => std::borrow::Cow::Owned(format!(
            "{PAIR_SYSTEM_PROMPT}\n\n{LOCAL_MODEL_PROMPT_SUFFIX}"
        )),
    }
}

/// Everything `croft pair` needs to sit down: the relay socket, the
/// workspace (cwd and MCP reader seat), the caret name, and the claude
/// launch knobs.
pub struct PairConfig {
    pub socket: PathBuf,
    pub workspace: PathBuf,
    pub name: String,
    pub model: Option<String>,
    pub task: Option<String>,
    pub provider: Provider,
}

/// The fence currently streaming into a buffer: byte offsets into the
/// replica text (kept fresh against concurrent remote edits by
/// [`shift_offset`]) plus the slice the fence's range deleted, for revert.
struct StreamRegion {
    file: String,
    start: usize,
    anchor: usize,
    original: String,
    /// Notes whose anchors sat at or inside the fence's range when it
    /// opened, as `(note id, offset - start)`: the delete collapses them
    /// and the streamed inserts drag them along, so the revert can only
    /// restore them from these recorded deltas (`start` keeps tracking
    /// remote edits, so `start + delta` stays exact in the restored text).
    displaced: Vec<(u64, usize)>,
}

/// What [`PairState::stage_turn`] overwrote, so a send that never leaves
/// the process can be undone ([`PairState::unstage_turn`]).
pub(crate) struct StagedTurn {
    file: String,
    /// The previous look at `file`; also the yield-diff baseline the
    /// caller reads before sending.
    pub(crate) prior_seen: Option<String>,
    prior_comment_only: bool,
    prior_target: Option<String>,
    /// Which staging this undo belongs to: a rollback that lands after a
    /// NEWER turn has staged (its send failed while the pilot mutex was
    /// wedged, so the unstage waited on a thread) is stale and must not
    /// stomp the live turn's books.
    stage_gen: u64,
}

/// One anchored navigator note: a byte offset into `file`'s replica text
/// (kept fresh against concurrent edits exactly like the stream region)
/// plus the accumulated body.
pub struct Note {
    /// Stable identity for the note's comment box: Ignore removes exactly
    /// this note, a reply appends to exactly this note. Monotonic per seat.
    pub id: u64,
    pub file: String,
    pub offset: usize,
    pub body: String,
}

/// Shared pilot state: the collab seat plus per-turn stream bookkeeping.
/// Locked briefly by the reader thread (apply), the pump thread (remote
/// shifts, cancel), and the driver (turn injection); never held across a
/// sleep or a child-process write.
pub(crate) struct PairState {
    session: CollabSession,
    region: Option<StreamRegion>,
    /// The current fence's body is being dropped (unusable header, missing
    /// owner, or a post-cancel fence).
    discarding: bool,
    /// A cancel landed this turn: every further fence event is ignored
    /// until the turn's result, and the next turn opens with a note.
    cancelled: bool,
    /// claude's init advertised interrupt_receipt_v1.
    can_interrupt: bool,
    /// Between sending a user message and seeing its result.
    turn_active: bool,
    /// Whose buffer rides in the next turn's injection.
    target_file: Option<String>,
    /// Prepended to the next user turn (set by cancel).
    pending_note: Option<String>,
    /// Bumped by every [`Self::stage_turn`]; pairs with
    /// [`StagedTurn::stage_gen`] so a deferred rollback can recognise that
    /// a newer turn has staged and drop itself.
    stage_gen: u64,
    /// Anchored navigator notes; offsets kept fresh by the pump.
    notes: Vec<Note>,
    /// Next note id (monotonic; ids are never reused within a seat).
    next_note_id: u64,
    /// The NOTE fence currently streaming: (file, 0-based row, body so far).
    note_in_flight: Option<(String, usize, String)>,
    /// The in-process host's sink: when seated inside croft the pilot's
    /// voice (commentary, notes, diagnostics) goes here instead of
    /// stdout/stderr, which belong to the TUI. None = terminal REPL.
    events: Option<Sender<crate::pair_host::PairEvent>>,
    /// This turn is a yielded one: the navigator may only comment. EDIT
    /// fences are discarded at the host, not just discouraged in the
    /// prompt. Reset at each turn's result.
    comment_only: bool,
    /// Where the seat wants its visible caret parked (file, 0-based row)
    /// once the file's bootstrap lands; the pump resolves it. The caret is
    /// the navigator's persistent presence between edits.
    pending_caret: Option<(String, usize)>,
    /// What the navigator last saw of each file (yield turns diff against
    /// this instead of resending history).
    last_seen: std::collections::HashMap<String, String>,
}

impl PairState {
    /// A fresh seat over `session`: no turn in flight, nothing streamed yet.
    /// `events` seats the pilot inside croft (its voice becomes
    /// [`crate::pair_host::PairEvent`]s); None keeps stdio.
    pub(crate) fn new(
        session: CollabSession,
        events: Option<Sender<crate::pair_host::PairEvent>>,
    ) -> Self {
        Self {
            session,
            region: None,
            discarding: false,
            cancelled: false,
            can_interrupt: false,
            turn_active: false,
            target_file: None,
            pending_note: None,
            stage_gen: 0,
            notes: Vec::new(),
            next_note_id: 1,
            note_in_flight: None,
            events,
            comment_only: false,
            pending_caret: None,
            last_seen: std::collections::HashMap::new(),
        }
    }

    /// The live replica text of `file`, split into lines (None = not live).
    pub(crate) fn doc_lines(&self, file: &str) -> Option<Vec<String>> {
        self.session
            .doc_text(file)
            .map(|t| t.split('\n').map(String::from).collect())
    }

    /// The anchored notes sitting in `file`, in landing order.
    pub(crate) fn notes_in<'a>(&'a self, file: &'a str) -> impl Iterator<Item = &'a Note> {
        self.notes.iter().filter(move |n| n.file == file)
    }

    /// True between sending a user turn and seeing its result. A new turn
    /// must not be sent while this holds: the shared `comment_only` flag and
    /// the target file would be clobbered mid-stream, defeating the
    /// host-enforced comment-only guarantee on a yield.
    pub(crate) fn turn_active(&self) -> bool {
        self.turn_active
    }

    /// Drop every note in every file (the user asked for a clean slate).
    pub(crate) fn clear_all_notes(&mut self) {
        self.notes.clear();
    }

    /// Drop exactly one note (the driver ignored its comment box).
    pub(crate) fn remove_note(&mut self, id: u64) {
        self.notes.retain(|n| n.id != id);
    }

    /// Append one line to a note's body (the driver replied in its box, so
    /// the box keeps the running conversation).
    pub(crate) fn append_to_note(&mut self, id: u64, line: &str) {
        if let Some(n) = self.notes.iter_mut().find(|n| n.id == id) {
            n.body.push('\n');
            n.body.push_str(line);
        }
    }

    /// The next note id (monotonic within the seat).
    fn take_note_id(&mut self) -> u64 {
        let id = self.next_note_id;
        self.next_note_id += 1;
        id
    }

    /// Arm a host turn targeting `file`: mode, target, and the last-seen
    /// bookkeeping the yield diff reads. Returns what the navigator
    /// previously saw of the file (None = first look).
    pub(crate) fn begin_turn(
        &mut self,
        file: &str,
        content: &str,
        comment_only: bool,
    ) -> Option<String> {
        self.comment_only = comment_only;
        self.target_file = Some(file.to_string());
        self.session.request_file(file);
        // Notes deliberately survive the new turn: they are open comment
        // boxes, and only the driver closes them (Ignore / Clear All).
        self.last_seen.insert(file.to_string(), content.to_string())
    }

    /// [`Self::begin_turn`] plus everything needed to undo it: the caller
    /// stages the look BEFORE the send, and a failed send must not keep it
    /// (`last_seen` is the yield-diff baseline — a retry would diff the
    /// file against itself — and a latched `comment_only` would silently
    /// edit-suppress the next successful turn).
    pub(crate) fn stage_turn(
        &mut self,
        file: &str,
        content: &str,
        comment_only: bool,
    ) -> StagedTurn {
        let prior_comment_only = self.comment_only;
        let prior_target = self.target_file.clone();
        let prior_seen = self.begin_turn(file, content, comment_only);
        self.stage_gen += 1;
        StagedTurn {
            file: file.to_string(),
            prior_seen,
            prior_comment_only,
            prior_target,
            stage_gen: self.stage_gen,
        }
    }

    /// Put back what [`Self::stage_turn`] overwrote (the send never left).
    /// A no-op when a NEWER turn has staged since: this rollback ran late
    /// (see [`StagedTurn::stage_gen`]) and its books are stale.
    pub(crate) fn unstage_turn(&mut self, staged: StagedTurn) {
        if self.stage_gen != staged.stage_gen {
            return;
        }
        // An applied undo re-opens the generation beneath it, so undo
        // records unwind LIFO all the way back to the original state
        // (turn A fails parked, turn B stages over the residue and fails:
        // B's undo restores A's books AND re-admits A's undo).
        self.stage_gen = staged.stage_gen - 1;
        self.comment_only = staged.prior_comment_only;
        self.target_file = staged.prior_target;
        match staged.prior_seen {
            Some(old) => {
                self.last_seen.insert(staged.file, old);
            }
            None => {
                self.last_seen.remove(&staged.file);
            }
        }
    }

    /// Park the navigator's visible caret at `row` (0-based, column 0):
    /// broadcast now when the file is live, else once its bootstrap lands
    /// (the pump resolves it). A newer park supersedes an unresolved one.
    pub(crate) fn park_caret(&mut self, file: &str, row: usize) {
        self.pending_caret = (!self.send_parked_caret(file, row)).then(|| (file.to_string(), row));
    }

    /// Broadcast the caret at an exact position and drop any unresolved
    /// pending park — a streamed edit or a landed note is newer attention,
    /// and a stale park firing afterwards would yank the caret back.
    fn caret_now(&mut self, file: &str, row: usize, col: usize) {
        self.pending_caret = None;
        self.session.send_caret(file, row, col);
    }

    /// This seat's site id in every live file: the navigator's wire
    /// identity (the App keys caret color and unseat cleanup off these).
    pub(crate) fn my_site_ids(&self) -> Vec<u64> {
        self.session.my_site_ids()
    }

    /// What the navigator last saw of `file` (None = it never looked).
    /// The proactive trigger diffs the live buffer against this.
    pub(crate) fn last_seen_of(&self, file: &str) -> Option<String> {
        self.last_seen.get(file).cloned()
    }

    /// Broadcast the parked caret when `file` is live, the row clamped to
    /// the document's last line. False = not live yet.
    fn send_parked_caret(&mut self, file: &str, row: usize) -> bool {
        let Some(lines) = self.doc_lines(file) else {
            return false;
        };
        let row = row.min(lines.len().saturating_sub(1));
        self.session.send_caret(file, row, 0);
        true
    }

    /// Resolve a pending caret park (one pump tick): broadcast it if the
    /// file went live, drop it if the bootstrap died unanswered.
    fn resolve_pending_caret(&mut self) {
        let Some((file, row)) = self.pending_caret.clone() else {
            return;
        };
        if self.send_parked_caret(&file, row) || !self.session.is_bootstrapping(&file) {
            self.pending_caret = None;
        }
    }
}

/// Bounded lock for anything that DECIDES or ACTS on the pilot's state
/// from the App's threads (is a turn running? send this ask; land this
/// note): transient contention is normal — the pilot's pump holds the
/// mutex for microseconds every 25ms poll — so an instant try_lock
/// spuriously refuses keypresses and misreports a quiet seat as busy. But
/// an unbounded lock joins the deadlock cycle when a pilot thread is
/// wedged in a blocking relay write. Retry briefly, then give up.
/// Per-frame render reads never wait at all (see `PairHost::caret_sites`):
/// they have a next frame, a decision does not.
pub(crate) fn lock_briefly(
    state: &Mutex<PairState>,
) -> Option<std::sync::MutexGuard<'_, PairState>> {
    let deadline = std::time::Instant::now() + Duration::from_millis(100);
    loop {
        if let Ok(guard) = state.try_lock() {
            return Some(guard);
        }
        if std::time::Instant::now() > deadline {
            return None;
        }
        std::thread::sleep(Duration::from_millis(1));
    }
}

/// Host and child DIAGNOSTICS, never the model's voice. Seated in croft
/// they go to the OUTPUT channel: [`say`]'s Commentary events are reserved
/// for the model's own prose, which the App anchors as a navigator comment
/// box — a diagnostic riding that channel was rendered as the navigator's
/// remark in the user's file and counted as one of its comments. The REPL
/// driver prints to stdout, its only voice.
fn diag(state: &Mutex<PairState>, level: crate::output::OutputLevel, text: &str) {
    // Bounded (see lock_briefly): diagnostics also fire from paths a
    // wedged pilot would block. Unknown seating falls back to OUTPUT — the
    // right sink when seated, and for the REPL a diagnostic in OUTPUT is
    // the lesser loss (stdout is unreachable without the lock, and stderr
    // would corrupt a seated alternate screen).
    let seated = lock_briefly(state).is_none_or(|st| st.events.is_some());
    if seated {
        crate::output::push("Navigator", level, text);
    } else {
        println!("{text}");
        let _ = std::io::Write::flush(&mut std::io::stdout());
    }
}

/// The pilot's voice: an event to the in-process host when seated inside
/// croft (stdout belongs to the TUI there), else the debug REPL's stdout.
fn say(state: &Mutex<PairState>, text: &str) {
    let sink = state.lock().unwrap().events.clone();
    match sink {
        Some(tx) => {
            let _ = tx.send(crate::pair_host::PairEvent::Commentary(text.to_string()));
        }
        None => {
            print!("{text}");
            let _ = std::io::Stdout::flush(&mut std::io::stdout());
        }
    }
}

/// Bounded wait for a requested file's bootstrap ([`LIVE_TIMEOUT`]). True
/// when the file went live; false when nobody answered (no owner).
fn wait_live(state: &Mutex<PairState>, file: &str) -> bool {
    let deadline = Instant::now() + LIVE_TIMEOUT;
    loop {
        let st = state.lock().unwrap();
        if st.session.is_live(file) {
            return true;
        }
        if !st.session.is_bootstrapping(file) || Instant::now() >= deadline {
            return false;
        }
        drop(st);
        std::thread::sleep(Duration::from_millis(20));
    }
}

/// Where a composed user turn goes. The claude backend wraps it in a
/// stream-json user message on the child's stdin; the local backend queues
/// the raw body to its HTTP worker instead. Everything upstream of the sink
/// (turn composition, pending notes, turn_active) is shared.
#[derive(Clone)]
pub(crate) enum TurnSink {
    Claude(Arc<Mutex<Option<ChildStdin>>>),
    Local(Sender<String>),
}

impl TurnSink {
    /// Deliver one composed user-turn body to the model conversation.
    fn send_user(&self, content: &str) -> Result<()> {
        match self {
            TurnSink::Claude(writer) => {
                let msg = json!({
                    "type": "user",
                    "message": { "role": "user", "content": content },
                });
                let mut w = writer.lock().unwrap();
                let w = w.as_mut().context("claude stdin already closed")?;
                writeln!(w, "{msg}").context("writing user turn to claude")?;
                w.flush().context("flushing claude stdin")
            }
            TurnSink::Local(turns) => {
                anyhow::ensure!(
                    turns.send(content.to_string()).is_ok(),
                    "the local turn worker is gone"
                );
                Ok(())
            }
        }
    }
}

/// Kill the claude child when the pilot unwinds, however it unwinds.
struct ChildGuard(Child);

impl Drop for ChildGuard {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

/// What the reader thread reports at each turn's `result` event.
pub(crate) struct TurnEnd {
    pub(crate) is_error: bool,
    /// The turn was cancelled by a participant (the interrupt surfaces as
    /// an error result; the driver names the real cause instead).
    pub(crate) cancelled: bool,
    pub(crate) text: String,
}

/// The claude CLI invocation for a pair session: a persistent stream-json
/// conversation over stdio, sandboxed to the read-only toolbox, with the
/// Install dirs to probe for the claude CLI when it is not on PATH (npm
/// global bin, the native installer's `~/.claude/local`, homebrew).
fn claude_search_dirs() -> Vec<PathBuf> {
    let mut dirs = Vec::new();
    if let Some(home) = std::env::var_os("HOME") {
        let home = PathBuf::from(home);
        dirs.push(home.join(".claude").join("local"));
        dirs.push(home.join(".local").join("bin"));
        dirs.push(home.join(".npm-global").join("bin"));
    }
    dirs.push(PathBuf::from("/opt/homebrew/bin"));
    dirs.push(PathBuf::from("/usr/local/bin"));
    dirs
}

/// Resolve the claude CLI to a spawnable program string. A terminal launch
/// has claude on PATH and spawns it by bare name; a macOS GUI launch
/// (Croft.app) inherits the stripped launchd PATH, so `Command::new("claude")`
/// fails with ENOENT and the navigator can never seat. When claude is absent
/// from PATH we probe the usual install dirs and pin the absolute path,
/// mirroring the LSP path-only resolution. `None` means fall back to the bare
/// name so the spawn error still surfaces to the user.
fn resolve_claude_in(on_path: bool, dirs: &[PathBuf]) -> Option<String> {
    if on_path {
        return Some(String::from("claude"));
    }
    dirs.iter()
        .map(|d| d.join("claude"))
        .find(|p| p.is_file())
        .map(|p| p.to_string_lossy().into_owned())
}

/// The claude program to spawn, resolved to an absolute path on a stripped
/// GUI PATH (see [`resolve_claude_in`]).
fn claude_program() -> String {
    resolve_claude_in(
        crate::lsp::manager::is_on_path("claude"),
        &claude_search_dirs(),
    )
    .unwrap_or_else(|| String::from("claude"))
}

/// fence protocol appended to its system prompt and a read-only collab-agent
/// seat as its MCP server.
pub(crate) fn claude_command(cfg: &PairConfig) -> Result<Command> {
    let exe = std::env::current_exe().context("resolving croft binary path")?;
    let mcp_config = json!({
        "mcpServers": {
            "croft-collab": {
                "command": exe.to_string_lossy(),
                "args": [
                    "collab-agent",
                    "--workspace", cfg.workspace.to_string_lossy(),
                    "--name", format!("{}-reader", cfg.name),
                ],
            }
        }
    });
    let mut cmd = Command::new(claude_program());
    cmd.arg("-p")
        .args(["--input-format", "stream-json"])
        .args(["--output-format", "stream-json"])
        .arg("--verbose")
        .arg("--include-partial-messages")
        .args(["--permission-mode", "dontAsk"])
        .args(["--setting-sources", SETTING_SOURCES])
        .args(["--tools", BUILTIN_TOOLS])
        .args(["--allowedTools", ALLOWED_TOOLS])
        .arg("--strict-mcp-config")
        .args(["--mcp-config", &mcp_config.to_string()])
        .args(["--append-system-prompt", &system_prompt(&cfg.provider)])
        .current_dir(&cfg.workspace);
    if let Some(model) = &cfg.model {
        cmd.args(["--model", model]);
    }
    Ok(cmd)
}

/// `croft pair --repl`: join the workspace's collab relay as the pilot seat
/// on the configured provider and run the REPL until stdin closes.
pub fn run(cfg: PairConfig) -> Result<()> {
    let pilot = match &cfg.provider {
        Provider::Claude => seat_pilot(&cfg.socket, &cfg.name, claude_command(&cfg)?, None)?,
        Provider::Local { base_url } => {
            let model = cfg
                .model
                .as_deref()
                .context("a local provider needs --model (there is no CLI default)")?;
            seat_local(&cfg.socket, &cfg.name, base_url, model, None)?
        }
    };
    let stdin = std::io::stdin();
    run_pilot(pilot, &cfg.name, cfg.task, &mut stdin.lock())
}

/// Connect the pilot's collab seat, retrying briefly (the dispatch just
/// ensured the relay, but its accept loop may still be coming up).
fn connect_session(socket: &Path, name: &str) -> Result<CollabSession> {
    let deadline = Instant::now() + Duration::from_secs(5);
    loop {
        if let Some(ch) = CollabChannel::connect(socket, CollabRole::Guest) {
            return Ok(CollabSession::new(ch, name.to_string()));
        }
        anyhow::ensure!(
            Instant::now() < deadline,
            "collab relay never came up at {}",
            socket.display()
        );
        std::thread::sleep(Duration::from_millis(10));
    }
}

/// A seated pilot: the transport's threads over shared state. Both drivers
/// — the debug REPL ([`run_pilot`]) and the in-process
/// [`crate::pair_host::PairHost`] — run on top of this.
pub(crate) struct Pilot {
    pub(crate) state: Arc<Mutex<PairState>>,
    pub(crate) sink: TurnSink,
    pub(crate) turn_rx: Receiver<TurnEnd>,
    stop: Arc<AtomicBool>,
    transport: Transport,
}

/// The per-backend half of a seated pilot: what owns the conversation and
/// which threads to reap at shutdown.
enum Transport {
    /// The claude CLI child: a persistent stream-json conversation over its
    /// stdio, read by a dedicated thread.
    Claude {
        guard: ChildGuard,
        reader: std::thread::JoinHandle<()>,
        pump: std::thread::JoinHandle<()>,
    },
    /// A local Anthropic-compatible endpoint: no child; a detached worker
    /// drains the queued turn bodies through one HTTP stream each and exits
    /// when the queue closes (shutdown never joins it — a mid-stream read
    /// can take minutes).
    Local { pump: std::thread::JoinHandle<()> },
}

impl Pilot {
    /// The conversation is gone (claude's stdout hit EOF). A local seat has
    /// no child to lose: endpoint failures surface per turn instead.
    pub(crate) fn reader_finished(&self) -> bool {
        match &self.transport {
            Transport::Claude { reader, .. } => reader.is_finished(),
            Transport::Local { .. } => false,
        }
    }

    /// Tear the seat down: leave no stream badge behind, hang up, then reap.
    /// Claude: the real CLI does not reliably exit on stdin EOF (MCP
    /// teardown lingers), and the reader joins only when claude's stdout
    /// closes — so the polite exit gets a short grace before the kill. The
    /// caller's exit must never hinge on a child's manners. Local: closing
    /// the turn queue ends the worker after its current stream; it is
    /// detached, not joined, because a mid-stream HTTP read can take minutes
    /// — the armed `cancelled` flag guarantees it applies nothing more.
    pub(crate) fn shutdown(self) {
        let Pilot {
            state,
            sink,
            turn_rx: _,
            stop,
            transport,
        } = self;
        {
            let mut st = state.lock().unwrap();
            revert_region(&mut st);
        }
        stop.store(true, Ordering::Relaxed);
        match transport {
            Transport::Claude {
                mut guard,
                reader,
                pump,
            } => {
                if let TurnSink::Claude(writer) = &sink {
                    writer.lock().unwrap().take(); // EOF asks claude to end
                }
                let grace = Instant::now() + Duration::from_secs(2);
                loop {
                    match guard.0.try_wait() {
                        Ok(Some(_)) => break,
                        Ok(None) if Instant::now() < grace => {
                            std::thread::sleep(Duration::from_millis(50))
                        }
                        _ => {
                            let _ = guard.0.kill();
                            break;
                        }
                    }
                }
                let _ = pump.join();
                let _ = reader.join();
            }
            Transport::Local { pump } => {
                // Nothing from a still-draining stream may land after this.
                state.lock().unwrap().cancelled = true;
                drop(sink); // closes the turn queue; the worker exits after its stream
                let _ = pump.join();
            }
        }
    }
}

/// Connect the collab seat, spawn the claude child, and start the reader,
/// stderr, and pump threads. `events` seats the pilot inside croft (its
/// voice becomes [`crate::pair_host::PairEvent`]s); None keeps stdio.
pub(crate) fn seat_pilot(
    socket: &Path,
    name: &str,
    mut cmd: Command,
    events: Option<Sender<crate::pair_host::PairEvent>>,
) -> Result<Pilot> {
    let session = connect_session(socket, name)?;
    let state = Arc::new(Mutex::new(PairState::new(session, events.clone())));

    cmd.stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    // Own session, same reasoning as the MCP transport: a sidecar must never
    // touch croft's controlling tty; everything rides the piped stdio.
    //
    // SAFETY: `setsid` is async-signal-safe and the only call in the hook.
    #[cfg(unix)]
    unsafe {
        use std::os::unix::process::CommandExt;
        cmd.pre_exec(|| {
            libc::setsid();
            Ok(())
        });
    }
    let mut child = cmd.spawn().context("spawning the claude CLI")?;
    let child_stdin = child.stdin.take().context("claude stdin missing")?;
    let child_stdout = child.stdout.take().context("claude stdout missing")?;
    let child_stderr = child.stderr.take().context("claude stderr missing")?;
    let guard = ChildGuard(child);
    let sink = TurnSink::Claude(Arc::new(Mutex::new(Some(child_stdin))));

    let stop = Arc::new(AtomicBool::new(false));
    let (turn_tx, turn_rx) = std::sync::mpsc::channel::<TurnEnd>();

    // Reader: claude's stdout events through the fence machine.
    let reader = {
        let state = Arc::clone(&state);
        std::thread::spawn(move || {
            let mut fence = FenceMachine::new();
            let mut decoder = crate::mcp::transport::LineDecoder::new();
            let mut stdout = child_stdout;
            let mut buf = [0u8; 8192];
            loop {
                let n = match stdout.read(&mut buf) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => n,
                };
                decoder.feed(&buf[..n]);
                while let Some(msg) = decoder.next_message() {
                    handle_claude_event(&state, &mut fence, &msg, &turn_tx);
                }
            }
        })
    };

    // Stderr tee, same as the DAP transport: claude's diagnostics reach the
    // driver without touching the protocol stream.
    {
        let events = events.clone();
        std::thread::spawn(move || {
            let mut reader = std::io::BufReader::new(child_stderr);
            let mut line = String::new();
            loop {
                line.clear();
                match reader.read_line(&mut line) {
                    Ok(0) | Err(_) => break,
                    // Seated, claude's stderr chatter (MCP startup and the
                    // like) is a diagnostic for the OUTPUT channel — as a
                    // Commentary event it was anchored into the user's file
                    // as one of the navigator's own comment boxes.
                    Ok(_) => match &events {
                        Some(_) => {
                            crate::output::push(
                                "Navigator",
                                crate::output::OutputLevel::Info,
                                &format!("[claude] {}", line.trim_end()),
                            );
                        }
                        None => eprint!("[claude] {line}"),
                    },
                }
            }
        });
    }

    // Pump: remote spans shift the streamed region; StreamCancel cancels.
    let pump = {
        let state = Arc::clone(&state);
        let sink = sink.clone();
        let stop = Arc::clone(&stop);
        std::thread::spawn(move || {
            let req_id = AtomicU64::new(0);
            while !stop.load(Ordering::Relaxed) {
                pump_session(&state, &sink, &req_id);
                std::thread::sleep(Duration::from_millis(25));
            }
        })
    };

    Ok(Pilot {
        state,
        sink,
        turn_rx,
        stop,
        transport: Transport::Claude {
            guard,
            reader,
            pump,
        },
    })
}

/// Seat the pilot on a local Anthropic-compatible endpoint: the same collab
/// guest seat and pump as the claude transport, but no child — a worker
/// owns the conversation (the endpoint is stateless) and runs one blocking
/// [`local::stream_turn`] per queued turn body.
pub(crate) fn seat_local(
    socket: &Path,
    name: &str,
    base_url: &str,
    model: &str,
    events: Option<Sender<crate::pair_host::PairEvent>>,
) -> Result<Pilot> {
    let session = connect_session(socket, name)?;
    let state = Arc::new(Mutex::new(PairState::new(session, events)));
    let stop = Arc::new(AtomicBool::new(false));
    let (turns_tx, turns_rx) = std::sync::mpsc::channel::<String>();
    let (end_tx, turn_rx) = std::sync::mpsc::channel::<TurnEnd>();
    let sink = TurnSink::Local(turns_tx);

    // Detached worker: owns the conversation, exits when the queue closes.
    {
        let state = Arc::clone(&state);
        let (base_url, model) = (base_url.to_string(), model.to_string());
        let system = system_prompt(&Provider::Local {
            base_url: base_url.clone(),
        })
        .into_owned();
        std::thread::spawn(move || {
            let mut messages: Vec<Value> = Vec::new();
            while let Ok(body) = turns_rx.recv() {
                messages.push(json!({ "role": "user", "content": body }));
                local::stream_turn(&base_url, &model, &system, &mut messages, &state, &end_tx);
            }
        });
    }

    // Pump: remote spans shift the streamed region; StreamCancel reverts
    // (no interrupt to deliver — the local stream just stops applying).
    let pump = {
        let state = Arc::clone(&state);
        let sink = sink.clone();
        let stop = Arc::clone(&stop);
        std::thread::spawn(move || {
            let req_id = AtomicU64::new(0);
            while !stop.load(Ordering::Relaxed) {
                pump_session(&state, &sink, &req_id);
                std::thread::sleep(Duration::from_millis(25));
            }
        })
    };

    Ok(Pilot {
        state,
        sink,
        turn_rx,
        stop,
        transport: Transport::Local { pump },
    })
}

/// The debug REPL driver (hidden `--repl`), transport-agnostic so the e2e
/// tests can drive it with a scripted fake. Blocks until `input` (the
/// pilot's own terminal) hits EOF or the model conversation hangs up
/// mid-turn.
fn run_pilot(
    pilot: Pilot,
    name: &str,
    task: Option<String>,
    input: &mut dyn BufRead,
) -> Result<()> {
    // REPL: the initial --task then the pilot's stdin, one turn per line.
    println!("croft pair: '{name}' seated; type a task ('@<file> <task>' to focus a buffer)");
    let mut pending = task;
    let mut hung_up = false;
    loop {
        let line = match pending.take() {
            Some(t) => t,
            None => {
                let mut line = String::new();
                match input.read_line(&mut line) {
                    Ok(0) | Err(_) => break,
                    Ok(_) => line.trim().to_string(),
                }
            }
        };
        if line.is_empty() {
            continue;
        }
        send_turn(&pilot.state, &pilot.sink, &line)?;
        match pilot.turn_rx.recv() {
            Ok(end) if end.cancelled => println!("\n[turn cancelled]"),
            Ok(end) if end.is_error => println!("\n[turn failed: {}]", end.text),
            Ok(_) => println!("\n[turn done]"),
            Err(_) => {
                // Reader gone: claude hung up mid-turn.
                hung_up = true;
                break;
            }
        }
    }
    pilot.shutdown();
    anyhow::ensure!(!hung_up, "claude exited mid-conversation");
    Ok(())
}

/// One inbound claude event: init capabilities, token deltas through the
/// fence machine, and each turn's result.
fn handle_claude_event(
    state: &Mutex<PairState>,
    fence: &mut FenceMachine,
    msg: &Value,
    turn_tx: &Sender<TurnEnd>,
) {
    match msg.get("type").and_then(Value::as_str) {
        Some("system") if msg.get("subtype").and_then(Value::as_str) == Some("init") => {
            let can = msg
                .get("capabilities")
                .and_then(Value::as_array)
                .is_some_and(|caps| {
                    caps.iter()
                        .any(|c| c.as_str() == Some("interrupt_receipt_v1"))
                });
            state.lock().unwrap().can_interrupt = can;
        }
        Some("stream_event") => {
            let delta = msg.pointer("/event/delta");
            if delta.and_then(|d| d.get("type")).and_then(Value::as_str) == Some("text_delta")
                && let Some(text) = delta.and_then(|d| d.get("text")).and_then(Value::as_str)
            {
                for event in fence.push(text) {
                    apply_fence_event(state, event);
                }
            }
        }
        Some("result") => {
            // claude's stdout is an external input: a result with no
            // dispatched turn behind it (every dispatch sets turn_active,
            // and the arm below clears it exactly once) is a duplicate or
            // spontaneous emission. Ending a turn it does not own would
            // queue a phantom TurnEnd — releasing the host's busy gate
            // under a newer turn — and the finish()/flag resets would
            // revert that turn's open fence and staging.
            if !state.lock().unwrap().turn_active {
                return;
            }
            for event in fence.finish() {
                apply_fence_event(state, event);
            }
            let mut st = state.lock().unwrap();
            let cancelled = st.cancelled;
            st.turn_active = false;
            st.cancelled = false;
            st.discarding = false;
            st.comment_only = false;
            drop(st);
            let _ = turn_tx.send(TurnEnd {
                is_error: msg
                    .get("is_error")
                    .and_then(Value::as_bool)
                    .unwrap_or(false),
                cancelled,
                text: msg
                    .get("result")
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .to_string(),
            });
        }
        _ => {} // hook noise, control_response acks, message_start/stop, ...
    }
}

/// Apply one fence event to the collab seat. Commentary prints; edits apply
/// at the tracked anchor; abort reverts. Never holds the state lock across
/// the EditStart bootstrap wait.
fn apply_fence_event(state: &Mutex<PairState>, event: FenceEvent) {
    match event {
        FenceEvent::Commentary(text) => {
            say(state, &text);
        }
        FenceEvent::EditStart { file, start, end } => {
            {
                let mut st = state.lock().unwrap();
                if st.cancelled {
                    st.discarding = true;
                    return;
                }
                if st.comment_only {
                    // The host gate, not just a prompt rule: a yielded turn
                    // may never touch a buffer, whatever the model says.
                    st.discarding = true;
                    drop(st);
                    diag(
                        state,
                        crate::output::OutputLevel::Warn,
                        "[pair] edit suppressed: this is a yielded, comment-only turn",
                    );
                    return;
                }
                st.target_file = Some(file.clone());
                st.session.request_file(&file);
            }
            if wait_live(state, &file) {
                let mut st = state.lock().unwrap();
                open_region(&mut st, &file, start, end);
            } else {
                state.lock().unwrap().discarding = true;
                diag(
                    state,
                    crate::output::OutputLevel::Warn,
                    &format!(
                        "[pair] no live croft session serves {file}; edit dropped \
                         (start croft in this workspace first)"
                    ),
                );
            }
        }
        FenceEvent::EditBody(delta) => {
            let mut st = state.lock().unwrap();
            if st.cancelled || st.discarding {
                return;
            }
            let Some((file, anchor)) = st.region.as_ref().map(|r| (r.file.clone(), r.anchor))
            else {
                return;
            };
            let Some(doc) = st.session.doc_text(&file).map(str::to_string) else {
                return;
            };
            let anchor = anchor.min(doc.len());
            let new = format!("{}{}{}", &doc[..anchor], delta, &doc[anchor..]);
            st.session.local_change(&file, &new);
            // Our own insert moves any note anchored below it in this file
            // (notes and edits can both land in one ask turn).
            let span = ResolvedSpan {
                at: anchor,
                deleted: 0,
                inserted: delta.clone(),
            };
            shift_notes(&mut st.notes, &file, std::slice::from_ref(&span));
            let next = anchor + delta.len();
            if let Some(r) = st.region.as_mut() {
                r.anchor = next;
            }
            let lines: Vec<String> = new.split('\n').map(String::from).collect();
            let (row, col) = position(&lines, next);
            st.caret_now(&file, row, col);
        }
        FenceEvent::EditEnd => {
            let mut st = state.lock().unwrap();
            st.discarding = false;
            if st.cancelled {
                return; // already reverted by the cancel
            }
            if let Some(r) = st.region.take() {
                st.session.send_stream_state(&r.file, false);
            }
        }
        FenceEvent::EditAbort => {
            let mut st = state.lock().unwrap();
            st.discarding = false;
            if st.cancelled {
                st.region = None;
                return;
            }
            revert_region(&mut st);
        }
        FenceEvent::NoteStart { file, row } => {
            let mut st = state.lock().unwrap();
            if st.cancelled {
                return;
            }
            // Non-blocking: the offset resolves lazily at NoteEnd, so a
            // bootstrap kicked off here has the body's stream time to land.
            st.session.request_file(&file);
            st.note_in_flight = Some((file, row, String::new()));
        }
        FenceEvent::NoteBody(delta) => {
            let mut st = state.lock().unwrap();
            if let Some((_, _, body)) = st.note_in_flight.as_mut() {
                body.push_str(&delta);
            }
        }
        FenceEvent::NoteEnd => {
            let pending = {
                let mut st = state.lock().unwrap();
                let pending = st.note_in_flight.take();
                if st.cancelled { None } else { pending }
            };
            let Some((file, row, body)) = pending else {
                return;
            };
            // NoteStart's request_file may still be bootstrapping (a fast
            // fence outruns the 25ms pump); give it the same bounded wait
            // an edit gets. Still no live doc = the owner never served the
            // file: nothing to anchor to (mirrors the edit-drop path).
            if !wait_live(state, &file) {
                diag(
                    state,
                    crate::output::OutputLevel::Warn,
                    &format!(
                        "[pair] no live croft session serves {file}; note dropped \
                         (start croft in this workspace first)"
                    ),
                );
                return;
            }
            let mut st = state.lock().unwrap();
            let Some(lines) = st.doc_lines(&file) else {
                // The file left the live session between wait_live releasing
                // the lock and this reacquisition: same outcome, same warning.
                drop(st);
                diag(
                    state,
                    crate::output::OutputLevel::Warn,
                    &format!(
                        "[pair] no live croft session serves {file}; note dropped \
                         (start croft in this workspace first)"
                    ),
                );
                return;
            };
            let offset = note_offset(&lines, row);
            let row_now = position(&lines, offset).0;
            // The AI is visibly "looking" where it just commented.
            st.caret_now(&file, row_now, 0);
            let id = st.take_note_id();
            let sink = st.events.clone();
            // Pushed under the SAME lock as the offset computation: pushing
            // after the REPL's say() left a window where a concurrent
            // remote edit shifted every note EXCEPT this not-yet-pushed
            // one, stranding its anchor below the edit.
            st.notes.push(Note {
                id,
                file: file.clone(),
                offset,
                body: body.clone(),
            });
            match sink {
                Some(tx) => {
                    let _ = tx.send(crate::pair_host::PairEvent::NoteAdded {
                        file,
                        row: row_now,
                        body,
                    });
                }
                None => {
                    // REPL driver: no event channel, so print the note or it
                    // would be silently swallowed (say re-locks internally,
                    // hence the drop).
                    drop(st);
                    say(state, &format!("[note {file}:{}] {body}\n", row_now + 1));
                }
            }
        }
        FenceEvent::NoteAbort => {
            state.lock().unwrap().note_in_flight = None;
        }
    }
}

/// EditStart's second half, once the file is live: delete the fence's range
/// in one replica change and open the streamed region at its start.
fn open_region(st: &mut PairState, file: &str, start: (usize, usize), end: (usize, usize)) {
    let Some(doc) = st.session.doc_text(file).map(str::to_string) else {
        st.discarding = true;
        return;
    };
    let lines: Vec<String> = doc.split('\n').map(String::from).collect();
    let (s, e) = range_bytes(&lines, start, end);
    let (s, e) = (s.min(doc.len()), e.min(doc.len()));
    if s > e {
        st.discarding = true;
        // The OUTPUT channel, never stderr: the resident navigator runs
        // in-process, so an eprintln! lands on the alternate screen and
        // corrupts the render (the pdftoppm/DAP capture class). The
        // whole-line header form makes an inverted range a one-token slip
        // for a weak local model.
        crate::output::push(
            "Navigator",
            crate::output::OutputLevel::Warn,
            "fence range is inverted; edit dropped",
        );
        return;
    }
    let original = doc[s..e].to_string();
    let new = format!("{}{}", &doc[..s], &doc[e..]);
    // Announce the stream before its first edit, the region's delete: the
    // host groups the stream's edits into one undo step from the moment it
    // sees the announcement, so a delete sent first was a step of its own
    // (#1207).
    st.session.send_stream_state(file, true);
    st.session.local_change(file, &new);
    // Anchors at or inside the range are about to be collapsed by the
    // delete (and then dragged along by the streamed inserts): record
    // their pre-edit deltas so a revert can put them back exactly.
    let displaced: Vec<(u64, usize)> = st
        .notes
        .iter()
        .filter(|n| n.file == file && (s..e).contains(&n.offset))
        .map(|n| (n.id, n.offset - s))
        .collect();
    // Our own delete moves any note anchored below the cut in this file.
    let span = ResolvedSpan {
        at: s,
        deleted: e - s,
        inserted: String::new(),
    };
    shift_notes(&mut st.notes, file, std::slice::from_ref(&span));
    st.region = Some(StreamRegion {
        file: file.to_string(),
        start: s,
        anchor: s,
        original,
        displaced,
    });
    st.discarding = false;
    let lines: Vec<String> = new.split('\n').map(String::from).collect();
    let (row, col) = position(&lines, s);
    st.caret_now(file, row, col);
}

/// Put the streamed region's original slice back (cancel, abort, or exit)
/// and broadcast the stream as inactive. No-op without an open region.
fn revert_region(st: &mut PairState) {
    let Some(r) = st.region.take() else {
        return;
    };
    if let Some(doc) = st.session.doc_text(&r.file).map(str::to_string) {
        let start = r.start.min(doc.len());
        let anchor = r.anchor.clamp(start, doc.len());
        let new = format!("{}{}{}", &doc[..start], r.original, &doc[anchor..]);
        st.session.local_change(&r.file, &new);
        // The inverse of the shifts open_region and EditBody applied: the
        // revert deletes the streamed bytes and puts the original back, so
        // notes the edit moved must move back with it.
        let span = ResolvedSpan {
            at: start,
            deleted: anchor - start,
            inserted: r.original.clone(),
        };
        shift_notes(&mut st.notes, &r.file, std::slice::from_ref(&span));
        // Anchors that sat inside the range cannot be un-shifted (the
        // delete collapsed them); restore them from the deltas recorded at
        // open. `start` tracked remote edits all along, so `start + delta`
        // lands exactly where the anchor sat in the restored slice.
        for (id, delta) in &r.displaced {
            if let Some(n) = st
                .notes
                .iter_mut()
                .find(|n| n.id == *id && n.file == r.file)
            {
                n.offset = start + delta;
            }
        }
    }
    st.session.send_stream_state(&r.file, false);
}

/// One pump tick: drain the relay; remote spans shift the streamed region's
/// offsets (concurrent human edits), StreamCancel interrupts and reverts.
fn pump_session(state: &Mutex<PairState>, sink: &TurnSink, req_id: &AtomicU64) {
    let mut interrupt = false;
    {
        let mut st = state.lock().unwrap();
        let events = st.session.poll(|_| None);
        for event in events {
            match event {
                CollabEvent::RemoteEdit { file, spans, .. } => {
                    if let Some(r) = st.region.as_mut()
                        && r.file == file
                    {
                        for span in &spans {
                            r.start = shift_offset(r.start, span);
                            r.anchor = shift_offset(r.anchor, span);
                        }
                    }
                    shift_notes(&mut st.notes, &file, &spans);
                }
                CollabEvent::StreamCancel => {
                    if !st.turn_active || st.cancelled {
                        continue;
                    }
                    st.cancelled = true;
                    st.pending_note = Some(
                        "Note: your previous streamed edit was cancelled and reverted by a \
                         participant. Stop that approach and ask what they want instead."
                            .to_string(),
                    );
                    revert_region(&mut st);
                    interrupt = st.can_interrupt;
                    match st.events.clone() {
                        Some(tx) => {
                            let _ = tx.send(crate::pair_host::PairEvent::Commentary(
                                "[stream cancelled by a participant; reverted]".to_string(),
                            ));
                        }
                        None => println!("\n[stream cancelled by a participant; reverted]"),
                    }
                }
                _ => {}
            }
        }
        st.resolve_pending_caret();
    }
    // The claude write happens outside the state lock (lock order: state
    // then writer, same as send_turn; never both held). Only the claude
    // backend can interrupt mid-turn; can_interrupt never arms elsewhere.
    if interrupt {
        let TurnSink::Claude(writer) = sink else {
            return; // can_interrupt only ever arms on the claude transport
        };
        if let Some(w) = writer.lock().unwrap().as_mut() {
            let id = req_id.fetch_add(1, Ordering::Relaxed);
            let msg = json!({
                "type": "control_request",
                "request_id": format!("croft-pair-{id}"),
                "request": { "subtype": "interrupt" },
            });
            let _ = writeln!(w, "{msg}");
            let _ = w.flush();
        }
    }
}

/// `@<file> <task>` focuses a buffer; everything else is just the task.
fn parse_task_line(line: &str) -> (Option<String>, String) {
    let Some(rest) = line.strip_prefix('@') else {
        return (None, line.to_string());
    };
    match rest.split_once(char::is_whitespace) {
        Some((file, task)) => (Some(file.to_string()), task.trim().to_string()),
        None => (Some(rest.to_string()), String::new()),
    }
}

/// Compose one user turn: the task and the target file context. The file
/// is ALWAYS named when known — parse_task_line has already stripped the
/// `@file` prefix, so a buffer that never went live must not erase the
/// target from the task. (The pending cancel note rides in at write time,
/// [`with_pending_note`].)
fn compose_turn_text(task: &str, file: Option<&str>, buffer: Option<&str>) -> String {
    let mut content = String::new();
    content.push_str(task);
    match (file, buffer) {
        (Some(file), Some(text)) => {
            content.push_str(&format!(
                "\n\n--- CURRENT BUFFER ({file}) ---\n{text}\n--- END BUFFER ---"
            ));
        }
        (Some(file), None) => {
            content.push_str(&format!(
                "\n\nTarget file: {file} (its buffer is not shared yet; \
                 read it with the collab tools before editing)"
            ));
        }
        (None, _) => {}
    }
    content
}

/// `content` with each line prefixed `N|` (0-based), the numbering the ask
/// and yield turns use so NOTE rows have an unambiguous ground truth.
fn numbered(content: &str) -> String {
    content
        .split('\n')
        .enumerate()
        .map(|(i, l)| format!("{i}|{l}"))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Compose an ask turn: the instruction, where it was invoked (a 0-based
/// line or line range, with the gutter's 1-based number beside it), the
/// selected text when there is one, and the numbered buffer.
pub(crate) fn compose_ask_turn(
    file: &str,
    range: (usize, usize),
    selection: &str,
    instruction: &str,
    content: &str,
) -> String {
    let mut text = String::new();
    let (s, e) = range;
    if s == e {
        text.push_str(&format!(
            "Your partner invoked you on {file} at line {s} (0-based; line {} in \
             your partner's gutter).\n",
            s + 1
        ));
    } else {
        text.push_str(&format!(
            "Your partner invoked you on {file} at lines {s}-{e} (0-based; lines \
             {}-{} in your partner's gutter).\n",
            s + 1,
            e + 1
        ));
    }
    if !selection.is_empty() {
        text.push_str(&format!(
            "--- SELECTED LINES ---\n{selection}\n--- END SELECTED ---\n"
        ));
    }
    text.push_str(&format!("\nTask: {instruction}\n"));
    text.push_str(&format!(
        "\n--- CURRENT BUFFER ({file}, each line prefixed with its 0-based \
         number and '|') ---\n{}\n--- END BUFFER ---",
        numbered(content)
    ));
    text
}

/// Compose a yield turn: the driver handed the navigator the floor. Comment
/// only — the host discards EDIT fences on this turn — with the diff since
/// the navigator last saw the file, and the numbered buffer.
pub(crate) fn compose_yield_turn(file: &str, content: &str, diff: Option<&str>) -> String {
    let mut text = String::from(
        "Your partner yielded the turn: review the file below and speak \
         through NOTE fences anchored to the lines you mean. This turn is \
         COMMENT-ONLY: any EDIT fence will be discarded by the host. \
         Propose changes in your notes and wait to be asked.\n",
    );
    if let Some(diff) = diff {
        text.push_str(&format!(
            "\n--- CHANGES SINCE YOUR LAST LOOK ---\n{diff}\n--- END CHANGES ---\n"
        ));
    }
    text.push_str(&format!(
        "\n--- CURRENT BUFFER ({file}, each line prefixed with its 0-based \
         number and '|') ---\n{}\n--- END BUFFER ---",
        numbered(content)
    ));
    text
}

/// Compose a reply turn: the driver answered one of the navigator's notes
/// inside its comment box. Names the note, carries the reply, lets the
/// model edit when the reply asks for a change (#1965), and grounds the
/// model with the numbered buffer.
pub(crate) fn compose_reply_turn(
    file: &str,
    row: usize,
    note_body: &str,
    reply: &str,
    content: &str,
) -> String {
    format!(
        "Your partner replied to your note on {file} at line {row} (0-based; \
         line {gutter} in your partner's gutter).\n\
         --- YOUR NOTE ---\n{note_body}\n--- END NOTE ---\n\
         --- THEIR REPLY ---\n{reply}\n--- END REPLY ---\n\
         If their reply asks you to make a change, make it with EDIT fences. \
         Otherwise answer with NOTE fences (anchor follow-ups to the lines \
         you mean; a NOTE re-anchored to row {row} continues this box).\n\
         \n--- CURRENT BUFFER ({file}, each line prefixed with its 0-based \
         number and '|') ---\n{}\n--- END BUFFER ---",
        numbered(content),
        gutter = row + 1,
    )
}

/// Anchor a note into `file` at `row` from the app side (commentary landing
/// as a comment box). Mirrors the NoteEnd path: request the file, give the
/// bootstrap the same bounded wait, then anchor by byte offset. None = the
/// owner never served the file.
/// Test-only: the e2e suite anchors seed notes right after a spawn, before
/// the bootstrap settles; production (the App tick thread) must never block
/// and uses [`inject_note_now`].
#[cfg(test)]
pub(crate) fn inject_note(
    state: &Mutex<PairState>,
    file: &str,
    row: usize,
    body: &str,
) -> Option<u64> {
    state.lock().unwrap().session.request_file(file);
    if !wait_live(state, file) {
        return None;
    }
    inject_note_now(state, file, row, body)
}

/// Non-blocking [`inject_note`]: anchors only when `file` is already live.
/// The App's tick thread lands turn commentary through this — it must never
/// sit out a bootstrap wait.
pub(crate) fn inject_note_now(
    state: &Mutex<PairState>,
    file: &str,
    row: usize,
    body: &str,
) -> Option<u64> {
    // Bounded lock (see lock_briefly): the App's tick thread must never
    // wait indefinitely on the pilot mutex (held across blocking relay
    // writes). None sends the caller to its OUTPUT fallback.
    let mut st = lock_briefly(state)?;
    if !st.session.is_live(file) {
        return None;
    }
    let lines = st.doc_lines(file)?;
    let offset = note_offset(&lines, row);
    // The AI is visibly "looking" where it just commented.
    st.caret_now(file, position(&lines, offset).0, 0);
    let id = st.take_note_id();
    st.notes.push(Note {
        id,
        file: file.to_string(),
        offset,
        body: body.to_string(),
    });
    Some(id)
}

/// Compose and send one user turn: pending cancel note, the task, and the
/// target file's current buffer (so the model's fence coordinates have a
/// ground truth).
pub(crate) fn send_turn(state: &Mutex<PairState>, sink: &TurnSink, line: &str) -> Result<()> {
    let (file, task) = parse_task_line(line);
    if let Some(file) = &file {
        let mut st = state.lock().unwrap();
        st.target_file = Some(file.clone());
        st.session.request_file(file);
        drop(st);
        // Bounded wait so the injection below can carry the buffer.
        let deadline = Instant::now() + LIVE_TIMEOUT;
        while Instant::now() < deadline {
            let st = state.lock().unwrap();
            if st.session.is_live(file) || !st.session.is_bootstrapping(file) {
                break;
            }
            drop(st);
            std::thread::sleep(Duration::from_millis(20));
        }
    }
    let (file, buffer) = {
        let st = state.lock().unwrap();
        let file = st.target_file.clone();
        let buffer = file
            .as_deref()
            .and_then(|f| st.session.doc_text(f))
            .map(str::to_string);
        (file, buffer)
    };
    if file.is_some() && buffer.is_none() {
        diag(
            state,
            crate::output::OutputLevel::Warn,
            "[pair] target file is not live (no owner answered); \
             sending the task with the file name only",
        );
    }
    let body = compose_turn_text(&task, file.as_deref(), buffer.as_deref());
    write_user_turn(state, sink, body)
}

/// Send one composed user turn through the sink, prepending any pending
/// cancel note and marking the turn active. Lock order: state then writer,
/// never both held.
pub(crate) fn write_user_turn(
    state: &Mutex<PairState>,
    sink: &TurnSink,
    body: String,
) -> Result<()> {
    let (content, note) = {
        let mut st = state.lock().unwrap();
        let note = st.pending_note.take();
        st.turn_active = true;
        (with_pending_note(note.clone(), body), note)
    };
    let sent = sink.send_user(&content);
    if sent.is_err() {
        // The turn never left: unlatch it (a wedged turn_active refused
        // every later ask/yield/reply for the seat's life) and put the
        // cancel note back — it is still owed to the model on the next
        // turn that actually sends.
        let mut st = state.lock().unwrap();
        st.turn_active = false;
        if st.pending_note.is_none() {
            st.pending_note = note;
        }
    }
    sent
}

/// The pending cancel note rides in front of the next turn's body.
fn with_pending_note(note: Option<String>, body: String) -> String {
    match note {
        Some(n) => format!("{n}\n\n{body}"),
        None => body,
    }
}

/// A scripted claude: speaks just enough stream-json for the pilot.
/// argv: <log file> <mode>. Logs every stdin line (the e2es assert the
/// interrupt landed there). "stream" mode streams one fenced edit split
/// across deltas (header split mid-marker on purpose); "cancel" mode stops
/// mid-body and BLOCKS on stdin — only the pilot's interrupt line unblocks
/// it — then streams more body the pilot must drop; "notes" pins one NOTE
/// fence; "repeat" stays seated and inserts the turn's number (1, 2, ...) at
/// 0:0 on EVERY turn;
/// "linger" refuses to exit on stdin EOF. Crate-visible so the App's
/// navigator tests drive the same fake.
#[cfg(test)]
pub(crate) const FAKE_CLAUDE: &str = r#"
import json, sys

log = open(sys.argv[1], "a")
mode = sys.argv[2]

# The real claude CLI is chatty on stderr while its MCP servers start; the
# tee must route this to OUTPUT, never into the model's comment boxes.
print("mcp server starting", file=sys.stderr)
sys.stderr.flush()

def emit(obj):
    sys.stdout.write(json.dumps(obj) + "\n")
    sys.stdout.flush()

def delta(text):
    emit({"type": "stream_event", "event": {
        "type": "content_block_delta",
        "delta": {"type": "text_delta", "text": text}}})

emit({"type": "system", "subtype": "init",
      "capabilities": ["interrupt_receipt_v1"]})

line = sys.stdin.readline()
if not line:
    sys.exit(0)
log.write(line)
log.flush()

if mode == "hang":
    # Read one turn, then never respond: turn_active stays true so the host
    # reports busy and rejects a second turn.
    import time
    time.sleep(60)
    sys.exit(0)

if mode == "notes":
    delta("Reviewing.\n")
    delta("<<<NOTE demo.txt:1>>>\n")
    delta("second line could be tighter\n")
    delta("<<<END>>>\n")
    emit({"type": "result", "subtype": "success",
          "is_error": False, "result": "ok"})
    # Stay seated like the real CLI: wait for the next turn (or EOF).
    sys.stdin.readline()
    sys.exit(0)

if mode == "repeat":
    # An edit on every turn, numbered so a test can tell which turn's edit
    # reached the owner and watch the host gate decide turn by turn.
    turn = 0
    while line:
        turn += 1
        delta("<<<EDIT demo.txt:0:0-0:0>>>\n%d\n<<<END>>>\n" % turn)
        emit({"type": "result", "subtype": "success",
              "is_error": False, "result": "ok"})
        line = sys.stdin.readline()
        log.write(line)
        log.flush()
    sys.exit(0)

delta("Let me fix that.\n")
delta("<<<EDIT demo.txt:0:6-0:11>")
delta(">>\n")
delta("streamed")
if mode == "cancel":
    line2 = sys.stdin.readline()
    log.write(line2)
    log.flush()
    delta(" MORE-AFTER-CANCEL")
    delta("\n<<<END>>>\n")
    emit({"type": "result", "subtype": "success",
          "is_error": False, "result": "cancelled turn"})
else:
    delta(" edit")
    delta("\n<<<END>>>\nDone.\n")
    emit({"type": "result", "subtype": "success",
          "is_error": False, "result": "ok"})
if mode == "linger":
    # The real claude CLI does NOT reliably exit on stdin EOF (MCP
    # teardown lingers); the pilot must not gamble its own exit on it.
    import time
    time.sleep(60)
"#;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::collab::{ResolvedSpan, relay_serve};
    use crate::lsp::manager::is_on_path;

    // Live smoke of the WHOLE local backend — the real seat_local worker,
    // fence machine, collab apply, and owner convergence — against a real
    // Anthropic-compatible endpoint. Gated so the normal suite/CI skips it.
    //
    //   CROFT_SPIKE_OLLAMA=1 \
    //   CROFT_SPIKE_OLLAMA_URL=http://localhost:11434 \
    //   CROFT_SPIKE_OLLAMA_MODEL=qwen3-coder:30b \
    //   cargo test --release ollama_live -- --nocapture --ignored
    #[test]
    #[ignore = "needs a live Ollama; run explicitly with CROFT_SPIKE_OLLAMA=1"]
    fn ollama_live_smoke_drives_seat_local_end_to_end() {
        if std::env::var("CROFT_SPIKE_OLLAMA").is_err() {
            eprintln!("skip: set CROFT_SPIKE_OLLAMA=1 to run the live smoke");
            return;
        }
        let url = std::env::var("CROFT_SPIKE_OLLAMA_URL")
            .unwrap_or_else(|_| "http://localhost:11434".into());
        let model =
            std::env::var("CROFT_SPIKE_OLLAMA_MODEL").unwrap_or_else(|_| "qwen3-coder:30b".into());

        let harness = OwnerHarness::start("def greet(name):\n    return \"hi \" + name\n");
        let pilot = seat_local(&harness.socket, "pilot", &url, &model, None).unwrap();
        send_turn(
            &pilot.state,
            &pilot.sink,
            "@demo.txt Rewrite greet to return the f-string f\"Hello, {name}!\" \
             instead of concatenation, using an EDIT fence.",
        )
        .unwrap();
        let end = pilot
            .turn_rx
            .recv_timeout(Duration::from_secs(300))
            .expect("turn ends");
        assert!(!end.is_error, "turn failed: {}", end.text);
        harness.wait_until("the f-string edit to converge", |h| {
            h.doc().is_some_and(|d| d.contains("f\"Hello, {name}!\""))
        });
        let doc = harness.doc().unwrap();
        assert!(
            !doc.contains("+ name"),
            "the old concatenation must be gone:\n{doc}"
        );
        pilot.shutdown();
    }

    use std::sync::atomic::{AtomicBool, Ordering};

    /// The Claude sink wraps a turn body in a stream-json user message and
    /// writes it to the child's stdin, byte-identical to the pre-TurnSink
    /// path (`cat` echoes its stdin back so the test can read what landed).
    #[test]
    fn turn_sink_claude_writes_stream_json_to_stdin() {
        let mut child = Command::new("cat")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .expect("spawn cat");
        let stdin = child.stdin.take().unwrap();
        let stdout = child.stdout.take().unwrap();
        let sink = TurnSink::Claude(Arc::new(Mutex::new(Some(stdin))));
        sink.send_user("hello\nworld").unwrap();
        let TurnSink::Claude(w) = &sink else {
            unreachable!()
        };
        w.lock().unwrap().take(); // EOF so cat exits
        let mut line = String::new();
        std::io::BufReader::new(stdout)
            .read_line(&mut line)
            .unwrap();
        let _ = child.wait();
        let v: Value = serde_json::from_str(&line).expect("one stream-json line");
        assert_eq!(v["type"], "user");
        assert_eq!(v["message"]["role"], "user");
        assert_eq!(v["message"]["content"], "hello\nworld");
    }

    /// The local backend appends the whole-line-fence guidance to the shared
    /// pair prompt: weaker models are steered to row ranges instead of
    /// character columns (the spike's coordinate slip).
    #[test]
    fn local_provider_appends_line_range_guidance() {
        let prompt = system_prompt(&Provider::Local {
            base_url: String::from("http://localhost:11434"),
        });
        assert!(prompt.starts_with(PAIR_SYSTEM_PROMPT));
        assert!(
            prompt.contains("<start_row>-<end_row>"),
            "suffix must teach the two-integer whole-line header"
        );
    }

    /// The claude backend's prompt is byte-identical to what 0.1.635 shipped.
    #[test]
    fn claude_provider_prompt_is_unchanged() {
        assert_eq!(system_prompt(&Provider::Claude), PAIR_SYSTEM_PROMPT);
    }

    /// Bounded poll toward `expected` through a contention-lossy accessor,
    /// returning the last value read. The host's UI-tick reads are
    /// deliberately imprecise under momentary pump contention
    /// (`notes_snapshot` serves its stale cache on a contended try_lock,
    /// `is_busy` answers busy on a lost `lock_briefly` race), so a one-shot
    /// read of a state-final value can flake on a starved runner. The
    /// deadline only bounds a real regression.
    fn settle<T: PartialEq>(expected: &T, mut read: impl FnMut() -> T) -> T {
        let deadline = Instant::now() + Duration::from_secs(60);
        loop {
            let got = read();
            if &got == expected || Instant::now() >= deadline {
                return got;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
    }

    /// A relay plus a pumping owner session that serves `demo.txt`,
    /// collecting every owner-side event for the assertions.
    struct OwnerHarness {
        _dir: tempfile::TempDir,
        socket: PathBuf,
        owner: Arc<Mutex<CollabSession>>,
        events: Arc<Mutex<Vec<CollabEvent>>>,
        stop: Arc<AtomicBool>,
        pump: Option<std::thread::JoinHandle<()>>,
    }

    impl OwnerHarness {
        fn start(text: &'static str) -> Self {
            let dir = tempfile::tempdir().unwrap();
            let socket = dir.path().join("p.collab.sock");
            {
                let s = socket.clone();
                std::thread::spawn(move || {
                    let _ = relay_serve(&s);
                });
            }
            let deadline = Instant::now() + Duration::from_secs(5);
            let owner = loop {
                if let Some(ch) = CollabChannel::connect(&socket, CollabRole::Owner) {
                    break CollabSession::new(ch, "owner".into());
                }
                assert!(Instant::now() < deadline, "relay never came up");
                std::thread::sleep(Duration::from_millis(10));
            };
            let owner = Arc::new(Mutex::new(owner));
            let events: Arc<Mutex<Vec<CollabEvent>>> = Arc::new(Mutex::new(Vec::new()));
            let stop = Arc::new(AtomicBool::new(false));
            let pump = {
                let (owner, events, stop) = (owner.clone(), events.clone(), stop.clone());
                std::thread::spawn(move || {
                    while !stop.load(Ordering::Relaxed) {
                        {
                            let mut o = owner.lock().unwrap();
                            let ev = o.poll(|_| Some(text.to_string()));
                            events.lock().unwrap().extend(ev);
                        }
                        std::thread::sleep(Duration::from_millis(5));
                    }
                })
            };
            Self {
                _dir: dir,
                socket,
                owner,
                events,
                stop,
                pump: Some(pump),
            }
        }

        fn doc(&self) -> Option<String> {
            self.owner
                .lock()
                .unwrap()
                .doc_text("demo.txt")
                .map(str::to_string)
        }

        fn wait_until(&self, what: &str, mut cond: impl FnMut(&Self) -> bool) {
            // A liveness backstop, generous on purpose: the python3 helper
            // and relay round trips race the parallel suite's load (#47),
            // and a tight ceiling here measured the machine, not croft.
            let deadline = Instant::now() + Duration::from_secs(60);
            while !cond(self) {
                assert!(Instant::now() < deadline, "timed out waiting for {what}");
                std::thread::sleep(Duration::from_millis(10));
            }
        }

        fn stream_states(&self) -> Vec<(String, bool)> {
            self.events
                .lock()
                .unwrap()
                .iter()
                .filter_map(|e| match e {
                    CollabEvent::StreamState { name, active, .. } => Some((name.clone(), *active)),
                    _ => None,
                })
                .collect()
        }

        fn remote_edit_count(&self) -> usize {
            self.events
                .lock()
                .unwrap()
                .iter()
                .filter(|e| matches!(e, CollabEvent::RemoteEdit { .. }))
                .count()
        }

        fn carets(&self) -> Vec<(String, usize, usize)> {
            self.events
                .lock()
                .unwrap()
                .iter()
                .filter_map(|e| match e {
                    CollabEvent::Caret { name, row, col, .. } => Some((name.clone(), *row, *col)),
                    _ => None,
                })
                .collect()
        }
    }

    impl Drop for OwnerHarness {
        fn drop(&mut self) {
            self.stop.store(true, Ordering::Relaxed);
            if let Some(p) = self.pump.take() {
                let _ = p.join();
            }
        }
    }

    /// A one-shot Anthropic-SSE stub: accepts one connection, drains the
    /// request, and streams `deltas` as `content_block_delta`/`text_delta`
    /// events followed by `message_stop`, closing to end the stream.
    fn serve_sse_once(deltas: Vec<&'static str>) -> (String, std::thread::JoinHandle<()>) {
        let mut body = String::new();
        for d in deltas {
            let ev = json!({
                "type": "content_block_delta",
                "index": 0,
                "delta": { "type": "text_delta", "text": d },
            });
            body.push_str(&format!("event: content_block_delta\ndata: {ev}\n\n"));
        }
        body.push_str("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n");
        serve_http_once(format!(
            "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\
             connection: close\r\n\r\n{body}"
        ))
    }

    /// One-shot HTTP stub answering `resp` verbatim after draining the whole
    /// request (headers + Content-Length body), per the SSE-stub trap.
    fn serve_http_once(resp: String) -> (String, std::thread::JoinHandle<()>) {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let base_url = format!("http://{}", listener.local_addr().unwrap());
        let server = std::thread::spawn(move || {
            let (mut sock, _) = listener.accept().unwrap();
            // Drain the WHOLE request (headers + Content-Length body) before
            // responding: answering after the first read races the client's
            // body write — the close RSTs the socket and eats the response.
            let mut req = Vec::new();
            let mut buf = [0u8; 4096];
            loop {
                let n = sock.read(&mut buf).unwrap_or(0);
                if n == 0 {
                    break;
                }
                req.extend_from_slice(&buf[..n]);
                let text = String::from_utf8_lossy(&req).to_ascii_lowercase();
                if let Some(head_end) = text.find("\r\n\r\n") {
                    let content_length = text[..head_end]
                        .lines()
                        .find_map(|l| l.strip_prefix("content-length:"))
                        .and_then(|v| v.trim().parse::<usize>().ok())
                        .unwrap_or(0);
                    if req.len() >= head_end + 4 + content_length {
                        break;
                    }
                }
            }
            let _ = sock.write_all(resp.as_bytes());
        });
        (base_url, server)
    }

    /// A guest PairState over the harness relay plus the same pump thread
    /// the seated pilot runs (bootstraps only land when someone polls).
    fn pumped_state(
        harness: &OwnerHarness,
    ) -> (
        Arc<Mutex<PairState>>,
        Arc<AtomicBool>,
        std::thread::JoinHandle<()>,
    ) {
        let session = connect_session(&harness.socket, "pilot").unwrap();
        let state = Arc::new(Mutex::new(PairState::new(session, None)));
        let stop = Arc::new(AtomicBool::new(false));
        let pump = {
            let (state, stop) = (state.clone(), stop.clone());
            let sink = TurnSink::Claude(Arc::new(Mutex::new(None)));
            std::thread::spawn(move || {
                let req_id = AtomicU64::new(0);
                while !stop.load(Ordering::Relaxed) {
                    pump_session(&state, &sink, &req_id);
                    std::thread::sleep(Duration::from_millis(5));
                }
            })
        };
        (state, stop, pump)
    }

    /// The UI thread must NEVER wait on the pilot's state mutex: pilot
    /// threads hold it across blocking relay writes (write_frame_blocking
    /// spins on WouldBlock with no deadline), and the App draining the
    /// relay is what completes those writes — so a blocking read from the
    /// render/tick path closes a circular wait and hangs the editor. Every
    /// UI-facing host method answers from a fallback when the mutex is
    /// contended.
    #[test]
    fn ui_reads_answer_instantly_while_the_pilot_mutex_is_held() {
        let harness = OwnerHarness::start("hello world");
        let host = crate::pair_host::PairHost::spawn(PairConfig {
            socket: harness.socket.clone(),
            workspace: harness._dir.path().to_path_buf(),
            name: String::from("nav"),
            model: Some(String::from("m")),
            task: None,
            provider: Provider::Local {
                base_url: String::from("http://127.0.0.1:9"),
            },
        })
        .unwrap();
        let state = host.state_for_tests().expect("pilot state");
        let (locked_tx, locked_rx) = std::sync::mpsc::channel();
        let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
        let holder = std::thread::spawn(move || {
            let _guard = state.lock().unwrap();
            locked_tx.send(()).unwrap();
            let _ = release_rx.recv();
        });
        locked_rx.recv().unwrap();
        let (done_tx, done_rx) = std::sync::mpsc::channel();
        let reader = std::thread::spawn(move || {
            let busy = host.is_busy();
            let _ = host.caret_sites();
            let _ = host.notes_snapshot("demo.txt");
            let seen = host.last_seen("demo.txt");
            let rejected = host.send_yield_turn("demo.txt", "x").is_err();
            done_tx.send((busy, seen, rejected)).unwrap();
            drop(host);
        });
        let (busy, seen, rejected) = done_rx
            .recv_timeout(Duration::from_secs(2))
            .expect("UI reads must answer instantly while the pilot mutex is held");
        assert!(busy, "contended = the pilot is mid-work = busy");
        assert_eq!(seen, None, "no baseline is better than a blocked frame");
        assert!(rejected, "a send under contention reports mid-turn");
        release_tx.send(()).unwrap();
        holder.join().unwrap();
        reader.join().unwrap();
    }

    /// is_busy() must stay true from the send until the App CONSUMES the
    /// turn's end: the reader clears turn_active before it queues TurnEnd,
    /// so a tick landing in that window saw an idle seat and started a new
    /// turn that stole the finished turn's origin and counters.
    #[test]
    fn the_seat_stays_busy_until_turn_done_is_consumed() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let harness = OwnerHarness::start("hello world");
        let script = harness._dir.path().join("fake_claude.py");
        std::fs::write(&script, FAKE_CLAUDE).unwrap();
        let log = harness._dir.path().join("stdin.log");
        let mut cmd = Command::new("python3");
        cmd.arg(&script).arg(&log).arg("stream");
        let mut host =
            crate::pair_host::PairHost::spawn_cmd(&harness.socket, "nav", None, cmd).unwrap();
        host.send_yield_turn("demo.txt", "hello world").unwrap();
        let state = host.state_for_tests().expect("pilot state");
        // Wait until the PILOT finished the turn (its reader cleared the
        // latch); the App has not polled yet.
        let deadline = Instant::now() + Duration::from_secs(60);
        while state.lock().unwrap().turn_active() {
            assert!(Instant::now() < deadline, "the fake turn never finished");
            std::thread::sleep(Duration::from_millis(5));
        }
        assert!(
            host.is_busy(),
            "the turn's end has not been consumed yet: the seat is still busy"
        );
        // The gate must hold at the SEND paths too, not just is_busy():
        // direct callers would otherwise overwrite the unconsumed turn's
        // staging in this window.
        let refused = host
            .send_yield_turn("demo.txt", "hello world")
            .expect_err("a send in the finish window must be refused");
        assert!(
            refused.to_string().contains("mid-turn"),
            "the refusal names the reason: {refused}"
        );
        let deadline = Instant::now() + Duration::from_secs(5);
        loop {
            if host
                .poll()
                .iter()
                .any(|e| matches!(e, crate::pair_host::PairEvent::TurnDone { .. }))
            {
                break;
            }
            assert!(Instant::now() < deadline, "TurnDone never arrived");
            std::thread::sleep(Duration::from_millis(5));
        }
        assert!(
            !settle(&false, || host.is_busy()),
            "consumed: the seat is idle again"
        );
        drop(host);
    }

    /// A yield whose send failed must not keep the look: last_seen is the
    /// diff baseline (a retry would diff the file against itself and show
    /// the model nothing), and the latched comment_only would silently
    /// edit-suppress the next successful turn.
    #[test]
    fn a_failed_yield_leaves_no_look_behind() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let harness = OwnerHarness::start("hello world");
        // A child whose stdin is dead by the time Died is observable: it
        // closes stdin BEFORE stdout, so stdout's EOF (what fires Died)
        // proves the write end already has no reader. A child that merely
        // exits (`-c pass`) races process teardown: on a starved runner the
        // reader sees stdout close while the process, and with it stdin's
        // read end, is still winding down, and the send lands in the pipe
        // buffer instead of failing. The sleep keeps the pid alive for the
        // host's grace-kill teardown, like the real CLI's linger.
        let mut cmd = Command::new("python3");
        cmd.arg("-c")
            .arg("import os,time; os.close(0); os.close(1); time.sleep(60)");
        let mut host =
            crate::pair_host::PairHost::spawn_cmd(&harness.socket, "nav", None, cmd).unwrap();
        let deadline = Instant::now() + Duration::from_secs(60);
        loop {
            if host
                .poll()
                .iter()
                .any(|e| matches!(e, crate::pair_host::PairEvent::Died(_)))
            {
                break;
            }
            assert!(Instant::now() < deadline, "the child never died");
            std::thread::sleep(Duration::from_millis(10));
        }
        let err = host.send_yield_turn("demo.txt", "hello world").unwrap_err();
        // Pin the failure to the sink write AFTER staging: a pre-staging
        // rejection ("mid-turn", "pilot is gone") would pass the rollback
        // assertions below vacuously, without ever staging a look.
        assert!(
            format!("{err:#}").contains("claude"),
            "the send must fail at the claude sink, not before staging: {err:#}"
        );
        assert_eq!(
            host.last_seen("demo.txt"),
            None,
            "a failed yield keeps no baseline"
        );
        assert!(
            !settle(&false, || host.is_busy()),
            "a failed yield keeps no busy latch"
        );
        drop(host);
    }

    /// A send that never reached the endpoint must not wedge the seat: the
    /// busy latch and the pending cancel note were committed BEFORE the
    /// write, so a dead stdin left is_busy() true for the rest of the
    /// seat's life and silently ate the "your edit was cancelled" preamble
    /// owed to the model.
    #[test]
    fn a_failed_send_unlatches_the_turn_and_keeps_the_cancel_note() {
        let harness = OwnerHarness::start("hello world");
        let (state, stop, pump) = pumped_state(&harness);
        state.lock().unwrap().pending_note = Some(String::from("cancelled: f.rs"));
        let dead = TurnSink::Claude(Arc::new(Mutex::new(None)));
        let err = write_user_turn(&state, &dead, String::from("hi"))
            .expect_err("a dead stdin must fail the send");
        assert!(err.to_string().contains("stdin"), "{err}");
        {
            let st = state.lock().unwrap();
            assert!(
                !st.turn_active,
                "a turn that never left must not stay active"
            );
            assert_eq!(
                st.pending_note.as_deref(),
                Some("cancelled: f.rs"),
                "the cancel note is still owed to the model"
            );
        }
        stop.store(true, Ordering::Relaxed);
        pump.join().unwrap();
    }

    /// An unseat moments before exit must still reap the pilot's child:
    /// Drop detaches its grace-kill onto a thread, and a thread that dies
    /// with the process leaves the child running (orphaned, still holding
    /// its MCP subprocesses). join_teardowns() is the exit path's barrier
    /// for every detached teardown.
    #[test]
    fn join_teardowns_reaps_a_dropped_hosts_child() {
        if !crate::lsp::manager::is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let harness = OwnerHarness::start("hello world");
        let marker = format!("croft-teardown-{}", std::process::id());
        let mut cmd = std::process::Command::new("python3");
        cmd.arg("-c")
            .arg("import time; time.sleep(120)")
            .arg(&marker);
        let host =
            crate::pair_host::PairHost::spawn_cmd(&harness.socket, "nav", None, cmd).unwrap();
        let alive = |m: &str| {
            std::process::Command::new("pgrep")
                .args(["-f", m])
                .output()
                .map(|o| !o.stdout.is_empty())
                .unwrap_or(false)
        };
        assert!(alive(&marker), "the sleeper child must be running");
        drop(host);
        crate::pair_host::join_teardowns();
        assert!(
            !alive(&marker),
            "after join_teardowns the dropped host's child must be reaped"
        );
    }

    /// A valid fence header arriving as the turn's LAST bytes (no trailing
    /// newline) is protocol residue, not prose: flushing it as commentary
    /// rendered the raw <<<NOTE ...>>> marker inside a comment box. A
    /// malformed <<<-prefixed tail keeps the existing commentary behavior
    /// (the malformed-header rule).
    #[test]
    fn an_unterminated_fence_header_never_leaks_into_commentary() {
        let mut m = FenceMachine::new();
        let mut events = m.push("thinking\n<<<NOTE src/f.rs:12>>>");
        events.extend(m.finish());
        let commentary = commentary_of(&events);
        assert!(commentary.contains("thinking"));
        assert!(
            !commentary.contains("<<<NOTE"),
            "protocol residue leaked: {commentary:?}"
        );
        let mut events = m.push("<<<EDIT src/f.rs:0:0-0:5>>>");
        events.extend(m.finish());
        assert!(
            !commentary_of(&events).contains("<<<EDIT"),
            "an EDIT header tail is the same class"
        );
        let mut events = m.push("<<<EDIT garbage");
        events.extend(m.finish());
        assert!(
            commentary_of(&events).contains("<<<EDIT garbage"),
            "a malformed tail stays commentary"
        );
    }

    /// The persistent AI caret: a park before the file is live resolves as
    /// soon as the bootstrap lands (the pump broadcasts it), and a park on a
    /// live file broadcasts immediately, clamped to the last line.
    #[test]
    fn park_caret_waits_for_bootstrap_then_broadcasts() {
        let harness = OwnerHarness::start("l0\nl1\nl2");
        let (state, stop, pump) = pumped_state(&harness);
        {
            let mut st = state.lock().unwrap();
            st.begin_turn("demo.txt", "l0\nl1\nl2", false); // requests the file
            st.park_caret("demo.txt", 1); // not live yet: pending
        }
        harness.wait_until("the parked caret to broadcast", |h| {
            h.carets()
                .iter()
                .any(|(n, r, c)| n == "pilot" && *r == 1 && *c == 0)
        });
        // Live now: an out-of-range park clamps to the last line.
        state.lock().unwrap().park_caret("demo.txt", 99);
        harness.wait_until("the clamped caret", |h| {
            h.carets().iter().any(|(n, r, _)| n == "pilot" && *r == 2)
        });
        stop.store(true, Ordering::Relaxed);
        let _ = pump.join();
    }

    /// Every landed note parks the pilot's caret at its anchor row: the AI
    /// is visibly "looking" where it just commented.
    #[test]
    fn a_landed_note_parks_the_pilot_caret_at_its_row() {
        let harness = OwnerHarness::start("l0\nl1\nl2");
        let (state, stop, pump) = pumped_state(&harness);
        apply_fence_event(
            &state,
            FenceEvent::NoteStart {
                file: "demo.txt".into(),
                row: 2,
            },
        );
        apply_fence_event(&state, FenceEvent::NoteBody("look here".into()));
        apply_fence_event(&state, FenceEvent::NoteEnd);
        harness.wait_until("the note's caret", |h| {
            h.carets().iter().any(|(n, r, _)| n == "pilot" && *r == 2)
        });
        stop.store(true, Ordering::Relaxed);
        let _ = pump.join();
    }

    /// Ask and reply turns park the navigator's caret at their focus row
    /// (the invoked range start / the answered note's row), so the caret is
    /// visible from the first interaction even on comment-only turns.
    #[test]
    fn ask_and_reply_turns_park_the_navigator_caret() {
        let harness = OwnerHarness::start("l0\nl1\nl2");
        let mut cmd = Command::new("cat");
        cmd.stdin(Stdio::piped());
        let asker =
            crate::pair_host::PairHost::spawn_cmd(&harness.socket, "asker", None, cmd).unwrap();
        asker
            .send_ask_turn("demo.txt", (1, 1), "", "look at this", "l0\nl1\nl2")
            .unwrap();
        harness.wait_until("the ask turn's caret", |h| {
            h.carets().iter().any(|(n, r, _)| n == "asker" && *r == 1)
        });
        // The caret reaching the owner and the seat recording its site id
        // are two arrivals, not one: the assertion must wait for the state
        // it checks, not for a neighbour that usually lands first (#338).
        harness.wait_until("the seat's per-file site ids (its wire identity)", |_| {
            !asker.caret_sites().is_empty()
        });

        let mut cmd = Command::new("cat");
        cmd.stdin(Stdio::piped());
        let replier =
            crate::pair_host::PairHost::spawn_cmd(&harness.socket, "replier", None, cmd).unwrap();
        replier
            .send_reply_turn("demo.txt", 2, "seed note", "why here?", "l0\nl1\nl2")
            .unwrap();
        harness.wait_until("the reply turn's caret", |h| {
            h.carets().iter().any(|(n, r, _)| n == "replier" && *r == 2)
        });
    }

    /// A rollback deferred past its moment (the failed send could not get
    /// the pilot mutex, so the unstage was handed to a waiting thread) must
    /// land as a no-op once a NEWER turn has staged: unconditionally
    /// restoring the old turn's books would flip the live turn
    /// comment-only, retarget it, and rot its yield-diff baseline.
    #[test]
    fn a_stale_rollback_never_stomps_a_newer_turn() {
        let harness = OwnerHarness::start("hello");
        let session = connect_session(&harness.socket, "pilot").unwrap();
        let state = Mutex::new(PairState::new(session, None));
        let mut st = state.lock().unwrap();
        let staged_a = st.stage_turn("demo.txt", "one", false);
        // Turn B stages before A's deferred rollback lands.
        let _staged_b = st.stage_turn("demo.txt", "two", true);
        st.unstage_turn(staged_a); // the deferred rollback finally runs
        assert_eq!(
            st.last_seen_of("demo.txt").as_deref(),
            Some("two"),
            "a stale rollback must not replace the live turn's baseline"
        );
        assert!(
            st.comment_only,
            "a stale rollback must not unlatch the live turn's comment-only"
        );
    }

    /// A failed send's undo that could not get the pilot mutex is parked,
    /// not handed to an untracked thread: while parked (contended lock) a
    /// new send is refused, and once the lock is free the undo applies and
    /// the park clears — the books are never a mix of two turns.
    #[test]
    fn a_parked_rollback_blocks_sends_until_it_applies() {
        let harness = OwnerHarness::start("hello");
        let session = connect_session(&harness.socket, "pilot").unwrap();
        let state = Mutex::new(PairState::new(session, None));
        let staged = state.lock().unwrap().stage_turn("demo.txt", "one", false);
        let parked = Mutex::new(Some(staged));
        // Contended: still parked, the caller must refuse to stage.
        assert!(!crate::pair_host::drain_parked(&parked, || None));
        assert!(parked.lock().unwrap().is_some(), "the undo is not lost");
        // Free: the undo applies and the park clears.
        assert!(crate::pair_host::drain_parked(&parked, || Some(
            state.lock().unwrap()
        )));
        assert!(parked.lock().unwrap().is_none());
        assert_eq!(
            state.lock().unwrap().last_seen_of("demo.txt"),
            None,
            "the parked undo restored the pre-turn baseline"
        );
    }

    /// Rollbacks are undo records: applied newest-first they must unwind
    /// all the way back to the original state. Turn A fails (rollback
    /// parked), turn B stages over A's residue and fails too; B's undo
    /// puts A's books back and must also re-admit A's undo, or the seat
    /// stays latched to A's staged look, comment-only flag, and target.
    #[test]
    fn nested_rollbacks_unwind_to_the_original_state() {
        let harness = OwnerHarness::start("hello");
        let session = connect_session(&harness.socket, "pilot").unwrap();
        let state = Mutex::new(PairState::new(session, None));
        let mut st = state.lock().unwrap();
        let staged_a = st.stage_turn("demo.txt", "one", false);
        let staged_b = st.stage_turn("demo.txt", "two", true);
        st.unstage_turn(staged_b); // B's send failed: newest undo first
        st.unstage_turn(staged_a); // then A's parked undo lands
        assert_eq!(
            st.last_seen_of("demo.txt"),
            None,
            "both failed turns unwound: no baseline remains"
        );
        assert!(!st.comment_only, "the original comment-only state is back");
        assert_eq!(st.target_file, None, "the original target is back");
    }

    /// claude's stdout is an external input: a `result` line with no
    /// dispatched turn behind it (a duplicate emission, or a spontaneous
    /// one) must end nothing. Queuing a phantom TurnEnd would release the
    /// host's busy gate under a newer turn, and the handler's flag resets
    /// would clear that turn's comment-only staging.
    #[test]
    fn an_unsolicited_result_ends_no_turn() {
        let harness = OwnerHarness::start("hello");
        let session = connect_session(&harness.socket, "pilot").unwrap();
        let state = Mutex::new(PairState::new(session, None));
        let mut fence = FenceMachine::new();
        let (turn_tx, turn_rx) = std::sync::mpsc::channel();
        let result = json!({ "type": "result", "is_error": false, "result": "done" });

        // A dispatched turn ends exactly once.
        state.lock().unwrap().turn_active = true;
        handle_claude_event(&state, &mut fence, &result, &turn_tx);
        assert!(
            turn_rx.try_recv().is_ok(),
            "the genuine result ends the turn"
        );

        // A newer comment-only turn stages, then the duplicate arrives.
        state.lock().unwrap().stage_turn("demo.txt", "one", true);
        handle_claude_event(&state, &mut fence, &result, &turn_tx);
        assert!(
            turn_rx.try_recv().is_err(),
            "a duplicate result must not queue a phantom TurnEnd"
        );
        assert!(
            state.lock().unwrap().comment_only,
            "a duplicate result must not clear the newer turn's comment-only staging"
        );
    }

    /// An edit taking over the caret supersedes an unresolved pending park:
    /// once the region opens (and parks the caret at its start), the stale
    /// ask-row park must never fire afterwards and yank the caret back.
    #[test]
    fn an_open_region_supersedes_a_pending_caret_park() {
        let harness = OwnerHarness::start("l0\nl1\nl2");
        let session = connect_session(&harness.socket, "pilot").unwrap();
        let state = Mutex::new(PairState::new(session, None));
        {
            let mut st = state.lock().unwrap();
            st.begin_turn("demo.txt", "l0\nl1\nl2", false);
            st.park_caret("demo.txt", 1);
            assert!(st.pending_caret.is_some(), "not live yet: the park waits");
        }
        // Ingest the bootstrap by hand (no pump thread, so nothing can
        // resolve the pending park before the edit lands).
        let deadline = Instant::now() + Duration::from_secs(5);
        loop {
            let mut st = state.lock().unwrap();
            let _ = st.session.poll(|_| None);
            if st.session.is_live("demo.txt") {
                break;
            }
            drop(st);
            assert!(Instant::now() < deadline, "demo.txt never went live");
            std::thread::sleep(Duration::from_millis(5));
        }
        let mut st = state.lock().unwrap();
        open_region(&mut st, "demo.txt", (0, 0), (0, 0));
        assert!(
            st.pending_caret.is_none(),
            "the edit's caret supersedes the pending park"
        );
    }

    /// A PARSEABLE whole-line header with an inverted range (`5-3`) drops
    /// the edit through the OUTPUT channel, never stderr: the resident
    /// navigator runs in-process, so an eprintln! would land on the
    /// alternate screen and corrupt the render. The inverted header is a
    /// one-token slip for the weak local models the whole-line form serves.
    #[test]
    fn an_inverted_fence_range_drops_the_edit_via_output_not_stderr() {
        let harness = OwnerHarness::start("l0\nl1\nl2\nl3\nl4\nl5");
        let session = connect_session(&harness.socket, "pilot").unwrap();
        let state = Mutex::new(PairState::new(session, None));
        state
            .lock()
            .unwrap()
            .begin_turn("demo.txt", "l0\nl1\nl2\nl3\nl4\nl5", false);
        let deadline = Instant::now() + Duration::from_secs(5);
        loop {
            let mut st = state.lock().unwrap();
            let _ = st.session.poll(|_| None);
            if st.session.is_live("demo.txt") {
                break;
            }
            drop(st);
            assert!(Instant::now() < deadline, "demo.txt never went live");
            std::thread::sleep(Duration::from_millis(5));
        }
        let baseline = crate::output::snapshot("Navigator")
            .unwrap_or_default()
            .len();
        let mut st = state.lock().unwrap();
        open_region(&mut st, "demo.txt", (4, 0), (2, usize::MAX));
        assert!(st.discarding, "the inverted edit's body must be discarded");
        assert_eq!(
            st.session.doc_text("demo.txt"),
            Some("l0\nl1\nl2\nl3\nl4\nl5"),
            "nothing may be applied"
        );
        let lines = crate::output::snapshot("Navigator").unwrap_or_default();
        assert!(
            lines
                .iter()
                .skip(baseline)
                .any(|l| l.text.contains("inverted")),
            "the drop is reported on the OUTPUT channel"
        );
    }

    /// Offline slice of the local backend: one canned /v1/messages SSE turn
    /// streams a fenced edit through the REAL fence machine and apply path
    /// into the owner's replica, appends the assistant message, and ends
    /// the turn cleanly. No Ollama needed.
    #[test]
    fn stream_turn_applies_a_fenced_edit() {
        let harness = OwnerHarness::start("hello world");
        let (state, stop, pump) = pumped_state(&harness);
        let (base_url, server) = serve_sse_once(vec![
            "Let me fix that.\n",
            "<<<EDIT demo.txt:0:6-0:11>",
            ">>\n",
            "streamed",
            " edit",
            "\n<<<END>>>\nDone.\n",
        ]);

        let (turn_tx, turn_rx) = std::sync::mpsc::channel();
        let mut messages = vec![json!({ "role": "user", "content": "fix demo.txt" })];
        local::stream_turn(
            &base_url,
            "test-model",
            PAIR_SYSTEM_PROMPT,
            &mut messages,
            &state,
            &turn_tx,
        );
        server.join().unwrap();

        harness.wait_until("the streamed edit to converge", |h| {
            h.doc().as_deref() == Some("hello streamed edit")
        });
        assert!(
            harness.remote_edit_count() >= 3,
            "the edit must arrive as multiple streamed ops, got {}",
            harness.remote_edit_count()
        );
        let end = turn_rx.try_recv().expect("turn ended");
        assert!(!end.is_error && !end.cancelled);
        assert_eq!(messages.len(), 2, "assistant reply appended");
        assert_eq!(messages[1]["role"], "assistant");
        assert!(
            messages[1]["content"]
                .as_str()
                .unwrap()
                .contains("<<<EDIT demo.txt:0:6-0:11>>>"),
            "conversation history carries the fence verbatim"
        );
        assert!(!state.lock().unwrap().turn_active());
        stop.store(true, Ordering::Relaxed);
        pump.join().unwrap();
    }

    /// #1207: the stream is announced before its first edit (the region's
    /// delete), so the host folds every edit of it, delete included, into
    /// one undo step; announced after, the delete was a step of its own.
    #[test]
    fn a_stream_is_announced_before_its_first_edit() {
        let harness = OwnerHarness::start("hello world");
        let (state, stop, pump) = pumped_state(&harness);
        let (base_url, server) = serve_sse_once(vec![
            "<<<EDIT demo.txt:0:6-0:11>>>\n",
            "streamed",
            "\n<<<END>>>\n",
        ]);
        let (turn_tx, _turn_rx) = std::sync::mpsc::channel();
        let mut messages = vec![json!({ "role": "user", "content": "fix demo.txt" })];
        local::stream_turn(
            &base_url,
            "test-model",
            PAIR_SYSTEM_PROMPT,
            &mut messages,
            &state,
            &turn_tx,
        );
        server.join().unwrap();
        harness.wait_until("the streamed edit to converge", |h| {
            h.doc().as_deref() == Some("hello streamed")
        });
        harness.wait_until("the stream to end", |h| {
            h.events
                .lock()
                .unwrap()
                .iter()
                .any(|e| matches!(e, CollabEvent::StreamState { active: false, .. }))
        });
        let events = harness.events.lock().unwrap();
        let first = |pred: &dyn Fn(&CollabEvent) -> bool| events.iter().position(pred);
        let announced = first(&|e| matches!(e, CollabEvent::StreamState { active: true, .. }))
            .expect("the stream is announced");
        let edited =
            first(&|e| matches!(e, CollabEvent::RemoteEdit { .. })).expect("the stream edits");
        let ended = first(&|e| matches!(e, CollabEvent::StreamState { active: false, .. }))
            .expect("the stream ends");
        assert!(
            announced < edited,
            "announced at {announced}, first edit at {edited}"
        );
        // Negative: the end still follows the last edit.
        let last_edit = events
            .iter()
            .rposition(|e| matches!(e, CollabEvent::RemoteEdit { .. }))
            .unwrap();
        assert!(
            last_edit < ended,
            "last edit at {last_edit}, ended at {ended}"
        );
        drop(events);
        stop.store(true, Ordering::Relaxed);
        pump.join().unwrap();
    }

    /// A dead endpoint fails the turn — naming the endpoint — instead of
    /// wedging turn_active or killing the seat.
    #[test]
    fn stream_turn_names_a_dead_endpoint() {
        let harness = OwnerHarness::start("hello world");
        let (state, stop, pump) = pumped_state(&harness);
        // A bound-then-dropped port: connection refused.
        let dead = {
            let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
            format!("http://{}", l.local_addr().unwrap())
        };
        let (turn_tx, turn_rx) = std::sync::mpsc::channel();
        let mut messages = vec![json!({ "role": "user", "content": "hi" })];
        state.lock().unwrap().turn_active = true;
        local::stream_turn(
            &dead,
            "test-model",
            PAIR_SYSTEM_PROMPT,
            &mut messages,
            &state,
            &turn_tx,
        );
        let end = turn_rx.try_recv().expect("turn ended");
        assert!(end.is_error);
        assert!(
            end.text.contains(&dead),
            "the failure names the endpoint: {}",
            end.text
        );
        assert!(!state.lock().unwrap().turn_active());
        assert!(
            messages.is_empty(),
            "the unanswered user message is popped so the next ask starts clean"
        );
        stop.store(true, Ordering::Relaxed);
        pump.join().unwrap();
    }

    /// A stream that dies before `message_stop` is a FAILED turn: the old
    /// code reported success ("claude finished its turn") while the partial
    /// edit had been reverted and nothing happened - and it appended the
    /// partial text as an assistant message, corrupting the conversation.
    #[test]
    fn a_mid_stream_drop_reports_failure_and_balances_the_conversation() {
        let harness = OwnerHarness::start("hello world");
        let (state, stop, pump) = pumped_state(&harness);
        let ev = json!({
            "type": "content_block_delta",
            "index": 0,
            "delta": { "type": "text_delta", "text": "half a rep" },
        });
        let (base_url, server) = serve_http_once(format!(
            "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\
             connection: close\r\n\r\nevent: content_block_delta\ndata: {ev}\n\n"
        ));
        let (turn_tx, turn_rx) = std::sync::mpsc::channel();
        let mut messages = vec![json!({ "role": "user", "content": "hi" })];
        state.lock().unwrap().turn_active = true;
        local::stream_turn(
            &base_url,
            "test-model",
            PAIR_SYSTEM_PROMPT,
            &mut messages,
            &state,
            &turn_tx,
        );
        server.join().unwrap();
        let end = turn_rx.try_recv().expect("turn ended");
        assert!(
            end.is_error,
            "an unclean stream end is a failure: {}",
            end.text
        );
        assert!(
            messages.is_empty(),
            "the conversation stays balanced for the next ask"
        );
        stop.store(true, Ordering::Relaxed);
        pump.join().unwrap();
    }

    /// The HTTP error body carries the fix ("model 'x' not found, try
    /// pulling it first"); throwing it away left an opaque status code.
    #[test]
    fn an_http_error_body_reaches_the_surfaced_failure() {
        let harness = OwnerHarness::start("hello world");
        let (state, stop, pump) = pumped_state(&harness);
        let (base_url, server) = serve_http_once(String::from(
            "HTTP/1.1 404 Not Found\r\ncontent-type: application/json\r\n\
             connection: close\r\n\r\n{\"error\":\"model 'qwn3' not found, try pulling it\"}",
        ));
        let (turn_tx, turn_rx) = std::sync::mpsc::channel();
        let mut messages = vec![json!({ "role": "user", "content": "hi" })];
        state.lock().unwrap().turn_active = true;
        local::stream_turn(
            &base_url,
            "qwn3",
            PAIR_SYSTEM_PROMPT,
            &mut messages,
            &state,
            &turn_tx,
        );
        server.join().unwrap();
        let end = turn_rx.try_recv().expect("turn ended");
        assert!(end.is_error);
        assert!(
            end.text.contains("not found, try pulling it"),
            "the body's own words must survive: {}",
            end.text
        );
        assert!(messages.is_empty());
        stop.store(true, Ordering::Relaxed);
        pump.join().unwrap();
    }

    /// `stop_reason: max_tokens` means the reply (and any fence in it) was
    /// cut off; reporting success would pretend the half-edit was the turn.
    #[test]
    fn a_token_limit_truncation_is_a_failed_turn() {
        let harness = OwnerHarness::start("hello world");
        let (state, stop, pump) = pumped_state(&harness);
        let delta = json!({
            "type": "content_block_delta",
            "index": 0,
            "delta": { "type": "text_delta", "text": "prose" },
        });
        let md = json!({
            "type": "message_delta",
            "delta": { "stop_reason": "max_tokens" },
        });
        let (base_url, server) = serve_http_once(format!(
            "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\
             connection: close\r\n\r\n\
             event: content_block_delta\ndata: {delta}\n\n\
             event: message_delta\ndata: {md}\n\n\
             event: message_stop\ndata: {{\"type\":\"message_stop\"}}\n\n"
        ));
        let (turn_tx, turn_rx) = std::sync::mpsc::channel();
        let mut messages = vec![json!({ "role": "user", "content": "hi" })];
        state.lock().unwrap().turn_active = true;
        local::stream_turn(
            &base_url,
            "test-model",
            PAIR_SYSTEM_PROMPT,
            &mut messages,
            &state,
            &turn_tx,
        );
        server.join().unwrap();
        let end = turn_rx.try_recv().expect("turn ended");
        assert!(end.is_error, "truncation must not read as success");
        assert!(end.text.contains("truncated"), "{}", end.text);
        stop.store(true, Ordering::Relaxed);
        pump.join().unwrap();
    }

    /// The environment credential only ever travels to https or loopback
    /// destinations; a cleartext remote hop gets the harmless placeholder.
    #[test]
    fn the_credential_never_rides_cleartext_to_a_remote_host() {
        use local::auth_for;
        assert_eq!(
            auth_for("http://box:8080", Some("secret")),
            (String::from("croft"), None),
        );
        assert_eq!(
            auth_for("http://localhost.evil.com:80", Some("secret")),
            (String::from("croft"), None),
        );
        let bearer = Some(String::from("Bearer t"));
        assert_eq!(
            auth_for("http://localhost:11434", Some("t")),
            (String::from("t"), bearer.clone()),
        );
        assert_eq!(
            auth_for("http://127.0.0.1:11434", Some("t")),
            (String::from("t"), bearer.clone()),
        );
        assert_eq!(
            auth_for("http://[::1]:11434", Some("t")),
            (String::from("t"), bearer.clone()),
        );
        assert_eq!(
            auth_for("https://gw.example.com", Some("t")),
            (String::from("t"), bearer),
        );
        assert_eq!(
            auth_for("http://localhost:11434", None),
            (String::from("croft"), None)
        );
        // Userinfo must not fool the gate: the destination here is the
        // remote host, not localhost.
        assert_eq!(
            auth_for("http://localhost:pass@evil.example", Some("secret")),
            (String::from("croft"), None),
        );
        assert_eq!(
            auth_for("http://127.0.0.2:11434", Some("t")),
            (String::from("t"), Some(String::from("Bearer t"))),
            "any 127.x address is loopback"
        );
    }

    /// The wall-clock ceiling is enforced per CHUNK: a stream of non-newline
    /// bytes never completes a line, so a per-line check would have let a
    /// trickling endpoint hold the seat busy indefinitely.
    #[test]
    fn a_trickling_stream_is_cut_at_the_deadline() {
        let harness = OwnerHarness::start("hello world");
        let (state, stop, pump) = pumped_state(&harness);
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let base_url = format!("http://{}", listener.local_addr().unwrap());
        let stop_trickle = Arc::new(AtomicBool::new(false));
        let server = {
            let stop_trickle = Arc::clone(&stop_trickle);
            std::thread::spawn(move || {
                let (mut sock, _) = listener.accept().unwrap();
                let mut req = [0u8; 4096];
                let _ = sock.read(&mut req);
                let _ =
                    sock.write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\n");
                // Non-newline bytes, forever (until the test releases us).
                while !stop_trickle.load(Ordering::Relaxed) {
                    if sock.write_all(b".").is_err() {
                        break;
                    }
                    std::thread::sleep(Duration::from_millis(20));
                }
            })
        };
        let (turn_tx, turn_rx) = std::sync::mpsc::channel();
        let mut messages = vec![json!({ "role": "user", "content": "hi" })];
        state.lock().unwrap().turn_active = true;
        let started = Instant::now();
        local::stream_turn_until(
            &base_url,
            "test-model",
            PAIR_SYSTEM_PROMPT,
            &mut messages,
            &state,
            &turn_tx,
            Instant::now() + Duration::from_millis(300),
        );
        let elapsed = started.elapsed();
        stop_trickle.store(true, Ordering::Relaxed);
        let _ = server.join();
        let end = turn_rx.try_recv().expect("turn ended");
        assert!(end.is_error, "a deadline cut is a failure: {}", end.text);
        assert!(
            elapsed < Duration::from_secs(3),
            "the ceiling must interrupt the trickle promptly, took {elapsed:?}"
        );
        assert!(messages.is_empty(), "the conversation stays balanced");
        stop.store(true, Ordering::Relaxed);
        pump.join().unwrap();
    }

    /// The deadline used to be polled only BETWEEN reads: a peer that sent
    /// headers and then held the body open without a single byte parked the
    /// loop inside the blocking `read` (up to the 300s socket timeout) past
    /// the ceiling. Each wait is bounded by the remaining turn time instead.
    #[test]
    fn a_silent_stream_body_is_cut_at_the_deadline() {
        let harness = OwnerHarness::start("hello world");
        let (state, stop, pump) = pumped_state(&harness);
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let base_url = format!("http://{}", listener.local_addr().unwrap());
        // The thread ends on its own after the silence window; dropping the
        // handle detaches it.
        std::thread::spawn(move || {
            let (mut sock, _) = listener.accept().unwrap();
            let mut req = [0u8; 4096];
            let _ = sock.read(&mut req);
            let _ = sock.write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\n");
            // Not one body byte: hold the connection open in silence, long
            // enough that only the deadline can explain a prompt return.
            std::thread::sleep(Duration::from_secs(4));
        });
        let (turn_tx, turn_rx) = std::sync::mpsc::channel();
        let mut messages = vec![json!({ "role": "user", "content": "hi" })];
        state.lock().unwrap().turn_active = true;
        let started = Instant::now();
        local::stream_turn_until(
            &base_url,
            "test-model",
            PAIR_SYSTEM_PROMPT,
            &mut messages,
            &state,
            &turn_tx,
            Instant::now() + Duration::from_millis(300),
        );
        let elapsed = started.elapsed();
        let end = turn_rx.try_recv().expect("turn ended");
        assert!(end.is_error, "a deadline cut is a failure: {}", end.text);
        assert!(
            elapsed < Duration::from_secs(3),
            "the ceiling must interrupt a silent body promptly, took {elapsed:?}"
        );
        assert!(messages.is_empty(), "the conversation stays balanced");
        stop.store(true, Ordering::Relaxed);
        pump.join().unwrap();
    }

    /// A deadline cut must also RELEASE the connection. Returning on time
    /// while a detached reader stayed blocked in `read` kept the socket and
    /// a thread alive for up to the 300s socket timeout per failed turn, so
    /// repeated failures accumulated both. The server observing EOF right
    /// after the cut is the proof the transport let go.
    #[test]
    fn a_deadline_cut_releases_the_connection() {
        let harness = OwnerHarness::start("hello world");
        let (state, stop, pump) = pumped_state(&harness);
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let base_url = format!("http://{}", listener.local_addr().unwrap());
        let (eof_tx, eof_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let (mut sock, _) = listener.accept().unwrap();
            let mut req = [0u8; 4096];
            let _ = sock.read(&mut req);
            let _ = sock.write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\n");
            // Silent body: block until the CLIENT hangs up. EOF or a reset
            // is the release; draining any leftover request bytes first.
            let mut probe = [0u8; 64];
            loop {
                match sock.read(&mut probe) {
                    Ok(0) | Err(_) => break,
                    Ok(_) => {}
                }
            }
            let _ = eof_tx.send(());
        });
        let (turn_tx, turn_rx) = std::sync::mpsc::channel();
        let mut messages = vec![json!({ "role": "user", "content": "hi" })];
        state.lock().unwrap().turn_active = true;
        local::stream_turn_until(
            &base_url,
            "test-model",
            PAIR_SYSTEM_PROMPT,
            &mut messages,
            &state,
            &turn_tx,
            Instant::now() + Duration::from_millis(300),
        );
        let end = turn_rx.try_recv().expect("turn ended");
        assert!(end.is_error, "a deadline cut is a failure: {}", end.text);
        eof_rx.recv_timeout(Duration::from_secs(2)).expect(
            "the deadline cut must close the connection, not park it until the socket timeout",
        );
        assert!(messages.is_empty(), "the conversation stays balanced");
        stop.store(true, Ordering::Relaxed);
        pump.join().unwrap();
    }

    /// Malformed SSE data mid-stream silently dropped a chunk of the reply
    /// and still reported success; a broken endpoint must fail the turn.
    #[test]
    fn malformed_sse_data_fails_the_turn() {
        let harness = OwnerHarness::start("hello world");
        let (state, stop, pump) = pumped_state(&harness);
        let (base_url, server) = serve_http_once(String::from(
            "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\
             connection: close\r\n\r\ndata: {not json\n\n\
             event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n",
        ));
        let (turn_tx, turn_rx) = std::sync::mpsc::channel();
        let mut messages = vec![json!({ "role": "user", "content": "hi" })];
        state.lock().unwrap().turn_active = true;
        local::stream_turn(
            &base_url,
            "test-model",
            PAIR_SYSTEM_PROMPT,
            &mut messages,
            &state,
            &turn_tx,
        );
        server.join().unwrap();
        let end = turn_rx.try_recv().expect("turn ended");
        assert!(end.is_error);
        assert!(end.text.contains("malformed"), "{}", end.text);
        assert!(messages.is_empty());
        stop.store(true, Ordering::Relaxed);
        pump.join().unwrap();
    }

    /// A 3xx from the endpoint must NOT be followed: ureq replays the
    /// x-api-key header to the redirect target, so a loopback endpoint
    /// answering 302 could bounce the credential to an arbitrary host. The
    /// redirect surfaces as a failed turn naming the status.
    #[test]
    fn a_redirect_is_refused_not_followed() {
        let harness = OwnerHarness::start("hello world");
        let (state, stop, pump) = pumped_state(&harness);
        let (base_url, server) = serve_http_once(String::from(
            "HTTP/1.1 302 Found\r\nlocation: http://127.0.0.1:1/v1/messages\r\n\
             connection: close\r\n\r\n",
        ));
        let (turn_tx, turn_rx) = std::sync::mpsc::channel();
        let mut messages = vec![json!({ "role": "user", "content": "hi" })];
        state.lock().unwrap().turn_active = true;
        local::stream_turn(
            &base_url,
            "test-model",
            PAIR_SYSTEM_PROMPT,
            &mut messages,
            &state,
            &turn_tx,
        );
        server.join().unwrap();
        let end = turn_rx.try_recv().expect("turn ended");
        assert!(end.is_error);
        assert!(
            end.text.contains("302"),
            "the redirect is refused with its status, not followed: {}",
            end.text
        );
        assert!(messages.is_empty());
        stop.store(true, Ordering::Relaxed);
        pump.join().unwrap();
    }

    /// The childless local seat end to end: seat_local connects the guest
    /// seat, the queued turn streams the stub endpoint's fenced edit into
    /// the owner's replica, the turn ends cleanly, and shutdown returns
    /// promptly (no child, no grace-kill).
    #[test]
    fn seat_local_drives_a_turn_end_to_end() {
        let harness = OwnerHarness::start("hello world");
        let (base_url, server) = serve_sse_once(vec![
            "Let me fix that.\n",
            "<<<EDIT demo.txt:0:6-0:11>",
            ">>\n",
            "streamed",
            " edit",
            "\n<<<END>>>\nDone.\n",
        ]);
        let pilot = seat_local(&harness.socket, "pilot", &base_url, "test-model", None).unwrap();
        assert!(!pilot.reader_finished(), "a local seat never loses a child");

        send_turn(&pilot.state, &pilot.sink, "fix demo.txt").unwrap();
        let end = pilot
            .turn_rx
            .recv_timeout(Duration::from_secs(60))
            .expect("turn ends");
        assert!(!end.is_error && !end.cancelled, "{}", end.text);
        server.join().unwrap();

        harness.wait_until("the streamed edit to converge", |h| {
            h.doc().as_deref() == Some("hello streamed edit")
        });
        harness.wait_until("stream-state inactive", |h| {
            h.stream_states().contains(&("pilot".to_string(), false))
        });

        let start = Instant::now();
        pilot.shutdown();
        assert!(
            start.elapsed() < Duration::from_secs(2),
            "local shutdown must not block on a grace-kill"
        );
    }

    /// PairHost::spawn dispatches on the provider: a Local config refuses to
    /// seat without a model (there is no CLI default to fall back to), and
    /// with one it seats childless and drives a whole-line ask turn from the
    /// endpoint into the owner's replica.
    #[test]
    fn pair_host_spawns_local_backend_without_a_child() {
        let harness = OwnerHarness::start("hello world");
        let no_model = PairConfig {
            socket: harness.socket.clone(),
            workspace: harness._dir.path().to_path_buf(),
            name: String::from("claude"),
            model: None,
            task: None,
            provider: Provider::Local {
                base_url: String::from("http://127.0.0.1:9"),
            },
        };
        let err = match crate::pair_host::PairHost::spawn(no_model) {
            Err(e) => e,
            Ok(_) => panic!("a local provider without a model must refuse to seat"),
        };
        assert!(
            err.to_string().contains("--model"),
            "the refusal must hint at --model: {err}"
        );

        let (base_url, server) = serve_sse_once(vec![
            "<<<EDIT demo.txt:0-0>",
            ">>\nhello streamed edit\n",
            "<<<END>>>\n",
        ]);
        let mut host = crate::pair_host::PairHost::spawn(PairConfig {
            socket: harness.socket.clone(),
            workspace: harness._dir.path().to_path_buf(),
            name: String::from("claude"),
            model: Some(String::from("test-model")),
            task: None,
            provider: Provider::Local { base_url },
        })
        .unwrap();
        assert!(!host.is_busy());
        host.send_ask_turn("demo.txt", (0, 0), "", "rewrite line 0", "hello world")
            .unwrap();
        server.join().unwrap();
        harness.wait_until("the whole-line edit to converge", |h| {
            h.doc().as_deref() == Some("hello streamed edit")
        });
        harness.wait_until("the turn to end", |h| {
            let _ = h; // the turn end arrives on the host's own channel
            host.poll().iter().any(|e| {
                matches!(
                    e,
                    crate::pair_host::PairEvent::TurnDone {
                        cancelled: false,
                        failed: None
                    }
                )
            })
        });
    }

    /// The badge title names who is actually typing: bare caret name on the
    /// claude backend, "name (model)" on a local one.
    #[test]
    fn local_navigator_badge_names_the_model() {
        let harness = OwnerHarness::start("hello world");
        let host = crate::pair_host::PairHost::spawn(PairConfig {
            socket: harness.socket.clone(),
            workspace: harness._dir.path().to_path_buf(),
            name: String::from("claude"),
            model: Some(String::from("test-model")),
            task: None,
            provider: Provider::Local {
                base_url: String::from("http://127.0.0.1:9"),
            },
        })
        .unwrap();
        assert_eq!(host.title(), "claude (test-model)");

        let mut cmd = Command::new("cat");
        cmd.stdin(Stdio::piped());
        let host =
            crate::pair_host::PairHost::spawn_cmd(&harness.socket, "navigator", None, cmd).unwrap();
        assert_eq!(host.title(), "navigator");
    }

    /// Spawn the pilot against the scripted claude on a background thread
    /// (it blocks until the turn ends and its input hits EOF).
    fn spawn_pilot(
        socket: &Path,
        script: &Path,
        log: &Path,
        mode: &str,
    ) -> std::thread::JoinHandle<Result<()>> {
        let mut cmd = Command::new("python3");
        cmd.arg(script).arg(log).arg(mode);
        let socket = socket.to_path_buf();
        std::thread::spawn(move || {
            let pilot = seat_pilot(&socket, "pilot", cmd, None)?;
            run_pilot(
                pilot,
                "pilot",
                Some("fix demo.txt".into()),
                &mut std::io::Cursor::new(Vec::new()),
            )
        })
    }

    /// End to end: the fake claude's fenced edit streams through the pilot
    /// into the owner's replica as MULTIPLE ops (token streaming, not one
    /// bulk insert), bracketed by StreamState active/inactive.
    #[test]
    fn pilot_streams_a_fenced_edit_into_the_owner() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let harness = OwnerHarness::start("hello world");
        let script = harness._dir.path().join("fake_claude.py");
        std::fs::write(&script, FAKE_CLAUDE).unwrap();
        let log = harness._dir.path().join("stdin.log");

        let pilot = spawn_pilot(&harness.socket, &script, &log, "stream");

        harness.wait_until("the streamed edit to converge", |h| {
            h.doc().as_deref() == Some("hello streamed edit")
        });
        harness.wait_until("stream-state inactive", |h| {
            h.stream_states().contains(&("pilot".to_string(), false))
        });
        assert!(
            harness
                .stream_states()
                .contains(&("pilot".to_string(), true)),
            "owner saw the stream start"
        );
        assert!(
            harness.remote_edit_count() >= 3,
            "the edit must arrive as multiple streamed ops, got {}",
            harness.remote_edit_count()
        );
        pilot.join().unwrap().expect("pilot exits cleanly");
    }

    /// A claude child that never exits on stdin EOF (the real CLI's MCP
    /// teardown can linger) must not hang the pilot's exit: cleanup kills
    /// it after a short grace instead of joining the reader forever.
    #[test]
    fn pilot_exit_does_not_hang_on_a_lingering_claude() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let harness = OwnerHarness::start("hello world");
        let script = harness._dir.path().join("fake_claude.py");
        std::fs::write(&script, FAKE_CLAUDE).unwrap();
        let log = harness._dir.path().join("stdin.log");

        let pilot = spawn_pilot(&harness.socket, &script, &log, "linger");
        harness.wait_until("the streamed edit to converge", |h| {
            h.doc().as_deref() == Some("hello streamed edit")
        });
        // The pilot's REPL input is already at EOF; once the turn ends it
        // must return promptly despite the child sleeping for 60s — half
        // that sleep keeps the discriminant while absorbing suite load.
        let deadline = Instant::now() + Duration::from_secs(30);
        while !pilot.is_finished() {
            assert!(
                Instant::now() < deadline,
                "pilot exit hung on the lingering claude child"
            );
            std::thread::sleep(Duration::from_millis(50));
        }
        pilot.join().unwrap().expect("pilot exits cleanly");
    }

    /// Cancel mid-stream: the owner broadcasts StreamCancel while the fake
    /// claude is blocked mid-body; the pilot reverts the streamed text,
    /// writes a control_request interrupt to claude's stdin, and drops the
    /// post-cancel deltas. The conversation still ends its turn cleanly.
    #[test]
    fn pilot_cancel_reverts_and_interrupts() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let harness = OwnerHarness::start("hello world");
        let script = harness._dir.path().join("fake_claude.py");
        std::fs::write(&script, FAKE_CLAUDE).unwrap();
        let log = harness._dir.path().join("stdin.log");

        let pilot = spawn_pilot(&harness.socket, &script, &log, "cancel");

        // Wait until part of the body landed (stream mid-flight).
        harness.wait_until("the partial body to converge", |h| {
            h.doc().is_some_and(|d| d.contains("streamed"))
        });
        harness.owner.lock().unwrap().send_stream_cancel();

        // The pilot reverts and the turn still completes.
        harness.wait_until("the revert to converge", |h| {
            h.doc().as_deref() == Some("hello world")
        });
        pilot.join().unwrap().expect("pilot exits cleanly");

        assert_eq!(
            harness.doc().as_deref(),
            Some("hello world"),
            "post-cancel deltas must never land"
        );
        harness.wait_until("stream-state inactive", |h| {
            h.stream_states().contains(&("pilot".to_string(), false))
        });
        let log_text = std::fs::read_to_string(&log).unwrap();
        assert!(
            log_text.contains("control_request") && log_text.contains("interrupt"),
            "the interrupt must land on claude's stdin: {log_text:?}"
        );
    }

    /// Feed `input` to a fresh machine in `chunk`-sized pieces plus finish,
    /// collecting every event.
    fn run_chunks(input: &str, chunk: usize) -> Vec<FenceEvent> {
        let mut m = FenceMachine::new();
        let mut events = Vec::new();
        let chars: Vec<char> = input.chars().collect();
        for piece in chars.chunks(chunk) {
            let s: String = piece.iter().collect();
            events.extend(m.push(&s));
        }
        events.extend(m.finish());
        events
    }

    /// Concatenated body text of every EditBody event.
    fn body_of(events: &[FenceEvent]) -> String {
        events
            .iter()
            .filter_map(|e| match e {
                FenceEvent::EditBody(s) => Some(s.as_str()),
                _ => None,
            })
            .collect()
    }

    /// Concatenated commentary of every Commentary event.
    fn commentary_of(events: &[FenceEvent]) -> String {
        events
            .iter()
            .filter_map(|e| match e {
                FenceEvent::Commentary(s) => Some(s.as_str()),
                _ => None,
            })
            .collect()
    }

    /// Concatenated body of every NoteBody event.
    fn note_body_of(events: &[FenceEvent]) -> String {
        events
            .iter()
            .filter_map(|e| match e {
                FenceEvent::NoteBody(s) => Some(s.as_str()),
                _ => None,
            })
            .collect()
    }

    /// A NOTE fence parses across arbitrary delta splits: the row binds
    /// rightmost (file names may carry ':'), the body accumulates, and the
    /// fence closes on END without leaking markers into commentary.
    #[test]
    fn note_fence_parses_across_delta_splits() {
        let input = "Look at this.\n\
                     <<<NOTE src/f.rs:12>>>\n\
                     the caller in cli.rs:88\nstill expects Config\n\
                     <<<END>>>\n\
                     trailing\n";
        for chunk in [1, 3, 7, input.len()] {
            let events = run_chunks(input, chunk);
            let start = events
                .iter()
                .find_map(|e| match e {
                    FenceEvent::NoteStart { file, row } => Some((file.clone(), *row)),
                    _ => None,
                })
                .unwrap_or_else(|| panic!("no NoteStart at chunk {chunk}"));
            assert_eq!(start, ("src/f.rs".to_string(), 12), "chunk {chunk}");
            assert_eq!(
                note_body_of(&events),
                "the caller in cli.rs:88\nstill expects Config",
                "chunk {chunk}"
            );
            assert_eq!(
                events
                    .iter()
                    .filter(|e| matches!(e, FenceEvent::NoteEnd))
                    .count(),
                1,
                "chunk {chunk}"
            );
            let commentary = commentary_of(&events);
            assert!(commentary.contains("Look at this."), "chunk {chunk}");
            assert!(commentary.contains("trailing"), "chunk {chunk}");
            assert!(!commentary.contains("<<<NOTE"), "chunk {chunk}");
        }
    }

    /// Malformed NOTE headers degrade to commentary, exactly like EDIT ones.
    #[test]
    fn malformed_note_headers_become_commentary() {
        for bad in [
            "<<<NOTE src/f.rs>>>\nbody\n<<<END>>>\n",
            "<<<NOTE src/f.rs:x>>>\nbody\n<<<END>>>\n",
            "<<<NOTE :3>>>\nbody\n<<<END>>>\n",
            "<<<NOTE>>>\nbody\n<<<END>>>\n",
        ] {
            let events = run_chunks(bad, 5);
            assert!(
                !events
                    .iter()
                    .any(|e| matches!(e, FenceEvent::NoteStart { .. })),
                "{bad:?} must not start a note"
            );
        }
    }

    /// A turn ending mid-note aborts it so nothing anchors.
    #[test]
    fn unterminated_note_aborts_at_finish() {
        let mut m = FenceMachine::new();
        let mut events = m.push("<<<NOTE f.rs:3>>>\nhalf a thought");
        events.extend(m.finish());
        assert!(events.iter().any(|e| matches!(e, FenceEvent::NoteAbort)));
        assert!(!events.iter().any(|e| matches!(e, FenceEvent::NoteEnd)));
    }

    /// Interop guard: EDIT and NOTE fences coexist in one turn and neither
    /// disturbs the other's events (the 0.1.634 edit protocol is unchanged).
    #[test]
    fn edit_and_note_fences_coexist_in_one_turn() {
        let input = "<<<EDIT a.rs:0:0-0:0>>>\nnew\n<<<END>>>\n\
                     <<<NOTE b.rs:4>>>\nremark\n<<<END>>>\n";
        let events = run_chunks(input, 2);
        assert_eq!(body_of(&events), "new");
        assert_eq!(note_body_of(&events), "remark");
        assert_eq!(
            events
                .iter()
                .filter(|e| matches!(e, FenceEvent::EditEnd))
                .count(),
            1
        );
        assert_eq!(
            events
                .iter()
                .filter(|e| matches!(e, FenceEvent::NoteEnd))
                .count(),
            1
        );
    }

    /// The core streaming property: a full fenced edit parses identically no
    /// matter how the deltas split it, down to one char at a time, and the
    /// body arrives across multiple EditBody events (streaming), not one.
    #[test]
    fn fence_parses_identically_across_arbitrary_delta_splits() {
        let input = "I will fix the loop.\n\
                     <<<EDIT src/f.rs:3:0-5:10>>>\n\
                     for x in xs {\n    go(x);\n}\n\
                     <<<END>>>\n\
                     Done.\n";
        for chunk in [1, 2, 3, 7, input.len()] {
            let events = run_chunks(input, chunk);
            let start = events
                .iter()
                .find_map(|e| match e {
                    FenceEvent::EditStart { file, start, end } => {
                        Some((file.clone(), *start, *end))
                    }
                    _ => None,
                })
                .unwrap_or_else(|| panic!("no EditStart at chunk {chunk}"));
            assert_eq!(
                start,
                ("src/f.rs".to_string(), (3, 0), (5, 10)),
                "chunk {chunk}"
            );
            assert_eq!(
                body_of(&events),
                "for x in xs {\n    go(x);\n}",
                "chunk {chunk}"
            );
            assert_eq!(
                events
                    .iter()
                    .filter(|e| matches!(e, FenceEvent::EditEnd))
                    .count(),
                1,
                "chunk {chunk}"
            );
            let commentary = commentary_of(&events);
            assert!(
                commentary.contains("I will fix the loop."),
                "chunk {chunk}: {commentary:?}"
            );
            assert!(commentary.contains("Done."), "chunk {chunk}");
            assert!(
                !commentary.contains("<<<EDIT"),
                "header must not leak into commentary at chunk {chunk}"
            );
        }
        // Char-at-a-time must still stream the body incrementally.
        let events = run_chunks(input, 1);
        let bodies = events
            .iter()
            .filter(|e| matches!(e, FenceEvent::EditBody(_)))
            .count();
        assert!(bodies > 1, "body must stream, got {bodies} event(s)");
    }

    /// The whole-line header form `<file>:SR-ER` (two integers) opens an
    /// edit covering those entire rows, inclusive: start (SR,0) and an end
    /// column that clamps to the end of row ER.
    #[test]
    fn parse_header_accepts_whole_line_range() {
        let event = parse_header("<<<EDIT demo.txt:3-5>>>").expect("whole-line header parses");
        let FenceEvent::EditStart { file, start, end } = event else {
            panic!("not an EditStart: {event:?}");
        };
        assert_eq!(file, "demo.txt");
        assert_eq!(start, (3, 0));
        assert_eq!(end, (5, usize::MAX));
    }

    /// The spike's coordinate slip, fixed: a whole-line fence on the exact
    /// spike buffer replaces the row entirely — no `+ name` leftover — using
    /// the same range_bytes clamping the pilot's open_region applies.
    #[test]
    fn whole_line_edit_replaces_entire_rows() {
        let buffer = "def greet(name):\n    return \"hi \" + name\n";
        let input = "<<<EDIT greet.py:1-1>>>\n    return f\"Hello, {name}!\"\n<<<END>>>\n";
        let events = run_chunks(input, 3);
        let (start, end) = events
            .iter()
            .find_map(|e| match e {
                FenceEvent::EditStart { start, end, .. } => Some((*start, *end)),
                _ => None,
            })
            .expect("whole-line fence opens an edit");
        let lines: Vec<String> = buffer.split('\n').map(String::from).collect();
        let (s, e) = range_bytes(&lines, start, end);
        let result = format!("{}{}{}", &buffer[..s], body_of(&events), &buffer[e..]);
        assert_eq!(result, "def greet(name):\n    return f\"Hello, {name}!\"\n");
    }

    /// A truncated four-int header (`file:SR:SC-ER`, missing its end column)
    /// must NOT fall back to the whole-line form: its "file" would be the
    /// bogus `file:SR`. It stays commentary.
    #[test]
    fn truncated_four_int_header_stays_commentary() {
        assert!(parse_header("<<<EDIT src/f.rs:3:0-5>>>").is_none());
    }

    /// A header that fails to parse is commentary, never an edit.
    #[test]
    fn malformed_headers_become_commentary() {
        for bad in [
            "<<<EDIT src/f.rs:3:0-5>>>\nbody\n<<<END>>>\n",
            "<<<EDIT src/f.rs>>>\nbody\n<<<END>>>\n",
            "<<<EDIT src/f.rs:a:0-5:10>>>\nbody\n<<<END>>>\n",
            "<<<EDIT>>>\nbody\n<<<END>>>\n",
        ] {
            let events = run_chunks(bad, 5);
            assert!(
                !events
                    .iter()
                    .any(|e| matches!(e, FenceEvent::EditStart { .. })),
                "{bad:?} must not start an edit"
            );
            assert!(
                commentary_of(&events).contains("body"),
                "{bad:?}: the un-fenced body is commentary"
            );
        }
    }

    /// Exactly one trailing newline is stripped: the one that separates the
    /// body from the END marker. A body that ends in a blank line keeps it.
    #[test]
    fn end_marker_strips_exactly_one_trailing_newline() {
        let input = "<<<EDIT f:0:0-0:0>>>\nabc\n\n<<<END>>>\n";
        for chunk in [1, 4, input.len()] {
            assert_eq!(body_of(&run_chunks(input, chunk)), "abc\n", "chunk {chunk}");
        }
    }

    /// A body line that merely contains the END marker text with a suffix is
    /// body, not a terminator.
    #[test]
    fn end_marker_with_trailing_chars_is_body() {
        let input = "<<<EDIT f:0:0-0:0>>>\nkeep <<<END>>>ish\n<<<END>>>\n";
        for chunk in [1, 3, input.len()] {
            assert_eq!(
                body_of(&run_chunks(input, chunk)),
                "keep <<<END>>>ish",
                "chunk {chunk}"
            );
        }
    }

    /// Two fences in one turn each produce their own start/body/end, with
    /// the commentary between them intact.
    #[test]
    fn multiple_fences_in_one_turn() {
        let input = "<<<EDIT a:0:0-0:0>>>\nfirst\n<<<END>>>\n\
                     between\n\
                     <<<EDIT b:1:2-3:4>>>\nsecond\n<<<END>>>\n";
        let events = run_chunks(input, 2);
        let starts: Vec<String> = events
            .iter()
            .filter_map(|e| match e {
                FenceEvent::EditStart { file, .. } => Some(file.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(starts, ["a", "b"]);
        assert_eq!(body_of(&events), "firstsecond");
        assert_eq!(
            events
                .iter()
                .filter(|e| matches!(e, FenceEvent::EditEnd))
                .count(),
            2
        );
        assert!(commentary_of(&events).contains("between"));
    }

    /// The model stopping mid-fence (turn ends before <<<END>>>) aborts the
    /// edit so the pilot can revert what already streamed in.
    #[test]
    fn unterminated_fence_aborts_at_finish() {
        let mut m = FenceMachine::new();
        let mut events = m.push("<<<EDIT f:0:0-0:0>>>\npartial body");
        events.extend(m.finish());
        assert!(
            events.iter().any(|e| matches!(e, FenceEvent::EditAbort)),
            "{events:?}"
        );
        // The machine is reusable for the next turn afterwards.
        let events = {
            let mut e = m.push("plain text\n");
            e.extend(m.finish());
            e
        };
        assert!(commentary_of(&events).contains("plain text"));
    }

    /// An END marker arriving exactly at end-of-turn (no trailing newline)
    /// still closes the fence.
    #[test]
    fn end_marker_at_end_of_turn_closes_the_fence() {
        let mut m = FenceMachine::new();
        let mut events = m.push("<<<EDIT f:0:0-0:0>>>\nbody\n<<<END>>>");
        events.extend(m.finish());
        assert!(events.iter().any(|e| matches!(e, FenceEvent::EditEnd)));
        assert_eq!(body_of(&events), "body");
    }

    /// File names with colons and dashes still parse (coords bind rightmost).
    #[test]
    fn header_files_with_colons_and_dashes_parse() {
        let input = "<<<EDIT a-b:c.rs:10:2-11:0>>>\nx\n<<<END>>>\n";
        let events = run_chunks(input, input.len());
        match events
            .iter()
            .find(|e| matches!(e, FenceEvent::EditStart { .. }))
        {
            Some(FenceEvent::EditStart { file, start, end }) => {
                assert_eq!(file, "a-b:c.rs");
                assert_eq!((*start, *end), ((10, 2), (11, 0)));
            }
            other => panic!("expected EditStart, got {other:?}"),
        }
    }

    /// Anchor-shift math: spans entirely before an offset shift it by the
    /// span's size delta; spans straddling it clamp to the span's new end;
    /// spans after leave it alone.
    #[test]
    fn shift_offset_handles_before_straddle_and_after() {
        // Insert of 3 bytes at 2, entirely before offset 10.
        let ins = ResolvedSpan {
            at: 2,
            deleted: 0,
            inserted: "abc".into(),
        };
        assert_eq!(shift_offset(10, &ins), 13);
        // Delete of 4 bytes ending exactly at the offset: still "before".
        let del = ResolvedSpan {
            at: 6,
            deleted: 4,
            inserted: String::new(),
        };
        assert_eq!(shift_offset(10, &del), 6);
        // Straddle: delete [8, 14) around offset 10 with 1 byte inserted.
        let straddle = ResolvedSpan {
            at: 8,
            deleted: 6,
            inserted: "Z".into(),
        };
        assert_eq!(shift_offset(10, &straddle), 9);
        // Entirely after: change at the offset itself or beyond.
        let after = ResolvedSpan {
            at: 10,
            deleted: 3,
            inserted: "wxyz".into(),
        };
        assert_eq!(shift_offset(10, &after), 10);
        let insert_at = ResolvedSpan {
            at: 10,
            deleted: 0,
            inserted: "Q".into(),
        };
        // An insert exactly at the offset counts as before (pushes it right).
        assert_eq!(shift_offset(10, &insert_at), 11);
    }

    /// A sequence of spans replays through both region offsets like the
    /// pilot's pump does, keeping start <= anchor.
    #[test]
    fn shift_offset_sequences_track_a_region() {
        let mut start = 20usize;
        let mut anchor = 30usize;
        let spans = [
            // 5 bytes inserted at 0: both shift right.
            ResolvedSpan {
                at: 0,
                deleted: 0,
                inserted: "aaaaa".into(),
            },
            // Delete [40, 45): after both, no change.
            ResolvedSpan {
                at: 40,
                deleted: 5,
                inserted: String::new(),
            },
            // Delete [23, 28): straddles start (clamps it to the span's new
            // end, 23) and sits entirely before anchor (shifts it left 5).
            ResolvedSpan {
                at: 23,
                deleted: 5,
                inserted: String::new(),
            },
        ];
        for span in &spans {
            start = shift_offset(start, span);
            anchor = shift_offset(anchor, span);
        }
        assert_eq!(start, 23);
        assert_eq!(anchor, 30);
        assert!(start <= anchor);
    }

    /// The char-coordinate bridge: fence coords convert to byte offsets via
    /// collab::byte_offset, including multibyte lines.
    #[test]
    fn fence_range_converts_to_byte_offsets() {
        let lines: Vec<String> = ["let s = \"héllo\";", "next"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let (start, end) = range_bytes(&lines, (0, 10), (1, 2));
        // 'é' is 2 bytes: char col 10 sits after the quote + h + é.
        assert_eq!(start, crate::collab::byte_offset(&lines, 0, 10));
        assert_eq!(end, crate::collab::byte_offset(&lines, 1, 2));
        assert!(start < end);
    }

    /// The in-process host: a NOTE fence from the scripted claude surfaces
    /// as a PairEvent::NoteAdded, the snapshot converts its offset back to a
    /// row against the live replica, and the turn's end is observable.
    #[test]
    fn pair_host_emits_note_added_and_snapshots_rows() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let harness = OwnerHarness::start("hello world\nsecond line");
        let script = harness._dir.path().join("fake_claude.py");
        std::fs::write(&script, FAKE_CLAUDE).unwrap();
        let log = harness._dir.path().join("stdin.log");

        let mut cmd = Command::new("python3");
        cmd.arg(&script).arg(&log).arg("notes");
        let mut host =
            crate::pair_host::PairHost::spawn_cmd(&harness.socket, "navigator", None, cmd).unwrap();
        host.send_task("@demo.txt look this over").unwrap();

        // The reader queues NoteAdded (events channel) before TurnEnd (turn
        // channel), but poll() drains events FIRST: the poll that surfaces
        // TurnDone may have drained events before the note was queued, so
        // wait until BOTH landed; the deadline bounds a real regression.
        let deadline = Instant::now() + Duration::from_secs(60);
        let mut events: Vec<crate::pair_host::PairEvent> = Vec::new();
        while !(events
            .iter()
            .any(|e| matches!(e, crate::pair_host::PairEvent::TurnDone { .. }))
            && events
                .iter()
                .any(|e| matches!(e, crate::pair_host::PairEvent::NoteAdded { .. })))
        {
            assert!(
                Instant::now() < deadline,
                "no TurnDone + NoteAdded; saw {events:?}"
            );
            events.extend(host.poll());
            std::thread::sleep(Duration::from_millis(10));
        }
        let note = events
            .iter()
            .find_map(|e| match e {
                crate::pair_host::PairEvent::NoteAdded {
                    file, row, body, ..
                } => Some((file.clone(), *row, body.clone())),
                _ => None,
            })
            .unwrap_or_else(|| panic!("no NoteAdded; saw {events:?}"));
        assert_eq!(note.0, "demo.txt");
        assert_eq!(note.1, 1, "anchored to the fenced row");
        assert!(note.2.contains("second line could be tighter"));
        let expected = vec![(1, 1, "second line could be tighter".to_string())];
        assert_eq!(
            settle(&expected, || host.notes_snapshot("demo.txt")),
            expected,
            "(id, row, body): the first note of the seat gets id 1"
        );
        drop(host); // must not hang: the shutdown grace-kill path
    }

    /// A turn cannot be sent while one is still streaming: the host rejects
    /// the overlapping turn (before begin_turn runs) so the shared
    /// comment-only flag is never clobbered mid-stream. Without the guard, a
    /// yield fired during an ask would flip comment_only and the yield's
    /// edits could reach the buffer.
    #[test]
    fn a_turn_is_rejected_while_another_is_streaming() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let harness = OwnerHarness::start("line zero\nline one");
        let script = harness._dir.path().join("fake_claude.py");
        std::fs::write(&script, FAKE_CLAUDE).unwrap();
        let log = harness._dir.path().join("stdin.log");
        let mut cmd = Command::new("python3");
        cmd.arg(&script).arg(&log).arg("hang"); // reads one turn, never answers
        let host =
            crate::pair_host::PairHost::spawn_cmd(&harness.socket, "nav", None, cmd).unwrap();

        // First turn: an ask (edits allowed). turn_active is set synchronously
        // when the turn is written, so the host is busy immediately.
        host.send_ask_turn("demo.txt", (0, 0), "", "do a thing", "line zero\nline one")
            .unwrap();
        assert!(host.is_busy(), "the ask turn is streaming");

        // A yield fired now must be rejected, and must NOT have flipped the
        // in-flight turn into comment-only (begin_turn never ran).
        let err = host
            .send_yield_turn("demo.txt", "line zero\nline one")
            .unwrap_err();
        assert!(
            err.to_string().contains("mid-turn"),
            "expected a mid-turn rejection, got: {err}"
        );
        assert!(host.is_busy(), "the original ask turn is untouched");
        drop(host);
    }

    /// Comment boxes need stable identity: the host can inject a note
    /// (commentary landing as a box), append the driver's reply to it, and
    /// remove exactly one note by id (the box's Ignore button). Ids are
    /// distinct and survive removal of a sibling.
    #[test]
    fn host_adds_appends_and_removes_notes_by_id() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let harness = OwnerHarness::start("hello world\nsecond line");
        let script = harness._dir.path().join("fake_claude.py");
        std::fs::write(&script, FAKE_CLAUDE).unwrap();
        let log = harness._dir.path().join("stdin.log");
        let mut cmd = Command::new("python3");
        cmd.arg(&script).arg(&log).arg("notes");
        let host =
            crate::pair_host::PairHost::spawn_cmd(&harness.socket, "nav", None, cmd).unwrap();

        let id_a = host
            .add_note("demo.txt", 0, "turn summary")
            .expect("demo.txt is served by the owner");
        let id_b = host.add_note("demo.txt", 1, "second thought").unwrap();
        assert_ne!(id_a, id_b, "every note gets its own id");

        // Each read polls to the resolved value: `notes_snapshot` serves its
        // cache on a contended try_lock, which a loaded runner hits (see
        // `settle`).
        let expected = vec![
            (id_a, 0, "turn summary".to_string()),
            (id_b, 1, "second thought".to_string()),
        ];
        assert_eq!(
            settle(&expected, || host.notes_snapshot("demo.txt")),
            expected
        );

        host.append_to_note(id_a, "you: tell me more");
        let expected = vec![
            (id_a, 0, "turn summary\nyou: tell me more".to_string()),
            (id_b, 1, "second thought".to_string()),
        ];
        assert_eq!(
            settle(&expected, || host.notes_snapshot("demo.txt")),
            expected
        );

        host.remove_note(id_a);
        let expected = vec![(id_b, 1, "second thought".to_string())];
        assert_eq!(
            settle(&expected, || host.notes_snapshot("demo.txt")),
            expected,
            "only the ignored note is gone"
        );
        drop(host);
    }

    /// Boxes persist until the driver ignores them: a new turn on the same
    /// file must NOT wipe its existing notes (the old supersession rule is
    /// gone — under the box model it would close every open conversation on
    /// each ask or reply).
    #[test]
    fn notes_survive_a_new_turn_on_the_same_file() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let harness = OwnerHarness::start("hello world\nsecond line");
        let script = harness._dir.path().join("fake_claude.py");
        std::fs::write(&script, FAKE_CLAUDE).unwrap();
        let log = harness._dir.path().join("stdin.log");
        let mut cmd = Command::new("python3");
        cmd.arg(&script).arg(&log).arg("notes");
        let mut host =
            crate::pair_host::PairHost::spawn_cmd(&harness.socket, "nav", None, cmd).unwrap();
        host.send_task("@demo.txt look this over").unwrap();

        let deadline = Instant::now() + Duration::from_secs(60);
        while !host
            .poll()
            .iter()
            .any(|e| matches!(e, crate::pair_host::PairEvent::TurnDone { .. }))
        {
            assert!(Instant::now() < deadline, "no TurnDone");
            std::thread::sleep(Duration::from_millis(10));
        }
        // The reader applies NoteEnd before it sends the TurnEnd, so note
        // state is final here; the snapshot accessor is not exact under
        // contention (see `settle`), so poll it to the resolved value.
        let deadline = Instant::now() + Duration::from_secs(60);
        let before = loop {
            let snap = host.notes_snapshot("demo.txt");
            if snap.len() == 1 {
                break snap;
            }
            assert!(
                Instant::now() < deadline,
                "the scripted note landed: {snap:?}"
            );
            std::thread::sleep(Duration::from_millis(10));
        };

        // A follow-up turn targeting the same file: begin_turn runs
        // synchronously inside send_yield_turn.
        host.send_yield_turn("demo.txt", "hello world\nsecond line")
            .unwrap();
        assert_eq!(
            settle(&before, || host.notes_snapshot("demo.txt")),
            before,
            "open boxes survive the next turn"
        );
        drop(host);
    }

    /// The reply composer: the driver answered a note's box. The turn names
    /// the note (file, 0-based row, its body), carries the reply, lets the
    /// model edit when the reply asks for a change (#1965), and grounds the
    /// model with the numbered buffer.
    #[test]
    fn compose_reply_turn_carries_note_context_and_buffer() {
        let text = compose_reply_turn(
            "demo.txt",
            3,
            "this loop allocates per iteration",
            "is that actually hot?",
            "a\nb",
        );
        assert!(
            text.contains("replied to your note on demo.txt at line 3 (0-based"),
            "names the note's anchor: {text}"
        );
        assert!(
            text.contains("this loop allocates per iteration"),
            "quotes the note body: {text}"
        );
        assert!(
            text.contains("is that actually hot?"),
            "carries the reply: {text}"
        );
        assert!(
            text.contains("If their reply asks you to make a change, make it with EDIT fences"),
            "a reply asking for the change may edit: {text}"
        );
        assert!(
            !text.contains("COMMENT-ONLY") && !text.contains("will be discarded"),
            "a reply is not a comment-only turn: {text}"
        );
        assert!(
            text.contains("0|a\n1|b"),
            "grounds the model with the numbered buffer: {text}"
        );
    }

    /// Dropping the host (unseat / toggle-off) must not block the UI thread
    /// on the 2s grace-kill: teardown runs on a detached thread. The claude
    /// CLI lingers on stdin EOF, so the synchronous path would freeze the TUI
    /// for the full grace period on every deactivation.
    #[test]
    fn dropping_the_host_does_not_block_the_ui_thread() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let harness = OwnerHarness::start("line zero\nline one");
        let script = harness._dir.path().join("fake_claude.py");
        std::fs::write(&script, FAKE_CLAUDE).unwrap();
        let log = harness._dir.path().join("stdin.log");
        let mut cmd = Command::new("python3");
        cmd.arg(&script).arg(&log).arg("linger"); // streams a turn, then sleeps 60s
        let mut host =
            crate::pair_host::PairHost::spawn_cmd(&harness.socket, "nav", None, cmd).unwrap();
        // Drive one turn so the child reaches its sleep (ignoring stdin EOF).
        host.send_ask_turn("demo.txt", (0, 0), "", "do a thing", "line zero\nline one")
            .unwrap();
        let deadline = Instant::now() + Duration::from_secs(60);
        while !host
            .poll()
            .iter()
            .any(|e| matches!(e, crate::pair_host::PairEvent::TurnDone { .. }))
        {
            assert!(Instant::now() < deadline, "turn never finished");
            std::thread::sleep(Duration::from_millis(10));
        }
        let t = Instant::now();
        drop(host);
        assert!(
            t.elapsed() < Duration::from_secs(1),
            "Drop blocked on the grace-kill for {:?}; teardown must be detached",
            t.elapsed()
        );
    }

    /// claude resolves by bare name when on PATH, but a stripped GUI PATH
    /// falls back to probing install dirs and pinning the absolute path so
    /// the navigator can still seat on Croft.app launches.
    #[test]
    fn claude_resolves_to_an_absolute_path_off_a_stripped_path() {
        // On PATH: spawn by bare name (PATH resolves it).
        assert_eq!(
            resolve_claude_in(true, &[]).as_deref(),
            Some("claude"),
            "an on-PATH claude spawns by bare name"
        );
        // Off PATH, not in any probed dir: fall back to the bare name so the
        // spawn error surfaces (caller uses unwrap_or("claude")).
        let empty = tempfile::tempdir().unwrap();
        assert_eq!(
            resolve_claude_in(false, &[empty.path().to_path_buf()]),
            None
        );
        // Off PATH but present in a probed dir: pin the absolute path.
        let dir = tempfile::tempdir().unwrap();
        let claude = dir.path().join("claude");
        std::fs::write(&claude, "#!/bin/sh\n").unwrap();
        let got = resolve_claude_in(false, &[dir.path().to_path_buf()]).unwrap();
        assert_eq!(got, claude.to_string_lossy());
        assert!(
            Path::new(&got).is_absolute(),
            "GUI launch must get an absolute path, got {got}"
        );
    }

    /// The system prompt must teach the NOTE fence (with a concrete
    /// example), the numbered-buffer convention, and the yield rules the
    /// host enforces.
    #[test]
    fn system_prompt_teaches_note_fence_and_yield_rules() {
        assert!(PAIR_SYSTEM_PROMPT.contains("<<<NOTE <file>:<row>>>>"));
        assert!(PAIR_SYSTEM_PROMPT.contains("<<<NOTE demo.txt:4>>>"));
        assert!(PAIR_SYSTEM_PROMPT.contains("COMMENT-ONLY"));
        assert!(
            PAIR_SYSTEM_PROMPT.contains("- A reply turn answers one of your notes"),
            "the reply turn kind is taught (#1965)"
        );
        assert!(PAIR_SYSTEM_PROMPT.contains("N|"));
        assert!(PAIR_SYSTEM_PROMPT.contains("0-based row"));
    }

    /// #1926: the navigator's claude loads only the user's own settings, so
    /// a workspace's `.claude/settings.json` hooks never run; its built-in
    /// tools are exactly Read, Grep and Glob; and those carry no allow rule,
    /// so `dontAsk` keeps them inside the workspace.
    #[test]
    fn the_navigator_claude_cannot_reach_past_the_workspace() {
        let cfg = PairConfig {
            socket: PathBuf::from("/nonexistent/relay.sock"),
            workspace: std::env::temp_dir(),
            name: String::from("claude"),
            model: None,
            task: None,
            provider: Provider::Claude,
        };
        let cmd = claude_command(&cfg).expect("claude command");
        let args: Vec<String> = cmd
            .get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        let value_of = |flag: &str| {
            let at = args
                .iter()
                .position(|a| a == flag)
                .unwrap_or_else(|| panic!("{flag} missing from {args:?}"));
            args[at + 1].clone()
        };
        assert_eq!(value_of("--setting-sources"), "user");
        assert_eq!(value_of("--tools"), "Read,Grep,Glob");
        assert_eq!(value_of("--permission-mode"), "dontAsk");
        let allowed: Vec<String> = value_of("--allowedTools")
            .split(',')
            .map(|t| t.trim().to_string())
            .collect();
        assert!(
            allowed.iter().all(|t| t.starts_with("mcp__croft-collab__")),
            "a bare built-in allow rule matches every path: {allowed:?}"
        );
        assert!(args.iter().any(|a| a == "--strict-mcp-config"));
    }

    /// The ask-turn composer: instruction, invoked range, selected text,
    /// and the numbered buffer all ride the turn.
    #[test]
    fn compose_ask_turn_numbers_content_and_includes_selection() {
        let text = compose_ask_turn(
            "src/a.rs",
            (3, 5),
            "let x = 1;\nlet y = 2;",
            "simplify these",
            "l0\nl1\nl2\nlet x = 1;\nmid\nlet y = 2;",
        );
        assert!(text.contains("simplify these"));
        assert!(text.contains("lines 3-5"));
        assert!(text.contains("0-based"));
        assert!(text.contains("--- SELECTED LINES ---"));
        assert!(text.contains("let y = 2;"));
        assert!(text.contains("0|l0"));
        assert!(text.contains("3|let x = 1;"));

        // Single line, no selection: the range names one line and the
        // selected block is omitted.
        let one = compose_ask_turn("src/a.rs", (2, 2), "", "why is this here", "a\nb\nc");
        assert!(one.contains("line 2"));
        assert!(!one.contains("--- SELECTED LINES ---"));
        assert!(one.contains("2|c"));
    }

    /// #1966: the gutter numbers lines from 1, so every line a turn names
    /// carries that number beside its 0-based row, and the bare 0-based row
    /// never stands alone where the model would quote it to its partner.
    #[test]
    fn turns_name_the_gutter_line_beside_the_row() {
        let one = compose_ask_turn("src/a.rs", (4, 4), "", "fix this", "a\nb\nc\nd\ne");
        assert!(
            one.contains("at line 4 (0-based; line 5 in your partner's gutter)"),
            "{one}"
        );
        assert!(
            !one.contains("line 4 (0-based)."),
            "bare 0-based row: {one}"
        );

        let range = compose_ask_turn("src/a.rs", (0, 2), "a\nb\nc", "tidy", "a\nb\nc");
        assert!(
            range.contains("at lines 0-2 (0-based; lines 1-3 in your partner's gutter)"),
            "{range}"
        );
        assert!(
            !range.contains("lines 0-2 (0-based)."),
            "bare 0-based rows: {range}"
        );

        let reply = compose_reply_turn("main.py", 4, "a note", "correct this", "a\nb\nc\nd\ne");
        assert!(
            reply.contains("at line 4 (0-based; line 5 in your partner's gutter)"),
            "{reply}"
        );
        assert!(
            !reply.contains("line 4 (0-based)."),
            "bare 0-based row: {reply}"
        );
        assert!(
            reply.contains("a NOTE re-anchored to row 4 continues this box"),
            "the re-anchor target is a row: {reply}"
        );
        assert!(
            !reply.contains("re-anchoring to line 4"),
            "the re-anchor row called a line: {reply}"
        );

        // The prose rule the model follows when it writes a line number.
        assert!(
            PAIR_SYSTEM_PROMPT.contains("row N is line N+1"),
            "the system prompt teaches gutter numbers for prose"
        );
    }

    /// #1966: every numbered "line" the prompt shows is a gutter line. Fence
    /// coordinates are rows, so an example such as "pins a remark to line 4"
    /// for `<<<NOTE demo.txt:4>>>` cannot teach the model to quote the
    /// 0-based row to its partner. The local prompt carries the shared one.
    #[test]
    fn system_prompt_numbers_lines_only_by_the_gutter() {
        let prompt = system_prompt(&Provider::Local {
            base_url: String::new(),
        });
        for text in prompt.lines() {
            for (at, _) in text.match_indices("line") {
                let after = &text[at + "line".len()..];
                let after = after.strip_prefix('s').unwrap_or(after);
                let numbered = after
                    .strip_prefix(' ')
                    .is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit()));
                if numbered {
                    assert!(
                        text[..at].ends_with("gutter "),
                        "a 0-based row called a line: {text}"
                    );
                }
            }
        }
        // The examples still pair each row with its gutter line.
        assert!(prompt.contains("row 0 of demo.txt, your partner's gutter line 1"));
        assert!(prompt.contains("rows 3-4 of src/lib.rs, gutter lines 4-5"));
        assert!(prompt.contains("row 4 of demo.txt, gutter line 5"));
        assert!(prompt.contains("row 1 (gutter line 2)"));
    }

    /// The yield-turn composer: comment-only rule, the diff since the
    /// navigator last saw the file, and the numbered buffer.
    #[test]
    fn compose_yield_turn_carries_diff_and_forbids_edits() {
        let with_diff = compose_yield_turn(
            "src/a.rs",
            "line one\nline 2\n",
            Some("@@ -1,2 +1,2 @@\n line one\n-line two\n+line 2\n"),
        );
        assert!(with_diff.contains("COMMENT-ONLY"));
        assert!(with_diff.contains("--- CHANGES SINCE YOUR LAST LOOK ---"));
        assert!(with_diff.contains("+line 2"));
        assert!(with_diff.contains("0|line one"));

        let first_look = compose_yield_turn("src/a.rs", "just this\n", None);
        assert!(first_look.contains("COMMENT-ONLY"));
        assert!(!first_look.contains("--- CHANGES SINCE YOUR LAST LOOK ---"));
    }

    /// Host-enforced comment-only: the scripted claude streams an EDIT fence
    /// during a yielded turn; the owner's buffer must stay byte-identical
    /// and the suppression must be spoken.
    #[test]
    fn yield_turn_suppresses_edits() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let harness = OwnerHarness::start("hello world");
        let script = harness._dir.path().join("fake_claude.py");
        std::fs::write(&script, FAKE_CLAUDE).unwrap();
        let log = harness._dir.path().join("stdin.log");

        let mut cmd = Command::new("python3");
        cmd.arg(&script).arg(&log).arg("stream"); // streams an EDIT fence
        let mut host =
            crate::pair_host::PairHost::spawn_cmd(&harness.socket, "navigator", None, cmd).unwrap();
        host.send_yield_turn("demo.txt", "hello world").unwrap();

        let deadline = Instant::now() + Duration::from_secs(60);
        let mut events: Vec<crate::pair_host::PairEvent> = Vec::new();
        while !events
            .iter()
            .any(|e| matches!(e, crate::pair_host::PairEvent::TurnDone { .. }))
        {
            assert!(Instant::now() < deadline, "no TurnDone; saw {events:?}");
            events.extend(host.poll());
            std::thread::sleep(Duration::from_millis(10));
        }
        // The owner never saw an edit land.
        assert_eq!(harness.remote_edit_count(), 0, "edit must be suppressed");
        // Diagnostics NEVER ride Commentary: the App anchors that channel
        // as the navigator's own comment boxes, so the suppression notice
        // (and claude's stderr chatter) would be rendered as the model's
        // remark in the user's file and counted as a comment.
        assert!(
            !events.iter().any(|e| matches!(
                e,
                crate::pair_host::PairEvent::Commentary(c)
                    if c.contains("suppressed") || c.contains("[claude]")
            )),
            "diagnostics must not become comment boxes; saw {events:?}"
        );
        // Whole-snapshot search, no baseline index: OUTPUT is a shared
        // evicting ring, so a length captured earlier can drift under
        // concurrent tests and a skip() would step over the lines.
        let wait_output = |needle: &str| {
            let deadline = Instant::now() + Duration::from_secs(5);
            loop {
                let lines = crate::output::snapshot("Navigator").unwrap_or_default();
                if lines.iter().any(|l| l.text.contains(needle)) {
                    return;
                }
                assert!(
                    Instant::now() < deadline,
                    "OUTPUT never carried {needle:?}: {lines:?}"
                );
                std::thread::sleep(Duration::from_millis(10));
            }
        };
        wait_output("suppressed");
        wait_output("[claude] mcp server starting");
        drop(host);
    }

    /// Poll `host` until a turn ends, returning every event seen on the way.
    fn wait_turn_done(host: &mut crate::pair_host::PairHost) -> Vec<crate::pair_host::PairEvent> {
        let deadline = Instant::now() + Duration::from_secs(60);
        let mut events = Vec::new();
        while !events
            .iter()
            .any(|e| matches!(e, crate::pair_host::PairEvent::TurnDone { .. }))
        {
            assert!(Instant::now() < deadline, "no TurnDone; saw {events:?}");
            events.extend(host.poll());
            std::thread::sleep(Duration::from_millis(10));
        }
        events
    }

    /// #1965: a reply in a comment box is the driver's own words, so it is
    /// an invited turn like an ask. "correct this" under a note proposing a
    /// fix must be able to land that fix in the buffer.
    #[test]
    fn a_reply_turn_can_edit_the_buffer() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let harness = OwnerHarness::start("hello world");
        let script = harness._dir.path().join("fake_claude.py");
        std::fs::write(&script, FAKE_CLAUDE).unwrap();
        let log = harness._dir.path().join("stdin.log");

        let mut cmd = Command::new("python3");
        cmd.arg(&script).arg(&log).arg("stream"); // streams an EDIT fence
        let mut host =
            crate::pair_host::PairHost::spawn_cmd(&harness.socket, "navigator", None, cmd).unwrap();
        host.send_reply_turn("demo.txt", 0, "rename world", "correct this", "hello world")
            .unwrap();
        wait_turn_done(&mut host);
        harness.wait_until("the reply's edit on the owner", |h| {
            h.doc().as_deref() == Some("hello streamed edit")
        });
        drop(host);
    }

    /// #1965, the gate that must survive it: an edit-capable reply must not
    /// leave the next yielded turn able to edit. One seated model edits on
    /// every turn: reply 1 lands, yield 2 is discarded, reply 3 lands.
    #[test]
    fn a_yield_after_a_reply_still_discards_edits() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let harness = OwnerHarness::start("hello world");
        let script = harness._dir.path().join("fake_claude.py");
        std::fs::write(&script, FAKE_CLAUDE).unwrap();
        let log = harness._dir.path().join("stdin.log");

        let mut cmd = Command::new("python3");
        cmd.arg(&script).arg(&log).arg("repeat"); // inserts the turn number
        let mut host =
            crate::pair_host::PairHost::spawn_cmd(&harness.socket, "navigator", None, cmd).unwrap();
        host.send_reply_turn("demo.txt", 0, "a note", "correct this", "hello world")
            .unwrap();
        wait_turn_done(&mut host);
        harness.wait_until("reply 1's edit on the owner", |h| {
            h.doc().as_deref() == Some("1hello world")
        });

        host.send_yield_turn("demo.txt", "1hello world").unwrap();
        wait_turn_done(&mut host);
        // Presence: the yield reached the model, which streamed edit 2.
        let seen = std::fs::read_to_string(&log).unwrap();
        assert!(
            seen.contains("yielded the turn"),
            "the yield turn never reached the model: {seen}"
        );

        // Barrier: one pilot's edits reach the owner in order, so once
        // edit 3 has landed, a leaked edit 2 would already be in the doc.
        host.send_reply_turn("demo.txt", 0, "a note", "and again", "1hello world")
            .unwrap();
        wait_turn_done(&mut host);
        harness.wait_until("reply 3's edit on the owner", |h| {
            h.doc().is_some_and(|d| d.starts_with('3'))
        });
        assert_eq!(
            harness.doc().as_deref(),
            Some("31hello world"),
            "the yield's edit must be suppressed"
        );
        drop(host);
    }

    /// Remote-edit spans shift every note anchored in the edited file, and
    /// only that file (the same replay the stream region does).
    #[test]
    fn note_offsets_shift_on_remote_edit() {
        let mut notes = vec![
            Note {
                id: 1,
                file: "a.rs".into(),
                offset: 10,
                body: "n1".into(),
            },
            Note {
                id: 2,
                file: "b.rs".into(),
                offset: 10,
                body: "n2".into(),
            },
        ];
        let spans = [
            // 3 bytes inserted at 0: before the offset, shifts it right.
            ResolvedSpan {
                at: 0,
                deleted: 0,
                inserted: "abc".into(),
            },
            // Delete far after: no effect.
            ResolvedSpan {
                at: 40,
                deleted: 2,
                inserted: String::new(),
            },
        ];
        shift_notes(&mut notes, "a.rs", &spans);
        assert_eq!(notes[0].offset, 13);
        assert_eq!(notes[1].offset, 10, "other file's note must not move");
    }

    /// Aborting a streamed edit must also un-shift the notes that edit
    /// moved: open_region shifts notes for its delete and every EditBody
    /// shifts them for its insert, so the revert has to apply the inverse
    /// span. Without it, every cancel or abort left the turn's notes
    /// permanently drifted from the rows the model anchored them to.
    #[test]
    fn an_aborted_edit_un_shifts_the_notes_it_moved() {
        let harness = OwnerHarness::start("hello world");
        let (state, stop, pump) = pumped_state(&harness);
        {
            let mut st = state.lock().unwrap();
            st.begin_turn("demo.txt", "hello world", false);
            // Anchors below, AT, and INSIDE the edited span [0, 5): the
            // below one is shifted and must shift back; the at/inside ones
            // are collapsed by the delete and ride the streamed inserts,
            // so only their recorded pre-edit offsets can restore them.
            for offset in [8usize, 0, 2] {
                let id = st.take_note_id();
                st.notes.push(Note {
                    id,
                    file: String::from("demo.txt"),
                    offset,
                    body: String::from("remark"),
                });
            }
        }
        apply_fence_event(
            &state,
            FenceEvent::EditStart {
                file: String::from("demo.txt"),
                start: (0, 0),
                end: (0, 5),
            },
        );
        apply_fence_event(
            &state,
            FenceEvent::EditBody(String::from("hi there friend")),
        );
        apply_fence_event(&state, FenceEvent::EditAbort);
        let offsets: Vec<usize> = state
            .lock()
            .unwrap()
            .notes
            .iter()
            .map(|n| n.offset)
            .collect();
        assert_eq!(
            offsets,
            vec![8, 0, 2],
            "the revert must restore every note anchor the edit had moved"
        );
        stop.store(true, Ordering::Relaxed);
        pump.join().unwrap();
    }

    /// A note row just past EOF clamps to the last line instead of panicking
    /// or anchoring nowhere.
    #[test]
    fn note_anchor_row_clamps_past_eof() {
        let lines: Vec<String> = ["ab", "cd"].iter().map(|s| s.to_string()).collect();
        assert_eq!(note_offset(&lines, 0), 0);
        assert_eq!(note_offset(&lines, 1), 3);
        assert_eq!(note_offset(&lines, 99), 3);
    }

    /// Every composed turn names its target file, even when the buffer never
    /// went live (field bug 2026-07-15: parse_task_line had stripped the
    /// @file prefix, so a dead bootstrap left claude with no file at all).
    #[test]
    fn compose_turn_always_names_target_file() {
        let live = compose_turn_text("fix the error", Some("src/a.rs"), Some("body"));
        assert!(live.contains("--- CURRENT BUFFER (src/a.rs) ---"));
        assert!(live.contains("body"));

        let dead = compose_turn_text("fix the error", Some("src/a.rs"), None);
        assert!(
            dead.contains("src/a.rs"),
            "file must be named without a live buffer: {dead}"
        );
        assert!(dead.contains("fix the error"));

        let noted = with_pending_note(Some("stream was cancelled".into()), "task".into());
        assert!(noted.starts_with("stream was cancelled"));
        assert!(noted.contains("task"));
    }
}