car-server-core 0.55.0

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

use std::path::{Path, PathBuf};
use std::sync::Arc;

use super::contract::OutcomeContract;
use super::session::IntegratedSubtask;

/// One-line summary of an intent, for a commit subject or a pull-request title.
/// Capped at 72 characters on a char boundary — the git convention, and long
/// enough that the truncation is rare.
fn subject_from_intent(intent: &str) -> String {
    // Line endings normalized FIRST, and that ordering is the whole point. The
    // paragraph split below looks for `\n\n`, which a Windows-authored or
    // Windows-pasted intent never contains — it separates paragraphs with
    // `\r\n\r\n`. The split then matched nothing, `head` became the entire
    // document, and the `replace('\n', " ")` that follows left every `\r` in
    // place: the blank-line handling this function was given was silently off
    // for exactly the callers most likely to paste a long intent, and the
    // resulting commit subject and pull-request title carried embedded carriage
    // returns. `--intent-file` reads bytes, so this is not an exotic path.
    let trimmed = intent.replace("\r\n", "\n");
    let trimmed = trimmed.trim();
    // A blank line is git's own subject/body separator, and a caller that puts
    // one there is saying where the summary ends. Honour it BEFORE flattening:
    // `replace('\n', " ")` first destroyed the break, so a caller who correctly
    // led with a short summary still got the pointer text dragged in behind it
    // and truncated at 72 — the paragraph structure was gone before the length
    // check could act on it. With no blank line, the flatten-and-truncate
    // fallback below behaves exactly as it always has.
    let head = trimmed.split("\n\n").next().unwrap_or(trimmed).trim();
    // A lone `\r` (an old-Mac line ending, or one left by a mixed-ending file)
    // is not a line break to git — it is a control character inside the
    // subject.
    let s = head.replace(['\n', '\r'], " ");
    if s.len() > 72 {
        let mut end = 69;
        while !s.is_char_boundary(end) {
            end -= 1;
        }
        format!("{}...", &s[..end])
    } else {
        s
    }
}

/// What [`commit_worktree`] did, as a value rather than as a phrase inside an
/// error string.
///
/// "The worktree was clean" is a normal outcome on the PR path — a round whose
/// push failed re-delivers the commit it already made — so `deliver_pr_with` has
/// to tell it apart from a commit that genuinely failed. It used to do that with
/// `Err(e) if e.contains("no changes to deliver")`, and that phrase is not the
/// exclusive property of the clean-worktree check: [`git`] formats every failure
/// as `git {args:?} failed: {stderr}`, and the commit argv carries `subject` and
/// `body`, both derived from the caller's `intent`. An intent that merely
/// MENTIONS the phrase — "fix delivery so it reports 'no changes to deliver'
/// correctly" is ordinary work in this repo — turned a real commit failure
/// (`commit.gpgsign` with no agent, a shared `pre-commit` hook) into the
/// re-delivery branch: the previous commit was pushed, the pull-request body was
/// refreshed, and delivery returned `Ok` while the round's actual work sat
/// uncommitted in the worktree. A typed variant cannot be spelled by a caller.
enum CommitOutcome {
    /// A commit was made; the new SHA.
    Made(String),
    /// The worktree had nothing to commit. Not an error here — the callers
    /// decide what it means.
    NothingToCommit,
}

/// The placement ledger as a commit-message TRAILER block, or `None` when this
/// commit has no fleet-authored work in it.
///
/// The delivered commit's body opens "Authored by CAR Coder." A distributed run
/// makes that sentence wrong in a way nothing else corrects: the work was
/// authored across several machines, and the reader deciding on a
/// `car/coder/<id>` branch has no other artifact to ask. car#1263 settled the
/// shape of this argument one level up — a verdict's caveats have to reach the
/// thing the verdict is read on, not only a status call.
///
/// **`integrated`, not the ledger.** A [`car_multi::Placement`] is recorded when
/// a worker RETURNS, before the per-patch gate rules on what it produced. So a
/// full ledger is compatible with zero fleet-authored hunks — `NothingAccepted`
/// and `IntegrationRejected` both fall back to a locally-authored diff — and
/// rendering it would credit peers for a commit they contributed nothing to.
/// That false attribution is worse than the missing one this closes. `integrated`
/// is built where patches are applied, so it can only name work that landed.
///
/// Trailers, not prose. `git interpret-trailers` and `%(trailers:key=…)` can
/// read them, they survive a squash by concatenating, and they do not interleave
/// with the rendered contract. NOT `Co-authored-by:` — GitHub resolves those to
/// user accounts, and a machine is not a person.
///
/// **Nothing peer-supplied is interpolated raw.** A worker id and a subtask id
/// are sanitized (control characters stripped, length capped); the failure
/// strings on the ledger are deliberately NOT here at all. They carry a peer's
/// verbatim response body and git stderr — unbounded, multi-line, and appended
/// to the last paragraph of a `git commit -m`, which is a trailer-forgery seam,
/// a NUL byte that makes a green run undeliverable, and an `E2BIG`. They are
/// diagnostics with a lifetime, not a durable claim about authorship, so they
/// stay on the session record and the event.
pub fn placement_provenance(
    placements: &[car_multi::Placement],
    integrated: &[IntegratedSubtask],
    repaired_locally: bool,
) -> Option<String> {
    if integrated.is_empty() {
        return None;
    }
    let worker_of = |subtask_id: &str| -> Option<&car_multi::Placement> {
        placements.iter().find(|p| p.subtask_id == subtask_id)
    };
    let mut lines: Vec<String> = Vec::new();
    let mut any_remote = false;
    for landed in integrated {
        let Some(p) = worker_of(&landed.subtask_id) else {
            continue;
        };
        // No worker, no location: `remote` is meaningless when nothing ran, and
        // such a subtask cannot be in `integrated` anyway.
        let Some(worker) = p.worker_id.as_deref() else {
            continue;
        };
        any_remote |= p.remote;
        let mut line = format!(
            "CAR-Placement: subtask={} worker={} remote={}",
            trailer_value(&landed.subtask_id),
            trailer_value(worker),
            p.remote
        );
        if !landed.files.is_empty() {
            line.push_str(&format!(
                " files={}",
                landed
                    .files
                    .iter()
                    .map(|f| trailer_value(f))
                    .collect::<Vec<_>>()
                    .join(",")
            ));
        }
        lines.push(line);
    }
    if lines.is_empty() {
        return None;
    }
    // A pool always seeds the local worker, so a run whose every peer was
    // excluded still produces placements — all of them local. Saying "across the
    // fleet" there would be the same overclaim in a quieter form.
    if !any_remote && !repaired_locally {
        return None;
    }
    if repaired_locally {
        lines.push(
            "CAR-Placement: repaired-locally=true (the union failed the contract              and was repaired here, so not every delivered hunk is listed above)"
                .to_string(),
        );
    }
    Some(lines.join("\n"))
}

/// One trailer value: no newlines, no control characters, bounded.
///
/// Everything here reaches a `git commit -m` argument. A newline could forge a
/// paragraph or a `Signed-off-by:` in the delivered message, a NUL makes the
/// spawn itself fail, and an unbounded value reaches `E2BIG` — turning a green,
/// gate-passed run into an undeliverable one with no recovery but a hand commit.
fn trailer_value(raw: &str) -> String {
    const MAX: usize = 120;
    let cleaned: String = raw
        .chars()
        .map(|c| if c.is_control() { ' ' } else { c })
        .collect();
    let cleaned = cleaned.split_whitespace().collect::<Vec<_>>().join(" ");
    if cleaned.chars().count() > MAX {
        cleaned.chars().take(MAX).collect::<String>() + ""
    } else {
        cleaned
    }
}

/// Stage all worktree changes and create the CAR-Coder commit. Reports a clean
/// worktree as [`CommitOutcome::NothingToCommit`]; `Err` is reserved for a real
/// failure. Shared by all three delivery paths.
fn commit_worktree(
    worktree: &Path,
    intent: &str,
    contract: &OutcomeContract,
    // Where a distributed run's subtasks ran. `None` for every local delivery,
    // which is every delivery that is not `car code --distributed`.
    provenance: Option<&str>,
) -> Result<CommitOutcome, String> {
    // `--untracked-files=normal`, pinned rather than inherited: `status
    // --porcelain` honours `status.showUntrackedFiles`, and a repository or
    // global `no` makes a worktree holding nothing BUT new files report clean.
    // Delivery would then take the re-delivery branch and push a stale commit
    // while the round's entire output — every new file it wrote — stayed
    // behind.
    let status = git(
        worktree,
        &["status", "--porcelain", "--untracked-files=normal"],
    )?;
    if status.trim().is_empty() {
        return Ok(CommitOutcome::NothingToCommit);
    }
    git(worktree, &["add", "-A"])?;

    let subject = subject_from_intent(intent);
    let body = checkpoint_body(intent, contract, provenance);
    git(
        worktree,
        &[
            "-c",
            "user.name=car-coder",
            "-c",
            "user.email=coder@parslee.ai",
            "commit",
            "-m",
            &subject,
            "-m",
            &body,
        ],
    )?;
    Ok(CommitOutcome::Made(
        git(worktree, &["rev-parse", "HEAD"])?.trim().to_string(),
    ))
}

fn checkpoint_body(intent: &str, contract: &OutcomeContract, provenance: Option<&str>) -> String {
    let mut body = format!(
        "Authored by CAR Coder.\n\nIntent:\n{}\n\nOutcome contract (all checks passed):\n{}",
        intent.trim(),
        contract.render()
    );
    if let Some(provenance) = provenance {
        body.push_str("\n\n");
        body.push_str(provenance);
    }
    body
}

/// The interactive paths' reading of a clean worktree: nothing to publish, and
/// that is an error. Only the PR path has a second, legitimate meaning for it.
fn require_commit(outcome: CommitOutcome) -> Result<String, String> {
    match outcome {
        CommitOutcome::Made(sha) => Ok(sha),
        CommitOutcome::NothingToCommit => {
            Err("no changes to deliver — the worktree is clean".to_string())
        }
    }
}

/// The commit a HEADLESS round delivers when its worktree is already clean.
///
/// A clean worktree is not automatically an error on the headless paths, unlike
/// the interactive ones. The contract keeps a workspace alive across rounds
/// precisely so that a green session whose DELIVERY failed can re-deliver
/// without redoing the work: on that second round the commit already exists and
/// the worktree is clean. Deliver HEAD.
///
/// But "clean" has a second cause that must not be confused with it: a first
/// round where the contract was green with an EMPTY diff (the named check
/// already passed). There HEAD is still the base tip, and delivering it creates
/// a branch and a pull request that prove nothing — over the pull-request path,
/// `gh pr create` then fails with "No commits between …", reported as retriable
/// and requeued forever with junk branches accumulating. Only a genuine
/// re-delivery has something to deliver, and that means HEAD is already AHEAD of
/// the base.
///
/// The base is resolved remote-first with the local branch as an honest stand-in
/// — and the failure to resolve EITHER is an error rather than a `false`.
/// Reading `is_ok()` on an unresolvable ref collapses "not an ancestor" and
/// "could not check" into the same answer, i.e. "there is work to deliver": that
/// fails OPEN, restoring the empty-delivery bug this guard exists to close,
/// exactly when the network is down and the best-effort fetch did nothing.
fn head_beyond_base(worktree: &Path, base_branch: &str) -> Result<String, String> {
    let head = git(worktree, &["rev-parse", "HEAD"])?.trim().to_string();
    let base_ref = ["origin/", ""]
        .iter()
        .map(|p| format!("{p}{base_branch}"))
        .find(|r| git(worktree, &["rev-parse", "--verify", "--quiet", r]).is_ok())
        .ok_or_else(|| {
            format!(
                "the worktree is clean and neither origin/{base_branch} nor {base_branch} \
                 resolves, so whether there is anything to deliver cannot be determined"
            )
        })?;
    if git(worktree, &["merge-base", "--is-ancestor", &head, &base_ref]).is_ok() {
        return Err(format!(
            "nothing to deliver: the worktree is clean and its HEAD ({head}) is already \
             contained in {base_ref}, so there is no work to deliver"
        ));
    }
    Ok(head)
}

/// The checkout a task was opened against. A branch switch is significant even
/// if both branches currently point at the same commit.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct CheckoutIdentity {
    pub head: String,
    pub reference: String,
}

impl CheckoutIdentity {
    pub fn read(repo: &Path) -> Result<Self, String> {
        Ok(Self {
            head: git(repo, &["rev-parse", "HEAD"])?.trim().into(),
            reference: git(repo, &["rev-parse", "--symbolic-full-name", "HEAD"])?
                .trim()
                .into(),
        })
    }
}

/// The staged contents presented at review, tied to their original HEAD.
/// This receipt survives restart; it is not permission to deliver or a claim
/// that verification has been rerun.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ReviewIdentity {
    pub head: String,
    pub tree: String,
}

impl ReviewIdentity {
    pub fn read(worktree: &Path) -> Result<Self, String> {
        if !git(worktree, &["diff", "--name-only", "-z", "--"])?.is_empty()
            || !git(
                worktree,
                &["ls-files", "--others", "--exclude-standard", "-z"],
            )?
            .is_empty()
        {
            return Err("Task files changed after the review diff was staged. Review and verify the updated work before delivery.".into());
        }
        Ok(Self {
            head: git(worktree, &["rev-parse", "HEAD"])?.trim().into(),
            tree: git(worktree, &["write-tree"])?.trim().into(),
        })
    }

    pub fn validate(&self, worktree: &Path) -> Result<(), String> {
        if &Self::read(worktree)? != self {
            return Err("Task revision or staged files changed after review. Review and verify the updated work before delivery.".into());
        }
        Ok(())
    }
}

/// Freeze current non-ignored checkout contents without touching its index or
/// branch. Task diffs use this private commit as their baseline, so preexisting
/// edits are inputs, not changes attributed to the agent.
pub(super) fn snapshot_checkout(repo: &Path, session_id: &str) -> Result<Option<String>, String> {
    if session_id.is_empty()
        || !session_id
            .bytes()
            .all(|c| c.is_ascii_alphanumeric() || c == b'-')
    {
        return Err("invalid checkout snapshot session id".into());
    }
    if !git(repo, &["ls-files", "--unmerged"])?.is_empty() {
        return Err("Resolve the checkout's merge conflicts before starting a coding task.".into());
    }
    let identity = CheckoutIdentity::read(repo)?;
    let directory = tempfile::tempdir().map_err(|e| e.to_string())?;
    let index = directory.path().join("index");
    let isolated = |args: &[&str]| -> Result<String, String> {
        git_bytes_with_index(repo, args, Some(&index))
            .map(|bytes| String::from_utf8_lossy(&bytes).trim().to_string())
    };
    isolated(&["read-tree", &identity.head])?;
    isolated(&["add", "-A", "--", "."])?;
    let tree = isolated(&["write-tree"])?;
    if CheckoutIdentity::read(repo)? != identity {
        return Err("Checkout revision changed while capturing task inputs; start again.".into());
    }
    if tree == git(repo, &["rev-parse", "HEAD^{tree}"])?.trim() {
        return Ok(None);
    }
    let commit = git(
        repo,
        &[
            "-c",
            "user.name=car-coder",
            "-c",
            "user.email=coder@parslee.ai",
            "commit-tree",
            &tree,
            "-p",
            &identity.head,
            "-m",
            "CAR Coder: preserve checkout inputs before task",
        ],
    )?
    .trim()
    .to_string();
    git(
        repo,
        &[
            "update-ref",
            &format!("refs/car/coder-inputs/{session_id}"),
            &commit,
        ],
    )?;
    Ok(Some(commit))
}

/// Apply the reviewed patch without moving the checkout's HEAD or index. The
/// private checkpoint is a durable follow-up base, not a published branch.
/// A failed apply leaves the source worktree unchanged and available to retry.
pub(super) fn apply_to_checkout(
    repo: &Path,
    worktree: &Path,
    session_id: &str,
    expected: &CheckoutIdentity,
    intent: &str,
    contract: &OutcomeContract,
    provenance: Option<&str>,
) -> Result<(String, bool), String> {
    if session_id.is_empty()
        || !session_id
            .bytes()
            .all(|c| c.is_ascii_alphanumeric() || c == b'-')
    {
        return Err("invalid checkout delivery session id".into());
    }
    if &CheckoutIdentity::read(repo)? != expected {
        return Err("checkout revision or branch changed since this task started; work remains in its worktree. Review the new checkout before applying".into());
    }
    git(worktree, &["add", "-AN"])?;
    let patch = git_bytes(
        worktree,
        &[
            "-c",
            "core.quotePath=true",
            "-c",
            "core.autocrlf=false",
            "diff",
            "HEAD",
            "--binary",
            "--no-ext-diff",
            "--no-textconv",
        ],
    )?;
    if patch.is_empty() {
        return Err("no changes to apply".into());
    }
    let patch_file = tempfile::NamedTempFile::new().map_err(|e| e.to_string())?;
    std::fs::write(patch_file.path(), &patch).map_err(|e| e.to_string())?;
    let patch_path = patch_file
        .path()
        .to_str()
        .ok_or("non-UTF8 temporary patch path")?;
    let already_applied = if git(
        repo,
        &["apply", "--check", "--whitespace=nowarn", patch_path],
    )
    .is_ok()
    {
        false
    } else if git(
        repo,
        &[
            "apply",
            "--reverse",
            "--check",
            "--whitespace=nowarn",
            patch_path,
        ],
    )
    .is_ok()
    {
        true
    } else {
        return Err("reviewed changes conflict with the current checkout; no changes applied. Existing edits and the result worktree are preserved".into());
    };
    // Build a commit object without advancing the worktree HEAD. If apply fails
    // or the daemon stops before recording delivery, the same patch is still
    // available for a safe retry; a reverse check recognizes an applied patch.
    git(worktree, &["add", "-A"])?;
    let tree = git(worktree, &["write-tree"])?;
    let parent = git(worktree, &["rev-parse", "HEAD"])?;
    let commit = git(
        worktree,
        &[
            "-c",
            "user.name=car-coder",
            "-c",
            "user.email=coder@parslee.ai",
            "commit-tree",
            tree.trim(),
            "-p",
            parent.trim(),
            "-m",
            &subject_from_intent(intent),
            "-m",
            &checkpoint_body(intent, contract, provenance),
        ],
    )?
    .trim()
    .to_string();
    let checkpoint = format!("refs/car/coder/{session_id}");
    git(repo, &["update-ref", &checkpoint, &commit])?;
    // Re-check immediately before the write, after preparing the checkpoint.
    if &CheckoutIdentity::read(repo)? != expected {
        return Err(
            "checkout changed during delivery preparation; changes remain in the worktree".into(),
        );
    }
    if !already_applied {
        git(repo, &["apply", "--whitespace=nowarn", patch_path]).map_err(|e| {
            format!("checkout apply failed; retain the result worktree for recovery: {e}")
        })?;
    }
    Ok((commit, already_applied))
}

/// Result of a publish: the branch name to merge from.
pub fn publish_branch(
    repo: &Path,
    worktree: &Path,
    short_id: &str,
    intent: &str,
    contract: &OutcomeContract,
    provenance: Option<&str>,
) -> Result<String, String> {
    publish_branch_with_commit(repo, worktree, short_id, intent, contract, provenance)
        .map(|(branch, _)| branch)
}

/// Preserve the delivered commit independently of later branch movement.
pub(super) fn publish_branch_with_commit(
    repo: &Path,
    worktree: &Path,
    short_id: &str,
    intent: &str,
    contract: &OutcomeContract,
    provenance: Option<&str>,
) -> Result<(String, String), String> {
    let commit = require_commit(commit_worktree(worktree, intent, contract, provenance)?)?;
    let branch = format!("car/coder/{short_id}");
    // `git branch` (no checkout) in the original repo: refs are shared with
    // the worktree, so this is pure bookkeeping — no working-tree effects.
    git(repo, &["branch", &branch, &commit])?;
    Ok((branch, commit))
}

/// Paths a diff touches, `--no-renames` so both halves of a rename are listed.
fn changed_paths(repo: &Path, from: &str, to: &str) -> Result<Vec<String>, String> {
    let raw = git(
        repo,
        &[
            "-c",
            "core.quotePath=false",
            "diff",
            "--name-only",
            "--no-renames",
            "-z",
            from,
            to,
        ],
    )?;
    Ok(raw
        .split('\0')
        .filter(|path| !path.is_empty())
        .map(str::to_string)
        .collect())
}

/// Publish a branch for a task that started from a dirty checkout.
///
/// The worktree was provisioned at the private inputs snapshot, whose tree
/// holds the user's uncommitted (and untracked) files — including an un-ignored
/// `.env`. Committing on top of that snapshot would publish the user's
/// work-in-progress on `car/coder/<id>` alongside the reviewed diff, which is
/// neither what was reviewed nor the user's to publish.
///
/// So the delivered commit is rebuilt in a temporary index: the checkout's
/// `HEAD` (the snapshot's parent) plus the agent's diff, parented on that same
/// `HEAD`. That is only faithful when the two changesets are disjoint — if the
/// agent edited a file the user had also edited, the reviewed result cannot be
/// separated from the user's work, and delivery is REFUSED naming those paths
/// rather than guessing.
pub(super) fn publish_branch_off_snapshot(
    repo: &Path,
    worktree: &Path,
    short_id: &str,
    intent: &str,
    contract: &OutcomeContract,
    provenance: Option<&str>,
    snapshot: &str,
) -> Result<(String, String), String> {
    let checkout_head = git(repo, &["rev-parse", &format!("{snapshot}^")])
        .map_err(|e| format!("the task's private input snapshot has no parent commit: {e}"))?
        .trim()
        .to_string();
    let user_paths = changed_paths(repo, &checkout_head, snapshot)?;
    // Everything this task touched: its own commits in the worktree (a
    // continuation has some) plus what is still uncommitted there. Read-only —
    // the overlap refusal below must not disturb the reviewed worktree, which
    // stays deliverable to the checkout.
    let mut agent_paths = changed_paths(worktree, snapshot, "HEAD")?;
    agent_paths.extend(worktree_changed_paths(worktree)?);
    let mut overlap: Vec<&String> = agent_paths
        .iter()
        .filter(|path| user_paths.contains(path))
        .collect();
    overlap.sort();
    overlap.dedup();
    if !overlap.is_empty() {
        let named: Vec<&str> = overlap.iter().take(5).map(|p| p.as_str()).collect();
        return Err(format!(
            "your checkout has uncommitted changes to {} and this task changed the same \
             file(s), so a branch cannot be published without carrying your work into it. \
             Apply the result to your checkout instead, or commit/stash those changes and \
             run the task again — the result is preserved in its worktree either way",
            named.join(", ")
        ));
    }
    let commit = require_commit(commit_worktree(worktree, intent, contract, provenance)?)?;
    let patch = git_bytes(
        repo,
        &[
            "-c",
            "core.quotePath=true",
            "-c",
            "core.autocrlf=false",
            "diff",
            "--binary",
            "--no-renames",
            "--no-ext-diff",
            "--no-textconv",
            snapshot,
            &commit,
        ],
    )?;
    if patch.is_empty() {
        return Err(
            "no changes to deliver — the result is identical to the files this task started from"
                .into(),
        );
    }
    let patch_file = tempfile::NamedTempFile::new().map_err(|e| e.to_string())?;
    std::fs::write(patch_file.path(), &patch).map_err(|e| e.to_string())?;
    let patch_path = patch_file
        .path()
        .to_str()
        .ok_or("non-UTF8 temporary patch path")?;
    let directory = tempfile::tempdir().map_err(|e| e.to_string())?;
    let index = directory.path().join("index");
    let isolated = |args: &[&str]| -> Result<String, String> {
        git_bytes_with_index(repo, args, Some(&index))
            .map(|bytes| String::from_utf8_lossy(&bytes).trim().to_string())
    };
    isolated(&["read-tree", &checkout_head])?;
    isolated(&["apply", "--cached", "--whitespace=nowarn", patch_path]).map_err(|e| {
        format!("the reviewed changes do not apply to your checkout's revision: {e}")
    })?;
    let tree = isolated(&["write-tree"])?;
    let message = git(repo, &["log", "-1", "--format=%B", &commit])?;
    let delivered = git(
        repo,
        &[
            "-c",
            "user.name=car-coder",
            "-c",
            "user.email=coder@parslee.ai",
            "commit-tree",
            &tree,
            "-p",
            &checkout_head,
            "-m",
            message.trim(),
        ],
    )?
    .trim()
    .to_string();
    let branch = format!("car/coder/{short_id}");
    git(repo, &["branch", &branch, &delivered])?;
    Ok((branch, delivered))
}

/// Paths the worktree has changed but not committed, including untracked ones.
/// Read-only: `status` never writes the index, so a refusal downstream leaves
/// the reviewed worktree exactly as review left it.
fn worktree_changed_paths(worktree: &Path) -> Result<Vec<String>, String> {
    let raw = git(
        worktree,
        &[
            "status",
            "--porcelain",
            "-z",
            "--no-renames",
            "--untracked-files=all",
        ],
    )?;
    Ok(raw
        .split('\0')
        .filter(|entry| entry.len() > 3)
        // `XY <path>`: two status columns, a space, then the path.
        .map(|entry| entry[3..].to_string())
        .collect())
}

/// [`publish_branch`] for the HEADLESS branch mode, where a clean worktree is a
/// legitimate re-delivery rather than an error.
///
/// `car code-task --deliver branch` runs the same kept-workspace lifecycle as
/// `--deliver pr`, and only the pull-request path was ever taught what a clean
/// worktree means there. Branch mode went through `require_commit`, so this
/// sequence parked a healthy goal: round N delivers via `--deliver branch`,
/// committing the work into a kept workspace; round N+1 reuses it, HEAD is ahead
/// of the base so the vacuity guard correctly stands down, the contract is
/// already green so the loop edits nothing — and then the publish failed with
/// "no changes to deliver". [`DeliveryFailure::Commit`] is hard-coded
/// non-retriable, so a run whose contract was green and whose work was intact
/// exited 3, "park it and tell a human", every round.
///
/// The empty-first-round case is still refused, by the same rule the
/// pull-request path uses: see [`head_beyond_base`].
pub fn publish_branch_headless(
    repo: &Path,
    worktree: &Path,
    short_id: &str,
    intent: &str,
    contract: &OutcomeContract,
    base_branch: &str,
    provenance: Option<&str>,
) -> Result<String, String> {
    let commit = match commit_worktree(worktree, intent, contract, provenance)? {
        CommitOutcome::Made(sha) => sha,
        CommitOutcome::NothingToCommit => head_beyond_base(worktree, base_branch)?,
    };
    let branch = format!("car/coder/{short_id}");
    git(repo, &["branch", &branch, &commit])?;
    Ok(branch)
}

/// Deliver to a managed project's `main`. The worktree was checked out detached
/// at `main`'s tip, so its commit is a direct descendant — a fast-forward
/// updates both the `main` ref and the project's checkout. **ff-only**: if
/// `main` moved since the session started (something committed underneath us),
/// this errors instead of rebasing or forcing, preserving the guarantee that
/// the diff the user approved is exactly what lands. Returns the commit SHA.
pub fn commit_to_main(
    repo: &Path,
    worktree: &Path,
    intent: &str,
    contract: &OutcomeContract,
    provenance: Option<&str>,
) -> Result<String, String> {
    let commit = require_commit(commit_worktree(worktree, intent, contract, provenance)?)?;
    git(repo, &["merge", "--ff-only", &commit]).map_err(|e| {
        format!("could not fast-forward the project's main branch (it moved since the session started): {e}")
    })?;
    Ok(commit)
}

/// The staged diff as the approval surface needs it.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct StagedDiff {
    /// `git diff --cached --stat`, never truncated — it is small, and it is the
    /// one view that stays complete however large the patch gets.
    pub stat: String,
    /// The patch, tail-capped to the configured budget.
    pub patch: String,
    /// Whether `patch` is a tail rather than the whole thing. Carried as a
    /// field, not just the `…[truncated]…` marker inside the string, so a UI can
    /// say so without string-matching (car#706).
    pub truncated: bool,
    /// Size of the untruncated patch, so the surface can report how much was
    /// withheld.
    pub full_bytes: usize,
    /// Every repo-relative path the diff touches, sorted and deduped — for
    /// contract-overlap disclosure and the changed-file summary at the gate.
    ///
    /// Includes BOTH endpoints of a rename. See [`parse_name_status_z`] for why
    /// the destination alone is not an honest answer.
    pub changed_paths: Vec<String>,
}

/// Stage everything and collect the diff for the approval UI. Staging is what
/// `publish_branch` would commit anyway, and it makes untracked files visible.
///
/// `patch_cap_bytes` bounds only the patch body. The review surface used to
/// shrink exactly as the risk grew: the cap was a hardcoded 32 KB tail, so on a
/// long session — the regime where the automated check is weakest — the human
/// approved against a partial patch, with the fact of truncation buried in a
/// marker inside the string.
pub fn stage_and_diff(worktree: &Path, patch_cap_bytes: usize) -> Result<StagedDiff, String> {
    git(worktree, &["add", "-A"])?;
    read_staged_diff(worktree, patch_cap_bytes)
}

/// Read the staged review without changing the index or including new edits.
pub(super) fn read_staged_diff(
    worktree: &Path,
    patch_cap_bytes: usize,
) -> Result<StagedDiff, String> {
    let stat = git(worktree, &["diff", "--cached", "--stat"])?;
    let patch = git(worktree, &["diff", "--cached"])?;
    let names = git(
        worktree,
        &[
            // Redundant insurance, NOT the mechanism: `-z` below already emits
            // raw bytes, so non-ASCII paths arrive unquoted with or without
            // this. It matters only if someone later drops `-z`, at which point
            // paths would come back C-escaped (`café.txt` as the literal
            // `"caf\303\251.txt"`, quotes included) and match nothing.
            "-c",
            "core.quotepath=false",
            "diff",
            "--cached",
            // `--name-status -z`, NOT `--name-only`. Rename detection reports
            // only the DESTINATION under `--name-only`, so
            // `git mv secrets/key.txt public_key.txt` yielded exactly
            // `["public_key.txt"]` and the fact that `secrets/` was touched
            // vanished. Any consumer reasoning about which paths a session
            // affected was being told a rename is a creation. `-z` additionally
            // makes paths NUL-delimited, so a newline in a filename cannot
            // forge an entry.
            "--name-status",
            "-z",
        ],
    )?;
    let changed_paths = parse_name_status_z(&names);
    let full_bytes = patch.len();
    Ok(StagedDiff {
        patch: super::shell_tool::tail(&patch, patch_cap_bytes),
        truncated: full_bytes > patch_cap_bytes,
        full_bytes,
        stat,
        changed_paths,
    })
}

/// Parse `git diff --cached --name-status -z` into every path the diff touches.
///
/// The `-z` stream is a flat run of NUL-terminated fields. Most entries are two
/// fields — a status letter then a path. Rename (`R`) and copy (`C`) entries are
/// three: the status carries a similarity score, then the SOURCE path, then the
/// destination. **Both endpoints are returned**, because a caller asking "what
/// did this session touch" is asking about the source too: a file moved out of a
/// directory is a change to that directory, and reporting only the destination
/// is how `--name-only` made `git mv secrets/key.txt public_key.txt` look like
/// the creation of an unrelated file.
fn parse_name_status_z(raw: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut fields = raw.split('\0').filter(|f| !f.is_empty());
    while let Some(status) = fields.next() {
        // Git's status set is closed — A C D M R T U X B — with `R`/`C`
        // carrying a similarity score (`R100`) and `M` optionally a
        // dissimilarity score under `-B`. Validate rather than assume: if a
        // field that is NOT a status reaches here, the loop reads a path as a
        // status and every subsequent field shifts by one, emitting a list of
        // plausible-looking fictional paths — onto a reviewer's approval screen,
        // as fact. A short list plus a warning is recoverable; silent fiction is
        // not, so bail loudly instead of guessing.
        let bytes = status.as_bytes();
        let well_formed = status.len() <= 4
            && matches!(
                bytes[0],
                b'A' | b'C' | b'D' | b'M' | b'R' | b'T' | b'U' | b'X' | b'B'
            )
            && status[1..].bytes().all(|b| b.is_ascii_digit());
        if !well_formed {
            tracing::warn!(
                status = %status,
                "unexpected field in `git diff --name-status -z`; changed-path list truncated \
                 rather than risk a desynchronized parse"
            );
            break;
        }
        // A rename/copy is followed by two paths rather than one.
        let two_paths = bytes[0] == b'R' || bytes[0] == b'C';
        let Some(first) = fields.next() else {
            tracing::warn!(status = %status, "name-status stream ended mid-entry");
            break;
        };
        out.push(first.to_string());
        if two_paths {
            match fields.next() {
                Some(second) => out.push(second.to_string()),
                // A rename with no destination is a corrupt stream, not an
                // entry to swallow silently.
                None => {
                    tracing::warn!(status = %status, "rename/copy entry missing its destination");
                    break;
                }
            }
        }
    }
    out.sort();
    out.dedup();
    out
}

/// Run git in `dir`, with the repository-selecting environment cleared.
///
/// `-C <dir>` selects a directory, not a repository: git resolves the repository
/// from `GIT_DIR`/`GIT_WORK_TREE` FIRST and only walks up from the directory if
/// they are unset. So an inherited `GIT_DIR` silently wins over the `-C` this
/// module relies on, and every caller here — commit, push, `rev-parse HEAD` —
/// would operate on a repository nobody named while the path-based reasoning
/// upstream said the worktree was the right one. That is reachable without
/// anything exotic: a git hook, `git rebase --exec`, or an orchestrator that
/// exported them once for its own bookkeeping. Clearing them costs nothing and
/// makes `-C` mean what the rest of this file assumes it means.
pub(crate) fn git(dir: &Path, args: &[&str]) -> Result<String, String> {
    git_bytes(dir, args).map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
}

fn git_bytes(dir: &Path, args: &[&str]) -> Result<Vec<u8>, String> {
    git_bytes_with_index(dir, args, None)
}

fn git_bytes_with_index(
    dir: &Path,
    args: &[&str],
    index: Option<&Path>,
) -> Result<Vec<u8>, String> {
    let mut cmd = std::process::Command::new("git");
    cmd.env_remove("GIT_DIR")
        .env_remove("GIT_WORK_TREE")
        .env_remove("GIT_INDEX_FILE")
        .env_remove("GIT_OBJECT_DIRECTORY")
        .env_remove("GIT_ALTERNATE_OBJECT_DIRECTORIES")
        .env_remove("GIT_COMMON_DIR")
        .arg("-C")
        .arg(dir)
        .args(args);
    if let Some(index) = index {
        cmd.env("GIT_INDEX_FILE", index);
    }
    no_interactive_prompts(&mut cmd);
    let out = run_capped(cmd).map_err(|e| match e {
        RunFailure::Spawn(io) => format!("git {args:?}: {io}"),
        RunFailure::TimedOut(secs) => format!(
            "git {args:?} timed out after {secs}s and was killed; treat it as a transport failure"
        ),
    })?;
    if out.status.success() {
        Ok(out.stdout)
    } else {
        Err(format!(
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        ))
    }
}

/// Refuse every interactive credential prompt, on every child of this module.
///
/// `Command::output()` nulls the child's stdin, and that is NOT enough: git does
/// not prompt on stdin. `git_terminal_prompt` opens `/dev/tty` directly, so a
/// `car code-task --deliver pr` started from a shell, tmux or `nohup` with an
/// inherited controlling terminal — the ordinary way an orchestrator launches
/// it — blocked forever on `Username for 'https://github.com':` against an
/// HTTPS remote with no stored credential. The round never completed, never
/// failed, and emitted no `delivery_failed`, in a command whose entire premise
/// is that nobody is watching. `GIT_ASKPASS` and `SSH_ASKPASS_REQUIRE` close the
/// two GUI-helper doors to the same room.
///
/// With this set the hang becomes `fatal: could not read Username/Password …`
/// or `terminal prompts disabled`, all three of which
/// [`classify_push_error`] now reads as a permanent refusal — which is the
/// truthful answer: no credential is ever going to appear.
fn no_interactive_prompts(cmd: &mut std::process::Command) {
    cmd.env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_ASKPASS", "")
        .env("SSH_ASKPASS", "")
        .env("SSH_ASKPASS_REQUIRE", "never");
}

/// How long any subprocess on the delivery path may run before it is killed.
///
/// Generous on purpose: a first push of a large repository over a slow link is
/// legitimately minutes, and killing honest work would be worse than the hang
/// this bounds. The point is only that "forever" is not one of the outcomes.
const SUBPROCESS_TIMEOUT_SECS: u64 = 900;

/// Why a subprocess produced no output.
enum RunFailure {
    /// It never started.
    Spawn(std::io::Error),
    /// It started and outlived [`SUBPROCESS_TIMEOUT_SECS`]; it has been killed.
    TimedOut(u64),
}

/// `Command::output()` with a ceiling.
///
/// `output()` waits forever. Every network-touching call on this path — push,
/// fetch, every `gh` round trip — can hang indefinitely on a black-holed
/// connection or a credential prompt, and this module's callers have no other
/// clock: `car code-task` reports a hung round as nothing at all, not even an
/// empty failure. A killed child at least becomes a classified error.
///
/// stdout and stderr are drained on their own threads because a child that
/// fills a pipe buffer blocks on the write while we block on `try_wait`, which
/// is a deadlock no timeout could observe. On the kill path the threads are
/// deliberately NOT joined: a grandchild (ssh, a credential helper) can hold the
/// inherited pipe open after its parent dies, and joining would reintroduce
/// exactly the unbounded wait this exists to remove.
fn run_capped(cmd: std::process::Command) -> Result<std::process::Output, RunFailure> {
    run_capped_for(cmd, std::time::Duration::from_secs(SUBPROCESS_TIMEOUT_SECS))
}

/// [`run_capped`] with the ceiling injected, so a test can prove the kill path
/// in a second rather than in fifteen minutes. Production always passes
/// [`SUBPROCESS_TIMEOUT_SECS`].
fn run_capped_for(
    mut cmd: std::process::Command,
    timeout: std::time::Duration,
) -> Result<std::process::Output, RunFailure> {
    use std::io::Read as _;
    use std::process::Stdio;

    let mut child = cmd
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(RunFailure::Spawn)?;

    let mut child_out = child.stdout.take().expect("stdout piped");
    let mut child_err = child.stderr.take().expect("stderr piped");
    let out_reader = std::thread::spawn(move || {
        let mut buf = Vec::new();
        let _ = child_out.read_to_end(&mut buf);
        buf
    });
    let err_reader = std::thread::spawn(move || {
        let mut buf = Vec::new();
        let _ = child_err.read_to_end(&mut buf);
        buf
    });

    let deadline = std::time::Instant::now() + timeout;
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Ok(None) => {}
            Err(e) => return Err(RunFailure::Spawn(e)),
        }
        if std::time::Instant::now() >= deadline {
            let _ = child.kill();
            let _ = child.wait();
            return Err(RunFailure::TimedOut(timeout.as_secs()));
        }
        std::thread::sleep(std::time::Duration::from_millis(25));
    };

    Ok(std::process::Output {
        status,
        stdout: out_reader.join().unwrap_or_default(),
        stderr: err_reader.join().unwrap_or_default(),
    })
}

// ---------------------------------------------------------------------------
// PR delivery — the third mode
// ---------------------------------------------------------------------------
//
// `publish_branch` and `commit_to_main` deliver INTO the local repository and
// stop there; a human is standing at the approval gate. PR delivery is the
// headless mode: nobody is watching, the work has to leave this machine, and
// the next round is a fresh session that will only ever see what is on GitHub.
// That changes what "deliver" has to guarantee, and every rule below is one of
// those guarantees rather than a preference.

/// Which of the two things happened to the pull request for the target
/// branch. Mirrors the `pr_action` field of the delivery event stream.
///
/// There is deliberately no `Reopened`. The runtime never closes a pull
/// request, so it is never the party entitled to undo a close — see
/// [`closed_pr_refusal`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PrAction {
    /// No pull request existed for this branch, so one was created.
    Opened,
    /// An open pull request already existed; the push landed on it.
    Updated,
}

impl PrAction {
    /// The wire spelling used by the `delivery_completed` event.
    pub fn as_str(&self) -> &'static str {
        match self {
            PrAction::Opened => "opened",
            PrAction::Updated => "updated",
        }
    }
}

impl std::fmt::Display for PrAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// GitHub's three terminal states for a pull request, as this module needs to
/// distinguish them. `Merged` is deliberately NOT folded into `ClosedUnmerged`:
/// a merge is this branch's work LANDING, while a close is somebody's decision
/// against it, so the two demand opposite responses — the first lets the next
/// round open a fresh pull request, the second parks the round.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrState {
    /// Open — a push to its head branch updates it in place.
    Open,
    /// Closed without being merged. Somebody decided against it; the runtime
    /// does not reopen one (see [`closed_pr_refusal`]).
    ClosedUnmerged,
    /// Merged — its work landed, and a new pull request carries the next round.
    Merged,
}

/// One pull request as GitHub reports it for a head branch.
#[derive(Debug, Clone, PartialEq)]
pub struct PrRecord {
    pub number: u64,
    pub state: PrState,
    pub url: String,
    pub is_draft: bool,
    /// The branch this pull request merges INTO, as `gh` reports `baseRefName`.
    ///
    /// Carried because GitHub's one-open-pull-request constraint is per (head,
    /// base) PAIR, not per head — two open pull requests from the same branch
    /// into different bases are entirely legal. Reconciliation without this
    /// field picked the highest-numbered open pull request for the head and
    /// rewrote its body, so a second pull request opened from the same branch
    /// into `release/2.1` (by a human, or by a round invoked with a different
    /// `--pr-base`) captured every later round: its description — which this run
    /// did not author — was replaced wholesale, and the pull request the
    /// orchestrator actually tracks kept a stale body forever.
    pub base: String,
}

/// Everything PR delivery needs. Borrowed rather than owned because every field
/// already exists in the caller's session state.
pub struct PrDelivery<'a> {
    /// The repository. `gh` runs here, so this must be a checkout with the
    /// GitHub remote configured.
    pub repo: &'a Path,
    /// The session's worktree — where the changes are and where the commit is
    /// made. It shares `repo`'s config, so it can push to the same remote.
    pub worktree: &'a Path,
    /// The delivery branch. **Stable across sessions**: round N+1 pushes to the
    /// same branch, so a second branch is never created for the same goal.
    pub target_branch: &'a str,
    /// The base the pull request merges into.
    pub base_branch: &'a str,
    /// Open the pull request as a draft. Only ever consulted when a pull
    /// request is CREATED — see [`deliver_pr`] on why this never flips an
    /// existing one.
    pub draft: bool,
    /// The run intent; becomes the commit subject and the pull-request title.
    pub intent: &'a str,
    /// The contract that passed. Embedded in the commit body by
    /// [`commit_worktree`].
    pub contract: &'a OutcomeContract,
    /// The substantive pull-request description: what was done, what remains,
    /// what the contract proved. It is the next fresh session's context and
    /// must stand alone without the diff.
    pub body: &'a str,
    /// Where a distributed run's subtasks ran, from [`placement_provenance`].
    ///
    /// A FIELD rather than a `None` baked into the commit step, even though no
    /// caller can set it today: no distributed session can open a pull request
    /// (the heal loop hardcodes local, `car code-task` has no distributed mode),
    /// so this is out of reach rather than a gap. The day someone adds
    /// `--distributed` to a pull-request path, a named field makes them decide
    /// and a buried literal would silently drop the provenance (car#1322).
    pub provenance: Option<&'a str>,
}

/// The aggregate and per-check CI verdict vocabulary for one exact commit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CiState {
    Green,
    Pending,
    Red,
}

/// One named forge check, pipeline validation, or commit-status context.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct CiCheck {
    pub name: String,
    pub state: CiState,
}

/// Forge checks and status contexts for the delivered head SHA.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct CiSummary {
    /// The exact commit queried. CI from an older or newer branch head must not
    /// be presented as evidence about this delivery.
    pub head_sha: String,
    pub state: CiState,
    /// Every named check and its typed verdict, sorted by name.
    pub checks: Vec<CiCheck>,
    /// CI could not be observed; delivery succeeded but is never green.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observation_error: Option<String>,
}

impl CiSummary {
    fn from_checks(head_sha: &str, checks: Vec<(String, CiState)>) -> Self {
        // A provider can expose one check through more than one API. Keep one
        // name and retain the strongest verdict rather than reporting
        // contradictory duplicates.
        let mut by_name = std::collections::BTreeMap::<String, CiState>::new();
        for (name, state) in checks {
            by_name
                .entry(name)
                .and_modify(|current| {
                    if ci_severity(state) > ci_severity(*current) {
                        *current = state;
                    }
                })
                .or_insert(state);
        }

        let checks: Vec<CiCheck> = by_name
            .into_iter()
            .map(|(name, state)| CiCheck { name, state })
            .collect();
        let state = if checks.iter().any(|check| check.state == CiState::Red) {
            CiState::Red
        } else if checks.is_empty() || checks.iter().any(|check| check.state == CiState::Pending) {
            // A just-pushed commit may not have pipeline runs yet. Absence is
            // pending, never evidence that the commit is green.
            CiState::Pending
        } else {
            CiState::Green
        };
        Self {
            head_sha: head_sha.to_string(),
            state,
            checks,
            observation_error: None,
        }
    }

    fn names_with_state(&self, state: CiState) -> Vec<String> {
        self.checks
            .iter()
            .filter(|check| check.state == state)
            .map(|check| check.name.clone())
            .collect()
    }
}

fn ci_severity(state: CiState) -> u8 {
    match state {
        CiState::Green => 0,
        CiState::Pending => 1,
        CiState::Red => 2,
    }
}

/// A successful PR delivery.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PrDeliveryOutcome {
    /// The target branch the commit landed on.
    pub branch: String,
    /// The delivered commit SHA.
    pub commit: String,
    /// Whether the push actually ran (always `true` on success today; carried
    /// as a field because the event stream reports it).
    pub pushed: bool,
    pub pr_number: u64,
    pub pr_url: String,
    pub pr_action: PrAction,
    /// The pull request's ACTUAL draft state, not the requested one. On
    /// `Opened` these agree; on `Updated` this reports what GitHub says, because
    /// a car worker may have marked the pull request ready in an earlier round
    /// and delivery must not misreport that.
    pub draft: bool,
    /// CI observed for `commit` after the pull request was reconciled.
    pub ci: CiSummary,
}

impl PrDeliveryOutcome {
    /// Human-readable delivery status for logs and reports. The typed `ci`
    /// remains the source for clients that render their own presentation.
    pub fn delivery_report(&self) -> String {
        if let Some(error) = &self.ci.observation_error {
            return format!("delivered; CI unavailable at {}: {error}", self.commit);
        }
        match self.ci.state {
            CiState::Green if self.draft => format!(
                "delivered with green checks at {}; pull request remains draft",
                self.ci.head_sha
            ),
            CiState::Green => format!(
                "delivered with green checks and ready for review at {}",
                self.ci.head_sha
            ),
            CiState::Pending => {
                let names = named_checks_or(
                    &self.ci.names_with_state(CiState::Pending),
                    "no checks reported yet",
                );
                format!(
                    "delivered with pending checks at {}: {names}",
                    self.ci.head_sha
                )
            }
            CiState::Red => {
                let names =
                    named_checks_or(&self.ci.names_with_state(CiState::Red), "unknown check");
                format!("delivered red on {names} at {}", self.ci.head_sha)
            }
        }
    }
}

fn named_checks_or(names: &[String], fallback: &str) -> String {
    if names.is_empty() {
        fallback.to_string()
    } else {
        names.join(", ")
    }
}

/// Why a PR delivery stopped, at which stage, and whether the next round should
/// simply try again.
///
/// The stage is not decoration: it is the difference between "the work is safe
/// on disk, re-push it" and "this goal cannot progress without a human". It
/// maps 1:1 onto the `delivery_failed` event's `stage` field.
#[derive(Debug, Clone, PartialEq)]
pub enum DeliveryFailure {
    /// Refused before touching anything — a missing GitHub credential, a branch
    /// name git/`gh` would misread, a target branch equal to the base, or either
    /// half of the delivery-head policy ([`delivery_head_refusal`]): an
    /// **ambiguous head**, where the target branch already carries an open pull
    /// request into some other base that the push would silently add this
    /// round's commits to ([`ambiguous_head_refusal`]); or a **closed pull
    /// request** into this run's own base, which is somebody's decision that
    /// this branch should stop ([`closed_pr_refusal`]). Never retriable: nothing
    /// about running again changes any of them. Those two are the causes here
    /// that depend on remote STATE rather than on the invocation, so they are
    /// also the ones a `stage: "preflight"` reader is most likely to misread as
    /// a configuration mistake — clearing either means acting on the other pull
    /// request (closing the ambiguous one, reopening the closed one) or picking
    /// a different `--target-branch`.
    Preflight { reason: String },
    /// The worktree could not be committed. Not retriable — the same worktree
    /// will fail the same way.
    Commit { reason: String },
    /// The push was refused. `retriable` is `true` for the ordinary case (the
    /// branch moved, so the next round re-cuts from its head and replays) and
    /// `false` for credential/permission refusals.
    Push { reason: String, retriable: bool },
    /// A `gh` pull-request call failed. Usually retriable (a GitHub API blip);
    /// the work is not lost either way. Reached from two places, and the state
    /// of the remote differs between them: reconciliation runs after the push,
    /// so the commit is safely on the branch, while the head-ambiguity listing
    /// in preflight runs before it, so nothing has been committed or pushed at
    /// all. Both are the same verdict — retry the delivery — which is why they
    /// share a variant.
    Pr { reason: String, retriable: bool },
}

impl DeliveryFailure {
    /// The wire spelling of the stage — `preflight` | `commit` | `push` | `pr`.
    pub fn stage(&self) -> &'static str {
        match self {
            DeliveryFailure::Preflight { .. } => "preflight",
            DeliveryFailure::Commit { .. } => "commit",
            DeliveryFailure::Push { .. } => "push",
            DeliveryFailure::Pr { .. } => "pr",
        }
    }

    /// Whether the next round should just try the same delivery again.
    /// Preflight and commit failures are definitionally not retriable.
    pub fn retriable(&self) -> bool {
        match self {
            DeliveryFailure::Preflight { .. } | DeliveryFailure::Commit { .. } => false,
            DeliveryFailure::Push { retriable, .. } | DeliveryFailure::Pr { retriable, .. } => {
                *retriable
            }
        }
    }

    /// The human-readable reason, without the stage prefix.
    pub fn reason(&self) -> &str {
        match self {
            DeliveryFailure::Preflight { reason }
            | DeliveryFailure::Commit { reason }
            | DeliveryFailure::Push { reason, .. }
            | DeliveryFailure::Pr { reason, .. } => reason,
        }
    }
}

impl std::fmt::Display for DeliveryFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} failed: {}", self.stage(), self.reason())
    }
}

impl std::error::Error for DeliveryFailure {}

/// The forge operations PR delivery needs, behind one vendor-neutral seam.
///
/// Commit creation and the append-only push remain plain git. This trait owns
/// only the review artifact: authentication, pull-request reconciliation, body
/// refresh, and checks for one exact head. Keeping those operations together is
/// what prevents a second forge from becoming a parallel, weaker delivery path.
pub trait ForgeClient: Send + Sync {
    /// Fail with a message naming the forge credential or login remedy.
    fn auth_status(&self) -> Result<(), ForgeError>;
    /// Every pull request whose head is `head_branch`, in any state.
    fn list_prs_for_head(&self, dir: &Path, head_branch: &str)
        -> Result<Vec<PrRecord>, ForgeError>;
    fn create_pr(
        &self,
        dir: &Path,
        head_branch: &str,
        base_branch: &str,
        title: &str,
        body: &str,
        draft: bool,
    ) -> Result<PrRecord, ForgeError>;
    /// Replace a pull request's body wholesale.
    fn set_pr_body(&self, dir: &Path, number: u64, body: &str) -> Result<(), ForgeError>;
    /// Reopen a closed pull request when the caller has separately established
    /// that doing so is authorized. Current delivery policy deliberately never
    /// calls this: a human close parks the round.
    fn reopen_pr(&self, _dir: &Path, _number: u64) -> Result<(), ForgeError> {
        Err(ForgeError::local(
            "this forge client does not implement pull-request reopening",
        ))
    }
    /// Check runs, policies, and commit statuses for one exact PR head.
    fn ci_for_sha(&self, dir: &Path, number: u64, head_sha: &str) -> Result<CiSummary, ForgeError>;
}

/// Compatibility name for callers that supplied a fake before the seam became
/// forge-neutral. New code should use [`ForgeClient`].
pub use ForgeClient as GitHubApi;

/// Forge selected for one origin remote.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ForgeKind {
    GitHub,
    AzureDevOps,
}

impl ForgeKind {
    fn as_str(self) -> &'static str {
        match self {
            Self::GitHub => "github",
            Self::AzureDevOps => "azure-devops",
        }
    }
}

/// Explicit override for self-hosted or otherwise unrecognized forge URLs.
pub const FORGE_OVERRIDE_ENV: &str = "CAR_CODER_FORGE";

trait ForgeCommandRunner: Send + Sync {
    fn run(&self, dir: &Path, program: &str, args: &[String]) -> Result<String, ForgeError>;
}

struct ProcessForgeCommandRunner;

impl ForgeCommandRunner for ProcessForgeCommandRunner {
    fn run(&self, dir: &Path, program: &str, args: &[String]) -> Result<String, ForgeError> {
        run_forge_cli(dir, program, args)
    }
}

/// GitHub implementation backed by the `gh` CLI.
pub struct GhCli {
    runner: Option<Arc<dyn ForgeCommandRunner>>,
}

/// Preserve the original unit-value construction used by downstream callers:
/// `let gh = GhCli`. The type gained injectable state for offline tests, but
/// that internal change must not make existing GitHub callers migrate.
#[allow(non_upper_case_globals)]
pub const GhCli: GhCli = GhCli { runner: None };

impl Default for GhCli {
    fn default() -> Self {
        GhCli
    }
}

impl GhCli {
    fn runner(&self) -> &dyn ForgeCommandRunner {
        self.runner.as_deref().unwrap_or(&ProcessForgeCommandRunner)
    }
}

/// Azure DevOps implementation backed by the `az repos pr` CLI surface.
pub struct AzureDevOpsCli {
    runner: Arc<dyn ForgeCommandRunner>,
    auth_dir: Option<PathBuf>,
}

impl Default for AzureDevOpsCli {
    fn default() -> Self {
        Self {
            runner: Arc::new(ProcessForgeCommandRunner),
            auth_dir: None,
        }
    }
}

impl AzureDevOpsCli {
    fn for_repo(repo: &Path) -> Self {
        Self {
            runner: Arc::new(ProcessForgeCommandRunner),
            auth_dir: Some(repo.to_path_buf()),
        }
    }

    fn auth_dir(&self) -> &Path {
        self.auth_dir.as_deref().unwrap_or(Path::new("."))
    }
}

#[cfg(test)]
impl GhCli {
    fn with_runner(runner: Arc<dyn ForgeCommandRunner>) -> Self {
        Self {
            runner: Some(runner),
        }
    }
}

#[cfg(test)]
impl AzureDevOpsCli {
    fn with_runner(runner: Arc<dyn ForgeCommandRunner>, repo: &Path) -> Self {
        Self {
            runner,
            auth_dir: Some(repo.to_path_buf()),
        }
    }
}

/// `gh auth status` args. A separate fn so the guard tests can read the exact
/// argv without a network round trip.
fn gh_auth_status_args() -> Vec<String> {
    vec!["auth".into(), "status".into()]
}

/// The repository `gh` must act on: the one [`push_args`] pushes to.
///
/// Every `gh` call used to run with only `current_dir(dir)`, leaving `gh` to
/// pick a base repository through its OWN remote preference order — `upstream`
/// before `github` before `origin`. On the ordinary contributor layout that
/// `gh repo fork --remote` creates (`origin = you/repo`,
/// `upstream = acme/repo`), the two halves of delivery then addressed different
/// repositories: the commit went to `you/repo`, the listing queried
/// `acme/repo` and found nothing, and `gh pr create` opened a pull request on
/// `acme/repo` — a repository the operator never named. Round N+1 queried the
/// wrong repository again, so "exactly one pull request per branch" did not hold
/// either.
///
/// `None` when `origin` is not a GitHub URL — a local path, as every test in
/// this file uses — in which case `gh`'s own resolution is left alone, because
/// there is nothing better to say.
fn gh_repo_args(dir: &Path) -> Vec<String> {
    match git(dir, &["remote", "get-url", "origin"])
        .ok()
        .and_then(|url| parse_github_repo_spec(url.trim()))
    {
        Some(spec) => vec!["--repo".into(), spec],
        None => Vec::new(),
    }
}

/// `<owner>/<name>` for github.com, `<host>/<owner>/<name>` elsewhere — the
/// `[HOST/]OWNER/REPO` spelling `gh --repo` accepts. `None` for anything that is
/// not a remote URL naming exactly one repository.
fn parse_github_repo_spec(url: &str) -> Option<String> {
    // `scheme://[user@]host[:port]/owner/name[.git]`, or scp-style
    // `[user@]host:owner/name[.git]`.
    let after_scheme = url.split_once("://").map(|(_, rest)| rest);
    let (host_part, path) = match after_scheme {
        Some(rest) => rest.split_once('/')?,
        // No scheme. A leading `/` or `.` is a local path, not a URL.
        None if url.starts_with('/') || url.starts_with('.') => return None,
        None => url.split_once(':')?,
    };
    let host = host_part
        .rsplit('@')
        .next()?
        .split(':')
        .next()?
        .to_ascii_lowercase();
    if host.is_empty() {
        return None;
    }
    let path = path
        .trim_matches('/')
        .strip_suffix(".git")
        .unwrap_or(path.trim_matches('/'));
    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    // Exactly owner/name. Anything else is a shape this does not understand, and
    // guessing at it would aim delivery somewhere nobody asked for.
    let [owner, name] = segments[..] else {
        return None;
    };
    if host == "github.com" {
        Some(format!("{owner}/{name}"))
    } else {
        Some(format!("{host}/{owner}/{name}"))
    }
}

/// `gh pr list` args for one head branch, all states.
fn gh_pr_list_args(head_branch: &str) -> Vec<String> {
    vec![
        "pr".into(),
        "list".into(),
        "--head".into(),
        head_branch.to_string(),
        "--state".into(),
        "all".into(),
        "--json".into(),
        // `isCrossRepository` is requested so `parse_pr_list` can DROP forks'
        // pull requests. `--head` filters on the head ref NAME alone, so an
        // outside contributor's `them/repo:goalpool/g_abc` is returned
        // alongside — or instead of — ours. Goal-derived branch names collide
        // trivially and forks are the normal contribution path on a public
        // repo, and the consequences are not cosmetic: the update path would
        // `gh pr edit` a third party's description away, and a stranger's
        // CLOSED pull request would park every future round on this branch.
        //
        // `baseRefName` is requested for the neighbouring reason: `--head`
        // filters on the head ref alone, and GitHub allows several open pull
        // requests from one head into DIFFERENT bases. See [`PrRecord::base`].
        "number,state,url,isDraft,isCrossRepository,baseRefName".into(),
        // `gh pr list` pages at 30 by default. That was cosmetic while this
        // listing only chose which pull request to reconcile; it is not now,
        // because the same listing is the sole input to
        // [`delivery_head_refusal`] — a truncated page hides an open pull
        // request into another base, or a closed one into this base, and the
        // harmful push proceeds exactly as it did before the guard existed.
        // Few pull requests share one head branch, so this is unlikely, but the
        // failure is silent and it defeats the guard entirely, which is the
        // wrong pair of properties to leave to a default.
        "--limit".into(),
        "100".into(),
    ]
}

/// `gh pr create` args. `--draft` appears exactly when `draft` is set.
fn gh_pr_create_args(
    head_branch: &str,
    base_branch: &str,
    title: &str,
    body: &str,
    draft: bool,
) -> Vec<String> {
    let mut args = vec![
        "pr".into(),
        "create".into(),
        "--head".into(),
        head_branch.to_string(),
        "--base".into(),
        base_branch.to_string(),
        "--title".into(),
        title.to_string(),
        "--body".into(),
        body.to_string(),
    ];
    if draft {
        args.push("--draft".into());
    }
    args
}

/// `gh pr reopen` args. Delivery policy does not invoke this automatically.
fn gh_pr_reopen_args(number: u64) -> Vec<String> {
    vec!["pr".into(), "reopen".into(), number.to_string()]
}

/// `gh pr view` args for check runs and combined-status contexts.
fn gh_pr_checks_args(number: u64) -> Vec<String> {
    vec![
        "pr".into(),
        "view".into(),
        number.to_string(),
        "--json".into(),
        "headRefOid,statusCheckRollup".into(),
    ]
}

fn az_common_tail(output: &str) -> Vec<String> {
    vec![
        "--detect".into(),
        "true".into(),
        "--output".into(),
        output.into(),
        "--only-show-errors".into(),
    ]
}

fn az_auth_status_args() -> Vec<String> {
    let mut args = vec!["repos".into(), "list".into()];
    args.extend(az_common_tail("json"));
    args
}

fn az_pr_list_args(head_branch: &str) -> Vec<String> {
    let mut args = vec![
        "repos".into(),
        "pr".into(),
        "list".into(),
        "--source-branch".into(),
        head_branch.into(),
        "--status".into(),
        "all".into(),
        "--top".into(),
        "100".into(),
        "--include-links".into(),
        "true".into(),
    ];
    args.extend(az_common_tail("json"));
    args
}

fn az_pr_create_args(
    head_branch: &str,
    base_branch: &str,
    title: &str,
    body: &str,
    draft: bool,
) -> Vec<String> {
    let mut args = vec![
        "repos".into(),
        "pr".into(),
        "create".into(),
        "--source-branch".into(),
        head_branch.into(),
        "--target-branch".into(),
        base_branch.into(),
        "--title".into(),
        title.into(),
        "--description".into(),
        body.into(),
        "--draft".into(),
        draft.to_string(),
    ];
    args.extend(az_common_tail("json"));
    args
}

fn az_pr_update_args(number: u64, body: &str) -> Vec<String> {
    let mut args = vec![
        "repos".into(),
        "pr".into(),
        "update".into(),
        "--id".into(),
        number.to_string(),
        "--description".into(),
        body.into(),
    ];
    args.extend(az_common_tail("none"));
    args
}

fn az_pr_reopen_args(number: u64) -> Vec<String> {
    let mut args = vec![
        "repos".into(),
        "pr".into(),
        "update".into(),
        "--id".into(),
        number.to_string(),
        "--status".into(),
        "active".into(),
    ];
    args.extend(az_common_tail("none"));
    args
}

fn az_pr_show_args(number: u64) -> Vec<String> {
    let mut args = vec![
        "repos".into(),
        "pr".into(),
        "show".into(),
        "--id".into(),
        number.to_string(),
    ];
    args.extend(az_common_tail("json"));
    args
}

fn az_pr_policy_list_args(number: u64) -> Vec<String> {
    let mut args = vec![
        "repos".into(),
        "pr".into(),
        "policy".into(),
        "list".into(),
        "--id".into(),
        number.to_string(),
        "--top".into(),
        "100".into(),
    ];
    args.extend(az_common_tail("json"));
    args
}

/// Git's force marker in a refspec, named exactly once.
///
/// Named so the append-only source guard can ban the bare char literal
/// everywhere else in this file. `validate_branch_name` legitimately has to talk
/// about `+` — it exists to REFUSE names starting with one — and a scanner that
/// trips on the code refusing a force marker is the failure this guard family
/// keeps rediscovering. The previous carve-out was "only complain when the same
/// LINE also says `format!`", and rustfmt splits `format!(` from its string
/// routinely (it does so in `validate_branch_name` itself), so the one spelling
/// a real force refspec would take — bind the plus to a name, interpolate it —
/// walked straight through. One allowlisted definition line is narrower and has
/// no such hole.
const FORCE_MARKER: char = '+';

/// The push refspec, built as a function so a test can assert on it directly.
///
/// `<sha>:refs/heads/<branch>` with **no leading `+`**. A leading plus is git's
/// force marker; without it git refuses any update that is not a fast-forward,
/// which is precisely the guarantee this delivery path sells. The full
/// `refs/heads/` prefix is spelled out so a branch name that also matches a tag
/// cannot redirect the push.
fn push_args(commit: &str, target_branch: &str) -> Vec<String> {
    vec![
        "push".into(),
        "origin".into(),
        format!("{commit}:refs/heads/{target_branch}"),
    ]
}

/// A failed forge invocation, with rendered context and raw stderr separated.
///
/// The split is load-bearing: title and body arguments contain model output,
/// while [`classify_pr_error`] must classify only what the forge itself said.
#[derive(Debug, Clone)]
pub struct ForgeError {
    /// Human-readable, names the failing command. Never classified.
    pub message: String,
    /// The child's stderr, alone. The only text error classification reads.
    pub stderr: String,
}

/// Compatibility name for existing GitHub-specific callers.
pub type GhError = ForgeError;

impl std::fmt::Display for ForgeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

impl ForgeError {
    fn local(message: impl Into<String>) -> Self {
        let message = message.into();
        Self {
            stderr: message.clone(),
            message,
        }
    }
}

/// Run one forge CLI with an argument array and no interactive credential path.
fn run_forge_cli(dir: &Path, program: &str, args: &[String]) -> Result<String, ForgeError> {
    let mut cmd = std::process::Command::new(program);
    cmd.current_dir(dir).args(args);
    no_interactive_prompts(&mut cmd);
    if program == "gh" {
        // Preserve the GitHub implementation's pre-existing no-prompt posture.
        cmd.env("GH_PROMPT_DISABLED", "1");
    }
    let out = run_capped(cmd).map_err(|e| match e {
        RunFailure::Spawn(io) if io.kind() == std::io::ErrorKind::NotFound => {
            if program == "gh" {
                ForgeError::local(
                    "`gh` not found on PATH — install the GitHub CLI (https://cli.github.com) \
                     and authenticate it",
                )
            } else {
                ForgeError::local(
                    "`az` not found on PATH — install Azure CLI and the azure-devops extension, \
                     then authenticate it",
                )
            }
        }
        RunFailure::Spawn(io) => ForgeError::local(format!(
            "failed to run `{program} {}`: {io}",
            gh_subcommand_shape(args)
        )),
        RunFailure::TimedOut(secs) => ForgeError::local(format!(
            "`{program} {}` timed out after {secs}s and was killed",
            gh_subcommand_shape(args)
        )),
    })?;
    if out.status.success() {
        Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
    } else {
        let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
        Err(ForgeError {
            message: format!("{program} {} failed: {stderr}", gh_subcommand_shape(args)),
            stderr,
        })
    }
}

/// GitHub CLI entry point shared with the GitHub-only issue intake modules.
pub(super) fn gh(dir: &Path, args: &[String]) -> Result<String, GhError> {
    run_forge_cli(dir, "gh", args)
}

/// The shape of a forge argv for a human: flags kept, operand VALUES elided.
///
/// Even the human-readable half declines to echo `--title`, `--body`, and
/// Azure DevOps' equivalent `--description`. Their values are model output,
/// they can be thousands of lines, and a delivery
/// failure surfaces in an event stream and a `run_end.error` an orchestrator
/// logs. The flags themselves say everything a reader needs about which call
/// failed.
fn gh_subcommand_shape(args: &[String]) -> String {
    let mut out: Vec<String> = Vec::with_capacity(args.len());
    let mut elide_next = false;
    for arg in args {
        if std::mem::take(&mut elide_next) {
            out.push("<…>".to_string());
            continue;
        }
        if arg.starts_with("--") {
            elide_next = matches!(arg.as_str(), "--title" | "--body" | "--description");
        }
        out.push(arg.clone());
    }
    out.join(" ")
}

/// Parse `gh pr list --json number,state,url,isDraft,isCrossRepository` output.
///
/// **Cross-repository entries are dropped here**, at the parse boundary, so that
/// no downstream branch can reach one. Reconciliation's whole vocabulary —
/// update the body, park on a close — is about a pull request whose head branch
/// is the one we just pushed to on `origin`. A fork's pull request merely shares
/// the ref NAME, which is all `--head` matches on; acting on it would rewrite a
/// stranger's description, or let a stranger's close park this branch, while the
/// branch we actually pushed still has no pull request at all.
fn parse_pr_list(raw: &str) -> Result<Vec<PrRecord>, String> {
    let value: serde_json::Value = serde_json::from_str(raw.trim())
        .map_err(|e| format!("could not parse `gh pr list` JSON: {e}"))?;
    let items = value
        .as_array()
        .ok_or_else(|| "`gh pr list` did not return a JSON array".to_string())?;
    let mut out = Vec::with_capacity(items.len());
    for item in items {
        // Absent field ⇒ same-repo. `gh` omits nothing it was asked for, and an
        // older `gh` that does not know the field would otherwise refuse the
        // whole call rather than answer without it.
        if item
            .get("isCrossRepository")
            .and_then(|c| c.as_bool())
            .unwrap_or(false)
        {
            continue;
        }
        let number = item
            .get("number")
            .and_then(|n| n.as_u64())
            .ok_or_else(|| "pull request entry has no numeric `number`".to_string())?;
        let raw_state = item
            .get("state")
            .and_then(|s| s.as_str())
            .ok_or_else(|| "pull request entry has no `state`".to_string())?;
        // gh reports MERGED distinctly from CLOSED. An unknown state is not
        // guessed at: treating it as closed would park a run that should have
        // proceeded.
        let state = match raw_state.to_ascii_uppercase().as_str() {
            "OPEN" => PrState::Open,
            "CLOSED" => PrState::ClosedUnmerged,
            "MERGED" => PrState::Merged,
            other => return Err(format!("unrecognized pull request state `{other}`")),
        };
        out.push(PrRecord {
            number,
            state,
            url: item
                .get("url")
                .and_then(|u| u.as_str())
                .unwrap_or_default()
                .to_string(),
            is_draft: item
                .get("isDraft")
                .and_then(|d| d.as_bool())
                .unwrap_or(false),
            // Required, not defaulted. A missing base cannot be guessed at:
            // every default is a claim that some pull request merges into the
            // branch this round targets, and acting on the wrong one is the
            // failure this field was added to stop. `gh` returns every field it
            // was asked for.
            base: item
                .get("baseRefName")
                .and_then(|b| b.as_str())
                .ok_or_else(|| "pull request entry has no `baseRefName`".to_string())?
                .to_string(),
        });
    }
    Ok(out)
}

/// Parse GitHub check runs and combined-status contexts for one exact SHA.
fn parse_github_ci_summary(raw: &str, expected_head_sha: &str) -> Result<CiSummary, String> {
    let value: serde_json::Value = serde_json::from_str(raw.trim())
        .map_err(|e| format!("could not parse `gh pr view` CI JSON: {e}"))?;
    let actual_head = value
        .get("headRefOid")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "`gh pr view` CI response has no `headRefOid`".to_string())?;
    if actual_head != expected_head_sha {
        return Err(format!(
            "pull request head moved while delivery was reading CI: expected {expected_head_sha}, found {actual_head}"
        ));
    }

    let rollup = match value.get("statusCheckRollup") {
        None | Some(serde_json::Value::Null) => &[][..],
        Some(serde_json::Value::Array(items)) => items.as_slice(),
        Some(_) => {
            return Err("`gh pr view` CI response has a non-array `statusCheckRollup`".to_string())
        }
    };
    let mut checks = Vec::with_capacity(rollup.len());
    for item in rollup {
        let kind = item
            .get("__typename")
            .and_then(|v| v.as_str())
            .ok_or_else(|| "CI rollup entry has no `__typename`".to_string())?;
        let (name, state) = match kind {
            "CheckRun" => {
                let name = required_string(item, "name", "CI rollup entry")?;
                let status = item
                    .get("status")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| format!("check run `{name}` has no `status`"))?;
                let state = if status.eq_ignore_ascii_case("COMPLETED") {
                    let conclusion =
                        item.get("conclusion")
                            .and_then(|v| v.as_str())
                            .ok_or_else(|| {
                                format!("completed check run `{name}` has no `conclusion`")
                            })?;
                    match conclusion.to_ascii_uppercase().as_str() {
                        "SUCCESS" | "NEUTRAL" | "SKIPPED" => CiState::Green,
                        "ACTION_REQUIRED" | "CANCELLED" | "FAILURE" | "STALE"
                        | "STARTUP_FAILURE" | "TIMED_OUT" => CiState::Red,
                        other => {
                            return Err(format!(
                                "check run `{name}` has unrecognized conclusion `{other}`"
                            ))
                        }
                    }
                } else {
                    // Every non-completed run is conservatively pending. New
                    // queued spellings cannot become a false green.
                    CiState::Pending
                };
                (name, state)
            }
            "StatusContext" => {
                let name = required_string(item, "context", "CI rollup entry")?;
                let raw_state = item
                    .get("state")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| format!("status context `{name}` has no `state`"))?;
                let state = match raw_state.to_ascii_uppercase().as_str() {
                    "SUCCESS" => CiState::Green,
                    "EXPECTED" | "PENDING" => CiState::Pending,
                    "ERROR" | "FAILURE" => CiState::Red,
                    other => {
                        return Err(format!(
                            "status context `{name}` has unrecognized state `{other}`"
                        ))
                    }
                };
                (name, state)
            }
            other => return Err(format!("unrecognized CI rollup entry type `{other}`")),
        };
        checks.push((name, state));
    }
    Ok(CiSummary::from_checks(expected_head_sha, checks))
}

fn required_string(
    value: &serde_json::Value,
    field: &str,
    subject: &str,
) -> Result<String, String> {
    value
        .get(field)
        .and_then(|v| v.as_str())
        .filter(|s| !s.trim().is_empty())
        .map(str::to_string)
        .ok_or_else(|| format!("{subject} has no non-empty `{field}`"))
}

fn strip_heads_prefix(name: &str) -> String {
    name.strip_prefix("refs/heads/").unwrap_or(name).to_string()
}

fn azure_pr_url(value: &serde_json::Value, number: u64) -> String {
    value
        .pointer("/_links/web/href")
        .and_then(|v| v.as_str())
        .or_else(|| value.get("remoteUrl").and_then(|v| v.as_str()))
        .map(str::to_string)
        .or_else(|| {
            value
                .pointer("/repository/webUrl")
                .and_then(|v| v.as_str())
                .map(|base| format!("{}/pullrequest/{number}", base.trim_end_matches('/')))
        })
        .or_else(|| {
            value
                .get("url")
                .and_then(|v| v.as_str())
                .map(str::to_string)
        })
        .unwrap_or_default()
}

fn parse_azure_pr(value: &serde_json::Value) -> Result<PrRecord, String> {
    let number = value
        .get("pullRequestId")
        .and_then(|v| v.as_u64())
        .ok_or_else(|| "Azure DevOps pull request has no numeric `pullRequestId`".to_string())?;
    let raw_state = value
        .get("status")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "Azure DevOps pull request has no `status`".to_string())?;
    let state = match raw_state.to_ascii_lowercase().as_str() {
        "active" => PrState::Open,
        "abandoned" => PrState::ClosedUnmerged,
        "completed" => PrState::Merged,
        other => {
            return Err(format!(
                "unrecognized Azure DevOps pull request status `{other}`"
            ))
        }
    };
    let target = required_string(value, "targetRefName", "Azure DevOps pull request")?;
    Ok(PrRecord {
        number,
        state,
        url: azure_pr_url(value, number),
        is_draft: value
            .get("isDraft")
            .and_then(|v| v.as_bool())
            .unwrap_or(false),
        base: strip_heads_prefix(&target),
    })
}

fn parse_azure_pr_list(raw: &str) -> Result<Vec<PrRecord>, String> {
    let value: serde_json::Value = serde_json::from_str(raw.trim())
        .map_err(|e| format!("could not parse `az repos pr list` JSON: {e}"))?;
    let items = value
        .as_array()
        .ok_or_else(|| "`az repos pr list` did not return a JSON array".to_string())?;
    items.iter().map(parse_azure_pr).collect()
}

fn azure_pr_head(pr_raw: &str) -> Result<String, String> {
    let pr: serde_json::Value = serde_json::from_str(pr_raw.trim())
        .map_err(|e| format!("could not parse `az repos pr show` JSON: {e}"))?;
    pr.pointer("/lastMergeSourceCommit/commitId")
        .and_then(|v| v.as_str())
        .map(str::to_string)
        .ok_or_else(|| {
            "`az repos pr show` response has no `lastMergeSourceCommit.commitId`".to_string()
        })
}

fn parse_azure_ci_summary(
    pr_before_raw: &str,
    policies_raw: &str,
    pr_after_raw: &str,
    expected_head_sha: &str,
) -> Result<CiSummary, String> {
    // Azure exposes the PR head and policy evaluations through separate CLI
    // calls. Bracket the policy read with head reads so a push during this
    // sequence cannot attach another commit's result to the delivered SHA.
    let before_head = azure_pr_head(pr_before_raw)?;
    let after_head = azure_pr_head(pr_after_raw)?;
    if before_head != expected_head_sha || after_head != expected_head_sha {
        let actual = if before_head != expected_head_sha {
            before_head
        } else {
            after_head
        };
        return Err(format!(
            "pull request head moved while delivery was reading CI: expected {expected_head_sha}, found {actual}"
        ));
    }

    let policies: serde_json::Value = serde_json::from_str(policies_raw.trim())
        .map_err(|e| format!("could not parse `az repos pr policy list` JSON: {e}"))?;
    let items = policies
        .as_array()
        .ok_or_else(|| "`az repos pr policy list` did not return a JSON array".to_string())?;
    let mut checks = Vec::with_capacity(items.len());
    for item in items {
        let name = item
            .pointer("/configuration/type/displayName")
            .and_then(|v| v.as_str())
            .or_else(|| item.pointer("/type/displayName").and_then(|v| v.as_str()))
            .or_else(|| item.pointer("/context/name").and_then(|v| v.as_str()))
            .filter(|s| !s.trim().is_empty())
            .map(str::to_string)
            .or_else(|| {
                item.get("evaluationId")
                    .and_then(|v| v.as_str())
                    .map(|id| format!("policy {id}"))
            })
            .ok_or_else(|| "Azure DevOps policy has no name or evaluation id".to_string())?;
        let raw_state = item
            .get("status")
            .and_then(|v| v.as_str())
            .ok_or_else(|| format!("Azure DevOps policy `{name}` has no `status`"))?;
        let state = match raw_state.to_ascii_lowercase().as_str() {
            "approved" | "notapplicable" => CiState::Green,
            "queued" | "running" => CiState::Pending,
            "rejected" | "broken" => CiState::Red,
            other => {
                return Err(format!(
                    "Azure DevOps policy `{name}` has unrecognized status `{other}`"
                ))
            }
        };
        checks.push((name, state));
    }
    Ok(CiSummary::from_checks(expected_head_sha, checks))
}

/// Recover a pull request number from the URL `gh pr create` prints. `gh`
/// prints only the URL, and the number is its last path segment.
fn pr_number_from_url(url: &str) -> Result<u64, String> {
    url.trim()
        .rsplit('/')
        .find(|seg| !seg.is_empty())
        .and_then(|seg| seg.parse::<u64>().ok())
        .ok_or_else(|| format!("could not read a pull request number out of `{url}`"))
}

impl ForgeClient for GhCli {
    fn auth_status(&self) -> Result<(), ForgeError> {
        // Preserve the original GitHub preflight exactly: unlike repository-
        // scoped PR operations, `gh auth status` runs in the process cwd.
        self.runner()
            .run(Path::new("."), "gh", &gh_auth_status_args())
            .map(|_| ())
            .map_err(|e| ForgeError {
                message: format!(
                    "no usable GitHub credential: `gh auth status` failed. Authenticate with \
                 `gh auth login`, or set GH_TOKEN (or GITHUB_TOKEN) in this process's \
                 environment. Underlying error: {e}"
                ),
                stderr: e.stderr,
            })
    }

    fn list_prs_for_head(
        &self,
        dir: &Path,
        head_branch: &str,
    ) -> Result<Vec<PrRecord>, ForgeError> {
        let mut args = gh_repo_args(dir);
        args.extend(gh_pr_list_args(head_branch));
        parse_pr_list(&self.runner().run(dir, "gh", &args)?).map_err(ForgeError::local)
    }

    fn create_pr(
        &self,
        dir: &Path,
        head_branch: &str,
        base_branch: &str,
        title: &str,
        body: &str,
        draft: bool,
    ) -> Result<PrRecord, ForgeError> {
        let mut args = gh_repo_args(dir);
        args.extend(gh_pr_create_args(
            head_branch,
            base_branch,
            title,
            body,
            draft,
        ));
        let url = self.runner().run(dir, "gh", &args)?;
        Ok(PrRecord {
            number: pr_number_from_url(&url).map_err(ForgeError::local)?,
            state: PrState::Open,
            url: url.trim().to_string(),
            is_draft: draft,
            base: base_branch.to_string(),
        })
    }

    fn set_pr_body(&self, dir: &Path, number: u64, body: &str) -> Result<(), ForgeError> {
        let mut args = gh_repo_args(dir);
        args.extend([
            "pr".to_string(),
            "edit".to_string(),
            number.to_string(),
            "--body".to_string(),
            body.to_string(),
        ]);
        self.runner().run(dir, "gh", &args).map(|_| ())
    }

    fn reopen_pr(&self, dir: &Path, number: u64) -> Result<(), ForgeError> {
        let mut args = gh_repo_args(dir);
        args.extend(gh_pr_reopen_args(number));
        self.runner().run(dir, "gh", &args).map(|_| ())
    }

    fn ci_for_sha(&self, dir: &Path, number: u64, head_sha: &str) -> Result<CiSummary, ForgeError> {
        let mut args = gh_repo_args(dir);
        args.extend(gh_pr_checks_args(number));
        let raw = self.runner().run(dir, "gh", &args)?;
        parse_github_ci_summary(&raw, head_sha).map_err(ForgeError::local)
    }
}

impl ForgeClient for AzureDevOpsCli {
    fn auth_status(&self) -> Result<(), ForgeError> {
        self.runner
            .run(self.auth_dir(), "az", &az_auth_status_args())
            .map(|_| ())
            .map_err(|e| ForgeError {
                message: format!(
                    "no usable Azure DevOps credential: `az repos list` failed. Install the \
                     azure-devops extension and authenticate with `az login` or \
                     AZURE_DEVOPS_EXT_PAT. Underlying error: {e}"
                ),
                stderr: e.stderr,
            })
    }

    fn list_prs_for_head(
        &self,
        dir: &Path,
        head_branch: &str,
    ) -> Result<Vec<PrRecord>, ForgeError> {
        let raw = self.runner.run(dir, "az", &az_pr_list_args(head_branch))?;
        parse_azure_pr_list(&raw).map_err(ForgeError::local)
    }

    fn create_pr(
        &self,
        dir: &Path,
        head_branch: &str,
        base_branch: &str,
        title: &str,
        body: &str,
        draft: bool,
    ) -> Result<PrRecord, ForgeError> {
        let raw = self.runner.run(
            dir,
            "az",
            &az_pr_create_args(head_branch, base_branch, title, body, draft),
        )?;
        let value: serde_json::Value = serde_json::from_str(raw.trim()).map_err(|e| {
            ForgeError::local(format!("could not parse `az repos pr create` JSON: {e}"))
        })?;
        parse_azure_pr(&value).map_err(ForgeError::local)
    }

    fn set_pr_body(&self, dir: &Path, number: u64, body: &str) -> Result<(), ForgeError> {
        self.runner
            .run(dir, "az", &az_pr_update_args(number, body))
            .map(|_| ())
    }

    fn reopen_pr(&self, dir: &Path, number: u64) -> Result<(), ForgeError> {
        self.runner
            .run(dir, "az", &az_pr_reopen_args(number))
            .map(|_| ())
    }

    fn ci_for_sha(&self, dir: &Path, number: u64, head_sha: &str) -> Result<CiSummary, ForgeError> {
        let before = self.runner.run(dir, "az", &az_pr_show_args(number))?;
        let policies = self
            .runner
            .run(dir, "az", &az_pr_policy_list_args(number))?;
        let after = self.runner.run(dir, "az", &az_pr_show_args(number))?;
        parse_azure_ci_summary(&before, &policies, &after, head_sha).map_err(ForgeError::local)
    }
}

fn remote_host(remote_url: &str) -> Option<String> {
    let raw = remote_url.trim();
    let authority = if let Some((_, rest)) = raw.split_once("://") {
        rest.split('/').next()?
    } else {
        if raw.starts_with('/') || raw.starts_with('.') {
            return None;
        }
        let (left, _) = raw.split_once(':')?;
        // Do not mistake a Windows drive path for an scp-style remote.
        if left.len() == 1 {
            return None;
        }
        left
    };
    authority
        .rsplit('@')
        .next()?
        .split(':')
        .next()
        .filter(|host| !host.is_empty())
        .map(str::to_ascii_lowercase)
}

fn forge_kind_from_remote(
    remote_url: &str,
    override_value: Option<&str>,
) -> Result<ForgeKind, String> {
    if let Some(value) = override_value {
        return match value.trim().to_ascii_lowercase().as_str() {
            "github" | "gh" => Ok(ForgeKind::GitHub),
            "azure-devops" | "azure_devops" | "azdo" => Ok(ForgeKind::AzureDevOps),
            other => Err(format!(
                "unsupported {FORGE_OVERRIDE_ENV} value `{other}`; use `github` or `azure-devops`"
            )),
        };
    }

    let host = remote_host(remote_url).ok_or_else(|| {
        format!(
            "cannot identify a pull-request forge from origin `{remote_url}`; set \
             {FORGE_OVERRIDE_ENV}=github or {FORGE_OVERRIDE_ENV}=azure-devops"
        )
    })?;
    if matches!(host.as_str(), "github.com" | "ssh.github.com") {
        Ok(ForgeKind::GitHub)
    } else if matches!(host.as_str(), "dev.azure.com" | "ssh.dev.azure.com")
        || host.ends_with(".visualstudio.com")
    {
        Ok(ForgeKind::AzureDevOps)
    } else {
        Err(format!(
            "cannot identify a pull-request forge for origin host `{host}`; set \
             {FORGE_OVERRIDE_ENV}=github or {FORGE_OVERRIDE_ENV}=azure-devops"
        ))
    }
}

fn selected_forge(repo: &Path) -> Result<Box<dyn ForgeClient>, String> {
    let remote_url = git(repo, &["remote", "get-url", "origin"])
        .map_err(|e| format!("cannot read origin remote for forge selection: {e}"))?;
    let override_value = match std::env::var(FORGE_OVERRIDE_ENV) {
        Ok(value) => Some(value),
        Err(std::env::VarError::NotPresent) => None,
        Err(std::env::VarError::NotUnicode(_)) => {
            return Err(format!(
                "{FORGE_OVERRIDE_ENV} is not valid UTF-8; use `github` or `azure-devops`"
            ))
        }
    };
    let kind = forge_kind_from_remote(&remote_url, override_value.as_deref())?;
    tracing::debug!(forge = kind.as_str(), remote = %remote_url.trim(), "selected PR forge");
    Ok(match kind {
        ForgeKind::GitHub => Box::new(GhCli::default()),
        ForgeKind::AzureDevOps => Box::new(AzureDevOpsCli::for_repo(repo)),
    })
}

/// Reject a branch name git or a forge CLI would misread.
///
/// Argument arrays already close command injection, but they do NOT stop a name
/// beginning with `-` from being parsed as a flag, and a name beginning with `+`
/// is a force marker in a refspec. Both are refused here rather than sanitized:
/// a delivery to a silently-renamed branch is worse than a delivery that stops.
/// Reject a branch name git or `gh` would misread, BEFORE it reaches a command
/// line.
///
/// Public because the check has to run at the caller's preflight, not only
/// inside `deliver_pr_with`. `car code-task` hands the raw `--target-branch`
/// and `--pr-base` to `git fetch`, `git worktree add` and `git merge` long
/// before delivery — and `git fetch` accepts `--upload-pack=<cmd>`, so a name of
/// that shape is executed on local and ssh transports. Validating only at
/// delivery also spends an entire model session first, which defeats the
/// early-refusal design the preflight exists for.
pub fn validate_branch_name(label: &str, name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err(format!("{label} is empty"));
    }
    if name.starts_with('-') {
        return Err(format!(
            "{label} `{name}` starts with '-', which git and gh would read as a flag"
        ));
    }
    if name.starts_with(FORCE_MARKER) {
        return Err(format!(
            "{label} `{name}` starts with `{FORCE_MARKER}`, git's force marker in a refspec"
        ));
    }
    if let Some(bad) = name
        .chars()
        .find(|c| c.is_whitespace() || c.is_control() || "~^:?*[]\\".contains(*c))
    {
        return Err(format!(
            "{label} `{name}` contains `{bad}`, which is not legal in a git ref name"
        ));
    }
    // Forms git rejects that the checks above let through. Without these they
    // surface as `fatal: invalid refspec` at push time, which matches neither
    // the refused nor the moved list in `classify_push_error` and so lands on
    // the retriable default — retried forever against a name that can never
    // work.
    if name.contains("..")
        || name.ends_with('/')
        || name.starts_with('/')
        || name.ends_with(".lock")
        // Per COMPONENT, not just the whole name: git rejects `a.lock/b` too,
        // and a name that only fails at push time lands on the retriable
        // default and is retried forever against something that can never work.
        || name.split('/').any(|c| c.ends_with(".lock"))
        || name.ends_with('.')
        || name.contains("//")
        || name.contains("@{")
        || name.split('/').any(|c| c.is_empty() || c.starts_with('.'))
    {
        return Err(format!("{label} `{name}` is not a legal git ref name"));
    }
    Ok(())
}

/// Turn a raw push error into a reason plus a retriability verdict.
///
/// The two verdicts drive opposite behaviour in the orchestrator — retriable
/// means "requeue, this is not a no-progress cycle", non-retriable means "park
/// the goal and quote the failure class" — so a misread in either direction is
/// expensive, and both were happening against git's real output:
///
/// - A bare `contains("403")` matched the digits inside an echoed commit SHA, so
///   an ordinary lost race was parked. A parked goal is never relaunched, which
///   also meant the round-N+1 recovery (merging `origin/<target>` back in) never
///   got the chance to run. Now anchored on HTTP phrasing, which a branch or
///   repository name cannot produce.
/// - Git's actual permission wording is `Permission to <repo> denied to <user>`,
///   which does NOT contain the contiguous phrase `permission denied`, so a
///   genuine refusal matched nothing and fell through to the retriable default —
///   retried forever. The old test passed only because it used wording git does
///   not emit.
/// - Git's lost-race wording (`cannot lock ref …`, `! [remote rejected] …`)
///   matched none of the retriable keywords either. Note `[remote rejected]`
///   does not contain `[rejected]` — the bracket sits before `remote`. The
///   verdict was right by accident, and the reason text said nothing useful.
///
/// **Refusals are tested first**, because git prints refusal and rejection
/// wording on the same line — `! [remote rejected] main -> main (pre-receive
/// hook declined)` is a branch-protection refusal, not a race — and "do not
/// retry" has to win when both are present. Getting that order wrong is how
/// adding the race patterns would have introduced a fresh misclassification.
fn classify_push_error(err: &str) -> (String, bool) {
    let low = err.to_ascii_lowercase();

    let refused = low.contains("permission denied")
        || (low.contains("permission to") && low.contains("denied"))
        // Anchored on HTTP phrasing. Token-anchoring stopped the digits inside
        // a commit SHA matching, but a branch or repository name is delimited
        // by `-` `/` `_` `.` — so `feature-403`,
        // `goalpool/g_403` and `repo-403.git` all present `403` as a standalone
        // token, and git echoes branch and remote in every push error. Since
        // refusals are tested before races, an ordinary lost race on such a name
        // was parked as a permission refusal.
        || low.contains("returned error: 403")
        || low.contains("status code 403")
        || low.contains("http 403")
        || low.contains("error 403")
        || low.contains("authentication failed")
        // Git's credential layer emits these two SYMMETRICALLY, and which one
        // you get depends on whether the remote URL already carries a username:
        // `https://github.com/...` asks for a Username, and
        // `https://someuser@github.com/...` — the form `gh auth setup-git` and
        // most CI clones leave behind — asks for a Password. Only the first was
        // matched, so on the second shape a headless box with no credential
        // helper produced `fatal: could not read Password for
        // 'https://someuser@github.com'`, which matched nothing in `refused`
        // and nothing in `moved` and landed on the retriable default: a full
        // model session requeued every round, forever, against a credential
        // that will never appear. `gh auth status` cannot catch it either — gh
        // holds its own token, which git does not use. Whole phrases, so no
        // branch or repository name can synthesise one.
        || low.contains("could not read username")
        || low.contains("could not read password")
        // What git says once `GIT_TERMINAL_PROMPT=0` is set (see
        // [`no_interactive_prompts`]): the prompt that used to hang forever now
        // returns instantly, and it has to be read as the permanent refusal it
        // is rather than retried.
        || low.contains("terminal prompts disabled")
        // SSH's own version of the same permanence: the host key is unknown or
        // has changed, and no number of retries alters that. Without it the
        // failure fell through to the retriable default.
        || low.contains("host key verification failed")
        // 401 — a revoked or expired token. Same HTTP anchoring as 403 above,
        // for the same reason: the bare digits appear inside SHAs and branch
        // names, the phrasings do not.
        || low.contains("returned error: 401")
        || low.contains("status code 401")
        || low.contains("http 401")
        || low.contains("error 401")
        // 404 — the ordinary shape of a token that cannot see this private
        // repository. GitHub says `remote: Repository not found.` over HTTPS
        // and `ERROR: Repository not found.` over SSH, and the `gh auth status`
        // preflight cannot catch it: gh IS authenticated, it just has no access
        // HERE. It matched nothing above and nothing in `moved`, so it landed
        // on the retriable default and the orchestrator requeued a full model
        // session, forever, against a wall that cannot move. The whole phrase is
        // matched, not `not found` alone, so `fatal: pathspec … not found` and
        // friends cannot claim it.
        || low.contains("repository not found")
        // A remote that is missing or is not a repository at all. Permanent by
        // the same argument, and `classify_pr_error` already calls the same
        // condition (`no such remote`) permanent — so leaving it retriable here
        // meant the two classifiers disagreed about one fact.
        || low.contains("does not appear to be a git repository")
        // Branch protection / server-side policy. Arrives wrapped in rejection
        // wording, so it must be recognised before the race patterns below.
        || low.contains("pre-receive hook declined")
        || low.contains("protected branch")
        // `! [remote rejected]` is git's GENERIC server-refusal line; the real
        // reason is in the parentheses. These are permanent, and classifying
        // them as races told the orchestrator "requeue, nothing was judged" —
        // a full model session per round against an identical wall, forever.
        || low.contains("refusing to allow")
        || low.contains("workflow' scope")
        || low.contains("shallow update not allowed")
        || low.contains("file size limit")
        // A directory/file ref-namespace collision emits BOTH `cannot lock ref`
        // and `failed to update ref`, so without this it matches the race set
        // and retries forever. It matters specifically here: goalpool branches
        // live under a `goalpool/` prefix, so one remote branch literally named
        // `goalpool` poisons every goal. Captured from git 2.50.1:
        //   remote: error: cannot lock ref 'refs/heads/goalpool/g_1':
        //   'refs/heads/goalpool' exists; cannot create 'refs/heads/goalpool/g_1'
        || low.contains("exists; cannot create")
        // A ruleset or secret-scanning block. GitHub prints this reason inside
        // the `[remote rejected]` parentheses, and it is permanent in the
        // strongest sense — the same commit can never be pushed.
        || low.contains("push declined")
        || mentions_github_policy_code(&low);
    if refused {
        return (
            format!("push refused for credential/permission reasons: {err}"),
            false,
        );
    }

    let moved = low.contains("non-fast-forward")
        || low.contains("fetch first")
        || low.contains("[rejected]")
        || low.contains("remote rejected")
        || low.contains("cannot lock ref")
        || low.contains("failed to update ref");
    if moved {
        return (
            format!(
                "non-fast-forward: the target branch moved since this worktree was cut \
                 (lost a push race) — {err}"
            ),
            true,
        );
    }

    // Everything else (DNS, TLS, a transient 5xx from the host) is a transport
    // problem the next round may well get past.
    (err.to_string(), true)
}

/// Whether the text carries one of GitHub's `GHNNN:` push-policy codes.
///
/// This was a hand-written list that stopped at `GH008:` — which left `GH013`,
/// the code for a repository-rule violation and therefore the one secret-
/// scanning push protection emits, matching nothing in the refusal set. It then
/// fell through to `remote rejected` in the race set and was reported to the
/// orchestrator as "the branch moved, requeue": a full model session per round,
/// re-pushing the identical commit at the identical wall, forever. That is the
/// precise failure the `[remote rejected]` handling above exists to prevent, and
/// push protection is on by default for public repositories, so the gap was not
/// on an exotic path. Matching the SHAPE closes the family — including whatever
/// code GitHub adds next — rather than the members someone happened to list.
///
/// Two anchors keep it off ordinary text, because this file has twice shipped a
/// predicate that fired on a name. The digits must be followed by `:`, which
/// `validate_branch_name` rejects in a ref name, so no branch, tag or remote can
/// synthesise one; and they must be preceded by a non-alphanumeric, so no longer
/// word ending in `gh` can either.
fn mentions_github_policy_code(low: &str) -> bool {
    let bytes = low.as_bytes();
    bytes.windows(6).enumerate().any(|(i, w)| {
        w[0] == b'g'
            && w[1] == b'h'
            && w[2..5].iter().all(u8::is_ascii_digit)
            && w[5] == b':'
            && (i == 0 || !bytes[i - 1].is_ascii_alphanumeric())
    })
}

/// Classify a `gh` reconciliation failure the way [`classify_push_error`]
/// classifies a push.
///
/// Every `map_err` on the reconciliation path used to construct
/// `DeliveryFailure::Pr { retriable: true }` without looking at the reason, so
/// the stage's retriability field carried no information — the variant's own doc
/// said "usually retriable", but no code path could produce the "usually not"
/// case. Permanent GitHub refusals therefore returned exit 2, which the
/// orchestrator reads as "re-run me, nothing was judged": a whole fresh session
/// and another push to reach the identical error.
///
/// The permanent set is deliberately narrow — an unrecognised failure stays
/// retriable, because a GitHub API blip genuinely is the common case and
/// wrongly parking a healthy goal is the worse error of the two.
fn classify_pr_error(err: &str) -> (String, bool) {
    let low = err.to_ascii_lowercase();
    // NOT `already exists`. GitHub returns
    // `a pull request for branch "X" into branch "Y" already exists: #7`
    // precisely when a pull request DOES exist for that head — and reaching
    // `create_pr` at all means the listing returned nothing, so the two
    // statements contradict each other: a list/create race, replication lag
    // right after a push, or a `--head` that did not match. In every one of
    // those the commit is already pushed and a usable pull request is open, and
    // the error even names its number. It is the one candidate whose own
    // trigger condition proves the goal can progress, so parking on it strands
    // a goal at the exact moment it has succeeded.
    let permanent = low.contains("no commits between")
        || low.contains("draft pull requests are not supported")
        || low.contains("must be a collaborator")
        || low.contains("no such remote")
        || low.contains("could not resolve to a repository");
    (err.to_string(), !permanent)
}

/// Turn a failed `gh` call into a typed delivery failure.
///
/// The one place the split in [`GhError`] is spent: the verdict is taken from
/// `stderr` — what GitHub actually said — and the human-readable reason from
/// `message`. Every reconciliation `map_err` goes through here so no call site
/// can quietly hand the classifier the argv again.
fn pr_failure(e: GhError) -> DeliveryFailure {
    let (_, retriable) = classify_pr_error(&e.stderr);
    DeliveryFailure::Pr {
        reason: e.message,
        retriable,
    }
}

/// The ambiguous-delivery-head refusal, as a reason string — `None` when the
/// head is unambiguous and delivery may proceed.
///
/// `prs` is everything `gh` reports for the head branch (see
/// [`GitHubApi::list_prs_for_head`]); a pull request parks delivery when it is
/// **open** into a base other than this run's, because pushing to
/// `target_branch` adds this round's commits to it as well.
///
/// Half of [`delivery_head_refusal`], which is what callers should use; kept
/// separate so each half can be read and tested against its own rule.
///
/// OPEN pull requests only, and only into a FOREIGN base. A merged one is inert
/// — it cannot gain commits. A closed one is handled by the other half,
/// [`closed_pr_refusal`], on a different rule: it is not about where the push
/// lands but about whose decision a close is. Cross-repository pull requests
/// never reach here — [`parse_pr_list`] drops them — so a fork whose branch
/// happens to share this name cannot park a legitimate run.
pub fn ambiguous_head_refusal(
    prs: &[PrRecord],
    target_branch: &str,
    base_branch: &str,
) -> Option<String> {
    let foreign_open: Vec<&PrRecord> = prs
        .iter()
        .filter(|p| p.state == PrState::Open && p.base != base_branch)
        .collect();
    if foreign_open.is_empty() {
        return None;
    }
    let described = foreign_open
        .iter()
        .map(|p| format!("#{} into `{}`", p.number, p.base))
        .collect::<Vec<_>>()
        .join(", ");
    let numbers = foreign_open
        .iter()
        .map(|p| format!("#{}", p.number))
        .collect::<Vec<_>>()
        .join(", ");
    let plural = if foreign_open.len() == 1 { "" } else { "s" };
    Some(format!(
        "branch `{target_branch}` already has open pull request{plural} {described} — not into \
         `{base_branch}`, this run's base. Pushing this round's commits to `{target_branch}` \
         would add them to {numbers} as well, because a pull request tracks its head branch. \
         Close {numbers}, or deliver to a different --target-branch"
    ))
}

/// The closed-pull-request refusal, as a reason string — `None` when no pull
/// request into this run's base is closed-unmerged and delivery may proceed.
///
/// Half of [`delivery_head_refusal`]. Scoped to `base_branch` because that is
/// the pull request this run would otherwise reconcile: a pull request from
/// this branch into some OTHER base being closed says nothing about this run,
/// and letting it park delivery would hand any stale pull request a veto over a
/// base it does not merge into.
///
/// **An OPEN pull request into this base suppresses the veto entirely.** GitHub
/// allows at most one open pull request per (head, base) pair, so when one
/// exists it is unambiguously the one this run reconciles, and its existence is
/// a later human decision than any close: a reviewer who closes #40 as the
/// wrong approach and opens #55 from the same branch into the same base has
/// carried the work forward, not stopped it. Vetoing there would park every
/// subsequent round on the number the reviewer deliberately superseded while
/// the live pull request went stale, and the only remedies offered would be
/// reopening the dead one or renaming `--target-branch`. This keeps the rule
/// that predates car#1055 — an open pull request into the base always wins —
/// and narrows the change to the arm that used to reopen.
///
/// **The runtime never reopens a pull request it did not close** — and it never
/// closes one, so it is never the party entitled to undo a close. Until
/// car#1055 the closed case was a reopen: a reviewer who read the pull request,
/// edited the body and closed it got it reopened on the next round with their
/// edits replaced wholesale, every round, and closing it did not stop the
/// runtime. Nothing available at this seam distinguishes "closed because it
/// went stale" from "closed by a human who read it and said no", and the second
/// reading is the one that must win: a close is the cheapest stop signal a
/// person has on an agent acting under their account, and it has to hold
/// without them deleting a branch.
///
/// Cross-repository pull requests never reach here — [`parse_pr_list`] drops
/// them — so a fork's closed pull request cannot park a legitimate run.
pub fn closed_pr_refusal(
    prs: &[PrRecord],
    target_branch: &str,
    base_branch: &str,
) -> Option<String> {
    // Superseded: reconciliation would update the open one, and that is a
    // later decision than the close. See the doc comment.
    if prs
        .iter()
        .any(|p| p.state == PrState::Open && p.base == base_branch)
    {
        return None;
    }
    let closed: Vec<&PrRecord> = prs
        .iter()
        .filter(|p| p.state == PrState::ClosedUnmerged && p.base == base_branch)
        .collect();
    if closed.is_empty() {
        return None;
    }
    let numbers = closed
        .iter()
        .map(|p| format!("#{}", p.number))
        .collect::<Vec<_>>()
        .join(", ");
    let plural = if closed.len() == 1 { "" } else { "s" };
    let was = if closed.len() == 1 { "was" } else { "were" };
    Some(format!(
        "pull request{plural} {numbers} from `{target_branch}` into `{base_branch}` {was} \
         closed — the runtime does not reopen a pull request it did not close. Reopen {numbers} \
         yourself to continue on this branch, or deliver to a different --target-branch"
    ))
}

/// The whole delivery-head policy: [`ambiguous_head_refusal`] first, then
/// [`closed_pr_refusal`]. `None` when the head is clear and delivery may
/// proceed.
///
/// `prs` is everything `gh` reports for the head branch (see
/// [`GitHubApi::list_prs_for_head`]).
///
/// Split out of [`deliver_pr_with`] so `car code-task`'s own preflight can apply
/// exactly this policy — same inputs, same words — before the model session
/// starts. Both call sites are needed and neither is redundant: the early one
/// makes an already-parked head cost no session; the delivery-time one is what
/// actually stands between the push and a pull request opened or closed DURING
/// the session. Callers take this function rather than either half, so the two
/// preflights cannot drift apart one rule at a time.
pub fn delivery_head_refusal(
    prs: &[PrRecord],
    target_branch: &str,
    base_branch: &str,
) -> Option<String> {
    ambiguous_head_refusal(prs, target_branch, base_branch)
        .or_else(|| closed_pr_refusal(prs, target_branch, base_branch))
}

/// Deliver the worktree as a pull request on a stable branch.
///
/// This is the headless third delivery mode, alongside [`publish_branch`] (raw
/// repo, local branch) and [`commit_to_main`] (managed project, ff-only into
/// `main`). It commits the worktree with the same `car-coder` authorship, pushes
/// that commit onto `target_branch` on `origin`, and reconciles exactly one pull
/// request for that branch.
///
/// **This is host code and it is NOT a hole in the coder's tool policy.** The
/// model's own shell tool still refuses `git push` through
/// [`super::policy`]'s `DenyGitRemoteMutation` inspector, and that inspector is
/// deliberately untouched by this function. The distinction is who is acting:
/// the inspector chain gates commands the MODEL proposes, which is why it must
/// deny remote mutation — a model that can push can exfiltrate a repository and
/// can escape every gate downstream of it. `deliver_pr` runs after
/// `evaluate_contract` has re-executed the checks and observed their exit codes
/// itself, on a commit the runtime made, to a branch the runtime named. Nothing
/// the model said is trusted here; only what the runtime verified. Weakening the
/// inspector to let the model push would be a hole. Pushing from the runtime,
/// after verification, is the mechanism the inspector exists to protect.
///
/// The guarantees, in order of how badly their absence would hurt:
///
/// 1. **Preflight before work.** The origin URL selects GitHub or Azure DevOps,
///    then that forge's credential is checked before anything is committed or
///    pushed. An unknown host fails with the explicit override name. Missing
///    credentials produce [`DeliveryFailure::Preflight`]. This never returns
///    success without a pull request.
/// 2. **Append/fast-forward only.** The push is a plain `<sha>:refs/heads/<b>`
///    refspec with no force flag and no leading `+` anywhere on this path (a
///    test asserts that against this file's own source text). A non-fast-forward
///    rejection is a retriable [`DeliveryFailure::Push`], and the remote is left
///    exactly as it was.
/// 3. **Base-branch update policy: MERGE.** When the base moves and the branch
///    needs updating, the policy for this delivery path is `git merge
///    origin/<base>` in the worktree — **never rebase, never force**. Rebase
///    rewrites commits a reviewer may already have read and a reviewer may
///    already have commented on; force-updating the branch can silently discard
///    a round's work. Merge is additive and cannot lose a commit. Note that
///    `deliver_pr` does not itself run the merge: it delivers what is in the
///    worktree, and bringing the base in is the round orchestrator's step
///    before the session starts. The policy is stated here because this is the
///    function whose invariants it protects.
/// 4. **One pull request per (branch, base), and at most one OPEN pull request
///    per branch.** Among the pull requests whose head is `target_branch` AND
///    whose base is `base_branch`: an open one receives the push
///    ([`PrAction::Updated`]); otherwise one is created ([`PrAction::Opened`]).
///    The pair, not the head alone, is the forge's own constraint — see
///    [`PrRecord::base`] — and it is the right granularity for choosing WHICH
///    pull request to reconcile. It is not sufficient to decide whether
///    delivering is safe at all, because a pull request tracks its HEAD: the
///    push lands in every open pull request whose head is `target_branch`,
///    whatever base each merges into, and no base filter applied afterwards can
///    take that back. So a clear head is a PRECONDITION of delivery
///    ([`delivery_head_refusal`]), checked at preflight
///    ([`DeliveryFailure::Preflight`]) before anything is committed or pushed:
///    an open pull request from this branch into any OTHER base is refused,
///    naming each number and its base. A run with a changed `--pr-base`
///    therefore delivers only once the previous pull request is closed or
///    merged; with it still open the run is refused rather than quietly adding
///    this round's commits to it.
///
///    **A CLOSED pull request into this run's own base also parks the round,
///    and the runtime never reopens it.** The runtime never closes a pull
///    request, so it is never the party entitled to undo a close, and nothing
///    at this seam tells "closed because it went stale" from "closed by a
///    reviewer who read it and said no". Until car#1055 this path reopened the
///    pull request and replaced its body, so closing one did not stop the
///    runtime; now a close is a stop, and a human reopens it to continue. A
///    MERGED pull request parks nothing: it is inert, it cannot gain commits,
///    and its branch gets a fresh pull request for the next round.
/// 5. **Draft is a create-time decision only.** `draft` is honored when a pull
///    request is created and ignored otherwise. This function NEVER marks a
///    pull request ready for review — that is a car worker's judgment in a
///    later round, and a runtime that could flip it would be publishing
///    unreviewed work on the reviewer's behalf.
/// 6. **The body is refreshed, not appended.** On update the pull request body
///    is REPLACED with `body`. The body is the next fresh session's standing
///    context (it must describe the branch as it is now), and appending would
///    grow an unbounded log of stale round-by-round descriptions with the
///    current truth buried at the bottom.
///
/// The selected forge CLI runs in `repo`; git runs in `worktree`. They share
/// the same `origin` remote configuration.
pub fn deliver_pr(d: PrDelivery<'_>) -> Result<PrDeliveryOutcome, DeliveryFailure> {
    let forge = selected_forge(d.repo).map_err(|reason| DeliveryFailure::Preflight { reason })?;
    deliver_pr_with(d, forge.as_ref())
}

/// [`deliver_pr`] with the forge injected. Tests drive this with a fake;
/// production selects from `origin` plus [`FORGE_OVERRIDE_ENV`].
pub fn deliver_pr_with(
    d: PrDelivery<'_>,
    forge: &dyn ForgeClient,
) -> Result<PrDeliveryOutcome, DeliveryFailure> {
    // --- 1. Preflight: nothing is touched until this passes. ---------------
    validate_branch_name("target branch", d.target_branch)
        .map_err(|reason| DeliveryFailure::Preflight { reason })?;
    validate_branch_name("base branch", d.base_branch)
        .map_err(|reason| DeliveryFailure::Preflight { reason })?;
    // The two names were validated independently and never compared, so `main`
    // passed as BOTH. `push_args` then builds `<sha>:refs/heads/main` and the
    // model's unreviewed output is published to the base branch; reconciliation
    // only fails afterwards (`gh pr create --head main --base main` → "no
    // commits between", which `classify_pr_error` marks permanent), so the goal
    // parked with the code already on `main` and an append-only path has no way
    // to take it back. `--pr-base` defaults to the repository's default branch,
    // so `--target-branch main` alone is enough to reach it. This is the one
    // preflight refusal that protects the whole point of the mode.
    if d.target_branch == d.base_branch {
        return Err(DeliveryFailure::Preflight {
            reason: format!(
                "target branch and base branch are both `{}`; delivering would push \
                 unreviewed work directly onto the base instead of opening a pull request",
                d.target_branch
            ),
        });
    }
    forge
        .auth_status()
        .map_err(|e| DeliveryFailure::Preflight {
            reason: e.to_string(),
        })?;

    // --- 2. Preflight, continued: the head must be unambiguous. ------------
    // The listing that reconciliation needs, taken BEFORE the push, because a
    // pull request tracks its HEAD branch: every commit pushed to
    // `target_branch` appears in every open pull request whose head it is,
    // whatever base each merges into. The base filter at step 5 stops this run
    // from rewriting a foreign pull request's body, but it cannot stop the
    // push, which by then has already landed the model's commits on it — a
    // human's open pull request from this branch into `release/2.1` silently
    // gained unreviewed work while the run reported opening a different one
    // into `main`. GitHub offers no way to push to a branch without updating
    // every open pull request tracking it, so refusal is the only thing that
    // prevents it; a warning would go to the JSONL stream a machine
    // orchestrator reads, not to the person whose release pull request moved.
    //
    // The same listing also carries the CLOSED case, on a different rule: a
    // closed pull request into this run's own base is somebody's decision that
    // this branch should stop, and the runtime does not reopen it (car#1055).
    // That refusal belongs HERE, at preflight, and not at reconciliation —
    // parking at step 5 would leave the round's commits pushed onto the branch
    // with no pull request describing them.
    //
    // This is the LOAD-BEARING call: `car code-task` applies the same policy in
    // its own preflight so an already-parked head costs no model session, but a
    // pull request can be opened — or closed — while the session runs, and only
    // this one is between that pull request and the push.
    let listed = forge
        .list_prs_for_head(d.repo, d.target_branch)
        .map_err(pr_failure)?;
    if let Some(reason) = delivery_head_refusal(&listed, d.target_branch, d.base_branch) {
        return Err(DeliveryFailure::Preflight { reason });
    }

    // --- 3. Commit. --------------------------------------------------------
    let commit = match commit_worktree(d.worktree, d.intent, d.contract, d.provenance) {
        Ok(CommitOutcome::Made(c)) => c,
        Ok(CommitOutcome::NothingToCommit) => head_beyond_base(d.worktree, d.base_branch)
            .map_err(|reason| DeliveryFailure::Commit { reason })?,
        Err(reason) => return Err(DeliveryFailure::Commit { reason }),
    };

    // --- 4. Push: append-only. ---------------------------------------------
    let args = push_args(&commit, d.target_branch);
    let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
    if let Err(e) = git(d.worktree, &arg_refs) {
        let (reason, retriable) = classify_push_error(&e);
        return Err(DeliveryFailure::Push { reason, retriable });
    }

    // --- 5. Reconcile exactly one pull request for the branch. -------------
    // Over the `listed` vector step 2 already holds. The push cannot create a
    // pull request, so re-listing here would return the same set.

    // Restricted to this run's BASE. GitHub's one-open-pull-request constraint
    // is per (head, base) pair, so `--head <target>` alone can return several
    // legal pull requests that merge into different branches. Reconciling over
    // all of them took the highest-numbered one and replaced its body: a pull
    // request opened from this same branch into `release/2.1` — by a human, or
    // by a round invoked with a different `--pr-base` — captured every
    // subsequent round, had a description this run did not author overwritten,
    // and left the pull request the orchestrator tracks with a permanently stale
    // body. Step 2 now refuses the OPEN case outright, but the filter is still
    // load-bearing for the merged one: without it a pull request merged into
    // ANOTHER base would suppress creating this run's own. Filtering also makes
    // `d.base_branch` mean something on the update path, where it was validated
    // in preflight and then silently ignored.
    let existing: Vec<&PrRecord> = listed.iter().filter(|p| p.base == d.base_branch).collect();

    // No closed arm: step 2 refused every closed pull request into this base
    // before the commit, except where an OPEN one into the same base supersedes
    // it — and that one is picked up by the open arm just below, which is the
    // behaviour the close rule was never meant to change (car#1055).

    // Highest number wins when several match: it is the most recent.
    let open = existing
        .iter()
        .filter(|p| p.state == PrState::Open)
        .max_by_key(|p| p.number);

    let (record, action) = if let Some(pr) = open {
        // The push already landed on it. Refresh the body; do NOT touch its
        // draft state.
        forge
            .set_pr_body(d.repo, pr.number, d.body)
            .map_err(pr_failure)?;
        ((*pr).clone(), PrAction::Updated)
    } else {
        // None, or only merged ones — a merged pull request's work has landed,
        // so the next round needs one of its own.
        let created = forge
            .create_pr(
                d.repo,
                d.target_branch,
                d.base_branch,
                &subject_from_intent(d.intent),
                d.body,
                d.draft,
            )
            .map_err(pr_failure)?;
        (created, PrAction::Opened)
    };

    // --- 6. Read CI for the exact commit just delivered. ------------------
    // A branch can move between reconciliation and this read. The production
    // adapters validate the requested head against the observed PR head, so
    // another commit's green checks can never be reported for this one.
    // Publication has completed. An observational failure must not discard its
    // evidence or make self-heal retry delivery as if no PR had been opened.
    let ci = forge
        .ci_for_sha(d.repo, record.number, &commit)
        .unwrap_or_else(|error| {
            let mut ci = CiSummary::from_checks(&commit, Vec::new());
            ci.observation_error = Some(error.message);
            ci
        });

    Ok(PrDeliveryOutcome {
        branch: d.target_branch.to_string(),
        commit,
        pushed: true,
        pr_number: record.number,
        pr_url: record.url,
        pr_action: action,
        draft: record.is_draft,
        ci,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::coder::contract::ContractCheck;

    fn contract() -> OutcomeContract {
        OutcomeContract {
            allow_credentials: false,
            description: "x exists".into(),
            checks: vec![ContractCheck {
                name: "exists".into(),
                command: "test -f x.txt".into(),
                expect_exit_zero: true,
                output_contains: None,
                timeout_secs: 10,
                baseline: false,
                differential: None,
            }],
        }
    }

    fn placement(subtask: &str, worker: Option<&str>, remote: bool) -> car_multi::Placement {
        car_multi::Placement {
            subtask_id: subtask.to_string(),
            worker_id: worker.map(str::to_string),
            remote,
            attempts: Vec::new(),
        }
    }

    fn landed(subtask: &str, files: &[&str]) -> IntegratedSubtask {
        IntegratedSubtask {
            subtask_id: subtask.to_string(),
            files: files.iter().map(|f| f.to_string()).collect(),
        }
    }

    #[test]
    fn a_local_run_renders_no_trailers() {
        assert_eq!(placement_provenance(&[], &[], false), None);
        // A pool always seeds the local worker, so a distributed run whose every
        // peer was excluded still produces placements — all local. Announcing
        // the fleet there is the same overclaim in a quieter form.
        assert_eq!(
            placement_provenance(
                &[placement("s1", Some("this-host"), false)],
                &[landed("s1", &["a.rs"])],
                false
            ),
            None
        );
    }

    /// The defect this had to be reworked to avoid: a `Placement` is recorded
    /// when a worker RETURNS, before the per-patch gate rules on what it
    /// produced. `NothingAccepted` and `IntegrationRejected` both fall back to a
    /// locally-authored diff with the ledger fully populated, so rendering the
    /// ledger would credit peers for a commit they contributed nothing to.
    #[test]
    fn workers_that_ran_but_whose_patches_never_landed_are_not_credited() {
        let ran_everywhere = [
            placement("s1", Some("studio"), true),
            placement("s2", Some("laptop"), true),
        ];
        assert_eq!(
            placement_provenance(&ran_everywhere, &[], false),
            None,
            "nothing was integrated, so nothing may be claimed"
        );

        // And the partial case: two ran, one landed.
        let rendered =
            placement_provenance(&ran_everywhere, &[landed("s1", &["a.rs"])], false).unwrap();
        assert!(rendered.contains("worker=studio"), "{rendered}");
        assert!(
            !rendered.contains("laptop"),
            "a rejected patch's worker must not appear: {rendered}"
        );
    }

    #[test]
    fn a_locally_repaired_union_says_so_rather_than_crediting_the_fleet_alone() {
        let rendered = placement_provenance(
            &[placement("s1", Some("studio"), true)],
            &[landed("s1", &["a.rs"])],
            true,
        )
        .unwrap();
        assert!(rendered.contains("repaired-locally=true"), "{rendered}");
    }

    #[test]
    fn trailers_name_the_machine_and_the_files_it_wrote() {
        let rendered = placement_provenance(
            &[
                placement("s1", Some("studio"), true),
                placement("s2", Some("this-host"), false),
            ],
            &[landed("s1", &["src/a.rs", "src/b.rs"]), landed("s2", &[])],
            false,
        )
        .expect("a distributed run renders");

        // Parseable by `git interpret-trailers` / `%(trailers:key=…)`, rather
        // than English a downstream tool would have to regex.
        assert!(
            rendered.contains("CAR-Placement: subtask=s1 worker=studio remote=true"),
            "{rendered}"
        );
        // A subtask id is opaque model output; the files are what make the row
        // reviewable.
        assert!(rendered.contains("files=src/a.rs,src/b.rs"), "{rendered}");
        assert!(
            rendered.contains("CAR-Placement: subtask=s2 worker=this-host remote=false"),
            "{rendered}"
        );
        assert!(rendered.lines().all(|l| l.starts_with("CAR-Placement:")));
    }

    /// Peer-supplied text reaches a `git commit -m` argument. A newline could
    /// forge a paragraph or a `Signed-off-by:` in the delivered message, a NUL
    /// makes the spawn itself fail, and an unbounded value reaches `E2BIG` —
    /// turning a green, gate-passed run into an undeliverable one.
    #[test]
    fn nothing_from_a_peer_can_forge_a_trailer_or_break_the_commit() {
        let hostile = "studio\n\nSigned-off-by: Someone <x@y.z>";
        let rendered = placement_provenance(
            &[placement("s1", Some(hostile), true)],
            &[landed("s1", &["a.rs"])],
            false,
        )
        .unwrap();
        assert!(!rendered.contains('\n') || rendered.lines().count() == 1);
        assert!(
            !rendered.contains("Signed-off-by:\n") && rendered.lines().count() == 1,
            "a peer must not be able to add a paragraph: {rendered}"
        );

        // Control characters, including the NUL that fails the spawn outright.
        let rendered = placement_provenance(
            &[placement("s\u{0}1", Some("a\u{0}b"), true)],
            &[landed("s\u{0}1", &["x.rs"])],
            false,
        )
        .unwrap();
        assert!(!rendered.contains('\u{0}'), "{rendered}");

        // And bounded, so a long stderr cannot reach the argv ceiling.
        let long = "w".repeat(100_000);
        let rendered = placement_provenance(
            &[placement("s1", Some(&long), true)],
            &[landed("s1", &["x.rs"])],
            false,
        )
        .unwrap();
        assert!(rendered.len() < 400, "len {}", rendered.len());
    }

    /// The ledger's failure strings are the worst of the peer-supplied inputs —
    /// a verbatim remote response body and git stderr — and are deliberately not
    /// in the commit at all. They stay on the session record and the event.
    #[test]
    fn peer_failure_prose_never_reaches_the_commit() {
        let mut p = placement("s1", Some("studio"), true);
        p.attempts = vec![car_multi::FailedAttempt {
            worker_id: "laptop".into(),
            error: "SECRET-STDERR-abcdef".into(),
        }];
        let rendered = placement_provenance(&[p], &[landed("s1", &["a.rs"])], false).unwrap();
        assert!(!rendered.contains("SECRET-STDERR"), "{rendered}");
    }

    #[test]
    fn a_distributed_deliverys_commit_body_says_where_each_subtask_ran() {
        let repo_dir = tempfile::tempdir().unwrap();
        let repo = repo_dir.path();
        init_repo(repo);
        let ws = tempfile::tempdir().unwrap();
        git(
            repo,
            &["worktree", "add", "--detach", &ws.path().to_string_lossy()],
        )
        .unwrap();
        std::fs::write(ws.path().join("x.txt"), "made across the fleet").unwrap();

        let provenance = placement_provenance(
            &[placement("s1", Some("studio"), true)],
            &[landed("s1", &["x.txt"])],
            false,
        )
        .unwrap();
        let branch = publish_branch(
            repo,
            ws.path(),
            "fleet0001",
            "spread this out",
            &contract(),
            Some(&provenance),
        )
        .unwrap();

        // The commit is the artifact a reviewer of this branch reads, and
        // "Authored by CAR Coder" is wrong on its own for a run authored on
        // several machines.
        let message = git(repo, &["log", "-1", "--format=%B", &branch]).unwrap();
        assert!(message.contains("Authored by CAR Coder."), "{message}");
        assert!(
            message.contains("CAR-Placement: subtask=s1 worker=studio remote=true"),
            "{message}"
        );
        // The contract it already carried is still there.
        assert!(message.contains("Outcome contract"), "{message}");

        // And git itself parses it as a trailer, which is the whole reason for
        // the format — a downstream reader gets structure, not English.
        let trailers = git(
            repo,
            &[
                "log",
                "-1",
                "--format=%(trailers:key=CAR-Placement,valueonly)",
                &branch,
            ],
        )
        .unwrap();
        assert!(trailers.contains("subtask=s1 worker=studio"), "{trailers}");
    }

    /// A local delivery's commit body is byte-identical to what it was before
    /// provenance existed. `placement_provenance` returning `None` is only half
    /// the claim; this is the other half.
    #[test]
    fn a_local_deliverys_commit_body_is_unchanged() {
        let repo_dir = tempfile::tempdir().unwrap();
        let repo = repo_dir.path();
        init_repo(repo);
        let ws = tempfile::tempdir().unwrap();
        git(
            repo,
            &["worktree", "add", "--detach", &ws.path().to_string_lossy()],
        )
        .unwrap();
        std::fs::write(ws.path().join("x.txt"), "made here").unwrap();

        let branch =
            publish_branch(repo, ws.path(), "local001", "do it", &contract(), None).unwrap();
        let message = git(repo, &["log", "-1", "--format=%B", &branch]).unwrap();
        assert!(message.contains("Authored by CAR Coder."), "{message}");
        assert!(
            !message.contains("CAR-Placement"),
            "a local run claims nothing about a fleet: {message}"
        );
    }

    fn init_repo(dir: &Path) {
        for args in [
            vec!["init", "-q", "-b", "main"],
            // Git for Windows installs `core.autocrlf=true` globally, so a
            // checkout there rewrites `\n` to `\r\n` and every byte-exact
            // assertion below reads back content the test never wrote. Pin it
            // per-repo: a linked worktree shares this config file, so one
            // setting covers the workspace checkouts too.
            vec!["config", "core.autocrlf", "false"],
            vec![
                "-c",
                "user.name=t",
                "-c",
                "user.email=t@t",
                "commit",
                "-q",
                "--allow-empty",
                "-m",
                "init",
            ],
        ] {
            let out = std::process::Command::new("git")
                .arg("-C")
                .arg(dir)
                .args(&args)
                .output()
                .unwrap();
            assert!(
                out.status.success(),
                "{}",
                String::from_utf8_lossy(&out.stderr)
            );
        }
    }

    #[test]
    fn review_identity_detects_changes_without_rewriting_the_index() {
        let repo = tempfile::tempdir().unwrap();
        init_repo(repo.path());
        std::fs::write(repo.path().join("result.txt"), "verified\n").unwrap();
        git(repo.path(), &["add", "result.txt"]).unwrap();
        let identity = ReviewIdentity::read(repo.path()).unwrap();
        identity.validate(repo.path()).unwrap();

        std::fs::write(repo.path().join("result.txt"), "changed\n").unwrap();
        assert!(identity
            .validate(repo.path())
            .unwrap_err()
            .contains("changed"));
        assert_eq!(
            git(repo.path(), &["write-tree"]).unwrap().trim(),
            identity.tree
        );
        git(repo.path(), &["add", "result.txt"]).unwrap();
        assert!(identity
            .validate(repo.path())
            .unwrap_err()
            .contains("staged"));

        std::fs::write(repo.path().join("result.txt"), "verified\n").unwrap();
        git(repo.path(), &["add", "result.txt"]).unwrap();
        std::fs::write(repo.path().join("unreviewed.txt"), "extra\n").unwrap();
        assert!(identity
            .validate(repo.path())
            .unwrap_err()
            .contains("changed"));
        std::fs::remove_file(repo.path().join("unreviewed.txt")).unwrap();
        identity.validate(repo.path()).unwrap();

        git(
            repo.path(),
            &[
                "-c",
                "user.name=t",
                "-c",
                "user.email=t@t",
                "commit",
                "-qm",
                "moved HEAD",
            ],
        )
        .unwrap();
        assert!(identity
            .validate(repo.path())
            .unwrap_err()
            .contains("revision"));
    }

    #[test]
    fn checkout_snapshot_keeps_user_inputs_out_of_the_agent_diff() {
        let repo = tempfile::tempdir().unwrap();
        init_repo(repo.path());
        let identity = CheckoutIdentity::read(repo.path()).unwrap();
        assert!(snapshot_checkout(repo.path(), "clean").unwrap().is_none());
        std::fs::write(repo.path().join("personal.txt"), "staged").unwrap();
        git(repo.path(), &["add", "personal.txt"]).unwrap();
        std::fs::write(repo.path().join("personal.txt"), "current input").unwrap();
        std::fs::write(repo.path().join("AGENTS.md"), "preserve public names").unwrap();
        std::fs::write(repo.path().join(".gitignore"), "cache.txt\n").unwrap();
        std::fs::write(repo.path().join("cache.txt"), "ignored").unwrap();
        let index = git(repo.path(), &["diff", "--cached", "--binary"]).unwrap();
        let base = snapshot_checkout(repo.path(), "snapshot-test")
            .unwrap()
            .unwrap();
        let dir = tempfile::tempdir().unwrap();
        let ws = car_multi::AgentWorkspace::provision(
            &car_multi::WorkspaceConfig::git_worktree_at(repo.path(), dir.path()).with_rev(base),
            "task",
        )
        .unwrap();
        assert_eq!(
            std::fs::read_to_string(ws.path().join("personal.txt")).unwrap(),
            "current input"
        );
        assert!(ws.path().join("AGENTS.md").exists());
        assert!(!ws.path().join("cache.txt").exists());
        assert!(git(ws.path(), &["status", "--porcelain"])
            .unwrap()
            .is_empty());
        std::fs::write(
            ws.path().join("personal.txt"),
            "current input plus agent edit",
        )
        .unwrap();
        let diff = git(ws.path(), &["diff", "HEAD"]).unwrap();
        assert!(diff.contains("-current input"));
        assert!(!diff.contains("AGENTS.md"));
        apply_to_checkout(
            repo.path(),
            ws.path(),
            "snapshot-test",
            &identity,
            "extend input",
            &contract(),
            None,
        )
        .unwrap();
        assert_eq!(CheckoutIdentity::read(repo.path()).unwrap(), identity);
        assert_eq!(
            git(repo.path(), &["diff", "--cached", "--binary"]).unwrap(),
            index
        );
        assert_eq!(
            std::fs::read_to_string(repo.path().join("personal.txt")).unwrap(),
            "current input plus agent edit"
        );
        assert!(git(repo.path(), &["branch", "--list", "car/coder/*"])
            .unwrap()
            .is_empty());
    }

    #[test]
    fn checkout_delivery_preserves_dirty_files_index_and_branch_and_can_retry() {
        let repo = tempfile::tempdir().unwrap();
        init_repo(repo.path());
        let identity = CheckoutIdentity::read(repo.path()).unwrap();
        let base = tempfile::tempdir().unwrap();
        let ws = car_multi::AgentWorkspace::provision(
            &car_multi::WorkspaceConfig::git_worktree_at(repo.path(), base.path()),
            "checkout-test",
        )
        .unwrap();
        std::fs::write(repo.path().join("personal.txt"), "staged user edit").unwrap();
        git(repo.path(), &["add", "personal.txt"]).unwrap();
        std::fs::write(repo.path().join("personal.txt"), "unstaged user edit").unwrap();
        std::fs::write(repo.path().join("untracked.txt"), "user work").unwrap();
        let index = git(repo.path(), &["diff", "--cached", "--binary"]).unwrap();
        let branches = git(repo.path(), &["for-each-ref", "refs/heads"]).unwrap();
        std::fs::write(ws.path().join("result.txt"), "reviewed change").unwrap();
        std::fs::write(ws.path().join("legacy.txt"), b"legacy \xff\n").unwrap();
        let (commit, already) = apply_to_checkout(
            repo.path(),
            ws.path(),
            "coder-checkout-test",
            &identity,
            "add result",
            &contract(),
            None,
        )
        .unwrap();
        assert!(!already);
        assert_eq!(
            std::fs::read(repo.path().join("legacy.txt")).unwrap(),
            b"legacy \xff\n"
        );
        assert_eq!(CheckoutIdentity::read(repo.path()).unwrap(), identity);
        assert_eq!(
            git(repo.path(), &["diff", "--cached", "--binary"]).unwrap(),
            index
        );
        assert_eq!(
            git(repo.path(), &["for-each-ref", "refs/heads"]).unwrap(),
            branches
        );
        assert_eq!(
            std::fs::read_to_string(repo.path().join("personal.txt")).unwrap(),
            "unstaged user edit"
        );
        assert_eq!(
            std::fs::read_to_string(repo.path().join("untracked.txt")).unwrap(),
            "user work"
        );
        assert_eq!(
            std::fs::read_to_string(repo.path().join("result.txt")).unwrap(),
            "reviewed change"
        );
        assert_eq!(
            git(repo.path(), &["show", &format!("{commit}:result.txt")]).unwrap(),
            "reviewed change"
        );
        assert!(
            apply_to_checkout(
                repo.path(),
                ws.path(),
                "coder-checkout-test",
                &identity,
                "add result",
                &contract(),
                None,
            )
            .unwrap()
            .1
        );
    }

    #[test]
    fn checkout_delivery_conflict_does_not_apply_a_partial_patch() {
        let repo = tempfile::tempdir().unwrap();
        init_repo(repo.path());
        let identity = CheckoutIdentity::read(repo.path()).unwrap();
        let base = tempfile::tempdir().unwrap();
        let ws = car_multi::AgentWorkspace::provision(
            &car_multi::WorkspaceConfig::git_worktree_at(repo.path(), base.path()),
            "conflict-test",
        )
        .unwrap();
        std::fs::write(ws.path().join("a-new.txt"), "must not partially apply").unwrap();
        std::fs::write(ws.path().join("z-conflict.txt"), "agent version").unwrap();
        std::fs::write(repo.path().join("z-conflict.txt"), "user version").unwrap();
        assert!(apply_to_checkout(
            repo.path(),
            ws.path(),
            "coder-conflict",
            &identity,
            "add files",
            &contract(),
            None,
        )
        .is_err());
        assert!(!repo.path().join("a-new.txt").exists());
        assert_eq!(
            std::fs::read_to_string(repo.path().join("z-conflict.txt")).unwrap(),
            "user version"
        );
        assert!(ws.path().join("a-new.txt").exists());
        let changed = CheckoutIdentity {
            head: "different".into(),
            reference: identity.reference,
        };
        assert!(apply_to_checkout(
            repo.path(),
            ws.path(),
            "coder-conflict",
            &changed,
            "add files",
            &contract(),
            None,
        )
        .unwrap_err()
        .contains("checkout revision or branch changed"));
    }

    #[test]
    fn publishes_branch_without_touching_user_checkout() {
        let repo_dir = tempfile::tempdir().unwrap();
        let repo = repo_dir.path();
        init_repo(repo);

        // Provision a worktree the way a session does.
        let wt_base = tempfile::tempdir().unwrap();
        let config = car_multi::WorkspaceConfig::git_worktree_at(repo, wt_base.path());
        let ws = car_multi::AgentWorkspace::provision(&config, "coder-merge-test").unwrap();

        std::fs::write(ws.path().join("x.txt"), "made by coder").unwrap();
        let branch = publish_branch(
            repo,
            ws.path(),
            "abc12345",
            "create x.txt with content",
            &contract(),
            None,
        )
        .unwrap();
        assert_eq!(branch, "car/coder/abc12345");

        // The branch exists in the user's repo and contains the file…
        let show = git(repo, &["show", &format!("{branch}:x.txt")]).unwrap();
        assert_eq!(show, "made by coder");
        // …attributed to the coder…
        let author = git(repo, &["log", "-1", "--format=%an", &branch]).unwrap();
        assert_eq!(author.trim(), "car-coder");
        // …and the user's checkout is untouched.
        let status = git(repo, &["status", "--porcelain"]).unwrap();
        assert!(status.is_empty(), "user checkout dirtied: {status}");
        assert!(!repo.join("x.txt").exists());
    }

    #[test]
    fn clean_worktree_refuses_to_publish() {
        let repo_dir = tempfile::tempdir().unwrap();
        init_repo(repo_dir.path());
        let wt_base = tempfile::tempdir().unwrap();
        let config = car_multi::WorkspaceConfig::git_worktree_at(repo_dir.path(), wt_base.path());
        let ws = car_multi::AgentWorkspace::provision(&config, "coder-clean-test").unwrap();

        let err = publish_branch(repo_dir.path(), ws.path(), "def", "noop", &contract(), None)
            .unwrap_err();
        assert!(err.contains("no changes"), "{err}");
    }

    #[test]
    fn long_intent_is_truncated_in_subject() {
        let repo_dir = tempfile::tempdir().unwrap();
        let repo = repo_dir.path();
        init_repo(repo);
        let wt_base = tempfile::tempdir().unwrap();
        let config = car_multi::WorkspaceConfig::git_worktree_at(repo, wt_base.path());
        let ws = car_multi::AgentWorkspace::provision(&config, "coder-long-test").unwrap();
        std::fs::write(ws.path().join("y.txt"), "y").unwrap();

        let long_intent = "a very ".repeat(40) + "long intent";
        let branch =
            publish_branch(repo, ws.path(), "fff", &long_intent, &contract(), None).unwrap();
        let subject = git(repo, &["log", "-1", "--format=%s", &branch]).unwrap();
        assert!(subject.trim().len() <= 72);
        assert!(subject.contains("..."));
    }

    #[test]
    fn commit_to_main_fast_forwards_the_checkout() {
        let repo_dir = tempfile::tempdir().unwrap();
        let repo = repo_dir.path();
        init_repo(repo);
        let wt_base = tempfile::tempdir().unwrap();
        let config = car_multi::WorkspaceConfig::git_worktree_at(repo, wt_base.path());
        let ws = car_multi::AgentWorkspace::provision(&config, "coder-main-test").unwrap();
        std::fs::write(ws.path().join("z.txt"), "managed").unwrap();

        let commit = commit_to_main(repo, ws.path(), "add z", &contract(), None).unwrap();
        // main fast-forwarded to the commit; the file is in the repo checkout.
        let head = git(repo, &["rev-parse", "HEAD"]).unwrap();
        assert_eq!(head.trim(), commit);
        assert_eq!(
            std::fs::read_to_string(repo.join("z.txt")).unwrap(),
            "managed"
        );
        // No coder branch.
        assert!(git(repo, &["branch", "--list", "car/coder/*"])
            .unwrap()
            .is_empty());
    }

    #[test]
    fn commit_to_main_errors_when_main_moved() {
        let repo_dir = tempfile::tempdir().unwrap();
        let repo = repo_dir.path();
        init_repo(repo);
        let wt_base = tempfile::tempdir().unwrap();
        let config = car_multi::WorkspaceConfig::git_worktree_at(repo, wt_base.path());
        let ws = car_multi::AgentWorkspace::provision(&config, "coder-moved-test").unwrap();
        std::fs::write(ws.path().join("a.txt"), "from session").unwrap();

        // Something commits to main AFTER the worktree was provisioned, so the
        // worktree's commit is no longer a fast-forward of main.
        std::fs::write(repo.join("b.txt"), "concurrent").unwrap();
        for args in [
            vec!["-c", "user.name=t", "-c", "user.email=t@t", "add", "-A"],
            vec![
                "-c",
                "user.name=t",
                "-c",
                "user.email=t@t",
                "commit",
                "-q",
                "-m",
                "concurrent",
            ],
        ] {
            assert!(std::process::Command::new("git")
                .arg("-C")
                .arg(repo)
                .args(&args)
                .output()
                .unwrap()
                .status
                .success());
        }

        let err = commit_to_main(repo, ws.path(), "add a", &contract(), None).unwrap_err();
        assert!(err.contains("fast-forward"), "{err}");
    }

    // --- Rename-aware, byte-safe changed paths ---------------------------

    /// **The bypass this parser exists to close.** Under `--name-only`, git
    /// reports only a rename's destination, so moving a file OUT of a directory
    /// erased every trace of that directory from the change record. Anything
    /// reasoning about which paths a session touched was told a rename is a
    /// creation.
    #[test]
    fn a_rename_reports_both_endpoints_not_just_the_destination() {
        let paths = parse_name_status_z("R100\0secrets/key.txt\0public_key.txt\0");
        assert!(
            paths.contains(&"secrets/key.txt".to_string()),
            "the source directory must not vanish: {paths:?}"
        );
        assert!(paths.contains(&"public_key.txt".to_string()), "{paths:?}");
        assert_eq!(paths.len(), 2);
    }

    /// A copy carries the same three-field shape as a rename.
    #[test]
    fn a_copy_also_reports_both_endpoints() {
        let paths = parse_name_status_z("C75\0src/a.rs\0src/b.rs\0");
        assert_eq!(paths, vec!["src/a.rs".to_string(), "src/b.rs".to_string()]);
    }

    /// Ordinary two-field entries, and the mixed stream — a rename's extra
    /// field must not desynchronize the ones that follow it.
    #[test]
    fn mixed_entries_stay_in_sync_after_a_rename() {
        let paths = parse_name_status_z("M\0src/a.rs\0R100\0old/x.rs\0new/x.rs\0A\0src/z.rs\0");
        assert_eq!(
            paths,
            vec![
                "new/x.rs".to_string(),
                "old/x.rs".to_string(),
                "src/a.rs".to_string(),
                "src/z.rs".to_string(),
            ]
        );
    }

    /// A newline inside a filename must not be able to forge an entry — the
    /// reason for `-z` over line-splitting.
    #[test]
    fn a_newline_in_a_filename_does_not_forge_an_entry() {
        let paths = parse_name_status_z("A\0we\nird.txt\0");
        assert_eq!(paths, vec!["we\nird.txt".to_string()]);
    }

    #[test]
    fn an_empty_diff_yields_no_paths() {
        assert!(parse_name_status_z("").is_empty());
    }

    /// `T` (type change, e.g. file -> symlink) and `U` (unmerged) are
    /// single-path entries. Verified against real git; pinned here because the
    /// whole parser rests on "only R and C carry two paths".
    #[test]
    fn type_change_and_unmerged_are_single_path_entries() {
        assert_eq!(
            parse_name_status_z("T\0src/link.txt\0M\0src/after.rs\0"),
            vec!["src/after.rs".to_string(), "src/link.txt".to_string()]
        );
        assert_eq!(
            parse_name_status_z("U\0conflict.txt\0"),
            vec!["conflict.txt".to_string()]
        );
    }

    /// **The desync guard.** A field that is not a status means git's format
    /// moved under us; continuing would read paths as statuses and emit
    /// plausible-looking fiction onto a reviewer's approval screen. Bail.
    #[test]
    fn an_unrecognized_status_bails_instead_of_desynchronizing() {
        // `Z9` is not in git's closed status set.
        assert!(parse_name_status_z("Z9\0a.txt\0b.txt\0").is_empty());
        // A well-formed prefix is kept; the garbage tail is dropped, not guessed.
        assert_eq!(
            parse_name_status_z("M\0good.rs\0Z9\0a.txt\0"),
            vec!["good.rs".to_string()]
        );
    }

    /// A rename whose destination field never arrived is a corrupt stream, not
    /// an entry to swallow.
    #[test]
    fn a_rename_missing_its_destination_bails() {
        assert_eq!(
            parse_name_status_z("R100\0only-one.txt\0"),
            vec!["only-one.txt".to_string()]
        );
    }

    /// End-to-end against real git: the rename bypass, reproduced and closed.
    #[test]
    fn stage_and_diff_sees_a_renamed_out_of_directory_source() {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path();
        for args in [
            vec!["init", "-q", "."],
            vec!["config", "user.email", "t@t"],
            vec!["config", "user.name", "t"],
        ] {
            git(repo, &args).unwrap();
        }
        std::fs::create_dir(repo.join("secrets")).unwrap();
        std::fs::write(repo.join("secrets/key.txt"), "k").unwrap();
        git(repo, &["add", "-A"]).unwrap();
        git(repo, &["commit", "-qm", "init"]).unwrap();
        std::fs::rename(repo.join("secrets/key.txt"), repo.join("public_key.txt")).unwrap();

        let diff = stage_and_diff(repo, 64 * 1024).unwrap();
        assert!(
            diff.changed_paths.iter().any(|p| p.starts_with("secrets/")),
            "the source directory must appear: {:?}",
            diff.changed_paths
        );
        // Exactly the two endpoints — a parser that emitted status letters as
        // paths would also satisfy the assertion above.
        assert_eq!(
            diff.changed_paths,
            vec!["public_key.txt".to_string(), "secrets/key.txt".to_string()],
            "both endpoints, and nothing else"
        );
    }

    // --- PR delivery -----------------------------------------------------

    use std::path::PathBuf;
    use std::sync::Mutex;

    /// This file's own source text, for the guard tests below. The point of a
    /// source-level guard is that it fails on the WRITING of a forbidden token,
    /// not on some execution path a future test might not cover.
    const MERGE_RS_SOURCE: &str = include_str!("merge.rs");

    #[derive(Debug, Clone, PartialEq, Eq)]
    struct ForgeCall {
        program: String,
        args: Vec<String>,
    }

    struct FakeForgeCommands {
        responses: Mutex<std::collections::VecDeque<Result<String, ForgeError>>>,
        calls: Mutex<Vec<ForgeCall>>,
    }

    impl FakeForgeCommands {
        fn answers(responses: &[&str]) -> Arc<Self> {
            Arc::new(Self {
                responses: Mutex::new(responses.iter().map(|s| Ok((*s).to_string())).collect()),
                calls: Mutex::new(Vec::new()),
            })
        }

        fn calls(&self) -> Vec<ForgeCall> {
            self.calls.lock().unwrap().clone()
        }
    }

    impl ForgeCommandRunner for FakeForgeCommands {
        fn run(&self, _dir: &Path, program: &str, args: &[String]) -> Result<String, ForgeError> {
            self.calls.lock().unwrap().push(ForgeCall {
                program: program.to_string(),
                args: args.to_vec(),
            });
            self.responses
                .lock()
                .unwrap()
                .pop_front()
                .expect("a scripted forge response")
        }
    }

    fn repo_with_remote(remote: &str) -> tempfile::TempDir {
        let repo = tempfile::tempdir().unwrap();
        git(repo.path(), &["init", "-q"]).unwrap();
        git(repo.path(), &["remote", "add", "origin", remote]).unwrap();
        repo
    }

    #[test]
    fn remote_url_selects_github_or_azure_and_unknown_names_the_override() {
        for remote in [
            "https://github.com/acme/widgets.git",
            "git@github.com:acme/widgets.git",
        ] {
            assert_eq!(
                forge_kind_from_remote(remote, None).unwrap(),
                ForgeKind::GitHub
            );
        }
        for remote in [
            "https://dev.azure.com/acme/platform/_git/widgets",
            "git@ssh.dev.azure.com:v3/acme/platform/widgets",
            "https://acme.visualstudio.com/platform/_git/widgets",
        ] {
            assert_eq!(
                forge_kind_from_remote(remote, None).unwrap(),
                ForgeKind::AzureDevOps
            );
        }
        let error =
            forge_kind_from_remote("ssh://git@git.example.test/acme/widgets", None).unwrap_err();
        assert!(error.contains(FORGE_OVERRIDE_ENV), "{error}");
        assert_eq!(
            forge_kind_from_remote(
                "ssh://git@git.example.test/acme/widgets",
                Some("azure-devops")
            )
            .unwrap(),
            ForgeKind::AzureDevOps
        );
    }

    #[test]
    fn github_client_uses_the_existing_cli_contract_through_a_fake_runner() {
        let repo = repo_with_remote("https://github.com/acme/widgets.git");
        let runner = FakeForgeCommands::answers(&[
            "",
            r#"[{"number":7,"state":"OPEN","url":"https://github.com/acme/widgets/pull/7","isDraft":false,"isCrossRepository":false,"baseRefName":"main"}]"#,
            "https://github.com/acme/widgets/pull/8",
            "",
            "",
            r#"{"headRefOid":"abc123","statusCheckRollup":[{"__typename":"CheckRun","name":"test","status":"COMPLETED","conclusion":"SUCCESS"},{"__typename":"StatusContext","context":"legacy","state":"PENDING"}]}"#,
        ]);
        let github = GhCli::with_runner(runner.clone());

        github.auth_status().unwrap();
        let listed = github.list_prs_for_head(repo.path(), "car/work").unwrap();
        assert_eq!(listed[0].number, 7);
        let created = github
            .create_pr(repo.path(), "car/work", "main", "title", "body", true)
            .unwrap();
        assert_eq!(created.number, 8);
        github.set_pr_body(repo.path(), 7, "new body").unwrap();
        github.reopen_pr(repo.path(), 7).unwrap();
        let ci = github.ci_for_sha(repo.path(), 7, "abc123").unwrap();
        assert_eq!(ci.state, CiState::Pending);
        assert_eq!(ci.checks.len(), 2);

        let calls = runner.calls();
        assert_eq!(calls.len(), 6);
        assert!(calls.iter().all(|call| call.program == "gh"));
        assert_eq!(calls[0].args, gh_auth_status_args());
        let mut expected_list = gh_repo_args(repo.path());
        expected_list.extend(gh_pr_list_args("car/work"));
        assert_eq!(calls[1].args, expected_list);
        let mut expected_create = gh_repo_args(repo.path());
        expected_create.extend(gh_pr_create_args("car/work", "main", "title", "body", true));
        assert_eq!(calls[2].args, expected_create);
        let mut expected_edit = gh_repo_args(repo.path());
        expected_edit.extend([
            "pr".to_string(),
            "edit".to_string(),
            "7".to_string(),
            "--body".to_string(),
            "new body".to_string(),
        ]);
        assert_eq!(calls[3].args, expected_edit);
        let mut expected_reopen = gh_repo_args(repo.path());
        expected_reopen.extend(gh_pr_reopen_args(7));
        assert_eq!(calls[4].args, expected_reopen);
        let mut expected_checks = gh_repo_args(repo.path());
        expected_checks.extend(gh_pr_checks_args(7));
        assert_eq!(calls[5].args, expected_checks);
    }

    #[test]
    fn azure_client_creates_lists_updates_and_reads_checks_through_a_fake_runner() {
        let repo = repo_with_remote("https://dev.azure.com/acme/platform/_git/widgets");
        let listed = r#"[{"pullRequestId":41,"status":"active","isDraft":false,"targetRefName":"refs/heads/main","_links":{"web":{"href":"https://dev.azure.com/acme/platform/_git/widgets/pullrequest/41"}}}]"#;
        let created = r#"{"pullRequestId":42,"status":"active","isDraft":true,"targetRefName":"refs/heads/main","repository":{"webUrl":"https://dev.azure.com/acme/platform/_git/widgets"}}"#;
        let shown = r#"{"lastMergeSourceCommit":{"commitId":"def456"}}"#;
        let policies = r#"[
            {"status":"approved","configuration":{"type":{"displayName":"Build"}}},
            {"status":"running","configuration":{"type":{"displayName":"Security"}}},
            {"status":"rejected","configuration":{"type":{"displayName":"Windows"}}}
        ]"#;
        let runner =
            FakeForgeCommands::answers(&["[]", listed, created, "", "", shown, policies, shown]);
        let azure = AzureDevOpsCli::with_runner(runner.clone(), repo.path());

        azure.auth_status().unwrap();
        let prs = azure.list_prs_for_head(repo.path(), "car/work").unwrap();
        assert_eq!(prs[0].number, 41);
        assert_eq!(prs[0].base, "main");
        let pr = azure
            .create_pr(repo.path(), "car/work", "main", "title", "body", true)
            .unwrap();
        assert_eq!(pr.number, 42);
        assert!(pr.is_draft);
        assert_eq!(
            pr.url,
            "https://dev.azure.com/acme/platform/_git/widgets/pullrequest/42"
        );
        azure.set_pr_body(repo.path(), 41, "new body").unwrap();
        azure.reopen_pr(repo.path(), 41).unwrap();
        let ci = azure.ci_for_sha(repo.path(), 41, "def456").unwrap();
        assert_eq!(ci.state, CiState::Red);
        assert_eq!(
            ci.checks,
            vec![
                CiCheck {
                    name: "Build".into(),
                    state: CiState::Green,
                },
                CiCheck {
                    name: "Security".into(),
                    state: CiState::Pending,
                },
                CiCheck {
                    name: "Windows".into(),
                    state: CiState::Red,
                },
            ]
        );

        let calls = runner.calls();
        assert_eq!(calls.len(), 8);
        assert!(calls.iter().all(|call| call.program == "az"));
        assert_eq!(calls[0].args, az_auth_status_args());
        assert_eq!(calls[1].args, az_pr_list_args("car/work"));
        assert_eq!(
            calls[2].args,
            az_pr_create_args("car/work", "main", "title", "body", true)
        );
        assert_eq!(calls[3].args, az_pr_update_args(41, "new body"));
        assert_eq!(calls[4].args, az_pr_reopen_args(41));
        assert_eq!(calls[5].args, az_pr_show_args(41));
        assert_eq!(calls[6].args, az_pr_policy_list_args(41));
        assert_eq!(calls[7].args, az_pr_show_args(41));
    }

    #[test]
    fn azure_check_read_refuses_a_moved_head() {
        let error = parse_azure_ci_summary(
            r#"{"lastMergeSourceCommit":{"commitId":"delivered"}}"#,
            "[]",
            r#"{"lastMergeSourceCommit":{"commitId":"newer"}}"#,
            "delivered",
        )
        .unwrap_err();
        assert!(error.contains("expected delivered, found newer"), "{error}");
    }

    /// A scriptable stand-in for the `gh` CLI. Records every call so a test can
    /// assert on what delivery asked GitHub to do, not just on what came back.
    struct FakeGh {
        auth: Result<(), GhError>,
        prs: Mutex<Vec<PrRecord>>,
        calls: Mutex<Vec<String>>,
        next_number: Mutex<u64>,
        /// Per-method failure knobs. Reconciliation has three distinct `gh`
        /// seams and only `auth_status` could be made to fail, so the
        /// retriability each seam attaches to a failure — the whole reason
        /// `DeliveryFailure::Pr` carries the flag — was never exercised end to
        /// end. Each holds the STDERR the fake reports; the fake builds the
        /// human-readable half itself, so a test cannot accidentally hand the
        /// classifier a message.
        fail_list: Mutex<Option<String>>,
        fail_create: Mutex<Option<String>>,
        fail_set_body: Mutex<Option<String>>,
        fail_ci: Mutex<Option<String>>,
        checks: Mutex<Vec<(String, CiState)>>,
    }

    /// Production lines carrying a char-literal plus — a force refspec waiting
    /// to be interpolated. Returns 1-based line numbers.
    ///
    /// A FUNCTION rather than an inline loop so it can be pointed at sources
    /// that do violate it. Lives in the test module because its own needle is
    /// spelled with the very character it bans, and a production copy would
    /// report itself.
    ///
    /// Scoped to production: the test module below legitimately constructs
    /// `+`-prefixed names to prove `validate_branch_name` rejects them. The one
    /// production line allowed to name the character is [`FORCE_MARKER`]'s
    /// definition.
    fn force_char_offenders(src: &str) -> Vec<usize> {
        let production = src.split_once("mod tests {").map(|(h, _)| h).unwrap_or(src);
        let needle: String = ['\'', '+', '\''].iter().collect();
        production
            .lines()
            .enumerate()
            .filter(|(_, line)| line.contains(needle.as_str()))
            .filter(|(_, line)| !line.contains("FORCE_MARKER: char"))
            .map(|(i, _)| i + 1)
            .collect()
    }

    /// The error shape a real `gh` failure has: a message that names the
    /// command (and may echo argv) plus the remote's own stderr.
    fn gh_err(message: &str, stderr: &str) -> GhError {
        GhError {
            message: message.to_string(),
            stderr: stderr.to_string(),
        }
    }

    impl FakeGh {
        fn ok() -> Self {
            Self {
                auth: Ok(()),
                prs: Mutex::new(Vec::new()),
                calls: Mutex::new(Vec::new()),
                next_number: Mutex::new(101),
                fail_list: Mutex::new(None),
                fail_create: Mutex::new(None),
                fail_set_body: Mutex::new(None),
                fail_ci: Mutex::new(None),
                checks: Mutex::new(vec![
                    ("lint".to_string(), CiState::Green),
                    ("test".to_string(), CiState::Green),
                ]),
            }
        }

        fn no_credential() -> Self {
            Self {
                auth: Err(gh_err(
                    "no usable GitHub credential: `gh auth status` failed. Authenticate with \
                     `gh auth login`, or set GH_TOKEN (or GITHUB_TOKEN)",
                    "gh: To get started with GitHub CLI, please run: gh auth login",
                )),
                ..Self::ok()
            }
        }

        fn with_prs(prs: Vec<PrRecord>) -> Self {
            Self {
                prs: Mutex::new(prs),
                ..Self::ok()
            }
        }

        fn with_checks(checks: Vec<(&str, CiState)>) -> Self {
            let me = Self::ok();
            *me.checks.lock().unwrap() = checks
                .into_iter()
                .map(|(name, state)| (name.to_string(), state))
                .collect();
            me
        }

        /// `gh pr edit --body` fails with this stderr.
        fn failing_set_body(stderr: &str) -> Self {
            let me = Self::ok();
            *me.fail_set_body.lock().unwrap() = Some(stderr.to_string());
            me
        }

        fn calls(&self) -> Vec<String> {
            self.calls.lock().unwrap().clone()
        }
    }

    /// The message half a real `gh` failure carries — command shape plus
    /// stderr. Built here so the fake's message is never the bare stderr, which
    /// would make "the classifier read stderr" trivially true.
    fn fake_gh_failure(command: &str, stderr: &str, body: &str) -> GhError {
        gh_err(
            &format!("gh {command} --body {body} failed: {stderr}"),
            stderr,
        )
    }

    impl GitHubApi for FakeGh {
        fn auth_status(&self) -> Result<(), GhError> {
            self.calls.lock().unwrap().push("auth_status".into());
            self.auth.clone().map_err(|e| e.clone())
        }

        fn list_prs_for_head(&self, _dir: &Path, head: &str) -> Result<Vec<PrRecord>, GhError> {
            self.calls.lock().unwrap().push(format!("list {head}"));
            if let Some(stderr) = self.fail_list.lock().unwrap().clone() {
                return Err(gh_err(&format!("gh pr list failed: {stderr}"), &stderr));
            }
            Ok(self.prs.lock().unwrap().clone())
        }

        fn create_pr(
            &self,
            _dir: &Path,
            head: &str,
            base: &str,
            title: &str,
            body: &str,
            draft: bool,
        ) -> Result<PrRecord, GhError> {
            self.calls.lock().unwrap().push(format!(
                "create head={head} base={base} draft={draft} title={title} body={body}"
            ));
            if let Some(stderr) = self.fail_create.lock().unwrap().clone() {
                return Err(fake_gh_failure("pr create", &stderr, body));
            }
            let mut n = self.next_number.lock().unwrap();
            let record = PrRecord {
                number: *n,
                state: PrState::Open,
                url: format!("https://github.com/acme/repo/pull/{n}"),
                is_draft: draft,
                base: base.to_string(),
            };
            *n += 1;
            self.prs.lock().unwrap().push(record.clone());
            Ok(record)
        }

        fn set_pr_body(&self, _dir: &Path, number: u64, body: &str) -> Result<(), GhError> {
            self.calls
                .lock()
                .unwrap()
                .push(format!("set_body {number} {body}"));
            if let Some(stderr) = self.fail_set_body.lock().unwrap().clone() {
                return Err(fake_gh_failure("pr edit", &stderr, body));
            }
            Ok(())
        }

        fn reopen_pr(&self, _dir: &Path, number: u64) -> Result<(), GhError> {
            self.calls.lock().unwrap().push(format!("reopen {number}"));
            Ok(())
        }

        fn ci_for_sha(
            &self,
            _dir: &Path,
            number: u64,
            head_sha: &str,
        ) -> Result<CiSummary, GhError> {
            self.calls
                .lock()
                .unwrap()
                .push(format!("ci {number} {head_sha}"));
            if let Some(stderr) = self.fail_ci.lock().unwrap().clone() {
                return Err(gh_err(&format!("gh pr view failed: {stderr}"), &stderr));
            }
            Ok(CiSummary::from_checks(
                head_sha,
                self.checks.lock().unwrap().clone(),
            ))
        }
    }

    /// A bare `origin` plus a working clone that pushes to it — the smallest
    /// thing that can tell a fast-forward from a rejection for real.
    struct Fixture {
        origin: PathBuf,
        repo: PathBuf,
        wt_base: PathBuf,
        _dirs: Vec<tempfile::TempDir>,
    }

    fn fixture() -> Fixture {
        let origin_dir = tempfile::tempdir().unwrap();
        let repo_dir = tempfile::tempdir().unwrap();
        let wt_dir = tempfile::tempdir().unwrap();
        let origin = origin_dir.path().to_path_buf();
        let repo = repo_dir.path().to_path_buf();

        git(&origin, &["init", "-q", "--bare", "-b", "main"]).unwrap();
        git(&repo, &["init", "-q", "-b", "main"]).unwrap();
        git(&repo, &["config", "user.name", "t"]).unwrap();
        git(&repo, &["config", "user.email", "t@t"]).unwrap();
        std::fs::write(repo.join("README.md"), "seed").unwrap();
        git(&repo, &["add", "-A"]).unwrap();
        git(&repo, &["commit", "-qm", "seed"]).unwrap();
        git(
            &repo,
            &["remote", "add", "origin", origin.to_str().unwrap()],
        )
        .unwrap();
        git(&repo, &["push", "-q", "origin", "main"]).unwrap();

        Fixture {
            origin,
            repo,
            wt_base: wt_dir.path().to_path_buf(),
            _dirs: vec![origin_dir, repo_dir, wt_dir],
        }
    }

    impl Fixture {
        /// Cut a session worktree from `from_ref`, the way a round does.
        fn cut(&self, name: &str, from_ref: &str) -> PathBuf {
            let path = self.wt_base.join(name);
            git(
                &self.repo,
                &[
                    "worktree",
                    "add",
                    "--detach",
                    "-q",
                    path.to_str().unwrap(),
                    from_ref,
                ],
            )
            .unwrap();
            path
        }

        /// The commit `origin` has on a branch, or `None` when it has no such
        /// branch.
        fn origin_head(&self, branch: &str) -> Option<String> {
            git(
                &self.origin,
                &["rev-parse", "--verify", &format!("refs/heads/{branch}")],
            )
            .ok()
            .map(|s| s.trim().to_string())
        }
    }

    fn delivery<'a>(
        f: &'a Fixture,
        worktree: &'a Path,
        contract: &'a OutcomeContract,
        target: &'a str,
        draft: bool,
        body: &'a str,
    ) -> PrDelivery<'a> {
        PrDelivery {
            repo: &f.repo,
            worktree,
            target_branch: target,
            base_branch: "main",
            draft,
            intent: "make x exist",
            contract,
            body,
            provenance: None,
        }
    }

    const TARGET: &str = "goalpool/g_abc123";

    #[test]
    fn github_rollup_combines_check_runs_and_status_contexts_for_the_exact_head() {
        let raw = r#"{
            "headRefOid":"abc123",
            "statusCheckRollup":[
                {"__typename":"CheckRun","name":"lint","status":"COMPLETED","conclusion":"SUCCESS"},
                {"__typename":"CheckRun","name":"tests","status":"IN_PROGRESS","conclusion":""},
                {"__typename":"StatusContext","context":"deploy","state":"FAILURE"},
                {"__typename":"StatusContext","context":"lint","state":"PENDING"}
            ]
        }"#;

        let summary = parse_github_ci_summary(raw, "abc123").unwrap();
        assert_eq!(summary.head_sha, "abc123");
        assert_eq!(summary.state, CiState::Red);
        // Duplicate providers use the strongest observed state for one name.
        assert_eq!(
            summary.checks,
            vec![
                CiCheck {
                    name: "deploy".into(),
                    state: CiState::Red,
                },
                CiCheck {
                    name: "lint".into(),
                    state: CiState::Pending,
                },
                CiCheck {
                    name: "tests".into(),
                    state: CiState::Pending,
                },
            ]
        );
    }

    #[test]
    fn github_rollup_with_no_checks_is_pending_not_green() {
        let summary = parse_github_ci_summary(
            r#"{"headRefOid":"abc123","statusCheckRollup":null}"#,
            "abc123",
        )
        .unwrap();
        assert_eq!(summary.state, CiState::Pending);
        assert!(summary.checks.is_empty());
    }

    #[test]
    fn github_rollup_refuses_ci_from_a_different_head() {
        let err = parse_github_ci_summary(
            r#"{"headRefOid":"newer","statusCheckRollup":[]}"#,
            "delivered",
        )
        .unwrap_err();
        assert!(err.contains("expected delivered, found newer"), "{err}");
    }

    #[test]
    fn ci_lookup_failure_preserves_successful_publication() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "made by coder").unwrap();
        let gh = FakeGh::ok();
        *gh.fail_ci.lock().unwrap() = Some("HTTP 503".into());
        let out = deliver_pr_with(delivery(&f, &wt, &c, TARGET, true, "body"), &gh).unwrap();
        assert!(out.pushed);
        assert_eq!(out.pr_number, 101);
        assert_eq!(out.pr_action, PrAction::Opened);
        assert!(!out.pr_url.is_empty());
        assert_eq!(out.ci.head_sha, out.commit);
        assert_eq!(out.ci.state, CiState::Pending);
        assert!(out.ci.checks.is_empty());
        assert!(out.delivery_report().contains("CI unavailable"));
        assert!(out.delivery_report().contains("HTTP 503"));
        assert_eq!(gh.prs.lock().unwrap().len(), 1);
    }

    #[test]
    fn a_green_delivery_pushes_the_commit_and_opens_one_pr() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "made by coder").unwrap();

        let gh = FakeGh::ok();
        let out =
            deliver_pr_with(delivery(&f, &wt, &c, TARGET, true, "round 1 body"), &gh).unwrap();

        assert!(out.pushed);
        assert_eq!(out.branch, TARGET);
        assert_eq!(out.pr_action, PrAction::Opened);
        assert_eq!(out.pr_number, 101);
        assert!(out.draft, "a draft was requested at create time");
        assert_eq!(out.ci.state, CiState::Green);
        assert_eq!(out.ci.head_sha, out.commit);
        assert_eq!(
            out.ci.checks,
            [
                CiCheck {
                    name: "lint".into(),
                    state: CiState::Green,
                },
                CiCheck {
                    name: "test".into(),
                    state: CiState::Green,
                },
            ]
        );
        assert_eq!(
            out.delivery_report(),
            format!(
                "delivered with green checks at {}; pull request remains draft",
                out.commit
            )
        );

        // The remote really has the commit, with the file and the coder identity.
        assert_eq!(f.origin_head(TARGET).as_deref(), Some(out.commit.as_str()));
        assert_eq!(
            git(&f.origin, &["show", &format!("refs/heads/{TARGET}:x.txt")]).unwrap(),
            "made by coder"
        );
        assert_eq!(
            git(
                &f.origin,
                &[
                    "log",
                    "-1",
                    "--format=%an <%ae>",
                    &format!("refs/heads/{TARGET}")
                ]
            )
            .unwrap()
            .trim(),
            "car-coder <coder@parslee.ai>"
        );
        // Preflight ran before anything else, and CI was read for the exact
        // commit after the pull request existed.
        assert_eq!(gh.calls()[0], "auth_status");
        assert_eq!(gh.calls().last(), Some(&format!("ci 101 {}", out.commit)));
    }

    #[test]
    fn a_red_delivery_names_failed_checks_at_the_delivered_head() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("red", "main");
        std::fs::write(wt.join("x.txt"), "made by coder").unwrap();
        let gh = FakeGh::with_checks(vec![
            ("lint", CiState::Green),
            ("windows", CiState::Red),
            ("test", CiState::Pending),
        ]);

        let out =
            deliver_pr_with(delivery(&f, &wt, &c, TARGET, false, "red delivery"), &gh).unwrap();

        assert_eq!(out.ci.state, CiState::Red);
        assert!(out.ci.checks.contains(&CiCheck {
            name: "windows".into(),
            state: CiState::Red
        }));
        assert!(out.ci.checks.contains(&CiCheck {
            name: "test".into(),
            state: CiState::Pending
        }));
        assert_eq!(
            out.delivery_report(),
            format!("delivered red on windows at {}", out.commit)
        );
    }

    #[test]
    fn a_second_delivery_appends_to_the_same_branch_and_the_same_pr() {
        let f = fixture();
        let c = contract();

        let wt1 = f.cut("s1", "main");
        std::fs::write(wt1.join("x.txt"), "round one").unwrap();
        let gh1 = FakeGh::ok();
        let first =
            deliver_pr_with(delivery(&f, &wt1, &c, TARGET, true, "round 1 body"), &gh1).unwrap();

        // Round 2 cuts from the branch's current head, as the contract requires.
        git(&f.repo, &["fetch", "-q", "origin"]).unwrap();
        let wt2 = f.cut("s2", &format!("origin/{TARGET}"));
        std::fs::write(wt2.join("y.txt"), "round two").unwrap();

        // GitHub already has the open PR from round 1.
        let gh2 = FakeGh::with_prs(vec![PrRecord {
            number: 101,
            state: PrState::Open,
            url: "https://github.com/acme/repo/pull/101".into(),
            is_draft: true,
            base: "main".into(),
        }]);
        let second =
            deliver_pr_with(delivery(&f, &wt2, &c, TARGET, true, "round 2 body"), &gh2).unwrap();

        assert_eq!(second.pr_action, PrAction::Updated);
        assert_eq!(second.pr_number, 101);
        assert_ne!(second.commit, first.commit);
        assert!(
            !gh2.calls().iter().any(|c| c.starts_with("create")),
            "a second PR must never be created for the same branch: {:?}",
            gh2.calls()
        );
        assert!(gh2.calls().iter().any(|c| c == "set_body 101 round 2 body"));

        // One linear history: seed -> round 1 -> round 2, no merges.
        assert_eq!(
            git(
                &f.origin,
                &["rev-list", "--count", &format!("refs/heads/{TARGET}")]
            )
            .unwrap()
            .trim(),
            "3"
        );
        assert_eq!(
            git(
                &f.origin,
                &[
                    "rev-list",
                    "--count",
                    "--merges",
                    &format!("refs/heads/{TARGET}")
                ]
            )
            .unwrap()
            .trim(),
            "0"
        );
        // Round 1's commit is still an ancestor — nothing was replaced.
        assert!(git(
            &f.origin,
            &["merge-base", "--is-ancestor", &first.commit, &second.commit]
        )
        .is_ok());
        // And exactly two branches exist on the remote: main and the target.
        let mut branches: Vec<String> = git(
            &f.origin,
            &["for-each-ref", "--format=%(refname:short)", "refs/heads/"],
        )
        .unwrap()
        .lines()
        .map(|l| l.to_string())
        .collect();
        branches.sort();
        assert_eq!(branches, vec![TARGET.to_string(), "main".to_string()]);
    }

    #[test]
    fn a_non_fast_forward_is_retriable_and_leaves_the_remote_alone() {
        let f = fixture();
        let c = contract();

        let wt1 = f.cut("s1", "main");
        std::fs::write(wt1.join("x.txt"), "round one").unwrap();
        let first =
            deliver_pr_with(delivery(&f, &wt1, &c, TARGET, true, "b1"), &FakeGh::ok()).unwrap();

        // A session that was cut from the OLD base — its commit is not a
        // descendant of what the branch now points at.
        let wt2 = f.cut("stale", "main");
        std::fs::write(wt2.join("z.txt"), "stale round").unwrap();
        let gh = FakeGh::with_prs(vec![PrRecord {
            number: 101,
            state: PrState::Open,
            url: "https://github.com/acme/repo/pull/101".into(),
            is_draft: true,
            base: "main".into(),
        }]);
        let err = deliver_pr_with(delivery(&f, &wt2, &c, TARGET, true, "b2"), &gh).unwrap_err();

        assert_eq!(err.stage(), "push");
        assert!(err.retriable(), "{err}");
        assert!(
            matches!(
                err,
                DeliveryFailure::Push {
                    retriable: true,
                    ..
                }
            ),
            "{err:?}"
        );
        assert!(
            err.reason().contains("non-fast-forward"),
            "the reason must name the condition: {}",
            err.reason()
        );
        // The remote still points at round 1.
        assert_eq!(
            f.origin_head(TARGET).as_deref(),
            Some(first.commit.as_str())
        );
        // And no PR work was attempted after the push failed.
        assert!(
            !gh.calls().iter().any(|c| c.starts_with("create")),
            "{:?}",
            gh.calls()
        );
    }

    #[test]
    fn a_missing_credential_fails_preflight_and_touches_nothing() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "never delivered").unwrap();

        let gh = FakeGh::no_credential();
        let err = deliver_pr_with(delivery(&f, &wt, &c, TARGET, true, "body"), &gh).unwrap_err();

        assert_eq!(err.stage(), "preflight");
        assert!(!err.retriable(), "a missing credential is not retriable");
        assert!(
            err.reason().contains("GH_TOKEN") || err.reason().contains("gh auth"),
            "the failure must name the missing credential: {}",
            err.reason()
        );
        // Nothing committed, nothing pushed.
        assert!(
            f.origin_head(TARGET).is_none(),
            "the remote gained a branch"
        );
        assert!(
            !git(&wt, &["status", "--porcelain"])
                .unwrap()
                .trim()
                .is_empty(),
            "the worktree was committed despite the preflight failure"
        );
        assert_eq!(gh.calls(), vec!["auth_status".to_string()]);
    }

    /// car#1055: a closed pull request into this run's base is somebody's
    /// decision that this branch should stop. It used to be reopened; now it
    /// parks the round at PREFLIGHT, before the commit and before the push,
    /// because parking at reconciliation would leave the round's commits on the
    /// branch with no pull request describing them.
    #[test]
    fn a_closed_unmerged_pull_request_parks_the_round() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "again").unwrap();

        let gh = FakeGh::with_prs(vec![PrRecord {
            number: 55,
            state: PrState::ClosedUnmerged,
            url: "https://github.com/acme/repo/pull/55".into(),
            is_draft: false,
            base: "main".into(),
        }]);
        let err = deliver_pr_with(delivery(&f, &wt, &c, TARGET, true, "revived"), &gh).unwrap_err();

        assert!(
            matches!(err, DeliveryFailure::Preflight { .. }),
            "a closed pull request is refused before the commit: {err:?}"
        );
        assert!(
            !err.retriable(),
            "retrying changes nothing — a human reopens #55 or picks another target branch"
        );
        // Actionable: it names the number and says who reopens it.
        assert!(
            err.reason().contains("#55") && err.reason().contains("Reopen"),
            "{}",
            err.reason()
        );

        // The listing is all it asked GitHub for: no reopen, no create, no body
        // rewrite.
        assert_eq!(
            gh.calls(),
            vec!["auth_status".to_string(), format!("list {TARGET}")]
        );
        // And nothing local moved either.
        assert_eq!(f.origin_head(TARGET), None, "nothing may be pushed");
        assert!(
            !git(&wt, &["status", "--porcelain"])
                .unwrap()
                .trim()
                .is_empty(),
            "the worktree was committed despite the preflight failure"
        );
    }

    /// The filed scenario (car#1055): a reviewer read the pull request, EDITED
    /// its body, and closed it. The next round must not hand `set_pr_body` this
    /// round's `body` and wipe those edits — which is what a reopen did, every
    /// round, for as long as the branch existed.
    #[test]
    fn a_reviewers_edited_body_survives_the_next_round() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "round two").unwrap();

        let gh = FakeGh::with_prs(vec![PrRecord {
            number: 40,
            state: PrState::ClosedUnmerged,
            url: "https://github.com/acme/repo/pull/40".into(),
            is_draft: false,
            base: "main".into(),
        }]);
        let err = deliver_pr_with(
            delivery(&f, &wt, &c, TARGET, false, "round two's generated body"),
            &gh,
        )
        .unwrap_err();

        assert_eq!(err.stage(), "preflight");
        assert!(
            !gh.calls().iter().any(|c| c.starts_with("set_body")),
            "the reviewer's description was rewritten: {:?}",
            gh.calls()
        );
        // Stronger than "no set_body": this round's generated body never
        // reached GitHub on ANY call, so nothing could have replaced the
        // reviewer's text by another route. That the pull request is also never
        // made live again is asserted by the exact-calls check in
        // `a_closed_unmerged_pull_request_parks_the_round` — there is no reopen
        // seam left on `GitHubApi` for a call to come from.
        assert!(
            !gh.calls()
                .iter()
                .any(|c| c.contains("round two's generated body")),
            "this round's body reached GitHub: {:?}",
            gh.calls()
        );
    }

    /// car#1055 must not veto a pull request a human has already SUPERSEDED.
    /// A reviewer closes #40 ("wrong approach") and opens #55 from the same
    /// branch into the same base to carry the work forward. `gh` reports both.
    /// The close is the older decision; the open one is what this round
    /// reconciles, exactly as it did before the close rule existed. Parking
    /// here would name a number the reviewer deliberately retired and leave #55
    /// permanently stale.
    #[test]
    fn a_superseding_open_pull_request_beats_the_closed_one() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "carried forward").unwrap();

        let gh = FakeGh::with_prs(vec![
            PrRecord {
                number: 40,
                state: PrState::ClosedUnmerged,
                url: "https://github.com/acme/repo/pull/40".into(),
                is_draft: false,
                base: "main".into(),
            },
            PrRecord {
                number: 55,
                state: PrState::Open,
                url: "https://github.com/acme/repo/pull/55".into(),
                is_draft: false,
                base: "main".into(),
            },
        ]);

        let out = deliver_pr_with(delivery(&f, &wt, &c, TARGET, false, "round body"), &gh).unwrap();

        assert_eq!(out.pr_action, PrAction::Updated);
        assert_eq!(out.pr_number, 55, "the live pull request receives the push");
        assert!(out.pushed);
        assert!(
            gh.calls().iter().any(|c| c.starts_with("set_body 55")),
            "{:?}",
            gh.calls()
        );
        // #40 is somebody's closed decision and stays that way: nothing is
        // created to paper over it and nothing touches it.
        assert!(
            !gh.calls().iter().any(|c| c.starts_with("create")),
            "{:?}",
            gh.calls()
        );
        assert!(
            !gh.calls().iter().any(|c| c.contains(" 40 ")),
            "{:?}",
            gh.calls()
        );
    }

    /// The unit-level statement of the same rule, on the half that carries it:
    /// the close veto is suppressed by an open pull request into THIS base, and
    /// only that base.
    #[test]
    fn the_close_veto_is_suppressed_only_by_an_open_pr_into_the_same_base() {
        let closed = PrRecord {
            number: 40,
            state: PrState::ClosedUnmerged,
            url: "u40".into(),
            is_draft: false,
            base: "main".into(),
        };
        let open_same = PrRecord {
            number: 55,
            state: PrState::Open,
            url: "u55".into(),
            is_draft: false,
            base: "main".into(),
        };
        let open_other = PrRecord {
            base: "release/2.1".into(),
            ..open_same.clone()
        };

        assert!(
            closed_pr_refusal(std::slice::from_ref(&closed), TARGET, "main").is_some(),
            "a lone closed pull request still parks the round"
        );
        assert!(
            closed_pr_refusal(&[closed.clone(), open_same], TARGET, "main").is_none(),
            "the open pull request into `main` supersedes the close"
        );
        assert!(
            closed_pr_refusal(&[closed, open_other], TARGET, "main").is_some(),
            "an open pull request into ANOTHER base says nothing about this base"
        );
    }

    #[test]
    fn a_merged_pr_does_not_block_a_new_one() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "next chapter").unwrap();

        let gh = FakeGh::with_prs(vec![PrRecord {
            number: 9,
            state: PrState::Merged,
            url: "https://github.com/acme/repo/pull/9".into(),
            is_draft: false,
            base: "main".into(),
        }]);
        let out = deliver_pr_with(delivery(&f, &wt, &c, TARGET, false, "fresh"), &gh).unwrap();

        assert_eq!(out.pr_action, PrAction::Opened);
        // A merge is this branch's work landing, not a decision against it: it
        // neither parks the round nor suppresses the next pull request.
        assert!(gh.calls().iter().any(|c| c.starts_with("create")));
    }

    #[test]
    fn an_updated_pr_never_has_its_draft_state_flipped() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "more work").unwrap();

        // A car worker marked it ready in an earlier round.
        let gh = FakeGh::with_prs(vec![PrRecord {
            number: 77,
            state: PrState::Open,
            url: "https://github.com/acme/repo/pull/77".into(),
            is_draft: false,
            base: "main".into(),
        }]);
        // Delivery still asks for a draft — it must be ignored on an existing PR.
        let out = deliver_pr_with(delivery(&f, &wt, &c, TARGET, true, "body"), &gh).unwrap();

        assert_eq!(out.pr_action, PrAction::Updated);
        assert!(
            !out.draft,
            "delivery must report the PR's real state, not re-draft a ready PR"
        );
    }

    #[test]
    fn a_clean_worktree_redelivers_head_after_an_earlier_push_failure() {
        let f = fixture();
        let c = contract();

        // Round 1: commit lands locally, push is impossible (no such remote).
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "work").unwrap();
        git(
            &f.repo,
            &["remote", "set-url", "origin", "/nonexistent/nope.git"],
        )
        .unwrap();
        let err =
            deliver_pr_with(delivery(&f, &wt, &c, TARGET, true, "b"), &FakeGh::ok()).unwrap_err();
        assert_eq!(err.stage(), "push");
        // A remote that is not a repository is permanent: re-running spends a
        // whole model session to reach the identical wall.
        assert!(
            !err.retriable(),
            "a missing remote cannot be fixed by trying again: {err}"
        );
        let committed = git(&wt, &["rev-parse", "HEAD"]).unwrap().trim().to_string();

        // Round 2 reuses the kept workspace. It is now CLEAN, but the work is
        // real and must be delivered rather than refused.
        git(
            &f.repo,
            &["remote", "set-url", "origin", f.origin.to_str().unwrap()],
        )
        .unwrap();
        let out = deliver_pr_with(delivery(&f, &wt, &c, TARGET, true, "b"), &FakeGh::ok()).unwrap();
        assert_eq!(out.commit, committed);
        assert_eq!(f.origin_head(TARGET).as_deref(), Some(committed.as_str()));
    }

    #[test]
    fn a_branch_name_that_looks_like_a_flag_is_refused_at_preflight() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "x").unwrap();

        for bad in [
            "--upload-pack=touch /tmp/pwn",
            "goalpool/../../etc",
            "has space",
        ] {
            let err =
                deliver_pr_with(delivery(&f, &wt, &c, bad, true, "b"), &FakeGh::ok()).unwrap_err();
            assert_eq!(err.stage(), "preflight", "for `{bad}`: {err}");
        }
        // A leading '+' would be a force marker in a refspec.
        let plus = format!("{}goalpool/x", '+');
        let err =
            deliver_pr_with(delivery(&f, &wt, &c, &plus, true, "b"), &FakeGh::ok()).unwrap_err();
        assert_eq!(err.stage(), "preflight", "{err}");
    }

    // --- Source-level guards ---------------------------------------------

    /// **The guarantee this delivery path sells.** A force-push on a shared
    /// delivery branch silently discards a round's work and rewrites commits a
    /// reviewer already read. The needles are assembled at runtime so this
    /// test's own source cannot trip it.
    #[test]
    fn no_force_push_token_appears_anywhere_in_this_file() {
        let dashes = "-".repeat(2);
        let plain = format!("{dashes}{}", "force");
        let lease = format!("{plain}-with-lease");
        // A force refspec is any string literal whose FIRST character is `+`.
        //
        // This needle used to be the literal `+refs`, which cannot see the force
        // refspec this file would actually produce: refspecs here are built by
        // interpolation ([`push_args`] formats the commit and branch in), so a
        // forced one is a format string beginning with a plus followed by
        // `{commit}:refs/heads/...` — no `+refs` substring anywhere in it. The
        // guard read as rigorous and could not fail on the one spelling that
        // matters. Anchoring on quote-then-plus catches both.
        //
        // Assembled from chars, like the needles above, so it does not appear
        // verbatim in this file and match its own definition.
        let plus_refspec: String = ['"', '+'].iter().collect();
        // `-f` is the commonest spelling of a force push and was not covered.
        // Quoted, so the bare two characters cannot match inside prose.
        let short_flag: String = ['"', '-', 'f', '"'].iter().collect();
        for needle in [
            plain.as_str(),
            lease.as_str(),
            plus_refspec.as_str(),
            short_flag.as_str(),
        ] {
            assert!(
                !MERGE_RS_SOURCE.contains(needle),
                "`{needle}` must appear nowhere on the delivery path"
            );
        }

        // A char-literal plus reaches the same force refspec by another route —
        // interpolating `'+'` as the first field of a format string — which the
        // quote-then-plus needle cannot see.
        //
        // Scoped to PRODUCTION lines that build a string. Both narrowings are
        // load-bearing, and each was found by this check firing on correct code:
        // a bare `'+'` is how `the_push_refspec_is_append_only_and_fully_
        // qualified` asserts no arg starts with one, and the branch-validation
        // test deliberately CONSTRUCTS a `+`-prefixed name to prove preflight
        // rejects it. Banning the spelling everywhere would fail on the two
        // tests that prove the property — the failure mode this guard family
        // keeps rediscovering.
        let production = MERGE_RS_SOURCE
            .split_once("mod tests {")
            .map(|(head, _)| head)
            .unwrap_or(MERGE_RS_SOURCE);
        // Rebase, in BOTH spellings. merge.rs's delivery path must never
        // rebase either — the base-update policy is merge precisely so a
        // reviewer's already-read commits are not rewritten — and a bare
        // `"rebase"` needle cannot see `"--rebase"`, two dashes sitting between
        // the quote and the `r`.
        for tok in [
            ['"', 'r', 'e', 'b', 'a', 's', 'e', '"']
                .iter()
                .collect::<String>(),
            ['"', '-', '-', 'r', 'e', 'b', 'a', 's', 'e', '"']
                .iter()
                .collect::<String>(),
        ] {
            assert!(
                !production.contains(tok.as_str()),
                "delivery must never rebase: `{tok}`"
            );
        }

        assert_eq!(
            force_char_offenders(MERGE_RS_SOURCE),
            Vec::<usize>::new(),
            "a char-literal plus on the delivery path is a force refspec"
        );
    }

    /// The guard above, run against sources that DO contain the violation.
    ///
    /// This is the half that was missing, and its absence is the defect: the
    /// scanner used to require `format!` and the char literal on the SAME line,
    /// and rustfmt routinely splits `format!(` from its string — it does so in
    /// this very file, in `validate_branch_name`. So the one spelling a real
    /// force refspec would take here (bind the plus to a name, interpolate it)
    /// tripped no needle, and no test could have noticed, because the guard was
    /// only ever run against a file that does not violate it. A green
    /// assertion over one input says nothing about whether the check can fail.
    #[test]
    fn the_force_char_scanner_catches_the_spellings_that_slipped_past_it() {
        // The exact bypass: rustfmt splits the macro from its string, and the
        // plus is bound to a name on a line with no `format!` on it.
        let wrapped = "fn f() {\n    let plus = '+';\n    let refspec = format!(\n        \
                       \"{plus}{commit}:refs/heads/{branch}\"\n    );\n}\n";
        assert!(
            !force_char_offenders(wrapped).is_empty(),
            "a plus bound to a name and interpolated is still a force refspec"
        );
        // The single-line spelling the old scanner did catch, still caught.
        let inline = "fn f() { let r = format!(\"{}{commit}:refs/heads/{b}\", '+'); }\n";
        assert!(!force_char_offenders(inline).is_empty());
        // And it stops at the test module, which legitimately constructs
        // `+`-prefixed names to prove `validate_branch_name` rejects them.
        let only_in_tests = "fn f() {}\nmod tests {\n    let plus = '+';\n}\n";
        assert!(force_char_offenders(only_in_tests).is_empty());
    }

    /// Marking a pull request ready for review is a car worker's judgment in a
    /// later round, never the runtime's. A string literal `ready` in this file
    /// would be a `gh pr ready` argument.
    #[test]
    fn delivery_never_marks_a_pull_request_ready_for_review() {
        // Spelled in pieces so this test's own source does not contain the token.
        let ready_arg = String::from('"') + "read" + "y" + "\"";
        assert!(
            !MERGE_RS_SOURCE.contains(&ready_arg),
            "the runtime must not flip a pull request out of draft"
        );
    }

    /// Every subprocess on this path is an argument array. A shell string would
    /// let a branch name carry a command.
    #[test]
    fn no_shell_invocation_appears_on_the_delivery_path() {
        for needle in ["Command::new(\"sh\")", "Command::new(\"bash\")"] {
            assert!(
                !MERGE_RS_SOURCE.contains(needle),
                "`{needle}` would reintroduce shell interpolation"
            );
        }
    }

    #[test]
    fn delivery_has_no_pull_request_merge_invocation() {
        let production = MERGE_RS_SOURCE
            .split_once("mod tests {")
            .map(|(head, _)| head)
            .unwrap_or(MERGE_RS_SOURCE);
        let lines: Vec<&str> = production.lines().collect();
        for (index, line) in lines.iter().enumerate() {
            if line.contains("\"pr\"") {
                let end = (index + 4).min(lines.len());
                let window = lines[index..end].join("\n");
                assert!(
                    !window.contains("\"merge\""),
                    "pull-request merge invocation at production line {}",
                    index + 1
                );
            }
        }
    }

    // --- Argument builders -------------------------------------------------

    #[test]
    fn pr_check_read_requests_the_rollup_and_head_sha() {
        assert_eq!(
            gh_pr_checks_args(41),
            ["pr", "view", "41", "--json", "headRefOid,statusCheckRollup"]
        );
    }

    #[test]
    fn draft_adds_the_draft_flag_and_nothing_else_does() {
        let with = gh_pr_create_args("h", "main", "t", "b", true);
        assert!(with.contains(&"--draft".to_string()), "{with:?}");
        let without = gh_pr_create_args("h", "main", "t", "b", false);
        assert!(!without.contains(&"--draft".to_string()), "{without:?}");
        // The body and title are passed as their own argv entries.
        assert!(with.windows(2).any(|w| w[0] == "--body" && w[1] == "b"));
        assert!(with.windows(2).any(|w| w[0] == "--title" && w[1] == "t"));
    }

    #[test]
    fn the_push_refspec_is_append_only_and_fully_qualified() {
        let args = push_args("abc123", "goalpool/g_1");
        assert_eq!(
            args,
            vec![
                "push".to_string(),
                "origin".to_string(),
                "abc123:refs/heads/goalpool/g_1".to_string(),
            ]
        );
        let plus = '+';
        assert!(
            !args.iter().any(|a| a.starts_with(plus)),
            "a leading plus is git's force marker: {args:?}"
        );

        // Ask git itself to validate the fully-qualified destination and reap
        // that fixture child explicitly. A previous measurement left the git
        // process attached to this test after its assertions had returned.
        let mut child = std::process::Command::new("git")
            .args(["check-ref-format", "refs/heads/goalpool/g_1"])
            .spawn()
            .expect("spawn git check-ref-format fixture");
        let status = child.wait().expect("reap git fixture child");
        assert!(status.success(), "git rejected the destination ref");
    }

    /// The listing is the sole input to [`ambiguous_head_refusal`], so an
    /// explicit `--limit` above `gh`'s default page of 30 is part of the guard:
    /// a truncated page hides an open pull request into another base and the
    /// push it exists to prevent goes ahead silently.
    #[test]
    fn pr_list_asks_for_every_state_of_one_head_branch() {
        let args = gh_pr_list_args("goalpool/g_1");
        assert!(args
            .windows(2)
            .any(|w| w[0] == "--head" && w[1] == "goalpool/g_1"));
        assert!(args.windows(2).any(|w| w[0] == "--state" && w[1] == "all"));
        let limit: u32 = args
            .windows(2)
            .find(|w| w[0] == "--limit")
            .map(|w| w[1].parse().expect("--limit is a number"))
            .expect("an explicit --limit, or gh silently pages at 30");
        assert!(
            limit >= 100,
            "the head listing must not be truncated below 100: {args:?}"
        );
    }

    // --- gh output parsing -------------------------------------------------

    #[test]
    fn pr_list_json_maps_merged_apart_from_closed() {
        let prs = parse_pr_list(
            r#"[{"number":1,"state":"OPEN","url":"u1","isDraft":true,"baseRefName":"main"},
                {"number":2,"state":"CLOSED","url":"u2","isDraft":false,"baseRefName":"main"},
                {"number":3,"state":"MERGED","url":"u3","isDraft":false,"baseRefName":"main"}]"#,
        )
        .unwrap();
        assert_eq!(prs[0].state, PrState::Open);
        assert!(prs[0].is_draft);
        assert_eq!(prs[1].state, PrState::ClosedUnmerged);
        assert_eq!(prs[2].state, PrState::Merged);
    }

    #[test]
    fn an_unknown_pr_state_is_an_error_not_a_guess() {
        assert!(
            parse_pr_list(r#"[{"number":1,"state":"WAT","url":"u","baseRefName":"main"}]"#)
                .is_err()
        );
        // A missing base is an error too, for the same reason: every default
        // would be a claim that this pull request merges into the branch this
        // round targets.
        assert!(
            parse_pr_list(r#"[{"number":1,"state":"OPEN","url":"u","isDraft":false}]"#).is_err(),
            "a pull request with no baseRefName cannot be reconciled against a base"
        );
        assert!(parse_pr_list("not json").is_err());
        assert!(parse_pr_list("[]").unwrap().is_empty());
    }

    #[test]
    fn a_pr_number_is_read_off_the_created_url() {
        assert_eq!(
            pr_number_from_url("https://github.com/acme/repo/pull/4821\n").unwrap(),
            4821
        );
        assert!(pr_number_from_url("https://github.com/acme/repo").is_err());
    }

    #[test]
    fn push_errors_split_into_retriable_and_not() {
        let (reason, retriable) = classify_push_error("! [rejected] abc -> b (non-fast-forward)");
        assert!(retriable);
        assert!(reason.contains("non-fast-forward"));

        let (_, retriable) = classify_push_error("remote: Permission denied to car-coder.");
        assert!(!retriable, "a permission refusal must not be retried");

        // git's REAL output, trailer included. "Please make sure you have the
        // correct access rights / and the repository exists." is the generic
        // die_initial_contact trailer printed on EVERY transport failure — a
        // DNS miss, an ssh timeout, a laptop off wifi — so matching it as a
        // credential refusal parked green rounds on ordinary network blips.
        // Reproduced against a scratch repo with an unresolvable ssh remote.
        let (_, retriable) = classify_push_error(
            "ssh: Could not resolve hostname github.com: nodename nor servname provided, \
             or not known\nfatal: Could not read from remote repository.\n\nPlease make \
             sure you have the correct access rights\nand the repository exists.",
        );
        assert!(retriable, "transport failures are worth another round");
    }

    /// A commit SHA that happens to contain the digits `403` must NOT be read as
    /// an HTTP 403.
    ///
    /// This is not a hypothetical. Git echoes the competing SHA on a lost push
    /// race, a 40-char hex string contains `403` roughly 0.9% of the time, and
    /// git prints two of them — so on the order of 2% of push failures. A bare
    /// `contains("403")` turns those into `retriable: false`, which exits 3, the
    /// park-the-goal path. The consequence is worse than the rate suggests: a
    /// parked goal is never relaunched, so the round-N+1 recovery that merges
    /// `origin/<target>` back in never runs, and a perfectly healthy race
    /// becomes a dead goal needing a human.
    #[test]
    fn a_sha_containing_403_is_not_mistaken_for_a_permission_refusal() {
        let (reason, retriable) = classify_push_error(
            "! [remote rejected] goalpool/g_1 -> goalpool/g_1 (cannot lock ref \
             'refs/heads/goalpool/g_1': is at a4973f07ba3815b8d45b86a7e9633d9fbc5e4403 \
             but expected b1c2d3e4f5061728394a5b6c7d8e9f0011223344)",
        );
        assert!(
            retriable,
            "a lost push race is retriable; the digits 403 inside a SHA are not an HTTP status"
        );
        assert!(
            reason.contains("race") || reason.contains("moved"),
            "the reason must name what actually happened: {reason}"
        );
    }

    /// Git's lost-race wording must be classified because it is recognised, not
    /// because it happens to fall through to the retriable default.
    ///
    /// Note `[remote rejected]` does NOT contain the substring `[rejected]` —
    /// the bracket sits before `remote`. Until this was added, none of the
    /// retriable keywords matched git's actual lost-race output, so the verdict
    /// was right by luck and the reason text said nothing useful.
    #[test]
    fn gits_lost_race_wording_is_recognised_rather_than_defaulted() {
        for message in [
            "! [remote rejected] main -> main (failed to update ref)",
            "error: cannot lock ref 'refs/heads/goalpool/g_1': is at aaa but expected bbb",
            "! [rejected] abc -> b (fetch first)",
        ] {
            let (reason, retriable) = classify_push_error(message);
            assert!(retriable, "{message}");
            assert!(
                reason.contains("moved") || reason.contains("race"),
                "the reason must tell an operator the branch moved, not echo git: {reason}"
            );
        }
    }

    /// `403` in a BRANCH or REPOSITORY name is not an HTTP status.
    ///
    /// Token-anchoring stopped the digits inside a commit SHA matching, but a
    /// name is delimited by `-` `/` `_` `.`, so `feature-403` presents `403` as
    /// a standalone token — and git echoes the branch and the remote URL in
    /// every push error. Since refusals are tested before races, an ordinary
    /// lost race on such a branch was parked as a permission refusal with a
    /// reason that was factually wrong.
    #[test]
    fn a_403_in_a_branch_or_repo_name_is_not_a_permission_refusal() {
        for message in [
            "! [rejected] abc1234 -> feature-403 (non-fast-forward)",
            "! [rejected] abc -> goalpool/g_403 (fetch first)",
            "! [remote rejected] x -> release_403 (failed to update ref)",
        ] {
            let (reason, retriable) = classify_push_error(message);
            assert!(retriable, "must stay a retriable race: {message}");
            assert!(
                reason.contains("moved") || reason.contains("race"),
                "{reason}"
            );
        }
        // A repository name carrying 403 must not poison an unrelated failure.
        let (_, retriable) =
            classify_push_error("fatal: unable to access 'https://github.com/org/repo-403.git/'");
        assert!(retriable, "a repo name is not a status code");
    }

    /// Permanent refusals that arrive inside `[remote rejected]` are not races.
    ///
    /// `! [remote rejected]` is git's GENERIC server-refusal line; the reason is
    /// in the parentheses. Classifying the whole class as a lost race returned
    /// exit 2 — "requeue, nothing was judged" — so each of these burned a full
    /// model session per round against an identical wall, forever.
    #[test]
    fn permanent_server_refusals_inside_remote_rejected_are_not_retried() {
        for message in [
            "! [remote rejected] b -> b (refusing to allow an OAuth App to create or update \
             workflow '.github/workflows/x.yml' without 'workflow' scope)",
            "! [remote rejected] b -> b (shallow update not allowed)",
            "remote: error: GH001: Large files detected. File exceeds GitHub's file size limit \
             of 100.00 MB",
            // Directory/file ref collision — captured from git 2.50.1 against a
            // scratch bare remote, not paraphrased. Emits BOTH `cannot lock
            // ref` and `failed to update ref`, so it reads as a lost race
            // unless refusals are matched first.
            "remote: error: cannot lock ref 'refs/heads/goalpool/g_1': \
             'refs/heads/goalpool' exists; cannot create 'refs/heads/goalpool/g_1'\n \
             ! [remote rejected] HEAD -> goalpool/g_1 (failed to update ref)",
        ] {
            let (_, retriable) = classify_push_error(message);
            assert!(!retriable, "permanent, must not be retried: {message}");
        }
    }

    /// A repository-rule violation — which is what secret-scanning push
    /// protection emits — is permanent, and the enumerated code list stopped
    /// short of it.
    ///
    /// `GH013` is the code GitHub returns for a ruleset block, and push
    /// protection is on by default for public repositories, so this is not an
    /// exotic path: a test fixture that reads like a token is enough. Walking
    /// the old predicates against the text below, nothing in the refusal set
    /// matched — the list ended at `GH008:` — so it fell through to
    /// `remote rejected` in the race set and was reported to the orchestrator as
    /// "the branch moved, requeue". Every following round then burned a full
    /// model session to re-push the identical commit at the identical wall,
    /// which is the exact failure `classify_push_error` says it exists to stop.
    ///
    /// Captured shape, not paraphrased — the `remote:` lines and the trailing
    /// `! [remote rejected]` are what git prints for a declined push.
    #[test]
    fn a_repository_rule_violation_is_permanent_not_a_lost_race() {
        let (reason, retriable) = classify_push_error(
            "remote: error: GH013: Repository rule violations found for \
             refs/heads/goalpool/g_1.\nremote:\nremote: - GITHUB PUSH PROTECTION\nremote:   \
             —— GitHub Personal Access Token ————————————————\nremote:\n \
             ! [remote rejected] goalpool/g_1 -> goalpool/g_1 (push declined due to \
             repository rule violations)\nerror: failed to push some refs to \
             'https://github.com/o/r.git'",
        );
        assert!(
            !retriable,
            "a ruleset block cannot be got past by pushing the same commit again"
        );
        assert!(
            !reason.contains("race") && !reason.contains("moved"),
            "and it must not be described as a lost push race: {reason}"
        );

        // The generic decline line carries the same verdict on its own — a
        // caller that only kept git's stderr summary still gets it right.
        let (_, retriable) = classify_push_error(
            "! [remote rejected] b -> b (push declined due to repository rule violations)",
        );
        assert!(!retriable);

        // Codes above the old ceiling are the family, not one member.
        for code in ["GH009", "GH011", "GH013"] {
            let (_, retriable) =
                classify_push_error(&format!("remote: error: {code}: blocked by policy"));
            assert!(!retriable, "{code} must be read as a policy refusal");
        }
    }

    /// …and the code shape must not fire on a NAME.
    ///
    /// This file has twice shipped a predicate that matched text git echoes for
    /// unrelated reasons — `403` inside a commit SHA, then inside a branch name.
    /// The colon is the anchor: `validate_branch_name` rejects `:` in a ref, so
    /// `GH013:` cannot arrive from a branch, a tag, or a remote name.
    #[test]
    fn a_github_code_in_a_branch_name_is_not_a_policy_refusal() {
        for message in [
            "! [rejected] abc -> fix-gh013-secret-scanning (non-fast-forward)",
            "! [remote rejected] x -> gh001 (failed to update ref)",
            "fatal: unable to access 'https://github.com/org/gh013.git/'",
        ] {
            let (_, retriable) = classify_push_error(message);
            assert!(retriable, "a name is not a status code: {message}");
        }
    }

    /// A permanent `gh` failure must not be reported as a retriable blip.
    #[test]
    fn permanent_pr_reconciliation_failures_are_not_retriable() {
        for message in [
            "GraphQL: No commits between main and goalpool/g_1",
            "GraphQL: Draft pull requests are not supported in this repository",
        ] {
            let (_, retriable) = classify_pr_error(message);
            assert!(!retriable, "permanent, must not be retried: {message}");
        }

        // `already exists` is RETRIABLE, and this assertion is the whole point:
        // the error is only ever returned when a pull request for that head
        // exists, while reaching `create_pr` means the listing found none — a
        // race, replication lag, or a head mismatch, all of which resolve on the
        // next round's re-list. Parking there strands a goal whose commit is
        // already pushed and whose pull request number is IN THE ERROR TEXT.
        let (_, retriable) = classify_pr_error(
            "a pull request for branch \"goalpool/g_1\" into branch \"main\" already exists: #7",
        );
        assert!(
            retriable,
            "the error proves a usable pull request exists; the next round adopts it"
        );
        // An unrecognised failure stays retriable: an API blip is the common
        // case, and wrongly parking a healthy goal is the worse error.
        let (_, retriable) = classify_pr_error("502 Bad Gateway");
        assert!(retriable);
    }

    /// **The E2E defect.** A caller's paragraph break decides the commit subject.
    ///
    /// goalpool writes a short summary, a blank line, then a pointer to the goal
    /// brief. `subject_from_intent` flattened newlines to spaces BEFORE the
    /// length check, so the break was gone before it could do anything and the
    /// subject read `"<summary>  Read the goal brief /tmp/..."`, truncated at 72.
    /// Leading with a short first line was not enough, because the flattening
    /// happened first.
    ///
    /// Asserted on the delivered COMMIT — `%s` and `%b` — rather than on the
    /// helper, because the subject a reviewer sees is the thing that matters and
    /// the helper is only how it gets there.
    #[test]
    fn a_paragraph_break_in_the_intent_ends_the_commit_subject() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("subject-check", "main");
        std::fs::write(wt.join("greet.js"), "console.log('hi');\n").unwrap();

        let summary = "Goal: implement greet() in the scratch repo";
        let body_text = "Read the goal brief /tmp/car-e2e-2/gp-home/logs/brief.md and \
                         follow it exactly. This pointer text must not reach the subject.";
        let intent = format!("{summary}\n\n{body_text}");

        let out = deliver_pr_with(
            PrDelivery {
                repo: &f.repo,
                worktree: &wt,
                target_branch: "goalpool/g_subject",
                base_branch: "main",
                draft: true,
                intent: &intent,
                contract: &c,
                body: "b",
                provenance: None,
            },
            &FakeGh::ok(),
        )
        .expect("delivery succeeds");

        let subject = git(&f.repo, &["log", "-1", "--format=%s", &out.commit]).unwrap();
        assert_eq!(
            subject.trim(),
            summary,
            "the subject must be exactly the first paragraph"
        );
        assert!(
            !subject.contains("goal brief"),
            "the pointer text must not ride along: {subject}"
        );

        // Nothing is lost — the rest is in the body, where git expects it.
        let body = git(&f.repo, &["log", "-1", "--format=%b", &out.commit]).unwrap();
        assert!(
            body.contains("goal brief"),
            "the remainder belongs in the body: {body}"
        );
    }

    /// An intent with no blank line still flattens and truncates at 72, exactly
    /// as before — a single-paragraph caller sees no change.
    #[test]
    fn a_single_paragraph_intent_still_truncates_as_before() {
        let short = "Add a --verbose flag to the CLI";
        assert_eq!(subject_from_intent(short), short);

        let long = "Add a --verbose flag to the export subcommand and thread it through \
                    every downstream call site so the whole pipeline reports progress";
        let subject = subject_from_intent(long);
        assert!(subject.ends_with("..."), "{subject}");
        assert!(subject.len() <= 72, "len {}: {subject}", subject.len());
        assert!(!subject.contains('\n'));

        // A multi-line first paragraph is still one line in the subject.
        assert_eq!(
            subject_from_intent("wrapped over\ntwo lines\n\nbody here"),
            "wrapped over two lines"
        );
    }

    /// **The E2E defect.** Runtime bookkeeping must not reach the delivered tree.
    ///
    /// The ownership marker used to be written into the WORKING TREE, and
    /// `commit_worktree` stages with `git add -A`, so every pull request this
    /// command opened carried a `.car-code-task` file in its diff for a human to
    /// review. It now lives in the worktree's gitdir, which `git add` cannot
    /// reach — so this asserts against the pushed tree rather than against the
    /// mechanism, and would catch any future bookkeeping file the same way.
    #[test]
    fn no_runtime_bookkeeping_reaches_the_delivered_tree() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("marker-check", "main");

        // Whatever the CLI writes to claim a workspace lives here, alongside
        // anything else git keeps per-worktree.
        let gitdir = std::fs::read_to_string(wt.join(".git"))
            .ok()
            .and_then(|m| {
                m.trim()
                    .strip_prefix("gitdir:")
                    .map(|g| g.trim().to_string())
            })
            .map(PathBuf::from)
            .expect("a worktree's .git is a file holding a gitdir pointer");
        std::fs::write(gitdir.join("car-code-task"), "claimed\n").unwrap();

        std::fs::write(wt.join("greet.js"), "console.log('hi');\n").unwrap();
        let out = deliver_pr_with(
            delivery(&f, &wt, &c, "goalpool/g_marker", true, "b"),
            &FakeGh::ok(),
        )
        .expect("delivery succeeds");

        let tree = git(&f.origin, &["ls-tree", "-r", "--name-only", &out.commit]).unwrap();
        assert!(
            tree.contains("greet.js"),
            "the actual work must be there: {tree}"
        );
        for bookkeeping in ["car-code-task", ".car-code-task"] {
            assert!(
                !tree.contains(bookkeeping),
                "`{bookkeeping}` is runtime bookkeeping and must not reach a reviewed diff: {tree}"
            );
        }
    }

    /// A clean worktree whose HEAD is still the base has nothing to deliver.
    ///
    /// The fallback exists for a re-delivery — a green round whose PUSH failed,
    /// re-pushing its existing commit. It could not tell that from a FIRST round
    /// that was green with an empty diff, where HEAD is the base tip: the push
    /// then succeeded, created a stray remote branch pointing at the base, and
    /// `gh pr create` failed with "No commits between …" — retried forever, with
    /// junk branches accumulating on the remote.
    #[test]
    fn a_clean_worktree_at_the_base_is_refused_rather_than_pushed_empty() {
        let f = fixture();
        let c = contract();
        // Cut from main and change NOTHING: HEAD is still the base tip, which is
        // exactly the first-round-green-with-an-empty-diff case.
        let wt = f.cut("empty-round", "main");
        let base_tip = git(&wt, &["rev-parse", "HEAD"]).unwrap().trim().to_string();

        let err = deliver_pr_with(
            delivery(&f, &wt, &c, "goalpool/g_empty", true, "b"),
            &FakeGh::ok(),
        )
        .expect_err("an empty round must not open a pull request");
        assert_eq!(err.stage(), "commit", "{err}");
        assert!(
            err.reason().contains("nothing to deliver"),
            "{}",
            err.reason()
        );
        assert!(err.reason().contains(&base_tip), "{}", err.reason());
        assert!(!err.retriable(), "an empty round will be empty again");

        // Nothing reached the remote: no stray branch pointing at the base.
        assert!(
            git(
                &f.origin,
                &[
                    "rev-parse",
                    "--verify",
                    "--quiet",
                    "refs/heads/goalpool/g_empty"
                ]
            )
            .is_err(),
            "no stray branch may be created for an empty round"
        );
    }

    /// A refusal wrapped in rejection wording must read as a refusal.
    ///
    /// Branch protection arrives as `! [remote rejected] … (pre-receive hook
    /// declined)`, which matches the lost-race patterns. Adding those patterns
    /// without ordering refusals first would have turned every protected-branch
    /// rejection into an infinite retry — a fresh bug introduced by the fix.
    #[test]
    fn a_policy_refusal_wrapped_in_rejection_wording_is_not_a_race() {
        let (_, retriable) =
            classify_push_error("! [remote rejected] main -> main (pre-receive hook declined)");
        assert!(!retriable, "branch protection is not worth retrying");
    }

    /// The permission signals still fire on the real thing.
    #[test]
    fn a_genuine_403_is_still_a_non_retriable_refusal() {
        for message in [
            "fatal: unable to access 'https://github.com/o/r/': The requested URL returned error: 403",
            "remote: Permission to o/r.git denied to car-coder.",
            "fatal: Authentication failed for 'https://github.com/o/r/'",
            "fatal: could not read Username for 'https://github.com'",
        ] {
            let (_, retriable) = classify_push_error(message);
            assert!(!retriable, "must not be retried: {message}");
        }
    }

    /// **The blocker.** `main` passed `validate_branch_name` as both the target
    /// and the base, and nothing compared them — so the refspec became
    /// `<sha>:refs/heads/main` and unreviewed model output was published to the
    /// base branch. Reconciliation only failed afterwards, by which time an
    /// append-only path has no way to take it back.
    #[test]
    fn delivering_onto_the_base_branch_is_refused_before_anything_is_pushed() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "unreviewed").unwrap();

        let gh = FakeGh::ok();
        let err = deliver_pr_with(delivery(&f, &wt, &c, "main", true, "b"), &gh).unwrap_err();

        assert_eq!(err.stage(), "preflight", "{err}");
        assert!(!err.retriable());
        assert!(err.reason().contains("base"), "{err}");
        // Nothing was committed, nothing was pushed, and `gh` was never even
        // asked for a credential — the refusal costs no session.
        assert!(
            git(&wt, &["log", "-1", "--format=%an"])
                .unwrap()
                .trim()
                .ne("car-coder"),
            "the worktree must not have been committed"
        );
        assert!(gh.calls().is_empty(), "{:?}", gh.calls());
    }

    /// **The stringly sentinel.** A commit that fails for an ordinary reason
    /// must never be mistaken for a clean worktree just because the caller's
    /// intent happens to contain the phrase the clean-worktree check used to
    /// report.
    #[test]
    fn a_commit_failure_is_not_mistaken_for_a_clean_worktree() {
        let f = fixture();
        let c = contract();

        // Round 1 delivers for real, so HEAD is ahead of the base and the
        // re-delivery branch would have something to push.
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "round one").unwrap();
        let first =
            deliver_pr_with(delivery(&f, &wt, &c, TARGET, true, "b"), &FakeGh::ok()).unwrap();

        // Round 2 has real work — and a commit that cannot succeed. Signing with
        // a program that does not exist is the portable stand-in for the real
        // causes (a gpg agent that is not running, a shared `pre-commit` hook).
        std::fs::write(
            wt.join("y.txt"),
            "round two — the work that must not be lost",
        )
        .unwrap();
        git(&f.repo, &["config", "commit.gpgsign", "true"]).unwrap();
        git(&f.repo, &["config", "gpg.program", "/nonexistent/gpg"]).unwrap();

        let intent = "fix delivery so it reports 'no changes to deliver' correctly";
        let d = PrDelivery {
            intent,
            ..delivery(&f, &wt, &c, TARGET, true, "b")
        };
        let err = deliver_pr_with(d, &FakeGh::ok()).unwrap_err();

        assert_eq!(err.stage(), "commit", "{err}");
        // The decisive assertion: round 1's commit must NOT have been re-pushed
        // and reported as this round's delivery.
        assert_eq!(
            f.origin_head(TARGET).as_deref(),
            Some(first.commit.as_str()),
            "the stale commit must not be re-delivered as if it were round 2"
        );
    }

    /// A fork's pull request shares only the head ref NAME. Adopting it would
    /// overwrite a stranger's description, or reopen their closed pull request,
    /// while our own branch still had none.
    #[test]
    fn a_cross_repository_pull_request_is_not_adopted() {
        let raw = r#"[
            {"number":200,"state":"OPEN","url":"https://github.com/acme/repo/pull/200",
             "isDraft":false,"isCrossRepository":true,"baseRefName":"main"},
            {"number":7,"state":"OPEN","url":"https://github.com/acme/repo/pull/7",
             "isDraft":false,"isCrossRepository":false,"baseRefName":"main"}
        ]"#;
        let prs = parse_pr_list(raw).unwrap();
        assert_eq!(
            prs.iter().map(|p| p.number).collect::<Vec<_>>(),
            vec![7],
            "only the same-repository pull request may be reconciled"
        );
        // The field is actually requested, or the filter has nothing to read.
        assert!(gh_pr_list_args("b")
            .iter()
            .any(|a| a == "number,state,url,isDraft,isCrossRepository,baseRefName"));
    }

    /// `gh` must be pointed at the repository the push went to. Its own
    /// resolution prefers `upstream`, which on a fork clone is a different
    /// repository entirely.
    #[test]
    fn the_github_repository_is_taken_from_the_same_remote_the_push_uses() {
        for (url, expect) in [
            ("https://github.com/acme/repo.git", Some("acme/repo")),
            ("https://github.com/acme/repo", Some("acme/repo")),
            ("git@github.com:acme/repo.git", Some("acme/repo")),
            ("ssh://git@github.com/acme/repo.git", Some("acme/repo")),
            (
                "https://x-token@github.com/acme/repo.git",
                Some("acme/repo"),
            ),
            // A GitHub Enterprise host must keep its host, or `--repo` would
            // aim at github.com.
            (
                "git@github.example.com:acme/repo.git",
                Some("github.example.com/acme/repo"),
            ),
            // Not a remote URL naming one repository: say nothing and leave
            // `gh`'s own resolution alone.
            ("/srv/mirrors/repo.git", None),
            ("../sibling", None),
        ] {
            assert_eq!(
                parse_github_repo_spec(url).as_deref(),
                expect,
                "for `{url}`"
            );
        }

        // And it reaches the argv: the fixture's origin is a local path, so
        // nothing is added there, while a GitHub origin adds `--repo`.
        let f = fixture();
        assert!(gh_repo_args(&f.repo).is_empty());
        git(
            &f.repo,
            &[
                "remote",
                "set-url",
                "origin",
                "git@github.com:acme/repo.git",
            ],
        )
        .unwrap();
        assert_eq!(
            gh_repo_args(&f.repo),
            vec!["--repo".to_string(), "acme/repo".to_string()]
        );
    }

    /// The two permanent push failures the refusal set had no spelling for.
    /// Both landed on the retriable default, so the orchestrator requeued a full
    /// model session against a wall that can never move.
    #[test]
    fn a_404_or_401_push_failure_is_permanent_not_a_race() {
        for message in [
            "remote: Repository not found.\nfatal: repository \
             'https://github.com/o/private.git/' not found",
            "ERROR: Repository not found.\nfatal: Could not read from remote repository.",
            "fatal: unable to access 'https://github.com/o/r/': The requested URL returned \
             error: 401",
            "fatal: 'origin' does not appear to be a git repository",
        ] {
            let (_, retriable) = classify_push_error(message);
            assert!(!retriable, "must not be retried forever: {message}");
        }
        // And the loosening test: an ordinary lost race is still retriable.
        let (_, retriable) =
            classify_push_error("! [rejected] goalpool/g_404 -> goalpool/g_404 (non-fast-forward)");
        assert!(retriable, "a moved branch is still worth another round");
    }

    /// A repository-selecting environment variable overrides `-C`, so every
    /// path-based guard upstream can say yes while git acts somewhere else.
    /// Asserted against the source text: the point is that the clearing is
    /// WRITTEN, not that some execution path happened to cover it.
    #[test]
    fn git_does_not_inherit_the_repository_from_the_environment() {
        let production = MERGE_RS_SOURCE
            .split_once("mod tests {")
            .map(|(head, _)| head)
            .unwrap_or(MERGE_RS_SOURCE);
        for var in ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"] {
            assert!(
                production.contains(&format!(".env_remove(\"{var}\")")),
                "`git()` must clear {var}, which otherwise overrides `-C`"
            );
        }
    }

    /// `status --porcelain` honours `status.showUntrackedFiles`, and a
    /// repository or global `no` makes a worktree holding nothing but NEW files
    /// look clean — so delivery took the re-delivery branch and pushed a stale
    /// commit while the round's whole output stayed behind.
    #[test]
    fn a_worktree_holding_only_untracked_work_is_not_read_as_clean() {
        let f = fixture();
        let c = contract();
        git(&f.repo, &["config", "status.showUntrackedFiles", "no"]).unwrap();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("brand-new.txt"), "a day of work").unwrap();

        let out = deliver_pr_with(delivery(&f, &wt, &c, TARGET, true, "b"), &FakeGh::ok()).unwrap();

        assert_eq!(
            git(
                &f.origin,
                &["show", &format!("refs/heads/{TARGET}:brand-new.txt")]
            )
            .unwrap(),
            "a day of work",
            "the untracked work must be in the delivered commit"
        );
        assert_eq!(out.pr_action, PrAction::Opened);
    }

    // --- Round-5 findings --------------------------------------------------

    /// The pull-request body is MODEL output, and it must never be able to
    /// decide whether a failure is permanent.
    ///
    /// Reproduces the reported chain exactly: a goal whose intent names one of
    /// the permanent phrases produces a body containing it, the push succeeds,
    /// and `gh pr edit --body …` then hits an ordinary 502. Before the split in
    /// [`GhError`] the classifier read the whole argv, matched the phrase inside
    /// the echoed body, and returned `retriable: false` — exit 3, a goal parked
    /// forever with its commit already safely on the remote.
    #[test]
    fn a_permanent_phrase_in_the_body_cannot_make_a_transient_failure_permanent() {
        let f = fixture();
        let c = contract();

        // Round 1 opens the pull request.
        let wt1 = f.cut("s1", "main");
        std::fs::write(wt1.join("x.txt"), "one").unwrap();
        deliver_pr_with(delivery(&f, &wt1, &c, TARGET, false, "one"), &FakeGh::ok()).unwrap();

        // Round 2 updates it, and `gh pr edit` fails transiently.
        git(&f.repo, &["fetch", "-q", "origin"]).unwrap();
        let wt2 = f.cut("s2", &format!("origin/{TARGET}"));
        std::fs::write(wt2.join("y.txt"), "two").unwrap();

        let body = "This round fixes the 'no commits between' error on empty deliveries.";
        let gh = FakeGh::failing_set_body("HTTP 502: Bad Gateway (https://api.github.com/…)");
        *gh.prs.lock().unwrap() = vec![PrRecord {
            number: 101,
            state: PrState::Open,
            url: "https://github.com/acme/repo/pull/101".into(),
            is_draft: false,
            base: "main".into(),
        }];

        let err = deliver_pr_with(delivery(&f, &wt2, &c, TARGET, false, body), &gh).unwrap_err();
        assert!(
            err.retriable(),
            "a 502 is retriable however the body is worded: {err:?}"
        );

        // And the classifier still calls a REAL permanent failure permanent,
        // so the fix is not "everything is retriable now".
        let gh2 = FakeGh::failing_set_body("GraphQL: No commits between main and goalpool/g_1");
        *gh2.prs.lock().unwrap() = vec![PrRecord {
            number: 101,
            state: PrState::Open,
            url: "https://github.com/acme/repo/pull/101".into(),
            is_draft: false,
            base: "main".into(),
        }];
        let wt3 = f.cut("s3", &format!("origin/{TARGET}"));
        std::fs::write(wt3.join("z.txt"), "three").unwrap();
        let err2 =
            deliver_pr_with(delivery(&f, &wt3, &c, TARGET, false, "plain"), &gh2).unwrap_err();
        assert!(!err2.retriable(), "{err2:?}");
    }

    /// GitHub's one-open-pull-request rule is per (head, base) PAIR, so two
    /// open pull requests from one head into different bases are legal — but a
    /// push cannot be aimed at only one of them. The head is ambiguous, and
    /// delivery refuses before it commits anything rather than reconciling one
    /// pull request while quietly appending to the other.
    ///
    /// This fixture used to assert the opposite — that reconciliation picked
    /// the same-base pull request and left the other alone — which is the
    /// behavior car#1054 overturned. Reconciliation's base filter is still
    /// there and still load-bearing for the closed and merged cases; its
    /// coverage now lives in
    /// [`a_changed_base_opens_its_own_pull_request_once_the_old_one_is_closed`].
    #[test]
    fn an_open_pull_request_into_another_base_is_refused_rather_than_reconciled() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "work").unwrap();

        // #10 into `main` — ours. #12 into `release/2.1` — somebody else's,
        // which the push would have landed on all the same.
        let gh = FakeGh::with_prs(vec![
            PrRecord {
                number: 10,
                state: PrState::Open,
                url: "https://github.com/acme/repo/pull/10".into(),
                is_draft: false,
                base: "main".into(),
            },
            PrRecord {
                number: 12,
                state: PrState::Open,
                url: "https://github.com/acme/repo/pull/12".into(),
                is_draft: false,
                base: "release/2.1".into(),
            },
        ]);

        let err =
            deliver_pr_with(delivery(&f, &wt, &c, TARGET, false, "round body"), &gh).unwrap_err();

        assert!(
            matches!(err, DeliveryFailure::Preflight { .. }),
            "an ambiguous head is refused before the commit: {err:?}"
        );
        assert!(
            !err.retriable(),
            "retrying changes nothing — a human closes #12 or picks another target branch"
        );
        // Actionable: it names the offending pull request and its base.
        assert!(
            err.reason().contains("#12") && err.reason().contains("release/2.1"),
            "{}",
            err.reason()
        );

        // Nothing was written anywhere: no branch on the remote, and no pull
        // request touched — including the one into our own base.
        assert_eq!(f.origin_head(TARGET), None, "nothing may be pushed");
        assert!(
            !gh.calls()
                .iter()
                .any(|c| c.starts_with("set_body") || c.starts_with("create")),
            "{:?}",
            gh.calls()
        );
    }

    /// The issue's scenario verbatim: a human's pull request into `release/2.1`
    /// is open on the delivery branch and the round runs `--pr-base main`. The
    /// PUSH is what lands the model's commits on the human's pull request, so
    /// the assertion that matters is that the remote branch never moves.
    #[test]
    fn a_human_pull_request_into_another_base_parks_delivery_before_the_push() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "unreviewed model output").unwrap();

        let gh = FakeGh::with_prs(vec![PrRecord {
            number: 200,
            state: PrState::Open,
            url: "https://github.com/acme/repo/pull/200".into(),
            is_draft: false,
            base: "release/2.1".into(),
        }]);

        let err =
            deliver_pr_with(delivery(&f, &wt, &c, TARGET, false, "round body"), &gh).unwrap_err();

        assert_eq!(err.stage(), "preflight");
        assert!(!err.retriable(), "{err:?}");
        assert!(err.reason().contains("#200"), "{}", err.reason());
        assert_eq!(
            f.origin_head(TARGET),
            None,
            "the model's commits must never reach a branch #200 tracks"
        );
        assert!(
            !gh.calls().iter().any(|c| c.starts_with("create")),
            "no second pull request is opened to paper over the refusal: {:?}",
            gh.calls()
        );
    }

    /// A changed `--pr-base` no longer opens a second pull request while the
    /// first is open: the push would land on both.
    #[test]
    fn a_changed_base_is_refused_while_the_old_pull_request_is_open() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "work").unwrap();

        let gh = FakeGh::with_prs(vec![PrRecord {
            number: 10,
            state: PrState::Open,
            url: "https://github.com/acme/repo/pull/10".into(),
            is_draft: false,
            base: "main".into(),
        }]);
        let mut d = delivery(&f, &wt, &c, TARGET, false, "body");
        d.base_branch = "release/2.1";

        let err = deliver_pr_with(d, &gh).unwrap_err();
        assert_eq!(err.stage(), "preflight");
        assert!(err.reason().contains("#10"), "{}", err.reason());
        assert_eq!(f.origin_head(TARGET), None);
    }

    /// …and once that pull request is closed the same run proceeds and opens
    /// its own, which is what keeps the base filter and the create path live.
    #[test]
    fn a_changed_base_opens_its_own_pull_request_once_the_old_one_is_closed() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "work").unwrap();

        let gh = FakeGh::with_prs(vec![PrRecord {
            number: 10,
            state: PrState::ClosedUnmerged,
            url: "https://github.com/acme/repo/pull/10".into(),
            is_draft: false,
            base: "main".into(),
        }]);
        let mut d = delivery(&f, &wt, &c, TARGET, false, "body");
        d.base_branch = "release/2.1";

        let out = deliver_pr_with(d, &gh).unwrap();
        assert_eq!(out.pr_action, PrAction::Opened);
        assert_ne!(out.pr_number, 10);
        assert!(
            gh.calls()
                .iter()
                .any(|c| c.contains("create head=") && c.contains("base=release/2.1")),
            "{:?}",
            gh.calls()
        );
        // #10 is closed but into ANOTHER base, so it neither parks this run
        // nor gets touched: [`closed_pr_refusal`] is base-scoped, or any stale
        // pull request would hold a veto over a base it does not merge into.
        assert!(
            !gh.calls().iter().any(|c| c.starts_with("set_body")),
            "{:?}",
            gh.calls()
        );
    }

    /// Only OPEN pull requests park a run. A merged one into another base is
    /// inert — it cannot gain commits — so it is not ambiguity.
    #[test]
    fn a_merged_pull_request_into_another_base_does_not_park_delivery() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "work").unwrap();

        let gh = FakeGh::with_prs(vec![
            PrRecord {
                number: 10,
                state: PrState::Open,
                url: "https://github.com/acme/repo/pull/10".into(),
                is_draft: false,
                base: "main".into(),
            },
            PrRecord {
                number: 12,
                state: PrState::Merged,
                url: "https://github.com/acme/repo/pull/12".into(),
                is_draft: false,
                base: "release/2.1".into(),
            },
        ]);

        let out = deliver_pr_with(delivery(&f, &wt, &c, TARGET, false, "round body"), &gh).unwrap();
        assert_eq!(out.pr_action, PrAction::Updated);
        assert_eq!(out.pr_number, 10);
    }

    /// A fork's pull request that happens to share the head branch NAME cannot
    /// park a legitimate run — `parse_pr_list` drops cross-repository entries
    /// before delivery ever sees them, and the new preflight must not
    /// reintroduce them by reading the raw `gh` output itself.
    #[test]
    fn a_cross_repository_pull_request_does_not_park_delivery() {
        let parsed = parse_pr_list(
            r#"[
              {"number": 77, "state": "OPEN", "url": "u77", "isDraft": false,
               "baseRefName": "release/2.1", "isCrossRepository": true},
              {"number": 10, "state": "OPEN", "url": "u10", "isDraft": false,
               "baseRefName": "main", "isCrossRepository": false}
            ]"#,
        )
        .unwrap();
        assert_eq!(parsed.len(), 1, "the fork entry is dropped: {parsed:?}");

        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "work").unwrap();
        let gh = FakeGh::with_prs(parsed);

        let out = deliver_pr_with(delivery(&f, &wt, &c, TARGET, false, "round body"), &gh).unwrap();
        assert_eq!(out.pr_action, PrAction::Updated);
        assert_eq!(out.pr_number, 10);
    }

    /// `could not read Password` is git's message when the remote URL already
    /// carries a username — the shape `gh auth setup-git` leaves behind — and it
    /// is exactly as permanent as `could not read Username`.
    #[test]
    fn credential_prompts_that_can_never_be_answered_are_permanent() {
        for message in [
            "fatal: could not read Username for 'https://github.com': No such device or address",
            "fatal: could not read Password for 'https://someuser@github.com': \
             No such device or address",
            "fatal: could not read Username for 'https://github.com': terminal prompts disabled",
            "Host key verification failed.\nfatal: Could not read from remote repository.",
        ] {
            let (_, retriable) = classify_push_error(message);
            assert!(
                !retriable,
                "a credential that will never appear must not be retried: {message}"
            );
        }
        // Unchanged: an ordinary lost race on a branch whose name contains none
        // of those words is still retriable.
        let (_, retriable) =
            classify_push_error("! [rejected] goalpool/g_pw -> goalpool/g_pw (non-fast-forward)");
        assert!(retriable);
    }

    /// git prompts on `/dev/tty`, not stdin, so nulling stdin is not enough:
    /// a delivery launched with an inherited controlling terminal hung forever.
    /// Probed through git itself rather than by reading this file.
    #[test]
    fn git_children_cannot_open_a_terminal_prompt() {
        let dir = tempfile::tempdir().unwrap();
        git(dir.path(), &["init", "-q", "-b", "main"]).unwrap();
        // A `!` alias runs through the shell, so it can report what git handed
        // its children.
        let seen = git(
            dir.path(),
            &[
                "-c",
                "alias.envprobe=!printf %s \"${GIT_TERMINAL_PROMPT-unset}\"",
                "envprobe",
            ],
        )
        .unwrap();
        assert_eq!(
            seen.trim(),
            "0",
            "GIT_TERMINAL_PROMPT must be 0 for every git this module runs"
        );
    }

    /// A subprocess that never exits is killed and reported, rather than
    /// hanging a round that nobody is watching.
    #[test]
    fn a_subprocess_that_never_finishes_is_killed_and_reported() {
        let mut cmd = std::process::Command::new("sleep");
        cmd.arg("60");
        let started = std::time::Instant::now();
        let err = run_capped_for(cmd, std::time::Duration::from_millis(300)).err();
        assert!(
            matches!(err, Some(RunFailure::TimedOut(_))),
            "the child must be killed, not waited on"
        );
        assert!(
            started.elapsed() < std::time::Duration::from_secs(20),
            "the kill must not wait for the child's own exit"
        );
    }

    /// The headless branch mode's clean-worktree path: round N committed the
    /// work, round N+1 reuses the workspace with nothing left to commit, and
    /// that is a re-delivery rather than an error.
    #[test]
    fn branch_mode_re_delivers_a_clean_worktree_whose_head_is_ahead_of_the_base() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        std::fs::write(wt.join("x.txt"), "work").unwrap();
        // Round N: commits and names a branch.
        let first =
            publish_branch_headless(&f.repo, &wt, "r1", "make x exist", &c, "main", None).unwrap();
        assert_eq!(first, "car/coder/r1");

        // Round N+1: the same worktree, now clean, HEAD ahead of the base.
        let second =
            publish_branch_headless(&f.repo, &wt, "r2", "make x exist", &c, "main", None).unwrap();
        assert_eq!(second, "car/coder/r2");
        assert_eq!(
            git(&f.repo, &["rev-parse", "car/coder/r1"]).unwrap().trim(),
            git(&f.repo, &["rev-parse", "car/coder/r2"]).unwrap().trim(),
            "the same commit is re-delivered, not redone"
        );
    }

    /// The empty-first-round case is still refused: a clean worktree sitting AT
    /// the base has nothing to deliver, and naming a branch for it would prove
    /// nothing.
    #[test]
    fn branch_mode_still_refuses_a_clean_worktree_that_holds_no_work() {
        let f = fixture();
        let c = contract();
        let wt = f.cut("s1", "main");
        let err =
            publish_branch_headless(&f.repo, &wt, "r1", "noop", &c, "main", None).unwrap_err();
        assert!(err.contains("nothing to deliver"), "{err}");
    }

    /// A Windows-authored intent separates paragraphs with `\r\n\r\n`, which the
    /// blank-line split never matched — so the whole document was flattened and
    /// truncated at 72, and carriage returns rode into the commit subject.
    #[test]
    fn a_crlf_intent_still_stops_at_its_blank_line() {
        let intent =
            "Add the retry shim\r\n\r\nPointers:\r\n- see src/net.rs\r\n- and the docs\r\n";
        let subject = subject_from_intent(intent);
        assert_eq!(subject, "Add the retry shim");
        assert!(!subject.contains('\r'), "{subject:?}");
        // Mixed endings, and a lone `\r` inside the summary, are flattened too.
        assert!(!subject_from_intent("a\rb\r\nc").contains('\r'));
    }

    /// The human-readable half never echoes the model's title or body either.
    /// It reaches an event stream and a `run_end.error` an orchestrator logs,
    /// and those values are unbounded model output.
    #[test]
    fn forge_command_shapes_elide_the_title_and_body() {
        for args in [
            gh_pr_create_args("head", "main", "a title", "a very long body", false),
            az_pr_create_args("head", "main", "a title", "a very long body", false),
        ] {
            let shape = gh_subcommand_shape(&args);
            assert!(!shape.contains("a title"), "{shape}");
            assert!(!shape.contains("a very long body"), "{shape}");
            assert!(shape.contains("--title"), "{shape}");
        }
    }
}