cflx 0.6.322

Conflux – a spec-driven parallel coding orchestrator that runs AI agents on git worktrees
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
#![cfg(feature = "heavy-tests")]

//! Git worktree / real-boundary E2E integration tests.
//!
//! These tests intentionally use real git repositories, worktree commands, and
//! filesystem/process boundaries. They are integration/e2e coverage, not unit tests.

use std::fs;
use std::io::Write;
use std::path::Path;
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};

use conflux::orchestration::execute_rejection_flow;

#[path = "support/shared_test_support.rs"]
mod shared_test_support;

static SCRIPT_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Initialize a Git repository with initial commit for testing.
/// Returns true if git is available and repo was initialized successfully.
async fn init_git_repo(path: &Path) -> bool {
    use tokio::process::Command as TokioCommand;

    let init_result = TokioCommand::new("git")
        .args(["init"])
        .current_dir(path)
        .output()
        .await;

    match init_result {
        Ok(output) if output.status.success() => {}
        _ => return false,
    }

    let _ = TokioCommand::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(path)
        .output()
        .await;

    let _ = TokioCommand::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(path)
        .output()
        .await;

    std::fs::write(path.join("README.md"), "# Test Project\n").unwrap();
    let _ = TokioCommand::new("git")
        .args(["add", "."])
        .current_dir(path)
        .output()
        .await;

    let commit_result = TokioCommand::new("git")
        .args(["commit", "-m", "Initial commit"])
        .current_dir(path)
        .output()
        .await;

    matches!(commit_result, Ok(output) if output.status.success())
}

#[tokio::test]
async fn test_git_worktree_create_and_cleanup() {
    let temp_dir = tempfile::tempdir().unwrap();
    let temp_path = temp_dir.path();

    if !init_git_repo(temp_path).await {
        println!("Skipping test: git not available");
        return;
    }

    let worktree_path = temp_path.join("worktrees").join("test-worktree");
    let branch_name = "test-branch";

    let head_output = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(temp_path)
        .output()
        .unwrap();
    let head = String::from_utf8(head_output.stdout)
        .unwrap()
        .trim()
        .to_string();

    std::fs::create_dir_all(worktree_path.parent().unwrap()).unwrap();

    let create_output = Command::new("git")
        .args([
            "worktree",
            "add",
            worktree_path.to_str().unwrap(),
            "-b",
            branch_name,
            &head,
        ])
        .current_dir(temp_path)
        .output()
        .unwrap();

    assert!(
        create_output.status.success(),
        "Worktree creation should succeed: {}",
        String::from_utf8_lossy(&create_output.stderr)
    );
    assert!(worktree_path.exists(), "Worktree directory should exist");

    let list_output = Command::new("git")
        .args(["worktree", "list"])
        .current_dir(temp_path)
        .output()
        .unwrap();

    let list = String::from_utf8(list_output.stdout).unwrap();
    assert!(
        list.contains("test-worktree"),
        "Worktree should appear in list"
    );

    let remove_output = Command::new("git")
        .args([
            "worktree",
            "remove",
            worktree_path.to_str().unwrap(),
            "--force",
        ])
        .current_dir(temp_path)
        .output()
        .unwrap();

    assert!(
        remove_output.status.success(),
        "Worktree removal should succeed"
    );
    assert!(
        !worktree_path.exists(),
        "Worktree directory should be removed"
    );

    let branch_delete = Command::new("git")
        .args(["branch", "-D", branch_name])
        .current_dir(temp_path)
        .output()
        .unwrap();

    assert!(
        branch_delete.status.success(),
        "Branch deletion should succeed"
    );
}

#[tokio::test]
async fn test_git_worktree_parallel_execution_flow() {
    let temp_dir = tempfile::tempdir().unwrap();
    let temp_path = temp_dir.path();

    if !init_git_repo(temp_path).await {
        println!("Skipping test: git not available");
        return;
    }

    let worktrees_dir = temp_path.join("worktrees");
    std::fs::create_dir_all(&worktrees_dir).unwrap();

    let head_output = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(temp_path)
        .output()
        .unwrap();
    let base_commit = String::from_utf8(head_output.stdout)
        .unwrap()
        .trim()
        .to_string();

    let change_ids = ["change-1", "change-2"];
    let mut branch_names = Vec::new();

    for change_id in &change_ids {
        let branch_name = format!("ws-{}", change_id);
        let worktree_path = worktrees_dir.join(&branch_name);

        let create_output = Command::new("git")
            .args([
                "worktree",
                "add",
                worktree_path.to_str().unwrap(),
                "-b",
                &branch_name,
                &base_commit,
            ])
            .current_dir(temp_path)
            .output()
            .unwrap();

        assert!(
            create_output.status.success(),
            "Worktree creation for {} should succeed: {}",
            change_id,
            String::from_utf8_lossy(&create_output.stderr)
        );

        branch_names.push(branch_name);
    }

    for (i, change_id) in change_ids.iter().enumerate() {
        let branch_name = &branch_names[i];
        let worktree_path = worktrees_dir.join(branch_name);

        let file_name = format!("{}.txt", change_id);
        std::fs::write(
            worktree_path.join(&file_name),
            format!("Content for {}", change_id),
        )
        .unwrap();

        let _ = Command::new("git")
            .args(["add", "."])
            .current_dir(&worktree_path)
            .output()
            .unwrap();

        let commit_output = Command::new("git")
            .args(["commit", "-m", &format!("Apply: {}", change_id)])
            .current_dir(&worktree_path)
            .output()
            .unwrap();

        assert!(
            commit_output.status.success(),
            "Commit in {} should succeed",
            change_id
        );
    }

    for branch_name in &branch_names {
        let merge_output = Command::new("git")
            .args(["merge", branch_name, "--no-edit"])
            .current_dir(temp_path)
            .output()
            .unwrap();

        assert!(
            merge_output.status.success(),
            "Merge of {} should succeed: {}",
            branch_name,
            String::from_utf8_lossy(&merge_output.stderr)
        );
    }

    assert!(
        temp_path.join("change-1.txt").exists(),
        "change-1.txt should be merged"
    );
    assert!(
        temp_path.join("change-2.txt").exists(),
        "change-2.txt should be merged"
    );

    for branch_name in &branch_names {
        let worktree_path = worktrees_dir.join(branch_name);

        let _ = Command::new("git")
            .args([
                "worktree",
                "remove",
                worktree_path.to_str().unwrap(),
                "--force",
            ])
            .current_dir(temp_path)
            .output()
            .unwrap();

        let _ = Command::new("git")
            .args(["branch", "-D", branch_name])
            .current_dir(temp_path)
            .output()
            .unwrap();
    }

    let final_list = Command::new("git")
        .args(["worktree", "list"])
        .current_dir(temp_path)
        .output()
        .unwrap();

    let list = String::from_utf8(final_list.stdout).unwrap();
    assert!(
        !list.contains("ws-change"),
        "Worktrees should be cleaned up"
    );
}

#[tokio::test]
async fn test_git_worktree_conflict_detection() {
    let temp_dir = tempfile::tempdir().unwrap();
    let temp_path = temp_dir.path();

    if !init_git_repo(temp_path).await {
        println!("Skipping test: git not available");
        return;
    }

    std::fs::write(temp_path.join("shared.txt"), "original content\n").unwrap();
    let _ = Command::new("git")
        .args(["add", "."])
        .current_dir(temp_path)
        .output()
        .unwrap();
    let _ = Command::new("git")
        .args(["commit", "-m", "Add shared file"])
        .current_dir(temp_path)
        .output()
        .unwrap();

    let worktrees_dir = temp_path.join("worktrees");
    std::fs::create_dir_all(&worktrees_dir).unwrap();

    let head_output = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(temp_path)
        .output()
        .unwrap();
    let base_commit = String::from_utf8(head_output.stdout)
        .unwrap()
        .trim()
        .to_string();

    let worktree1 = worktrees_dir.join("ws-conflict-1");
    let worktree2 = worktrees_dir.join("ws-conflict-2");

    let _ = Command::new("git")
        .args([
            "worktree",
            "add",
            worktree1.to_str().unwrap(),
            "-b",
            "ws-conflict-1",
            &base_commit,
        ])
        .current_dir(temp_path)
        .output()
        .unwrap();

    let _ = Command::new("git")
        .args([
            "worktree",
            "add",
            worktree2.to_str().unwrap(),
            "-b",
            "ws-conflict-2",
            &base_commit,
        ])
        .current_dir(temp_path)
        .output()
        .unwrap();

    std::fs::write(worktree1.join("shared.txt"), "content from worktree 1\n").unwrap();
    let _ = Command::new("git")
        .args(["add", "."])
        .current_dir(&worktree1)
        .output()
        .unwrap();
    let _ = Command::new("git")
        .args(["commit", "-m", "Change from worktree 1"])
        .current_dir(&worktree1)
        .output()
        .unwrap();

    std::fs::write(worktree2.join("shared.txt"), "content from worktree 2\n").unwrap();
    let _ = Command::new("git")
        .args(["add", "."])
        .current_dir(&worktree2)
        .output()
        .unwrap();
    let _ = Command::new("git")
        .args(["commit", "-m", "Change from worktree 2"])
        .current_dir(&worktree2)
        .output()
        .unwrap();

    let merge1 = Command::new("git")
        .args(["merge", "ws-conflict-1", "--no-edit"])
        .current_dir(temp_path)
        .output()
        .unwrap();
    assert!(merge1.status.success(), "First merge should succeed");

    let merge2 = Command::new("git")
        .args(["merge", "ws-conflict-2", "--no-edit"])
        .current_dir(temp_path)
        .output()
        .unwrap();

    assert!(
        !merge2.status.success(),
        "Second merge should fail with conflict"
    );

    let stderr = String::from_utf8_lossy(&merge2.stderr);
    let stdout = String::from_utf8_lossy(&merge2.stdout);
    let combined = format!("{}\n{}", stdout, stderr);

    assert!(
        combined.contains("CONFLICT")
            || combined.contains("conflict")
            || combined.contains("Merge conflict"),
        "Output should indicate conflict: {}",
        combined
    );

    let _ = Command::new("git")
        .args(["merge", "--abort"])
        .current_dir(temp_path)
        .output()
        .unwrap();

    let _ = Command::new("git")
        .args(["worktree", "remove", worktree1.to_str().unwrap(), "--force"])
        .current_dir(temp_path)
        .output()
        .unwrap();
    let _ = Command::new("git")
        .args(["worktree", "remove", worktree2.to_str().unwrap(), "--force"])
        .current_dir(temp_path)
        .output()
        .unwrap();
    let _ = Command::new("git")
        .args(["branch", "-D", "ws-conflict-1"])
        .current_dir(temp_path)
        .output()
        .unwrap();
    let _ = Command::new("git")
        .args(["branch", "-D", "ws-conflict-2"])
        .current_dir(temp_path)
        .output()
        .unwrap();
}

#[tokio::test]
async fn test_vcs_backend_auto_detection_git() {
    let temp_dir = tempfile::tempdir().unwrap();
    let temp_path = temp_dir.path();

    if !init_git_repo(temp_path).await {
        println!("Skipping test: git not available");
        return;
    }

    assert!(
        temp_path.join(".git").exists(),
        ".git directory should exist"
    );
}

#[tokio::test]
async fn test_git_worktree_staged_changes_error() {
    let temp_dir = tempfile::tempdir().unwrap();
    let temp_path = temp_dir.path();

    if !init_git_repo(temp_path).await {
        println!("Skipping test: git not available");
        return;
    }

    std::fs::write(temp_path.join("staged.txt"), "staged content").unwrap();
    let _ = Command::new("git")
        .args(["add", "staged.txt"])
        .current_dir(temp_path)
        .output()
        .unwrap();

    let status_output = Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(temp_path)
        .output()
        .unwrap();

    let status = String::from_utf8(status_output.stdout).unwrap();
    assert!(
        status.contains("A"),
        "Staged file should be detected with 'A' status"
    );
    assert!(!status.is_empty(), "Repo should have staged changes");
}

#[tokio::test]
#[allow(clippy::await_holding_lock)]
async fn test_blocked_rejection_flow_end_to_end_creates_marker_and_removes_worktree() {
    let temp_dir = tempfile::tempdir().unwrap();
    let repo_root = temp_dir.path();

    if !init_git_repo(repo_root).await {
        println!("Skipping test: git not available");
        return;
    }

    let change_id = "blocked-e2e";
    let change_dir = repo_root.join("openspec/changes").join(change_id);
    fs::create_dir_all(&change_dir).unwrap();
    fs::write(change_dir.join("proposal.md"), "# proposal\n").unwrap();
    fs::write(change_dir.join("tasks.md"), "- [ ] task\n").unwrap();

    let script_id = SCRIPT_COUNTER.fetch_add(1, Ordering::Relaxed);
    let mock_bin = repo_root.join(format!("mock_bin_{}", script_id));
    fs::create_dir_all(&mock_bin).unwrap();
    let mock_openspec = mock_bin.join("openspec");

    use std::os::unix::fs::OpenOptionsExt;
    let mut openspec_file = fs::OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .mode(0o755)
        .open(&mock_openspec)
        .unwrap();
    openspec_file
        .write_all(
            b"#!/bin/bash\nif [ \"$1\" = \"resolve\" ]; then\n  exit 0\nfi\necho \"unexpected openspec command\" >&2\nexit 1\n",
        )
        .unwrap();
    openspec_file.sync_all().unwrap();
    drop(openspec_file);

    let _env_guard = shared_test_support::env_lock();
    let original_path = std::env::var("PATH").unwrap_or_default();
    unsafe {
        std::env::set_var("PATH", format!("{}:{}", mock_bin.display(), original_path));
    }

    let base_branch = Command::new("git")
        .args(["branch", "--show-current"])
        .current_dir(repo_root)
        .output()
        .unwrap();
    assert!(base_branch.status.success());
    let base_branch = String::from_utf8(base_branch.stdout)
        .unwrap()
        .trim()
        .to_string();

    let worktree_path = repo_root.join(".worktrees").join(change_id);
    fs::create_dir_all(worktree_path.parent().unwrap()).unwrap();

    let add_output = Command::new("git")
        .args([
            "worktree",
            "add",
            "-b",
            &format!("wt/{}", change_id),
            worktree_path.to_str().unwrap(),
            &base_branch,
        ])
        .current_dir(repo_root)
        .output()
        .unwrap();
    assert!(add_output.status.success());

    let result = execute_rejection_flow(
        change_id,
        "E2E acceptance blocked",
        &worktree_path,
        &base_branch,
        repo_root,
    )
    .await;

    unsafe {
        std::env::set_var("PATH", original_path);
    }

    assert!(
        result.is_ok(),
        "rejection flow should succeed in e2e: {:?}",
        result
    );

    let rejected_marker = change_dir.join("REJECTED.md");
    assert!(
        rejected_marker.exists(),
        "REJECTED.md must exist after rejection"
    );
    let content = fs::read_to_string(rejected_marker).unwrap();
    assert!(content.contains("change_id: blocked-e2e"));
    assert!(content.contains("reason: E2E acceptance blocked"));

    let list_output = Command::new("git")
        .args(["worktree", "list", "--porcelain"])
        .current_dir(repo_root)
        .output()
        .unwrap();
    assert!(list_output.status.success());
    let list_text = String::from_utf8(list_output.stdout).unwrap();
    assert!(
        !list_text.contains(worktree_path.to_str().unwrap()),
        "rejected worktree should be removed"
    );
}

// ── Upstream integration (real Git / bare remote / process boundaries) ──────
//
// These cases deliberately exercise real repositories, a real local bare
// remote, real `git` subprocesses, and real verification-command processes.
// They are integration/e2e coverage, not unit tests, and stay behind
// `heavy-tests` so the default suite is unaffected.

mod upstream_integration_support {
    use std::path::Path;
    use std::process::Command;
    use std::sync::Arc;

    use conflux::upstream::checkpoint::BaseLaneState;
    use conflux::upstream::coordinator::{SchedulerOutcome, UpstreamCoordinator};
    use conflux::upstream::git_ops::GitUpstreamOps;
    use conflux::upstream::options::UpstreamIntegrationConfig;
    use conflux::upstream::ports::{
        NoopUpstreamObserver, PortResult, RepairAttemptResult, RepairRequest, UpstreamRepairAgent,
    };
    use conflux::upstream::verify::CommandVerifier;

    pub use conflux::upstream::checkpoint::CheckpointTrigger;
    pub use conflux::upstream::coordinator::{
        scan_pending_publications, FinalizeOutcome, PublicationOutcome, UpstreamStepOutcome,
    };

    pub fn git(cwd: &Path, args: &[&str]) -> String {
        let output = Command::new("git")
            .args(args)
            .current_dir(cwd)
            .output()
            .unwrap_or_else(|e| panic!("git {:?} failed to start: {}", args, e));
        assert!(
            output.status.success(),
            "git {:?} failed: {}",
            args,
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    }

    pub fn git_allow_failure(cwd: &Path, args: &[&str]) -> bool {
        Command::new("git")
            .args(args)
            .current_dir(cwd)
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    }

    pub fn configure_identity(path: &Path) {
        git(path, &["config", "user.email", "test@example.com"]);
        git(path, &["config", "user.name", "Test User"]);
        git(path, &["config", "commit.gpgsign", "false"]);
    }

    pub fn write_and_commit(path: &Path, file: &str, contents: &str, message: &str) -> String {
        let target = path.join(file);
        if let Some(parent) = target.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(&target, contents).unwrap();
        git(path, &["add", "."]);
        git(path, &["commit", "-m", message]);
        git(path, &["rev-parse", "HEAD"])
    }

    /// A base repository on branch `main` with a local bare remote `origin`.
    pub struct Fixture {
        pub _dir: tempfile::TempDir,
        pub repo: std::path::PathBuf,
        pub remote: std::path::PathBuf,
        pub clone2: std::path::PathBuf,
    }

    /// Build the fixture, or `None` when git is unavailable.
    pub fn fixture() -> Option<Fixture> {
        let dir = tempfile::tempdir().unwrap();
        let remote = dir.path().join("remote.git");
        let repo = dir.path().join("repo");
        let clone2 = dir.path().join("other");
        std::fs::create_dir_all(&repo).unwrap();

        if !git_allow_failure(dir.path(), &["init", "--bare", "-b", "main", "remote.git"]) {
            return None;
        }
        if !git_allow_failure(&repo, &["init", "-b", "main"]) {
            return None;
        }
        configure_identity(&repo);
        write_and_commit(&repo, "README.md", "# base\n", "Initial commit");
        git(
            &repo,
            &["remote", "add", "origin", remote.to_str().unwrap()],
        );
        git(&repo, &["push", "-u", "origin", "main"]);

        // A second clone stands in for another actor advancing the remote.
        git(
            dir.path(),
            &["clone", remote.to_str().unwrap(), clone2.to_str().unwrap()],
        );
        configure_identity(&clone2);

        Some(Fixture {
            _dir: dir,
            repo,
            remote,
            clone2,
        })
    }

    /// Add a `Merge change:` integration commit with real archive tree evidence.
    pub fn add_cumulative_change_merge(repo: &Path, change_id: &str) -> String {
        let base = git(repo, &["rev-parse", "HEAD"]);
        git(repo, &["checkout", "-b", &format!("wt-{}", change_id)]);
        // Active change directory, then archived: exactly what a real archive does.
        write_and_commit(
            repo,
            &format!("openspec/changes/archive/{}/proposal.md", change_id),
            "# archived\n",
            &format!("archive {}", change_id),
        );
        git(repo, &["checkout", "main"]);
        git(repo, &["reset", "--hard", &base]);
        git(
            repo,
            &[
                "merge",
                "--no-ff",
                "-m",
                &format!("Merge change: {}", change_id),
                &format!("wt-{}", change_id),
            ],
        );
        git(repo, &["rev-parse", "HEAD"])
    }

    /// Record the publication-required marker the base lane writes after an
    /// opted-in change integrates into cumulative base.
    ///
    /// This is a real commit in a real repository, so everything derived from it
    /// (restart refusal, retry routing, recovery) is exercised against genuine
    /// Git evidence rather than a fixture flag.
    pub fn mark_publication_required(repo: &Path, change_id: &str) -> String {
        let message = conflux::upstream::publication::format_publication_marker_message(
            change_id, "origin", "main",
        );
        git(repo, &["commit", "--allow-empty", "-m", &message]);
        git(repo, &["rev-parse", "HEAD"])
    }

    /// Integrate a change into cumulative base exactly as an opted-in run does:
    /// the `Merge change:` integration commit, then its publication marker.
    pub fn integrate_and_mark(repo: &Path, change_id: &str) -> String {
        add_cumulative_change_merge(repo, change_id);
        mark_publication_required(repo, change_id)
    }

    pub fn ops(repo: &Path) -> GitUpstreamOps {
        GitUpstreamOps::new(repo)
    }

    /// Verification command that always succeeds, executed as a real process.
    pub const PASSING_COMMAND: &str = "exit 0";

    /// Verification command that always fails, executed as a real process.
    pub const FAILING_COMMAND: &str = "exit 1";

    /// A repair agent that runs a real shell script in the repository.
    pub struct ScriptRepairAgent {
        pub repo: std::path::PathBuf,
        pub script: String,
        pub max_attempts: u32,
        pub calls: std::sync::Arc<std::sync::atomic::AtomicUsize>,
    }

    #[async_trait::async_trait]
    impl UpstreamRepairAgent for ScriptRepairAgent {
        fn max_attempts(&self) -> u32 {
            self.max_attempts
        }

        async fn repair(&self, _request: &RepairRequest) -> PortResult<RepairAttemptResult> {
            self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            let status = tokio::process::Command::new("sh")
                .arg("-c")
                .arg(&self.script)
                .current_dir(&self.repo)
                .status()
                .await
                .unwrap();
            Ok(RepairAttemptResult {
                command_success: status.success(),
            })
        }
    }

    /// A repair agent that must never be invoked.
    ///
    /// `budget` is the bounded retry budget Conflux owns; a zero budget proves a
    /// failure stalls without ever reaching the agent.
    pub struct ForbiddenRepairAgent;

    pub struct ZeroBudgetRepairAgent;

    #[async_trait::async_trait]
    impl UpstreamRepairAgent for ZeroBudgetRepairAgent {
        fn max_attempts(&self) -> u32 {
            0
        }

        async fn repair(&self, request: &RepairRequest) -> PortResult<RepairAttemptResult> {
            panic!(
                "zero-budget repair agent must not be invoked for cause {:?}",
                request.cause
            );
        }
    }

    #[async_trait::async_trait]
    impl UpstreamRepairAgent for ForbiddenRepairAgent {
        fn max_attempts(&self) -> u32 {
            2
        }

        async fn repair(&self, request: &RepairRequest) -> PortResult<RepairAttemptResult> {
            panic!(
                "repair agent must not be invoked for cause {:?}",
                request.cause
            );
        }
    }

    pub fn coordinator(
        repo: &Path,
        verify_command: &str,
        repair: Arc<dyn UpstreamRepairAgent>,
    ) -> UpstreamCoordinator {
        UpstreamCoordinator::new(
            UpstreamIntegrationConfig::new("origin", verify_command),
            "main",
            Arc::new(GitUpstreamOps::new(repo)),
            Arc::new(CommandVerifier::new(verify_command, repo)),
            repair,
            Arc::new(NoopUpstreamObserver),
        )
    }

    pub fn clean_lane() -> BaseLaneState {
        BaseLaneState::clean()
    }

    pub fn after_drain() -> CheckpointTrigger {
        CheckpointTrigger::AfterDrain
    }

    pub fn drained() -> SchedulerOutcome {
        SchedulerOutcome::DrainedSuccessfully
    }
}

#[tokio::test]
async fn upstream_integration_e2e_noop_when_remote_already_integrated() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    let head_before = git(&fx.repo, &["rev-parse", "HEAD"]);

    let outcome = coordinator
        .checkpoint(after_drain(), &clean_lane(), None)
        .await
        .unwrap();

    assert!(
        matches!(outcome, UpstreamStepOutcome::NoOp { .. }),
        "outcome: {:?}",
        outcome
    );
    assert_eq!(
        git(&fx.repo, &["rev-parse", "HEAD"]),
        head_before,
        "an ancestry-proven no-op must not create a commit"
    );
}

#[tokio::test]
async fn upstream_integration_e2e_remote_advance_creates_trailer_bearing_merge() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    // Local cumulative work.
    add_cumulative_change_merge(&fx.repo, "local-change");
    // Another actor advances the remote.
    let remote_sha = write_and_commit(&fx.clone2, "upstream.md", "upstream\n", "upstream work");
    git(&fx.clone2, &["push", "origin", "main"]);

    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    let outcome = coordinator
        .checkpoint(after_drain(), &clean_lane(), None)
        .await
        .unwrap();

    let merge_sha = match outcome {
        UpstreamStepOutcome::Integrated { merge_sha } => merge_sha,
        other => panic!("expected integration, got {:?}", other),
    };

    let message = git(&fx.repo, &["log", "-1", "--format=%B", &merge_sha]);
    assert!(
        message.contains("Cflx-Upstream-Remote: origin"),
        "{}",
        message
    );
    assert!(
        message.contains("Cflx-Upstream-Branch: main"),
        "{}",
        message
    );
    assert!(
        message.contains(&format!("Cflx-Upstream-SHA: {}", remote_sha)),
        "{}",
        message
    );

    let parents = git(&fx.repo, &["log", "-1", "--format=%P", &merge_sha]);
    assert_eq!(
        parents.split_whitespace().count(),
        2,
        "must be a --no-ff merge"
    );
    assert!(parents.split_whitespace().any(|p| p == remote_sha));
}

#[tokio::test]
async fn upstream_integration_e2e_strictly_remote_ahead_still_merges() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    // No local work at all: the remote is strictly ahead.
    write_and_commit(&fx.clone2, "upstream.md", "upstream\n", "upstream work");
    git(&fx.clone2, &["push", "origin", "main"]);

    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    let outcome = coordinator
        .checkpoint(after_drain(), &clean_lane(), None)
        .await
        .unwrap();

    assert!(
        matches!(outcome, UpstreamStepOutcome::Integrated { .. }),
        "strictly remote-ahead history is still integrated with --no-ff: {:?}",
        outcome
    );
    let parents = git(&fx.repo, &["log", "-1", "--format=%P"]);
    assert_eq!(parents.split_whitespace().count(), 2);
}

#[tokio::test]
async fn upstream_integration_e2e_first_parent_history_classification() {
    use conflux::upstream::coordinator::validate_initial_fetch;
    use conflux::upstream::git_ops::GitUpstreamOps;
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    let git_ops = GitUpstreamOps::new(&fx.repo);

    // A cumulative change integration with real archive tree evidence is accepted.
    add_cumulative_change_merge(&fx.repo, "accepted-change");
    let validation = validate_initial_fetch(&git_ops, "origin", "main")
        .await
        .unwrap()
        .expect("recognized cumulative history is publishable");
    assert_eq!(
        validation.spine.integrated_change_ids,
        vec!["accepted-change".to_string()]
    );

    // An unrelated first-parent commit is rejected before any mutation.
    write_and_commit(&fx.repo, "hotfix.md", "hotfix\n", "hotfix: local only");
    let rejected = validate_initial_fetch(&git_ops, "origin", "main")
        .await
        .unwrap()
        .expect_err("unrelated local-only history must be rejected");
    assert!(
        rejected.to_string().contains("unrelated commit"),
        "diagnostic: {}",
        rejected
    );
}

#[tokio::test]
async fn upstream_integration_e2e_restart_recovery_identifies_unpushed_merge() {
    use conflux::upstream::coordinator::{
        scan_unpushed_upstream_merges, upstream_recovery_refusal,
    };
    use conflux::upstream::git_ops::GitUpstreamOps;
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    add_cumulative_change_merge(&fx.repo, "local-change");
    write_and_commit(&fx.clone2, "upstream.md", "upstream\n", "upstream work");
    git(&fx.clone2, &["push", "origin", "main"]);

    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    coordinator
        .checkpoint(after_drain(), &clean_lane(), None)
        .await
        .unwrap();

    // Simulate a crash: a new process observes only repository state.
    let git_ops = GitUpstreamOps::new(&fx.repo);
    let evidence = scan_unpushed_upstream_merges(&git_ops).await.unwrap();
    assert_eq!(
        evidence.len(),
        1,
        "the unpushed upstream merge is recovered"
    );
    assert_eq!(evidence[0].trailers.remote, "origin");
    assert_eq!(evidence[0].trailers.branch, "main");

    // A run without `-u` must refuse to continue.
    let refusal = upstream_recovery_refusal(&evidence).expect("option-less run is refused");
    assert!(refusal.to_string().contains("--integrate-upstream=origin"));

    // Deleting runtime projections cannot change the safe next action.
    let _ = std::fs::remove_dir_all(fx.repo.join(".cflx"));
    let after = scan_unpushed_upstream_merges(&git_ops).await.unwrap();
    assert_eq!(after.len(), 1);

    // After the push, the same scan reports nothing to recover.
    let outcome = coordinator.finalize(drained()).await.unwrap();
    assert!(
        matches!(outcome, FinalizeOutcome::Completed { .. }),
        "{:?}",
        outcome
    );
    let published = scan_unpushed_upstream_merges(&git_ops).await.unwrap();
    assert!(
        published.is_empty(),
        "published merges are not recovery evidence"
    );
}

#[tokio::test]
async fn upstream_integration_e2e_semantic_repair_then_reverification() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    write_and_commit(&fx.clone2, "upstream.md", "upstream\n", "upstream work");
    git(&fx.clone2, &["push", "origin", "main"]);

    // Real verification process: fails until `fixed` exists in the worktree.
    let verify_command = "test -f fixed";
    let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let repair = std::sync::Arc::new(ScriptRepairAgent {
        repo: fx.repo.clone(),
        script: "touch fixed && git add fixed && git commit -m 'repair: satisfy verification'"
            .to_string(),
        max_attempts: 2,
        calls: calls.clone(),
    });

    let head_before = git(&fx.repo, &["rev-parse", "HEAD"]);
    let mut coordinator = coordinator(&fx.repo, verify_command, repair);
    let outcome = coordinator
        .checkpoint(after_drain(), &clean_lane(), None)
        .await
        .unwrap();

    assert!(
        matches!(outcome, UpstreamStepOutcome::Integrated { .. }),
        "outcome: {:?}",
        outcome
    );
    assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
    // Repair is forward-only: the pre-repair HEAD is still an ancestor.
    assert!(git_allow_failure(
        &fx.repo,
        &["merge-base", "--is-ancestor", &head_before, "HEAD"]
    ));
}

#[tokio::test]
async fn upstream_integration_e2e_blocked_and_cancelled_outcomes_never_push() {
    use conflux::upstream::coordinator::SchedulerOutcome;
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    add_cumulative_change_merge(&fx.repo, "local-change");
    let remote_before = git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]);

    for outcome in [
        SchedulerOutcome::BlockedOrStalled,
        SchedulerOutcome::Cancelled,
    ] {
        let mut coordinator = coordinator(
            &fx.repo,
            PASSING_COMMAND,
            std::sync::Arc::new(ForbiddenRepairAgent),
        );
        let result = coordinator.finalize(outcome).await.unwrap();
        assert!(
            matches!(result, FinalizeOutcome::Skipped { .. }),
            "{:?}",
            result
        );
    }

    assert_eq!(
        git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]),
        remote_before,
        "a non-drained outcome must not advance the remote"
    );
}

#[tokio::test]
async fn upstream_integration_e2e_successful_drain_pushes_once_and_confirms() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    let local_head = integrate_and_mark(&fx.repo, "local-change");

    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    let outcome = coordinator.finalize(drained()).await.unwrap();
    assert_eq!(
        outcome,
        FinalizeOutcome::Completed {
            pushed_head: local_head.clone()
        }
    );

    let remote_sha = git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]);
    assert!(
        remote_sha.starts_with(&local_head),
        "remote: {}",
        remote_sha
    );

    // At most one successful push: a repeat finalization does not push again.
    let repeat = coordinator.finalize(drained()).await.unwrap();
    assert_eq!(
        repeat,
        FinalizeOutcome::Completed {
            pushed_head: local_head
        }
    );
}

#[tokio::test]
async fn upstream_integration_e2e_zero_change_run_manufactures_no_history() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    let head_before = git(&fx.repo, &["rev-parse", "HEAD"]);
    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    let outcome = coordinator.finalize(drained()).await.unwrap();
    assert_eq!(outcome, FinalizeOutcome::NoWork);
    assert_eq!(git(&fx.repo, &["rev-parse", "HEAD"]), head_before);

    // A remote-only advance updates observation only.
    write_and_commit(&fx.clone2, "upstream.md", "upstream\n", "upstream work");
    git(&fx.clone2, &["push", "origin", "main"]);
    let outcome = coordinator.finalize(drained()).await.unwrap();
    assert_eq!(outcome, FinalizeOutcome::NoWork);
    assert_eq!(
        git(&fx.repo, &["rev-parse", "HEAD"]),
        head_before,
        "a remote-only advance must not create a synthetic local merge"
    );
}

#[tokio::test]
async fn upstream_integration_e2e_push_race_returns_to_integration_then_succeeds() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    // Local work plus a concurrent remote advance: the pre-push check must
    // suppress the stale push, integrate, reverify, and only then publish.
    integrate_and_mark(&fx.repo, "local-change");
    let racing_sha = write_and_commit(&fx.clone2, "upstream.md", "upstream\n", "upstream work");
    git(&fx.clone2, &["push", "origin", "main"]);

    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    let outcome = coordinator.finalize(drained()).await.unwrap();

    let pushed = match outcome {
        FinalizeOutcome::Completed { pushed_head } => pushed_head,
        other => panic!("expected completion, got {:?}", other),
    };

    // The racing revision was integrated rather than force-pushed over.
    assert!(git_allow_failure(
        &fx.repo,
        &["merge-base", "--is-ancestor", &racing_sha, &pushed]
    ));
    let remote_sha = git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]);
    assert!(remote_sha.starts_with(&pushed));
}

#[tokio::test]
async fn upstream_integration_e2e_hook_rejected_push_stalls_without_agent() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    integrate_and_mark(&fx.repo, "local-change");

    // A real pre-receive hook rejection: not a race, and the local tree is clean,
    // so this must stall with no agent invocation.
    let hook = fx.remote.join("hooks").join("pre-receive");
    std::fs::create_dir_all(hook.parent().unwrap()).unwrap();
    std::fs::write(&hook, "#!/bin/sh\nexit 1\n").unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
    }

    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    let outcome = coordinator.finalize(drained()).await.unwrap();
    assert!(
        matches!(outcome, FinalizeOutcome::Stalled { .. }),
        "outcome: {:?}",
        outcome
    );
    assert!(coordinator.pushed_head().is_none());
}

#[tokio::test]
async fn upstream_integration_e2e_checkpoint_batches_results_behind_one_fetch() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    write_and_commit(&fx.clone2, "upstream.md", "upstream\n", "upstream work");
    git(&fx.clone2, &["push", "origin", "main"]);

    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );

    // First completed result starts the checkpoint and integrates.
    let first = coordinator
        .checkpoint(
            CheckpointTrigger::BeforeBaseIntegration,
            &clean_lane(),
            Some("change-a"),
        )
        .await
        .unwrap();
    assert!(matches!(first, UpstreamStepOutcome::Integrated { .. }));

    // A second result arriving after release is a deterministic no-op, not a
    // second merge: the remote has not advanced again.
    let second = coordinator
        .checkpoint(
            CheckpointTrigger::BeforeBaseIntegration,
            &clean_lane(),
            Some("change-b"),
        )
        .await
        .unwrap();
    assert!(
        matches!(second, UpstreamStepOutcome::NoOp { .. }),
        "{:?}",
        second
    );

    let merges = git(&fx.repo, &["log", "--merges", "--format=%s", "HEAD"]);
    assert_eq!(
        merges
            .lines()
            .filter(|line| line.starts_with("Merge upstream:"))
            .count(),
        1,
        "one upstream advance produces exactly one merge"
    );
}

#[tokio::test]
async fn upstream_integration_e2e_dirty_base_defers_entire_checkpoint() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    write_and_commit(&fx.clone2, "upstream.md", "upstream\n", "upstream work");
    git(&fx.clone2, &["push", "origin", "main"]);

    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    let head_before = git(&fx.repo, &["rev-parse", "HEAD"]);
    let dirty = conflux::upstream::checkpoint::BaseLaneState {
        base_dirty_reason: Some("uncommitted changes".to_string()),
        lane_busy_reason: None,
    };

    let outcome = coordinator
        .checkpoint(
            CheckpointTrigger::BeforeBaseIntegration,
            &dirty,
            Some("change-a"),
        )
        .await
        .unwrap();
    assert!(
        matches!(outcome, UpstreamStepOutcome::Deferred { .. }),
        "{:?}",
        outcome
    );
    assert_eq!(git(&fx.repo, &["rev-parse", "HEAD"]), head_before);
    assert_eq!(coordinator.queued_results(), vec!["change-a".to_string()]);
}

#[tokio::test]
async fn upstream_integration_e2e_stale_result_verification_runs_against_current_base() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    // A worktree accepted against an older base is represented by a file the
    // upstream advance is incompatible with. The complete verification command
    // is a real process reading the current tree.
    write_and_commit(&fx.clone2, "upstream.md", "conflicting\n", "upstream work");
    git(&fx.clone2, &["push", "origin", "main"]);

    let mut coordinator = coordinator(
        &fx.repo,
        "test ! -f upstream.md",
        std::sync::Arc::new(ZeroBudgetRepairAgent),
    );
    let outcome = coordinator
        .verify_base_result("stale-change")
        .await
        .unwrap();
    assert!(
        matches!(outcome, UpstreamStepOutcome::Integrated { .. }),
        "the current base still satisfies the command before integration"
    );

    // After integrating upstream, the same completed result fails verification
    // and the base lane must stay closed.
    let integrated = coordinator
        .checkpoint(after_drain(), &clean_lane(), None)
        .await
        .unwrap();
    assert!(
        matches!(integrated, UpstreamStepOutcome::Stalled { .. }),
        "{:?}",
        integrated
    );

    let blocked = coordinator
        .verify_base_result("stale-change")
        .await
        .unwrap();
    match blocked {
        UpstreamStepOutcome::Stalled { reason } => assert!(reason.contains("stale-change")),
        other => panic!("expected stall, got {:?}", other),
    }
    assert!(coordinator.pushed_head().is_none());
}

// ── Per-change upstream publication (real Git / bare remote / processes) ────
//
// These cases prove the change-scoped publication contract against genuine
// repositories, a real local bare remote, real `git` subprocesses, and real
// verification-command processes. A stubbed publication, run-only wiring,
// missing crash evidence, a premature `merged`, or an unconfirmed push all fail
// here.

#[tokio::test]
async fn per_change_upstream_e2e_publishes_one_change_and_confirms_remotely() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    let head = integrate_and_mark(&fx.repo, "alpha");
    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );

    let outcome = coordinator.publish_change("alpha").await.unwrap();

    assert_eq!(
        outcome,
        PublicationOutcome::Published { head: head.clone() }
    );
    let observed = git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]);
    assert!(
        observed.starts_with(&head),
        "remote must actually contain the published revision: {}",
        observed
    );

    // Once published, the marker is no longer outstanding work.
    git(&fx.repo, &["fetch", "origin", "main"]);
    let pending = scan_pending_publications(&ops(&fx.repo)).await.unwrap();
    assert!(pending.is_empty(), "pending: {:?}", pending);
}

#[tokio::test]
async fn per_change_upstream_e2e_persistent_process_publishes_multiple_changes() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    // One long-lived coordinator, as a persistent local TUI keeps: publication
    // happens at each change boundary and never waits for scheduler drain.
    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );

    let alpha_head = integrate_and_mark(&fx.repo, "alpha");
    let first = coordinator.publish_change("alpha").await.unwrap();
    assert_eq!(
        first,
        PublicationOutcome::Published {
            head: alpha_head.clone()
        }
    );

    let beta_head = integrate_and_mark(&fx.repo, "beta");
    let second = coordinator.publish_change("beta").await.unwrap();
    assert_eq!(
        second,
        PublicationOutcome::Published {
            head: beta_head.clone()
        }
    );

    assert_ne!(alpha_head, beta_head);
    let observed = git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]);
    assert!(observed.starts_with(&beta_head), "remote: {}", observed);
    assert!(git_allow_failure(
        &fx.repo,
        &["merge-base", "--is-ancestor", &alpha_head, &beta_head]
    ));
}

#[tokio::test]
async fn per_change_upstream_e2e_records_durable_identity_without_an_upstream_merge() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    // The remote never advances, so no upstream merge commit is ever created.
    // The publication marker is therefore the only crash evidence available.
    let marker = integrate_and_mark(&fx.repo, "alpha");

    let log = git(&fx.repo, &["log", "--format=%s"]);
    assert!(!log.contains("Merge upstream:"), "log: {}", log);

    let pending = scan_pending_publications(&ops(&fx.repo)).await.unwrap();
    assert_eq!(pending.len(), 1);
    assert_eq!(pending[0].commit, marker);
    assert_eq!(pending[0].trailers.change_id, "alpha");
    assert_eq!(pending[0].trailers.remote, "origin");
    assert_eq!(pending[0].trailers.branch, "main");
}

#[tokio::test]
async fn per_change_upstream_e2e_option_less_restart_refuses_marked_unpublished_integration() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    integrate_and_mark(&fx.repo, "alpha");
    let head_before = git(&fx.repo, &["rev-parse", "HEAD"]);
    let remote_before = git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]);

    let refusal = conflux::upstream::ensure_no_unpushed_upstream_recovery(&fx.repo)
        .await
        .expect_err("an option-less restart must refuse marked unpublished history");

    let message = refusal.to_string();
    assert!(message.contains("alpha"), "{}", message);
    assert!(
        message.contains("--integrate-upstream=origin"),
        "{}",
        message
    );
    assert!(message.contains("--upstream-verify-command"), "{}", message);
    assert!(
        message.contains("it is not merged"),
        "the change must not be reported as terminal merged: {}",
        message
    );

    // Refusal happens before any orchestration mutation.
    assert_eq!(git(&fx.repo, &["rev-parse", "HEAD"]), head_before);
    assert_eq!(
        git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]),
        remote_before
    );
}

#[tokio::test]
async fn per_change_upstream_e2e_enabled_restart_resumes_publication() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    let head = integrate_and_mark(&fx.repo, "alpha");

    // A brand-new process: nothing but repository and remote evidence exists.
    let mut restarted = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    let pending = scan_pending_publications(&ops(&fx.repo)).await.unwrap();
    assert_eq!(pending.len(), 1);

    let outcome = restarted
        .publish_change(&pending[0].trailers.change_id)
        .await
        .unwrap();

    assert_eq!(
        outcome,
        PublicationOutcome::Published { head: head.clone() }
    );
    let observed = git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]);
    assert!(observed.starts_with(&head), "remote: {}", observed);
}

#[tokio::test]
async fn per_change_upstream_e2e_failed_verification_suppresses_push_and_stays_resumable() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    let head = integrate_and_mark(&fx.repo, "alpha");
    let remote_before = git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]);

    let mut failing = coordinator(
        &fx.repo,
        FAILING_COMMAND,
        std::sync::Arc::new(ZeroBudgetRepairAgent),
    );
    let outcome = failing.publish_change("alpha").await.unwrap();

    assert!(
        matches!(outcome, PublicationOutcome::Stalled { .. }),
        "outcome: {:?}",
        outcome
    );
    assert!(failing.pushed_head().is_none());
    assert_eq!(
        git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]),
        remote_before,
        "a failed verification must publish nothing"
    );

    // The change is still resumable from repository evidence.
    let pending = scan_pending_publications(&ops(&fx.repo)).await.unwrap();
    assert_eq!(pending.len(), 1);

    // Explicit retry with a working verification command completes it.
    let mut retried = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    let retry = retried.publish_change("alpha").await.unwrap();
    assert_eq!(retry, PublicationOutcome::Published { head: head.clone() });
    let observed = git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]);
    assert!(observed.starts_with(&head), "remote: {}", observed);
}

#[tokio::test]
async fn per_change_upstream_e2e_remote_advance_is_integrated_before_publication() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    integrate_and_mark(&fx.repo, "alpha");
    let racing = write_and_commit(&fx.clone2, "upstream.md", "upstream\n", "upstream work");
    git(&fx.clone2, &["push", "origin", "main"]);

    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    let outcome = coordinator.publish_change("alpha").await.unwrap();

    let published = match outcome {
        PublicationOutcome::Published { head } => head,
        other => panic!("expected publication, got {:?}", other),
    };
    assert!(
        git_allow_failure(
            &fx.repo,
            &["merge-base", "--is-ancestor", &racing, &published]
        ),
        "the remote advance must be integrated, never force-pushed over"
    );
    let observed = git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]);
    assert!(observed.starts_with(&published), "remote: {}", observed);
}

#[tokio::test]
async fn per_change_upstream_e2e_push_rejection_stalls_without_agent() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    integrate_and_mark(&fx.repo, "alpha");

    let hook = fx.remote.join("hooks").join("pre-receive");
    std::fs::create_dir_all(hook.parent().unwrap()).unwrap();
    std::fs::write(&hook, "#!/bin/sh\nexit 1\n").unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
    }

    let remote_before = git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]);
    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    let outcome = coordinator.publish_change("alpha").await.unwrap();

    assert!(
        matches!(outcome, PublicationOutcome::Stalled { .. }),
        "outcome: {:?}",
        outcome
    );
    assert!(coordinator.pushed_head().is_none());
    assert_eq!(
        git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]),
        remote_before
    );
    assert!(!scan_pending_publications(&ops(&fx.repo))
        .await
        .unwrap()
        .is_empty());
}

#[tokio::test]
async fn per_change_upstream_e2e_interrupted_push_is_confirmed_without_a_second_push() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    let head = integrate_and_mark(&fx.repo, "alpha");
    // The prior process pushed but stopped before recording confirmation.
    git(&fx.repo, &["push", "origin", "main"]);

    // A deny-everything hook proves no second push is attempted: if publication
    // tried to push again it would fail instead of confirming.
    let hook = fx.remote.join("hooks").join("pre-receive");
    std::fs::create_dir_all(hook.parent().unwrap()).unwrap();
    std::fs::write(&hook, "#!/bin/sh\nexit 1\n").unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
    }

    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    let outcome = coordinator.publish_change("alpha").await.unwrap();

    assert_eq!(outcome, PublicationOutcome::AlreadyConfirmed { head });
}

#[tokio::test]
async fn per_change_upstream_e2e_zero_change_recovery_requires_explicit_evidence() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    // Unmarked cumulative history is not recovery work.
    add_cumulative_change_merge(&fx.repo, "disabled-mode-change");
    let head_before = git(&fx.repo, &["rev-parse", "HEAD"]);
    let remote_before = git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]);

    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    assert_eq!(
        coordinator.finalize(drained()).await.unwrap(),
        FinalizeOutcome::NoWork
    );
    assert_eq!(git(&fx.repo, &["rev-parse", "HEAD"]), head_before);
    assert_eq!(
        git(&fx.repo, &["ls-remote", "origin", "refs/heads/main"]),
        remote_before
    );

    // An explicit marker is recovery work, and publishing it does not
    // retroactively make the earlier disabled-mode change a published change.
    let marked = mark_publication_required(&fx.repo, "opted-in-change");
    let outcome = coordinator.finalize(drained()).await.unwrap();
    assert_eq!(
        outcome,
        FinalizeOutcome::Completed {
            pushed_head: marked
        }
    );
}

#[tokio::test]
async fn per_change_upstream_e2e_default_off_history_never_blocks_startup() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    add_cumulative_change_merge(&fx.repo, "disabled-mode-change");

    // A disabled run starts normally: ordinary terminal `merged` history is not
    // publication evidence and is never promoted.
    conflux::upstream::ensure_no_unpushed_upstream_recovery(&fx.repo)
        .await
        .expect("disabled-mode history must not block an option-less start");
    assert!(scan_pending_publications(&ops(&fx.repo))
        .await
        .unwrap()
        .is_empty());
}

#[tokio::test]
async fn per_change_upstream_e2e_run_and_local_tui_construct_one_runtime() {
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    // Both frontends normalize the same raw option values, then run the same
    // startup validation against the same repository.
    let from_run =
        conflux::upstream::resolve_frontend_upstream_config(Some("origin"), Some("exit 0"), None)
            .expect("run options")
            .expect("enabled");
    let from_tui =
        conflux::upstream::resolve_frontend_upstream_config(Some("origin"), Some("exit 0"), None)
            .expect("tui options")
            .expect("enabled");
    assert_eq!(from_run, from_tui);

    let run_runtime =
        conflux::upstream::prepare_upstream_integration(from_run, &fx.repo, None, true, false)
            .await
            .expect("run startup validation");
    let tui_runtime =
        conflux::upstream::prepare_upstream_integration(from_tui, &fx.repo, None, true, false)
            .await
            .expect("local TUI startup validation");

    assert_eq!(run_runtime, tui_runtime);
    assert_eq!(run_runtime.branch, "main");
}

/// Real-repository fixtures for explicit-target resume classification.
///
/// These cases use real Git repositories, real worktrees, and real archive
/// trees. They are integration/e2e evidence for `explicit-target-resume-tests`,
/// not unit coverage of the resolver decision table.
mod explicit_target_resume_support {
    use std::path::{Path, PathBuf};

    pub use conflux::orchestration::target_resolution::{
        classify_base_completion, workspace_resume_evidence, BaseCompletionEvidence,
        BaseEvidenceErrorKind, ExplicitTargetPlan, TargetClassification, TargetResolution,
        TargetResolutionOptions, WorkspaceResumeEvidence,
    };

    pub use super::upstream_integration_support::{configure_identity, git, git_allow_failure};

    pub struct Repo {
        pub _dir: tempfile::TempDir,
        pub root: PathBuf,
    }

    /// A repository on branch `main` with one commit, or `None` without git.
    pub fn repo() -> Option<Repo> {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("repo");
        std::fs::create_dir_all(&root).unwrap();
        if !git_allow_failure(&root, &["init", "-b", "main"]) {
            return None;
        }
        configure_identity(&root);
        std::fs::write(root.join("README.md"), "# base\n").unwrap();
        git(&root, &["add", "."]);
        git(&root, &["commit", "-m", "Initial commit"]);
        Some(Repo { _dir: dir, root })
    }

    /// Write an active OpenSpec change directory (working copy only).
    pub fn write_active_change(root: &Path, change_id: &str) {
        let dir = root.join("openspec/changes").join(change_id);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("proposal.md"), format!("# {change_id}\n")).unwrap();
        std::fs::write(
            dir.join("tasks.md"),
            "## Implementation Tasks\n\n- [ ] Do the work\n",
        )
        .unwrap();
    }

    /// Write an archive entry (working copy only). `entry_name` may be date-prefixed.
    pub fn write_archive_entry(root: &Path, entry_name: &str, change_id: &str) {
        let dir = root.join("openspec/changes/archive").join(entry_name);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("proposal.md"), format!("# {change_id}\n")).unwrap();
        std::fs::write(
            dir.join("tasks.md"),
            "## Implementation Tasks\n\n- [x] Do the work\n",
        )
        .unwrap();
    }

    pub fn commit_all(root: &Path, message: &str) {
        git(root, &["add", "-A"]);
        git(root, &["commit", "-m", message]);
    }

    /// Add a cflx-managed worktree whose branch is the change ID.
    pub fn add_worktree(root: &Path, change_id: &str) -> PathBuf {
        let path = root.join(".openspec-worktrees").join(change_id);
        git(
            root,
            &[
                "worktree",
                "add",
                "-b",
                change_id,
                path.to_str().unwrap(),
                "HEAD",
            ],
        );
        path
    }

    /// Classify a requested target set against the repository's `main` base.
    pub async fn resolve(root: &Path, requested: &[&str], no_resume: bool) -> TargetResolution {
        let plan = ExplicitTargetPlan::new(
            requested.iter().map(|s| s.to_string()).collect(),
            "main".to_string(),
            TargetResolutionOptions { no_resume },
        );
        plan.resolve(root).await
    }

    /// Snapshot every path under the repository, for side-effect assertions.
    pub fn snapshot_tree(root: &Path) -> Vec<String> {
        fn walk(dir: &Path, base: &Path, out: &mut Vec<String>) {
            let Ok(entries) = std::fs::read_dir(dir) else {
                return;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                out.push(
                    path.strip_prefix(base)
                        .unwrap_or(&path)
                        .display()
                        .to_string(),
                );
                if path.is_dir() {
                    walk(&path, base, out);
                }
            }
        }
        let mut out = Vec::new();
        walk(root, root, &mut out);
        out.sort();
        out
    }
}

#[tokio::test]
async fn explicit_target_resume_base_evidence_completed_for_exact_and_date_prefixed_archive() {
    use explicit_target_resume_support::*;
    let Some(fx) = repo() else {
        println!("Skipping test: git not available");
        return;
    };

    write_archive_entry(&fx.root, "exact-change", "exact-change");
    write_archive_entry(&fx.root, "2026-07-30-dated-change", "dated-change");
    commit_all(&fx.root, "Archive both changes");

    assert_eq!(
        classify_base_completion("exact-change", &fx.root, "main").await,
        BaseCompletionEvidence::Completed
    );
    assert_eq!(
        classify_base_completion("dated-change", &fx.root, "main").await,
        BaseCompletionEvidence::Completed,
        "a date-prefixed archive entry proves the same completion"
    );
}

#[tokio::test]
async fn explicit_target_resume_base_evidence_not_completed_without_archive() {
    use explicit_target_resume_support::*;
    let Some(fx) = repo() else {
        println!("Skipping test: git not available");
        return;
    };

    // No archive directory at all.
    assert_eq!(
        classify_base_completion("missing-change", &fx.root, "main").await,
        BaseCompletionEvidence::NotCompleted
    );

    // An archive directory holding some other change is still NotCompleted.
    write_archive_entry(&fx.root, "other-change", "other-change");
    commit_all(&fx.root, "Archive other change");
    assert_eq!(
        classify_base_completion("missing-change", &fx.root, "main").await,
        BaseCompletionEvidence::NotCompleted
    );
}

#[tokio::test]
async fn explicit_target_resume_base_evidence_contradictory_when_active_dir_remains() {
    use explicit_target_resume_support::*;
    let Some(fx) = repo() else {
        println!("Skipping test: git not available");
        return;
    };

    write_archive_entry(&fx.root, "2026-07-30-half-change", "half-change");
    write_active_change(&fx.root, "half-change");
    commit_all(
        &fx.root,
        "Archive half-change without removing the active directory",
    );

    let evidence = classify_base_completion("half-change", &fx.root, "main").await;
    assert!(
        matches!(evidence, BaseCompletionEvidence::Contradictory { .. }),
        "archive plus active directory must not read as completed: {evidence:?}"
    );

    // An active change directory always outranks a candidate contradiction, so
    // this target remains ordinary work rather than a failure.
    let resolution = resolve(&fx.root, &["half-change"], false).await;
    assert_eq!(
        resolution.classification_of("half-change"),
        Some(TargetClassification::Active)
    );

    // When the leftover base directory is not an active change (here: no
    // proposal.md), the contradiction reaches classification as a safe failure
    // rather than a completion skip.
    write_archive_entry(&fx.root, "2026-07-30-stub-change", "stub-change");
    let stub_dir = fx.root.join("openspec/changes/stub-change");
    std::fs::create_dir_all(&stub_dir).unwrap();
    std::fs::write(stub_dir.join("tasks.md"), "## Implementation Tasks\n").unwrap();
    commit_all(
        &fx.root,
        "Archive stub-change leaving a stub directory behind",
    );

    let resolution = resolve(&fx.root, &["stub-change"], false).await;
    assert_eq!(
        resolution.classification_of("stub-change"),
        Some(TargetClassification::EvidenceError)
    );
    assert!(resolution.already_completed_ids().is_empty());
    let message = resolution.failure_error().unwrap().to_string();
    assert!(
        message.contains("unusable change evidence: stub-change"),
        "the contradiction is reported with actionable detail: {message}"
    );
}

#[tokio::test]
async fn explicit_target_resume_base_evidence_error_on_missing_branch() {
    use explicit_target_resume_support::*;
    let Some(fx) = repo() else {
        println!("Skipping test: git not available");
        return;
    };

    write_archive_entry(&fx.root, "some-change", "some-change");
    commit_all(&fx.root, "Archive some-change");

    let evidence = classify_base_completion("some-change", &fx.root, "no-such-branch").await;
    assert!(
        matches!(
            evidence,
            BaseCompletionEvidence::EvidenceError {
                kind: BaseEvidenceErrorKind::MissingBranch,
                ..
            }
        ),
        "an unreadable base branch is an evidence error, not 'not completed': {evidence:?}"
    );

    // A Git command failure is also an evidence error: run outside any repository.
    let non_repo = tempfile::tempdir().unwrap();
    let outside = classify_base_completion("some-change", non_repo.path(), "main").await;
    assert!(
        matches!(outside, BaseCompletionEvidence::EvidenceError { .. }),
        "{outside:?}"
    );
}

#[tokio::test]
async fn explicit_target_resume_base_evidence_rejects_uncommitted_and_subject_only_archives() {
    use explicit_target_resume_support::*;
    let Some(fx) = repo() else {
        println!("Skipping test: git not available");
        return;
    };

    // 1. A commit subject that looks like an archive, with no tree evidence.
    std::fs::write(fx.root.join("notes.md"), "note\n").unwrap();
    commit_all(&fx.root, "Archive: subject-only-change");
    assert_eq!(
        classify_base_completion("subject-only-change", &fx.root, "main").await,
        BaseCompletionEvidence::NotCompleted,
        "a commit subject is never accepted as completion proof"
    );

    // 2. An archive entry that exists only in the uncommitted working copy.
    write_archive_entry(
        &fx.root,
        "2026-07-30-uncommitted-change",
        "uncommitted-change",
    );
    assert_eq!(
        classify_base_completion("uncommitted-change", &fx.root, "main").await,
        BaseCompletionEvidence::NotCompleted,
        "an uncommitted working-copy archive is not in the base tree"
    );

    // 3. Committed on another branch only: still not in base.
    git(&fx.root, &["checkout", "-b", "side"]);
    commit_all(&fx.root, "Archive uncommitted-change on side branch");
    assert_eq!(
        classify_base_completion("uncommitted-change", &fx.root, "main").await,
        BaseCompletionEvidence::NotCompleted
    );
    assert_eq!(
        classify_base_completion("uncommitted-change", &fx.root, "side").await,
        BaseCompletionEvidence::Completed
    );
}

#[tokio::test]
async fn explicit_target_resume_workspace_evidence_requires_more_than_a_name() {
    use explicit_target_resume_support::*;
    let Some(fx) = repo() else {
        println!("Skipping test: git not available");
        return;
    };

    write_active_change(&fx.root, "applied-change");
    commit_all(&fx.root, "Add applied-change");

    // Applied: the worktree carries the active change directory.
    let applied_ws = add_worktree(&fx.root, "applied-change");
    let evidence = workspace_resume_evidence("applied-change", &applied_ws, "main").await;
    assert!(
        matches!(evidence, WorkspaceResumeEvidence::Resumable { .. }),
        "{evidence:?}"
    );

    // Name-only: a worktree that carries no proposal for the change.
    let bare_ws = add_worktree(&fx.root, "name-only-change");
    let evidence = workspace_resume_evidence("name-only-change", &bare_ws, "main").await;
    assert!(
        matches!(evidence, WorkspaceResumeEvidence::NotResumable { .. }),
        "a matching workspace name alone is not resume evidence: {evidence:?}"
    );

    // Missing path: the workspace was removed from disk.
    let missing = fx.root.join(".openspec-worktrees/never-created");
    let evidence = workspace_resume_evidence("never-created", &missing, "main").await;
    assert!(
        matches!(evidence, WorkspaceResumeEvidence::NotResumable { .. }),
        "{evidence:?}"
    );

    // Malformed: a change directory with no proposal.md.
    let malformed_ws = add_worktree(&fx.root, "malformed-change");
    std::fs::create_dir_all(malformed_ws.join("openspec/changes/malformed-change")).unwrap();
    let evidence = workspace_resume_evidence("malformed-change", &malformed_ws, "main").await;
    assert!(
        matches!(evidence, WorkspaceResumeEvidence::NotResumable { .. }),
        "a change directory without a proposal is not resume evidence: {evidence:?}"
    );
}

#[tokio::test]
async fn explicit_target_resume_workspace_evidence_accepts_archived_not_integrated() {
    use explicit_target_resume_support::*;
    let Some(fx) = repo() else {
        println!("Skipping test: git not available");
        return;
    };

    write_active_change(&fx.root, "archiving-change");
    commit_all(&fx.root, "Add archiving-change");

    // The worktree archived the change but the archive never reached base.
    let ws = add_worktree(&fx.root, "archiving-change");
    std::fs::remove_dir_all(ws.join("openspec/changes/archiving-change")).unwrap();
    write_archive_entry(&ws, "2026-07-30-archiving-change", "archiving-change");
    git(&ws, &["add", "-A"]);
    git(&ws, &["commit", "-m", "Archive: archiving-change"]);

    assert_eq!(
        classify_base_completion("archiving-change", &fx.root, "main").await,
        BaseCompletionEvidence::NotCompleted,
        "base has not integrated the archive yet"
    );

    let evidence = workspace_resume_evidence("archiving-change", &ws, "main").await;
    let WorkspaceResumeEvidence::Resumable { change, .. } = evidence else {
        panic!("archived-not-integrated workspace must be resumable: {evidence:?}");
    };
    assert_eq!(change.id, "archiving-change");

    // Base no longer lists the change as active and never received the archive,
    // so only the worktree can identify the requested target.
    std::fs::remove_dir_all(fx.root.join("openspec/changes/archiving-change")).unwrap();
    commit_all(
        &fx.root,
        "Drop archiving-change from base without archiving it",
    );
    assert_eq!(
        classify_base_completion("archiving-change", &fx.root, "main").await,
        BaseCompletionEvidence::NotCompleted
    );

    let resolution = resolve(&fx.root, &["archiving-change"], false).await;
    assert_eq!(
        resolution.classification_of("archiving-change"),
        Some(TargetClassification::ResumableWorkspace)
    );
    assert_eq!(resolution.processed_ids(), vec!["archiving-change"]);
    assert!(resolution.failure_error().is_none());
}

#[tokio::test]
async fn explicit_target_resume_repeated_target_set_skips_integrated_target() {
    use explicit_target_resume_support::*;
    let Some(fx) = repo() else {
        println!("Skipping test: git not available");
        return;
    };

    write_active_change(&fx.root, "change-one");
    write_active_change(&fx.root, "change-two");
    commit_all(&fx.root, "Add change-one and change-two");

    // First invocation: both are ordinary active work.
    let first = resolve(&fx.root, &["change-one", "change-two"], false).await;
    assert!(first.failure_error().is_none());
    assert_eq!(first.processed_ids(), vec!["change-one", "change-two"]);

    // change-one is archived and integrated into base.
    std::fs::remove_dir_all(fx.root.join("openspec/changes/change-one")).unwrap();
    write_archive_entry(&fx.root, "2026-07-30-change-one", "change-one");
    commit_all(&fx.root, "Archive: change-one");

    // Repeating the identical target set skips it instead of failing.
    let second = resolve(&fx.root, &["change-one", "change-two"], false).await;
    assert!(
        second.failure_error().is_none(),
        "a repeated completed target must not be an unknown-ID error: {:?}",
        second.failure_error().map(|e| e.to_string())
    );
    assert_eq!(second.already_completed_ids(), vec!["change-one"]);
    assert_eq!(second.processed_ids(), vec!["change-two"]);
    assert_eq!(
        second.requested_ids(),
        vec!["change-one", "change-two"],
        "request order is retained for terminal reporting"
    );
}

#[tokio::test]
async fn explicit_target_resume_active_target_wins_over_candidate_workspace() {
    use explicit_target_resume_support::*;
    let Some(fx) = repo() else {
        println!("Skipping test: git not available");
        return;
    };

    write_active_change(&fx.root, "dual-change");
    commit_all(&fx.root, "Add dual-change");
    let ws = add_worktree(&fx.root, "dual-change");
    assert!(ws.is_dir());

    let resolution = resolve(&fx.root, &["dual-change"], false).await;
    assert_eq!(
        resolution.classification_of("dual-change"),
        Some(TargetClassification::Active),
        "an active change is ordinary work even when a managed worktree exists"
    );
    assert!(resolution.resumable_ids().is_empty());
    assert!(ws.is_dir(), "classification must not remove the workspace");
}

#[tokio::test]
async fn explicit_target_resume_reports_unknown_and_duplicate_ids_together() {
    use explicit_target_resume_support::*;
    let Some(fx) = repo() else {
        println!("Skipping test: git not available");
        return;
    };

    write_active_change(&fx.root, "known-change");
    commit_all(&fx.root, "Add known-change");

    let before = snapshot_tree(&fx.root);
    let resolution = resolve(
        &fx.root,
        &["known-change", "ghost-a", "known-change", "ghost-b"],
        false,
    )
    .await;

    let message = resolution.failure_error().unwrap().to_string();
    assert!(
        message.contains("duplicate change IDs: known-change"),
        "{message}"
    );
    assert!(
        message.contains("unknown change IDs: ghost-a, ghost-b"),
        "all unknown IDs are reported together: {message}"
    );
    assert_eq!(
        snapshot_tree(&fx.root),
        before,
        "rejection happens before any workspace is created, deleted, or mutated"
    );
}

#[tokio::test]
async fn explicit_target_resume_no_resume_keeps_completion_and_preserves_refused_workspace() {
    use explicit_target_resume_support::*;
    let Some(fx) = repo() else {
        println!("Skipping test: git not available");
        return;
    };

    // A base-integrated change plus a workspace-only recoverable change.
    write_active_change(&fx.root, "done-change");
    write_active_change(&fx.root, "workspace-only");
    commit_all(&fx.root, "Add both changes");

    let ws = add_worktree(&fx.root, "workspace-only");

    std::fs::remove_dir_all(fx.root.join("openspec/changes/done-change")).unwrap();
    write_archive_entry(&fx.root, "2026-07-30-done-change", "done-change");
    // Remove the active copy of workspace-only from base so only the worktree has it.
    std::fs::remove_dir_all(fx.root.join("openspec/changes/workspace-only")).unwrap();
    commit_all(
        &fx.root,
        "Archive done-change and drop workspace-only from base",
    );

    let resolution = resolve(&fx.root, &["done-change", "workspace-only"], true).await;

    assert_eq!(
        resolution.already_completed_ids(),
        vec!["done-change"],
        "--no-resume does not erase base-integrated completion"
    );
    assert_eq!(resolution.resume_refused_ids(), vec!["workspace-only"]);
    let message = resolution.failure_error().unwrap().to_string();
    assert!(message.contains("refused by --no-resume"), "{message}");
    assert!(
        ws.is_dir(),
        "a refused worktree is never implicitly deleted or replaced"
    );
}

#[tokio::test]
async fn explicit_target_resume_dry_run_classification_has_no_side_effects() {
    use explicit_target_resume_support::*;
    let Some(fx) = repo() else {
        println!("Skipping test: git not available");
        return;
    };

    write_active_change(&fx.root, "active-change");
    write_active_change(&fx.root, "resumable-change");
    commit_all(&fx.root, "Add changes");

    let ws = add_worktree(&fx.root, "resumable-change");
    std::fs::remove_dir_all(fx.root.join("openspec/changes/resumable-change")).unwrap();
    write_archive_entry(&fx.root, "2026-07-30-completed-change", "completed-change");
    commit_all(
        &fx.root,
        "Archive completed-change, drop resumable-change from base",
    );

    let before = snapshot_tree(&fx.root);
    let head_before = git(&fx.root, &["rev-parse", "HEAD"]);

    let resolution = resolve(
        &fx.root,
        &[
            "active-change",
            "completed-change",
            "resumable-change",
            "ghost-change",
        ],
        false,
    )
    .await;

    assert_eq!(resolution.active_ids(), vec!["active-change"]);
    assert_eq!(resolution.already_completed_ids(), vec!["completed-change"]);
    assert_eq!(resolution.resumable_ids(), vec!["resumable-change"]);
    assert_eq!(resolution.unknown_ids(), vec!["ghost-change"]);

    let lines = resolution.report_lines();
    assert!(lines
        .iter()
        .any(|l| l.contains("already completed (skipped): completed-change")));
    assert!(lines
        .iter()
        .any(|l| l.contains("resumable workspaces: resumable-change")));

    assert_eq!(
        snapshot_tree(&fx.root),
        before,
        "read-only classification mutates nothing"
    );
    assert_eq!(git(&fx.root, &["rev-parse", "HEAD"]), head_before);
    assert!(
        ws.is_dir(),
        "no workspace cleanup happens during classification"
    );
}

#[tokio::test]
async fn explicit_target_resume_classifies_against_post_checkpoint_cumulative_base() {
    use explicit_target_resume_support::*;
    let Some(fx) = repo() else {
        println!("Skipping test: git not available");
        return;
    };

    write_active_change(&fx.root, "remote-completed");
    write_active_change(&fx.root, "local-change");
    commit_all(&fx.root, "Add both changes");

    let plan = ExplicitTargetPlan::new(
        vec!["remote-completed".to_string(), "local-change".to_string()],
        "main".to_string(),
        TargetResolutionOptions::default(),
    );

    // Before the checkpoint both targets are ordinary active work.
    let before = plan.resolve(&fx.root).await;
    assert_eq!(
        before.processed_ids(),
        vec!["remote-completed", "local-change"]
    );

    // The initial upstream checkpoint integrates a branch that archived one target.
    git(&fx.root, &["checkout", "-b", "upstream-work"]);
    std::fs::remove_dir_all(fx.root.join("openspec/changes/remote-completed")).unwrap();
    write_archive_entry(&fx.root, "2026-07-30-remote-completed", "remote-completed");
    commit_all(&fx.root, "Archive: remote-completed");
    git(&fx.root, &["checkout", "main"]);
    git(
        &fx.root,
        &["merge", "--no-ff", "-m", "Merge upstream", "upstream-work"],
    );

    // Classifying after the checkpoint sees the newly integrated archive.
    let after = plan.resolve(&fx.root).await;
    assert!(after.failure_error().is_none());
    assert_eq!(after.already_completed_ids(), vec!["remote-completed"]);
    assert_eq!(after.processed_ids(), vec!["local-change"]);
    assert_eq!(
        plan.resolved().await.unwrap().already_completed_ids(),
        vec!["remote-completed"],
        "the recorded resolution is available to terminal consumers"
    );
}

#[tokio::test]
async fn explicit_target_resume_all_completed_run_still_publishes_unpushed_history() {
    use explicit_target_resume_support::{
        resolve, write_active_change, write_archive_entry, TargetClassification,
    };
    use upstream_integration_support::*;
    let Some(fx) = fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    // Every requested target is already archived and integrated into base, and
    // that integration is opted-in but not yet published: the marker is what
    // makes it recognized recovery work rather than terminal `merged` history.
    write_active_change(&fx.repo, "done-one");
    write_archive_entry(&fx.repo, "2026-07-30-done-one", "done-one");
    std::fs::remove_dir_all(fx.repo.join("openspec/changes/done-one")).unwrap();
    git(&fx.repo, &["add", "-A"]);
    git(&fx.repo, &["commit", "-m", "Archive: done-one"]);
    integrate_and_mark(&fx.repo, "done-two");

    let resolution = resolve(&fx.repo, &["done-one", "done-two"], false).await;
    assert!(resolution.failure_error().is_none());
    assert_eq!(
        resolution.classification_of("done-one"),
        Some(TargetClassification::AlreadyCompleted)
    );
    assert_eq!(
        resolution.classification_of("done-two"),
        Some(TargetClassification::AlreadyCompleted)
    );
    assert!(
        resolution.processed_ids().is_empty(),
        "there is no change work left to dispatch"
    );

    // A skip-only run must still verify, push, and confirm the unpublished base.
    let mut coordinator = coordinator(
        &fx.repo,
        PASSING_COMMAND,
        std::sync::Arc::new(ForbiddenRepairAgent),
    );
    let outcome = coordinator.finalize(drained()).await.unwrap();
    assert!(
        matches!(outcome, FinalizeOutcome::Completed { .. }),
        "an all-already-completed run still finalizes recognized unpublished history: {outcome:?}"
    );
    assert_eq!(
        git(&fx.repo, &["rev-parse", "HEAD"]),
        git(&fx.repo, &["rev-parse", "origin/main"]),
        "the cumulative base is published"
    );
}

// ── Remote worktree operations (real Git worktrees / teardown / merge state) ──
//
// These cases prove the parts of `secure-remote-worktree-operations` that are
// only decidable against a real repository: mandatory teardown, dirty refusal,
// conflict preservation, `on_merged` ordering, and identity retirement across a
// real remove-and-recreate. They drive the production port
// (`RemoteWorktreeOperations` over `GitWorktreeBackend`), not a fake.

#[cfg(feature = "web-monitoring")]
mod remote_worktree_support {
    use std::path::{Path, PathBuf};
    use std::sync::Arc;

    use conflux::config::OrchestratorConfig;
    use conflux::web::remote_control_api::worktrees::{
        RemoteWorktreeOperations, WorktreeOperations, WorktreeRegistry,
    };
    use conflux::worktree_ops::git_backend::GitWorktreeBackend;
    use conflux::worktree_ops::service::{NullEventSink, WorktreeService};

    pub use super::upstream_integration_support::{configure_identity, git, git_allow_failure};

    /// A real repository plus the production remote worktree port over it.
    pub struct RemoteFixture {
        pub _dir: tempfile::TempDir,
        pub repo: PathBuf,
        pub workspaces: PathBuf,
        pub registry: Arc<WorktreeRegistry>,
        pub port: RemoteWorktreeOperations,
    }

    /// Build the fixture, or `None` when git is unavailable.
    pub fn remote_fixture() -> Option<RemoteFixture> {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path().join("repo");
        let workspaces = dir.path().join("workspaces");
        std::fs::create_dir_all(&repo).unwrap();
        std::fs::create_dir_all(&workspaces).unwrap();

        if !git_allow_failure(&repo, &["init", "-b", "main"]) {
            return None;
        }
        configure_identity(&repo);
        std::fs::write(repo.join("README.md"), "# base\n").unwrap();
        git(&repo, &["add", "."]);
        git(&repo, &["commit", "-m", "Initial commit"]);

        let registry = Arc::new(WorktreeRegistry::new());
        let service = Arc::new(WorktreeService::new(
            Arc::new(GitWorktreeBackend::new(
                repo.clone(),
                Arc::new(OrchestratorConfig::default()),
            )),
            Arc::new(NullEventSink),
            workspaces.clone(),
        ));
        let port = RemoteWorktreeOperations::new(service, registry.clone(), repo.clone());

        Some(RemoteFixture {
            _dir: dir,
            repo,
            workspaces,
            registry,
            port,
        })
    }

    /// Register a managed, non-archived change so create eligibility passes.
    ///
    /// Committed, not just written: a base merge requires a clean working tree,
    /// so leaving the declaration untracked would make every merge case fail for
    /// a reason that has nothing to do with what is under test.
    pub fn declare_change(repo: &Path, change_id: &str) {
        let dir = repo.join("openspec/changes").join(change_id);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("proposal.md"), "# proposal\n").unwrap();
        std::fs::write(dir.join("tasks.md"), "- [x] done\n").unwrap();
        git(repo, &["add", "-A"]);
        git(repo, &["commit", "-m", &format!("Declare {change_id}")]);
    }

    /// True when the base repository is sitting on an unresolved merge.
    pub fn merge_in_progress(repo: &Path) -> bool {
        repo.join(".git/MERGE_HEAD").exists()
    }

    /// The opaque ID currently bound to the worktree on `branch`, if any.
    pub async fn id_for_branch(port: &RemoteWorktreeOperations, branch: &str) -> Option<String> {
        port.list()
            .await
            .ok()?
            .worktrees
            .into_iter()
            .find(|worktree| worktree.branch == branch)
            .map(|worktree| worktree.worktree_id)
    }
}

#[cfg(feature = "web-monitoring")]
mod remote_worktree_tests {
    use super::remote_worktree_support::*;
    use conflux::web::remote_control_api::dto::ErrorCode;
    use conflux::web::remote_control_api::worktrees::WorktreeOperations;

    #[tokio::test]
    async fn remote_worktree_create_uses_current_base_head_and_allocates_an_id() {
        let Some(fx) = remote_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        declare_change(&fx.repo, "change-a");
        std::fs::write(fx.repo.join("second.txt"), "second\n").unwrap();
        git(&fx.repo, &["add", "."]);
        git(&fx.repo, &["commit", "-m", "Advance base"]);
        let head = git(&fx.repo, &["rev-parse", "HEAD"]);

        fx.port.create("change-a").await.expect("create succeeds");

        let worktree_path = fx.workspaces.join("change-a");
        assert!(worktree_path.is_dir(), "the worktree directory exists");
        assert_eq!(
            git(&worktree_path, &["rev-parse", "HEAD"]),
            head,
            "the worktree is cut from current managed base HEAD"
        );

        let listed = fx.port.list().await.expect("list succeeds");
        let created = listed
            .worktrees
            .iter()
            .find(|worktree| worktree.branch == "change-a")
            .expect("the created worktree is observable");
        assert_eq!(created.worktree_id.len(), 32);
        assert_eq!(created.dirty, Some(false));
        // Repository-relative, and never the absolute root in any spelling.
        let raw = serde_json::to_string(&listed.worktrees).unwrap();
        let canonical = std::fs::canonicalize(&fx.repo).unwrap();
        assert!(
            !raw.contains(fx.repo.to_str().unwrap()),
            "leaked root: {raw}"
        );
        assert!(
            !raw.contains(canonical.to_str().unwrap()),
            "leaked canonical root: {raw}"
        );
        assert_eq!(created.path, "../workspaces/change-a");
    }

    #[tokio::test]
    async fn remote_worktree_create_refuses_an_existing_worktree_and_an_unmanaged_change() {
        let Some(fx) = remote_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        declare_change(&fx.repo, "change-a");
        fx.port.create("change-a").await.expect("first create");

        let failure = fx
            .port
            .create("change-a")
            .await
            .expect_err("a second create must conflict");
        assert_eq!(failure.error_code, ErrorCode::WorktreeExists);

        let failure = fx
            .port
            .create("never-proposed")
            .await
            .expect_err("an unmanaged change must be refused");
        assert_eq!(failure.error_code, ErrorCode::WorktreeNotFound);
    }

    #[tokio::test]
    async fn remote_worktree_delete_runs_teardown_and_retires_the_identity() {
        let Some(fx) = remote_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        declare_change(&fx.repo, "change-a");

        // A real `.wt/teardown` proves the delete path is not bypassing it.
        let wt_dir = fx.repo.join(".wt");
        std::fs::create_dir_all(&wt_dir).unwrap();
        let marker = fx.repo.join("teardown-ran");
        std::fs::write(
            wt_dir.join("teardown"),
            format!("#!/bin/sh\ntouch {}\n", marker.display()),
        )
        .unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(
                wt_dir.join("teardown"),
                std::fs::Permissions::from_mode(0o755),
            )
            .unwrap();
        }
        git(&fx.repo, &["add", "-A"]);
        git(&fx.repo, &["commit", "-m", "Add teardown script"]);

        fx.port.create("change-a").await.expect("create succeeds");
        let id = id_for_branch(&fx.port, "change-a")
            .await
            .expect("an ID was allocated");

        fx.port.delete(&id).await.expect("delete succeeds");

        assert!(marker.exists(), "managed teardown must have run");
        assert!(!fx.workspaces.join("change-a").exists());
        assert!(fx.registry.is_retired(&id), "the ID must be retired");
        assert!(fx.registry.resolve(&id).is_none());

        let failure = fx
            .port
            .delete(&id)
            .await
            .expect_err("a retired ID addresses nothing");
        assert_eq!(failure.error_code, ErrorCode::WorktreeNotFound);
    }

    #[tokio::test]
    async fn remote_worktree_dirty_worktree_is_not_deletable() {
        let Some(fx) = remote_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        declare_change(&fx.repo, "change-a");
        fx.port.create("change-a").await.expect("create succeeds");
        let id = id_for_branch(&fx.port, "change-a").await.unwrap();

        std::fs::write(fx.workspaces.join("change-a/dirty.txt"), "uncommitted\n").unwrap();

        let failure = fx
            .port
            .delete(&id)
            .await
            .expect_err("a dirty worktree must not be deleted");
        assert_eq!(failure.error_code, ErrorCode::WorktreeDirty);
        assert!(
            fx.workspaces.join("change-a").exists(),
            "a refused delete retains the resource"
        );
        assert!(
            !fx.registry.is_retired(&id),
            "a refused delete retains the identity binding"
        );
    }

    #[tokio::test]
    async fn remote_worktree_successful_merge_lands_on_base_and_runs_on_merged() {
        let Some(fx) = remote_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        declare_change(&fx.repo, "change-a");
        fx.port.create("change-a").await.expect("create succeeds");

        let worktree = fx.workspaces.join("change-a");
        configure_identity(&worktree);
        std::fs::write(worktree.join("feature.txt"), "feature\n").unwrap();
        git(&worktree, &["add", "."]);
        git(&worktree, &["commit", "-m", "Add feature"]);

        let id = id_for_branch(&fx.port, "change-a").await.unwrap();
        fx.port.merge(&id).await.expect("merge succeeds");

        assert!(
            fx.repo.join("feature.txt").exists(),
            "the base contains the worktree result"
        );
        assert!(
            !merge_in_progress(&fx.repo),
            "a clean merge leaves no intermediate state"
        );
    }

    #[tokio::test]
    async fn remote_worktree_merge_conflict_preserves_state_and_blocks_further_mutation() {
        let Some(fx) = remote_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        declare_change(&fx.repo, "change-a");
        std::fs::write(fx.repo.join("shared.txt"), "base\n").unwrap();
        git(&fx.repo, &["add", "."]);
        git(&fx.repo, &["commit", "-m", "Add shared file"]);

        fx.port.create("change-a").await.expect("create succeeds");
        let worktree = fx.workspaces.join("change-a");
        configure_identity(&worktree);
        std::fs::write(worktree.join("shared.txt"), "from worktree\n").unwrap();
        git(&worktree, &["add", "."]);
        git(&worktree, &["commit", "-m", "Worktree edit"]);

        // Diverge base so the merge genuinely conflicts.
        std::fs::write(fx.repo.join("shared.txt"), "from base\n").unwrap();
        git(&fx.repo, &["add", "."]);
        git(&fx.repo, &["commit", "-m", "Base edit"]);

        let id = id_for_branch(&fx.port, "change-a").await.unwrap();
        let failure = fx
            .port
            .merge(&id)
            .await
            .expect_err("a conflicting merge must fail the command");

        assert_eq!(failure.error_code, ErrorCode::MergeConflict);
        assert!(failure.message.contains("shared.txt"));
        assert!(failure.message.contains("local_or_tui_required"));
        assert!(
            merge_in_progress(&fx.repo),
            "the intermediate merge state must be preserved, not aborted"
        );

        // Until a local resolve or abort happens, further mutation is refused.
        let busy = fx
            .port
            .merge(&id)
            .await
            .expect_err("the root stays busy after a preserved conflict");
        assert_eq!(busy.error_code, ErrorCode::RootBusy);
        let busy_delete = fx
            .port
            .delete(&id)
            .await
            .expect_err("the root stays busy for deletion too");
        assert_eq!(busy_delete.error_code, ErrorCode::RootBusy);
        assert!(
            merge_in_progress(&fx.repo),
            "the retained conflict state is not discarded by the refusals"
        );
    }

    #[tokio::test]
    async fn remote_worktree_recreated_worktree_receives_a_new_identity() {
        let Some(fx) = remote_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        declare_change(&fx.repo, "change-a");

        fx.port.create("change-a").await.expect("first create");
        let first = id_for_branch(&fx.port, "change-a").await.unwrap();
        fx.port.delete(&first).await.expect("delete succeeds");

        fx.port.create("change-a").await.expect("second create");
        let second = id_for_branch(&fx.port, "change-a").await.unwrap();

        assert_ne!(
            first, second,
            "a worktree recreated at the same path must not inherit the retired ID"
        );
        assert!(fx.registry.is_retired(&first));
        assert!(fx.registry.resolve(&second).is_some());
    }
}

// ============================================================================
// Explicit dirty worktree deletion — real Git
// ============================================================================
//
// These exercise the local TUI deletion path against a real repository: real
// `git status` output, a real `.wt/teardown` script, real worktree removal, and
// real branch refs. The decision logic is unit-tested elsewhere; what only a
// real repository can show is that the facts the decisions are made from are the
// ones Git actually reports, and that teardown can move them.

mod tui_dirty_worktree_delete_support {
    use std::path::PathBuf;
    use std::sync::Arc;

    use conflux::config::OrchestratorConfig;
    use conflux::worktree_ops::git_backend::GitWorktreeBackend;
    use conflux::worktree_ops::service::{NullEventSink, WorktreeService};

    pub use super::upstream_integration_support::{configure_identity, git, git_allow_failure};

    /// A real repository plus the shared worktree service over it.
    pub struct DirtyFixture {
        pub _dir: tempfile::TempDir,
        pub repo: PathBuf,
        pub workspaces: PathBuf,
        pub service: WorktreeService,
    }

    impl DirtyFixture {
        /// Add a worktree on `branch` at the current base commit.
        pub fn add_worktree(&self, branch: &str) -> PathBuf {
            let path = self.workspaces.join(branch);
            git(
                &self.repo,
                &["worktree", "add", "-b", branch, path.to_str().unwrap()],
            );
            path
        }

        /// Commit an executable `.wt/teardown` running `body` onto base.
        ///
        /// Installed on base *before* the worktree is added, so the script is
        /// inherited rather than committed onto the worktree's own branch: a
        /// commit there would put the branch ahead of base and refuse the
        /// deletion for a reason that has nothing to do with what is under test.
        pub fn install_base_teardown(&self, body: &str) {
            let dir = self.repo.join(".wt");
            std::fs::create_dir_all(&dir).unwrap();
            let script = dir.join("teardown");
            std::fs::write(&script, format!("#!/bin/sh\nset -e\n{body}\n")).unwrap();
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
            }
            git(&self.repo, &["add", "-A"]);
            git(&self.repo, &["commit", "-m", "Install teardown"]);
        }

        /// True when `branch` still has a local ref.
        pub fn branch_exists(&self, branch: &str) -> bool {
            std::process::Command::new("git")
                .args(["show-ref", "--verify", &format!("refs/heads/{branch}")])
                .current_dir(&self.repo)
                .output()
                .map(|out| out.status.success())
                .unwrap_or(false)
        }
    }

    /// Build the fixture, or `None` when git is unavailable.
    pub fn dirty_fixture() -> Option<DirtyFixture> {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path().join("repo");
        let workspaces = dir.path().join("workspaces");
        std::fs::create_dir_all(&repo).unwrap();
        std::fs::create_dir_all(&workspaces).unwrap();

        if !git_allow_failure(&repo, &["init", "-b", "main"]) {
            return None;
        }
        configure_identity(&repo);
        std::fs::write(repo.join("README.md"), "# base\n").unwrap();
        std::fs::write(repo.join(".gitignore"), "generated/\n").unwrap();
        git(&repo, &["add", "."]);
        git(&repo, &["commit", "-m", "Initial commit"]);

        let service = WorktreeService::new(
            Arc::new(GitWorktreeBackend::new(
                repo.clone(),
                Arc::new(OrchestratorConfig::default()),
            )),
            Arc::new(NullEventSink),
            workspaces.clone(),
        );

        Some(DirtyFixture {
            _dir: dir,
            repo,
            workspaces,
            service,
        })
    }
}

mod tui_dirty_worktree_delete_tests {
    use super::tui_dirty_worktree_delete_support::*;
    use conflux::worktree_ops::service::{DeleteOptions, ExpectedTarget, WorktreeOpError};

    #[tokio::test]
    async fn tui_dirty_worktree_delete_e2e_ordinary_delete_refuses_and_names_the_target() {
        let Some(fx) = dirty_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        let worktree = fx.add_worktree("change-dirty");
        // Both kinds of known dirt Git reports without ignored-file enumeration.
        std::fs::write(worktree.join("README.md"), "# edited\n").unwrap();
        std::fs::write(worktree.join("scratch.txt"), "untracked\n").unwrap();

        for options in [
            DeleteOptions::local(false),
            DeleteOptions::local(true),
            DeleteOptions::fail_closed(),
        ] {
            let refusal = fx
                .service
                .delete_worktree(
                    &worktree,
                    &ExpectedTarget::on_branch("change-dirty"),
                    options,
                )
                .await
                .expect_err("a dirty worktree must refuse an ordinary delete");

            let WorktreeOpError::Dirty { target, .. } = refusal else {
                panic!("expected a dirty refusal for {options:?}, got {refusal:?}");
            };
            // The escalation payload is the service's own fresh observation.
            assert_eq!(target.branch, "change-dirty");
            assert_eq!(target.head, git(&worktree, &["rev-parse", "HEAD"]));
            assert!(!target.identity.is_empty());
        }

        assert!(worktree.is_dir(), "the refused worktree is retained");
        assert_eq!(
            std::fs::read_to_string(worktree.join("scratch.txt")).unwrap(),
            "untracked\n",
            "and so is everything uncommitted in it"
        );
        assert!(fx.branch_exists("change-dirty"));
    }

    #[tokio::test]
    async fn tui_dirty_worktree_delete_e2e_explicit_discard_removes_the_worktree_and_branch() {
        let Some(fx) = dirty_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        let worktree = fx.add_worktree("change-dirty");
        std::fs::write(worktree.join("README.md"), "# edited\n").unwrap();
        std::fs::write(worktree.join("scratch.txt"), "untracked\n").unwrap();

        let outcome = fx
            .service
            .delete_worktree(
                &worktree,
                &ExpectedTarget::on_branch("change-dirty"),
                DeleteOptions::local_discarding_dirty(false),
            )
            .await
            .expect("explicit discard must delete");

        assert_eq!(outcome.branch, "change-dirty");
        assert!(!worktree.exists(), "the directory is gone");
        assert!(
            !fx.branch_exists("change-dirty"),
            "a branch with nothing ahead of base is cleaned up: {}",
            outcome.detail
        );
        assert!(!git(&fx.repo, &["worktree", "list", "--porcelain"]).contains("change-dirty"));
    }

    #[tokio::test]
    async fn tui_dirty_worktree_delete_e2e_skip_teardown_discards_without_running_teardown() {
        let Some(fx) = dirty_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        let marker = fx.repo.join("teardown-ran");
        fx.install_base_teardown(&format!("touch {}", marker.to_str().unwrap()));
        let worktree = fx.add_worktree("change-dirty");
        std::fs::write(worktree.join("README.md"), "# edited\n").unwrap();

        fx.service
            .delete_worktree(
                &worktree,
                &ExpectedTarget::on_branch("change-dirty"),
                DeleteOptions::local_discarding_dirty(true),
            )
            .await
            .expect("explicit discard with skip-teardown must delete");

        assert!(!worktree.exists());
        assert!(
            !marker.exists(),
            "skip-teardown must not run the teardown script"
        );
    }

    #[tokio::test]
    async fn tui_dirty_worktree_delete_e2e_teardown_commit_refuses_removal_and_keeps_the_branch() {
        let Some(fx) = dirty_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        // Teardown is operator code. This one commits, which moves both HEAD and
        // the branch ref out from under the facts the deletion was authorized
        // from — and creates a commit base does not have.
        fx.install_base_teardown(
            "printf 'teardown\\n' > teardown-artifact.txt\n\
             git add -A\n\
             git commit -m 'Teardown commit'",
        );
        let worktree = fx.add_worktree("change-dirty");
        let authorized_head = git(&worktree, &["rev-parse", "HEAD"]);
        std::fs::write(worktree.join("README.md"), "# edited\n").unwrap();

        let refusal = fx
            .service
            .delete_worktree(
                &worktree,
                &ExpectedTarget::on_branch("change-dirty"),
                DeleteOptions::local_discarding_dirty(false),
            )
            .await
            .expect_err("post-teardown drift must refuse removal");

        assert!(
            matches!(
                refusal,
                WorktreeOpError::NotFound(_) | WorktreeOpError::Ineligible(_)
            ),
            "expected a drift or eligibility refusal, got {refusal:?}"
        );
        assert!(
            worktree.is_dir(),
            "forced removal must not run on facts teardown invalidated"
        );
        assert!(
            fx.branch_exists("change-dirty"),
            "and the branch the teardown commit lives on must survive"
        );
        let head_now = git(&worktree, &["rev-parse", "HEAD"]);
        assert_ne!(
            head_now, authorized_head,
            "the test is only meaningful if teardown really moved HEAD"
        );
        assert_eq!(
            git(&fx.repo, &["rev-parse", "refs/heads/change-dirty"]),
            head_now,
            "the teardown commit is still reachable from the retained branch"
        );
    }

    #[tokio::test]
    async fn tui_dirty_worktree_delete_e2e_ignored_only_content_deletes_through_the_ordinary_path()
    {
        let Some(fx) = dirty_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        let worktree = fx.add_worktree("change-generated");
        // `generated/` is ignored by the committed `.gitignore`. Explicit status
        // observation without ignored-file enumeration classifies this clean, so
        // no destructive confirmation is involved — and the directory, generated
        // content included, still goes away.
        std::fs::create_dir_all(worktree.join("generated")).unwrap();
        std::fs::write(worktree.join("generated/build.log"), "noise\n").unwrap();

        fx.service
            .delete_worktree(
                &worktree,
                &ExpectedTarget::on_branch("change-generated"),
                DeleteOptions::local(false),
            )
            .await
            .expect("ignored-only content must not require a dirty discard");

        assert!(!worktree.exists());
    }

    #[tokio::test]
    async fn tui_dirty_worktree_delete_e2e_commits_ahead_never_offer_a_dirty_escalation() {
        let Some(fx) = dirty_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        let worktree = fx.add_worktree("change-ahead");
        std::fs::write(worktree.join("work.txt"), "work\n").unwrap();
        git(&worktree, &["add", "-A"]);
        git(&worktree, &["commit", "-m", "Unmerged work"]);
        // Dirty *and* ahead: dirty discard could waive the first but never the
        // second, so the refusal must be the ahead one — and it must arrive
        // carrying the dirty fact, so the confirmation it opens can name both.
        std::fs::write(worktree.join("README.md"), "# edited\n").unwrap();

        for options in [
            DeleteOptions::local(false),
            DeleteOptions::local_discarding_dirty(false),
        ] {
            let refusal = fx
                .service
                .delete_worktree(
                    &worktree,
                    &ExpectedTarget::on_branch("change-ahead"),
                    options,
                )
                .await
                .expect_err("unmerged commits must refuse deletion");
            let WorktreeOpError::CommitsAhead { target, .. } = refusal else {
                panic!("{options:?} must refuse with the typed ahead refusal: {refusal:?}");
            };
            assert_eq!(target.branch, "change-ahead");
            assert_eq!(target.head, git(&worktree, &["rev-parse", "HEAD"]));
            assert!(
                target.dirty,
                "{options:?}: the ahead target must report the uncommitted work Git sees"
            );
        }

        assert!(worktree.is_dir());
        assert!(fx.branch_exists("change-ahead"));
    }

    #[tokio::test]
    async fn tui_ahead_worktree_delete_e2e_removes_the_worktree_and_its_unmerged_branch() {
        let Some(fx) = dirty_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        let worktree = fx.add_worktree("change-ahead-discard");
        std::fs::write(worktree.join("work.txt"), "work\n").unwrap();
        git(&worktree, &["add", "-A"]);
        git(&worktree, &["commit", "-m", "Unmerged work"]);
        // Also dirty, so the one authorization has to cover both losses.
        std::fs::write(worktree.join("README.md"), "# edited\n").unwrap();
        let head = git(&worktree, &["rev-parse", "HEAD"]);

        let outcome = fx
            .service
            .delete_worktree(
                &worktree,
                &ExpectedTarget::on_branch("change-ahead-discard").with_head(head),
                DeleteOptions::local_discarding_ahead(false, true),
            )
            .await
            .expect("an explicitly authorized ahead discard must delete");

        assert!(!worktree.exists(), "the worktree directory must be gone");
        assert!(
            !fx.branch_exists("change-ahead-discard"),
            "the unmerged branch must be gone too: {}",
            outcome.detail
        );
        assert!(!outcome.branch_retained);
    }

    #[tokio::test]
    async fn tui_ahead_worktree_delete_e2e_refuses_a_confirmation_naming_a_stale_commit() {
        // The branch ref is the thing the whole authorization is anchored to, so
        // a real repository is where that anchor has to hold: a confirmation
        // taken at one commit may not delete a branch that has since moved on.
        // The post-removal half of that anchor — the compare-and-delete refusing
        // once the worktree is already gone — is unit-covered against a scripted
        // backend, because a real repository cannot move the ref inside that
        // window on demand.
        let Some(fx) = dirty_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        // Teardown is operator code that runs between the two observations, but
        // it may not move the very facts the deletion was authorized from. What
        // *can* move afterwards is the branch ref, so drive that directly by
        // authorizing from a stale HEAD.
        let worktree = fx.add_worktree("change-ahead-moved");
        std::fs::write(worktree.join("work.txt"), "work\n").unwrap();
        git(&worktree, &["add", "-A"]);
        git(&worktree, &["commit", "-m", "First unmerged commit"]);
        let stale_head = git(&worktree, &["rev-parse", "HEAD"]);
        std::fs::write(worktree.join("work.txt"), "more work\n").unwrap();
        git(&worktree, &["add", "-A"]);
        git(&worktree, &["commit", "-m", "Second unmerged commit"]);

        let refusal = fx
            .service
            .delete_worktree(
                &worktree,
                &ExpectedTarget::on_branch("change-ahead-moved").with_head(stale_head),
                DeleteOptions::local_discarding_ahead(false, false),
            )
            .await
            .expect_err("a confirmation naming a commit the branch left must refuse");

        assert!(
            matches!(refusal, WorktreeOpError::NotFound(_)),
            "the stale confirmation must be refused: {refusal:?}"
        );
        assert!(worktree.is_dir(), "nothing may be removed");
        assert!(
            fx.branch_exists("change-ahead-moved"),
            "and the branch keeps its unmerged commits"
        );
    }

    #[tokio::test]
    async fn tui_ahead_worktree_delete_e2e_ordinary_cleanup_still_only_deletes_merged_branches() {
        // The destructive operation must not have weakened the ordinary path:
        // an ahead branch reached without the explicit permission still refuses,
        // and a merged one is still cleaned up.
        let Some(fx) = dirty_fixture() else {
            println!("Skipping test: git not available");
            return;
        };
        let worktree = fx.add_worktree("change-merged");
        std::fs::write(worktree.join("work.txt"), "work\n").unwrap();
        git(&worktree, &["add", "-A"]);
        git(&worktree, &["commit", "-m", "Work to merge"]);
        git(
            &fx.repo,
            &["merge", "--no-ff", "-m", "Merge", "change-merged"],
        );

        fx.service
            .delete_worktree(
                &worktree,
                &ExpectedTarget::on_branch("change-merged"),
                DeleteOptions::local(false),
            )
            .await
            .expect("a merged worktree deletes under the ordinary policy");

        assert!(!worktree.exists());
        assert!(
            !fx.branch_exists("change-merged"),
            "merged-only cleanup still deletes a reachable branch"
        );
    }
}

// ── Stale worktree refresh (real Git worktrees / real command counts) ─────────
//
// These cases prove `harden-stale-worktree-refresh` against a real repository:
// which worktrees a periodic refresh actually spawns Git commands for, that the
// TUI and Web/UDS paths share one observation, that a revision change
// invalidates it, that an operator can still act on a worktree periodic refresh
// skipped, that merge diagnostics stay bounded, and that none of it touches the
// working trees.
//
// Command counts come from the inspection recorder, which attributes every
// spawned ahead/conflict command to the worktree it ran for. Each case filters
// to its own temporary repository, so the assertions are about what this test
// caused and nothing else.

mod stale_refresh_support {
    use std::path::{Path, PathBuf};

    pub use super::upstream_integration_support::{
        configure_identity, git, git_allow_failure, write_and_commit,
    };

    /// A repository whose worktrees live outside it, so a worktree directory is
    /// never itself untracked content in the tree under observation.
    pub struct RefreshFixture {
        pub _dir: tempfile::TempDir,
        pub repo: PathBuf,
        pub worktrees: PathBuf,
    }

    impl RefreshFixture {
        /// Register a secondary worktree on a new branch at the current base tip.
        pub fn add_worktree(&self, branch: &str) -> PathBuf {
            let path = self.worktrees.join(branch);
            git(
                &self.repo,
                &[
                    "worktree",
                    "add",
                    "-b",
                    branch,
                    path.to_str().unwrap(),
                    "HEAD",
                ],
            );
            path
        }

        /// Declare an active OpenSpec change, committed on the base branch.
        pub fn declare_change(&self, change_id: &str) {
            write_and_commit(
                &self.repo,
                &format!("openspec/changes/{}/proposal.md", change_id),
                "# change\n",
                &format!("Declare {}", change_id),
            );
        }

        /// Declare a change and mark it rejected, the state an operator reviews
        /// a retained worktree in.
        pub fn declare_rejected_change(&self, change_id: &str) {
            self.declare_change(change_id);
            write_and_commit(
                &self.repo,
                &format!("openspec/changes/{}/REJECTED.md", change_id),
                "# REJECTED\n",
                &format!("Reject {}", change_id),
            );
        }
    }

    /// Build the fixture, or `None` when git is unavailable.
    pub fn refresh_fixture() -> Option<RefreshFixture> {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path().join("repo");
        let worktrees = dir.path().join("worktrees");
        std::fs::create_dir_all(&repo).unwrap();
        std::fs::create_dir_all(&worktrees).unwrap();

        if !git_allow_failure(&repo, &["init", "-b", "main"]) {
            return None;
        }
        configure_identity(&repo);
        // Unique content, so two fixtures built in the same second cannot mint
        // the same commit id and therefore cannot share a cache key.
        write_and_commit(
            &repo,
            "README.md",
            &format!("# base {}\n", uuid_like()),
            "Initial commit",
        );

        Some(RefreshFixture {
            _dir: dir,
            repo,
            worktrees,
        })
    }

    /// A per-fixture discriminator. Not cryptographic: it only has to make two
    /// fixtures' initial commits differ.
    pub fn uuid_like() -> String {
        use std::sync::atomic::{AtomicU64, Ordering};
        static SEQUENCE: AtomicU64 = AtomicU64::new(0);
        format!(
            "{}-{}-{}",
            std::process::id(),
            SEQUENCE.fetch_add(1, Ordering::Relaxed),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        )
    }

    /// `git status --porcelain=v1 -uall` plus the bytes of every file in the tree.
    ///
    /// Refresh is supposed to be non-mutating, and "the index still agrees" is
    /// only half of that: a check that rewrote a file would leave status clean.
    pub fn tree_snapshot(worktree: &Path) -> (String, Vec<(PathBuf, Vec<u8>)>) {
        let status = git(worktree, &["status", "--porcelain=v1", "-uall"]);
        let mut files = Vec::new();
        collect_files(worktree, worktree, &mut files);
        files.sort_by(|a, b| a.0.cmp(&b.0));
        (status, files)
    }

    fn collect_files(root: &Path, dir: &Path, out: &mut Vec<(PathBuf, Vec<u8>)>) {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.file_name().is_some_and(|name| name == ".git") {
                continue;
            }
            if path.is_dir() {
                collect_files(root, &path, out);
            } else if let Ok(bytes) = std::fs::read(&path) {
                out.push((path.strip_prefix(root).unwrap().to_path_buf(), bytes));
            }
        }
    }

    /// The observed row for one worktree path.
    pub fn row<'a>(
        rows: &'a [conflux::tui::types::WorktreeInfo],
        path: &Path,
    ) -> &'a conflux::tui::types::WorktreeInfo {
        let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
        rows.iter()
            .find(|row| {
                std::fs::canonicalize(&row.path).unwrap_or_else(|_| row.path.clone()) == canonical
            })
            .unwrap_or_else(|| {
                panic!(
                    "every registered worktree must stay listed; {} is missing from {:?}",
                    path.display(),
                    rows.iter().map(|row| &row.path).collect::<Vec<_>>()
                )
            })
    }
}

#[tokio::test]
async fn stale_refresh_e2e_periodic_paths_inspect_only_current_change_worktrees() {
    use conflux::worktree_ops::inspection::{
        record_inspection_commands, recorded_inspection_count, InspectionCommand,
    };
    use conflux::worktree_ops::InspectionState;
    use stale_refresh_support::*;

    let Some(fx) = refresh_fixture() else {
        println!("Skipping test: git not available");
        return;
    };
    record_inspection_commands();

    fx.declare_change("live-change");
    fx.declare_rejected_change("rejected-change");
    let live = fx.add_worktree("live-change");
    let rejected = fx.add_worktree("rejected-change");
    let stale = fx.add_worktree("stale-change");
    let session = fx.add_worktree("ws-session-a1b2c3");
    for (worktree, name) in [
        (&live, "live"),
        (&rejected, "rejected"),
        (&stale, "stale"),
        (&session, "session"),
    ] {
        write_and_commit(
            worktree,
            "work.txt",
            &format!("{name}\n"),
            "Work ahead of base",
        );
    }

    // ── The TUI's periodic refresh ──────────────────────────────────────────
    let rows = conflux::tui::load_worktrees_with_conflict_check(&fx.repo)
        .await
        .expect("the TUI periodic refresh reads the worktree list");

    assert_eq!(
        rows.len(),
        5,
        "every registered worktree stays visible: {:?}",
        rows.iter().map(|row| &row.branch).collect::<Vec<_>>()
    );

    // A rejected change's worktree is retained on purpose and an operator
    // reviewing it needs accurate guidance, so it stays automatically eligible.
    assert_eq!(
        row(&rows, &rejected).inspection,
        InspectionState::Checked,
        "a rejected change's retained worktree is still inspected"
    );
    assert_eq!(
        recorded_inspection_count(&rejected, InspectionCommand::Conflicts),
        1
    );

    let live_row = row(&rows, &live);
    assert_eq!(live_row.inspection, InspectionState::Checked);
    assert!(
        live_row.has_commits_ahead,
        "a current change worktree is still checked for commits ahead"
    );
    assert_eq!(
        recorded_inspection_count(&live, InspectionCommand::Conflicts),
        1,
        "the current change worktree is simulated exactly once"
    );
    assert_eq!(
        recorded_inspection_count(&live, InspectionCommand::CommitsAhead),
        1
    );

    for (worktree, label) in [(&stale, "stale"), (&session, "ws-session")] {
        let skipped = row(&rows, worktree);
        assert_eq!(
            skipped.inspection,
            InspectionState::NotInspected,
            "{label} must be reported as uninspected, not as clean"
        );
        assert!(
            !skipped.has_commits_ahead && skipped.merge_conflict.is_none(),
            "{label} carries no fabricated ahead/conflict evidence"
        );
        assert_ne!(
            skipped.merge_status_label(),
            "merged",
            "{label} has commits ahead in reality; refresh must not claim otherwise"
        );
        assert_eq!(
            recorded_inspection_count(worktree, InspectionCommand::Conflicts),
            0,
            "{label} must cost no merge simulation"
        );
        assert_eq!(
            recorded_inspection_count(worktree, InspectionCommand::CommitsAhead),
            0,
            "{label} must cost no commits-ahead command"
        );
    }

    // ── The Web/UDS periodic refresh, on the same unchanged revisions ───────
    let web = conflux::web::WebState::new(&[]);
    web.refresh_from_disk_at(&fx.repo)
        .await
        .expect("the Web/UDS periodic refresh reads the same repository");
    let web_rows = web.get_state().await.worktrees;

    assert_eq!(
        recorded_inspection_count(&live, InspectionCommand::Conflicts),
        1,
        "an unchanged revision tuple is simulated once process-wide, not once per frontend"
    );
    assert_eq!(
        row(&web_rows, &live).inspection,
        InspectionState::Reused,
        "the Web path reuses the observation the TUI path produced"
    );
    assert!(row(&web_rows, &live).has_commits_ahead);
    assert_eq!(
        row(&web_rows, &stale).inspection,
        InspectionState::NotInspected,
        "both periodic paths apply the same eligibility policy"
    );
    assert_eq!(
        recorded_inspection_count(&stale, InspectionCommand::Conflicts)
            + recorded_inspection_count(&session, InspectionCommand::Conflicts),
        0
    );

    // ── A revision change invalidates the observation ───────────────────────
    write_and_commit(&live, "work.txt", "live again\n", "Move the worktree HEAD");
    let rows = conflux::tui::load_worktrees_with_conflict_check(&fx.repo)
        .await
        .expect("refresh after a revision change");

    assert_eq!(
        row(&rows, &live).inspection,
        InspectionState::Checked,
        "a moved worktree HEAD must be re-inspected, not reused"
    );
    assert_eq!(
        recorded_inspection_count(&live, InspectionCommand::Conflicts),
        2,
        "exactly one fresh simulation follows the revision change"
    );
    assert_eq!(
        recorded_inspection_count(&stale, InspectionCommand::Conflicts),
        0,
        "an ineligible worktree stays uninspected across revision changes"
    );

    // ── And a base-side change invalidates it too ───────────────────────────
    write_and_commit(&fx.repo, "base.txt", "base moved\n", "Move base HEAD");
    let rows = conflux::tui::load_worktrees_with_conflict_check(&fx.repo)
        .await
        .expect("refresh after a base change");

    assert_eq!(row(&rows, &live).inspection, InspectionState::Checked);
    assert_eq!(
        recorded_inspection_count(&live, InspectionCommand::Conflicts),
        3,
        "a moved base HEAD is a different revision tuple and is simulated again"
    );
}

#[tokio::test]
async fn stale_refresh_e2e_operator_actions_reinspect_skipped_worktrees() {
    use conflux::config::OrchestratorConfig;
    use conflux::worktree_ops::inspection::{
        record_inspection_commands, recorded_inspection_count, InspectionCommand,
    };
    use conflux::worktree_ops::service::{
        DeleteOptions, ExpectedTarget, NullEventSink, WorktreeOpError, WorktreeService,
    };
    use conflux::worktree_ops::InspectionState;
    use stale_refresh_support::*;
    use std::sync::Arc;

    let Some(fx) = refresh_fixture() else {
        println!("Skipping test: git not available");
        return;
    };
    record_inspection_commands();

    let session = fx.add_worktree("ws-session-a1b2c3");
    let stale = fx.add_worktree("stale-change");
    write_and_commit(&session, "session.txt", "session\n", "Session work");
    write_and_commit(&stale, "stale.txt", "stale\n", "Stale work");

    // Periodic refresh declines both: neither branch maps to a current change.
    let rows = conflux::tui::load_worktrees_with_conflict_check(&fx.repo)
        .await
        .expect("periodic refresh");
    assert_eq!(
        row(&rows, &session).inspection,
        InspectionState::NotInspected
    );
    assert_eq!(row(&rows, &stale).inspection, InspectionState::NotInspected);
    assert_eq!(
        recorded_inspection_count(&session, InspectionCommand::Conflicts),
        0
    );

    let service = WorktreeService::new(
        Arc::new(conflux::worktree_ops::git_backend::GitWorktreeBackend::new(
            fx.repo.clone(),
            Arc::new(OrchestratorConfig::default()),
        )),
        Arc::new(NullEventSink),
        fx.worktrees.clone(),
    );

    // ── Operator merge of an unclassified worktree ──────────────────────────
    service
        .merge_worktree(
            &session,
            conflux::worktree_ops::service::ConflictPolicy::AbortOnConflict,
        )
        .await
        .expect("a ws-session worktree periodic refresh skipped is still mergeable");

    assert_eq!(
        recorded_inspection_count(&session, InspectionCommand::CommitsAhead),
        1,
        "the merge decided eligibility from a fresh targeted observation"
    );
    assert_eq!(
        recorded_inspection_count(&stale, InspectionCommand::CommitsAhead),
        0,
        "a targeted observation pays for its target only"
    );
    assert_eq!(
        git(&fx.repo, &["log", "--format=%s", "-1"]),
        "Merge branch 'ws-session-a1b2c3'",
        "the merge really happened"
    );

    // ── Operator deletion of a stale worktree ───────────────────────────────
    // It carries unmerged commits, so a fail-closed deletion refuses — but it
    // refuses on freshly observed evidence, which is the point: periodic
    // filtering alone never makes a worktree permanently undeletable.
    let refusal = service
        .delete_worktree(
            &stale,
            &ExpectedTarget::on_branch("stale-change"),
            DeleteOptions::fail_closed(),
        )
        .await
        .expect_err("a worktree with unmerged commits fails closed");
    assert!(
        matches!(refusal, WorktreeOpError::CommitsAhead { .. }),
        "the refusal must name the observed commits, not an uninspected state: {refusal:?}"
    );
    assert!(
        recorded_inspection_count(&stale, InspectionCommand::CommitsAhead) >= 1,
        "deletion re-observed the worktree periodic refresh had skipped"
    );

    // With the loss explicitly confirmed, the same worktree deletes.
    service
        .delete_worktree(
            &stale,
            &ExpectedTarget::on_branch("stale-change"),
            DeleteOptions::local_discarding_ahead(true, false),
        )
        .await
        .expect("an explicitly confirmed stale worktree is still deletable");
    assert!(!stale.exists(), "the stale worktree was removed");
}

#[tokio::test]
async fn stale_refresh_e2e_refresh_never_touches_worktree_state() {
    use conflux::worktree_ops::inspection::record_inspection_commands;
    use stale_refresh_support::*;

    let Some(fx) = refresh_fixture() else {
        println!("Skipping test: git not available");
        return;
    };
    record_inspection_commands();

    fx.declare_change("live-change");
    let live = fx.add_worktree("live-change");
    let stale = fx.add_worktree("stale-change");

    // Both an inspected and an uninspected worktree carry every kind of dirt.
    for worktree in [&live, &stale] {
        write_and_commit(worktree, "tracked.txt", "committed\n", "Tracked file");
        std::fs::write(worktree.join("tracked.txt"), "unstaged edit\n").unwrap();
        std::fs::write(worktree.join("staged.txt"), "staged\n").unwrap();
        git(worktree, &["add", "staged.txt"]);
        std::fs::write(worktree.join("untracked.txt"), "untracked\n").unwrap();
    }

    let before: Vec<_> = [&live, &stale]
        .iter()
        .map(|worktree| tree_snapshot(worktree))
        .collect();

    conflux::tui::load_worktrees_with_conflict_check(&fx.repo)
        .await
        .expect("periodic refresh");
    let web = conflux::web::WebState::new(&[]);
    web.refresh_from_disk_at(&fx.repo)
        .await
        .expect("periodic refresh");

    for (index, worktree) in [&live, &stale].iter().enumerate() {
        let after = tree_snapshot(worktree);
        assert_eq!(
            before[index].0,
            after.0,
            "refresh changed the index/status of {}",
            worktree.display()
        );
        assert_eq!(
            before[index].1,
            after.1,
            "refresh changed file bytes in {}",
            worktree.display()
        );
    }
}

#[tokio::test]
async fn stale_refresh_e2e_large_conflict_diagnostics_stay_bounded() {
    use conflux::worktree_ops::inspection::{
        check_merge_conflicts, MAX_CONFLICT_SAMPLE, MAX_OUTPUT_PREFIX_BYTES,
    };
    use stale_refresh_support::*;

    let Some(fx) = refresh_fixture() else {
        println!("Skipping test: git not available");
        return;
    };

    // A conflict surface far wider than the sample bound: every one of these
    // files is edited differently on base and on the branch.
    const FILES: usize = 60;
    for index in 0..FILES {
        std::fs::write(fx.repo.join(format!("conflict_{index:03}.txt")), "shared\n").unwrap();
    }
    git(&fx.repo, &["add", "-A"]);
    git(&fx.repo, &["commit", "-m", "Shared files"]);

    let branch = fx.add_worktree("live-change");
    for index in 0..FILES {
        std::fs::write(
            branch.join(format!("conflict_{index:03}.txt")),
            format!("branch side {index}\n"),
        )
        .unwrap();
    }
    git(&branch, &["add", "-A"]);
    git(&branch, &["commit", "-m", "Branch edits"]);

    for index in 0..FILES {
        std::fs::write(
            fx.repo.join(format!("conflict_{index:03}.txt")),
            format!("base side {index}\n"),
        )
        .unwrap();
    }
    git(&fx.repo, &["add", "-A"]);
    git(&fx.repo, &["commit", "-m", "Base edits"]);

    let simulation = check_merge_conflicts(&branch, "main")
        .await
        .expect("a conflicting merge is an observation, not a command failure");

    assert!(simulation.conflicted, "the merge really does conflict");
    assert_eq!(
        simulation.conflict_count, FILES,
        "the count of conflicting paths stays truthful"
    );
    assert_eq!(
        simulation.conflict_sample.len(),
        MAX_CONFLICT_SAMPLE,
        "the sample is capped regardless of the conflict surface"
    );
    assert!(simulation.stdout_prefix.len() <= MAX_OUTPUT_PREFIX_BYTES);
    assert!(simulation.stderr_prefix.len() <= MAX_OUTPUT_PREFIX_BYTES);
    assert!(
        simulation.stdout_bytes > MAX_OUTPUT_PREFIX_BYTES,
        "this fixture is only meaningful if the raw output exceeds the bound, got {} bytes",
        simulation.stdout_bytes
    );

    let summary = simulation.summary();
    assert!(
        summary.len() < 16 * 1024,
        "a per-refresh diagnostic must stay small, got {} bytes",
        summary.len()
    );
    assert!(
        !summary.contains(&format!("conflict_{:03}.txt", FILES - 1)),
        "the summary must not carry the complete conflict list: {summary}"
    );
    assert!(
        summary.contains(&format!("stdout_bytes={}", simulation.stdout_bytes)),
        "the summary still discloses how much output there was: {summary}"
    );
}