cflx 0.6.327

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
use std::path::PathBuf;

use clap::{ArgGroup, Parser, Subcommand, ValueEnum};
use clap_complete::Shell;
use tracing::debug;

/// Build metadata included in versioned user-facing logs and output.
pub const VERSION_WITH_BUILD: &str = concat!(
    "v",
    env!("CARGO_PKG_VERSION"),
    " (",
    env!("BUILD_NUMBER"),
    ")"
);

/// Get version string with build number
const fn get_version_string() -> &'static str {
    VERSION_WITH_BUILD
}

fn parse_push_remote(value: &str) -> std::result::Result<String, String> {
    if value.contains(':') {
        return Err("branch selection is not supported for --push; use a remote name only".into());
    }
    Ok(value.to_string())
}

/// OpenSpec Orchestrator - Automate OpenSpec workflow
#[derive(Parser, Debug)]
#[command(name = "cflx")]
#[command(version = get_version_string())]
#[command(about = "Automates OpenSpec change workflow (list → apply → archive)")]
#[command(long_about = "Conflux - OpenSpec Change Orchestrator

Automates the OpenSpec change workflow:
  1. Lists pending changes in openspec/changes/
  2. Applies changes using configured AI agent
  3. Archives completed changes to openspec/specs/

SUBCOMMANDS:
  run      Execute orchestration loop (non-interactive)
  tui      Launch interactive TUI dashboard (default)
  client   Operate an existing owner (status/mark/start/stop/wait/subscribe/mcp) without becoming one
  init     Generate configuration template
  openapi  Print the generated /api/v2 OpenAPI 3.1 schema to stdout

KEY OPTIONS:
  --max-concurrent N    Limit concurrent workspaces (default: 3)
  --dry-run             Preview dependency execution groups without execution
  --vcs BACKEND         VCS backend: auto, git (default: auto)
  --web                 Enable the browser-facing TCP web monitoring server
  --web-port PORT       Web server port (default: 0 = auto-assign)
    --web-bind ADDR       Web server bind address (default: 127.0.0.1)
  --web-unix-socket PATH     Override the default ${GIT_COMMON_DIR}/cflx-api.sock
  --no-web-unix-socket       Do not serve /api/v2 on a Unix socket
  --web-auth-token TOKEN     Bearer token for the /api/v2 remote-control API
                             (visible in process listings; prefer the -env form)
  --web-auth-token-env VAR   Environment variable holding that bearer token
  --web-allowed-origin ORIGIN  Exact extra CORS origin for /api/v2 (repeatable)
    logs                 View persistent Conflux log files without mutating them

Use 'cflx <subcommand> --help' for more information on a specific command.")]
#[command(subcommand_required(false))]
pub struct Cli {
    /// Path to custom configuration file (JSONC format)
    #[arg(long, short = 'c')]
    pub config: Option<PathBuf>,

    /// Enable web monitoring server for remote status viewing
    #[arg(long)]
    pub web: bool,

    /// Port for web monitoring server (default: 0 = auto-assign by OS)
    #[arg(long, default_value = "0")]
    pub web_port: u16,

    /// Bind address for web monitoring server (default: 127.0.0.1)
    #[arg(long, default_value = "127.0.0.1")]
    pub web_bind: String,

    /// Literal bearer token for the `/api/v2` remote-control API.
    ///
    /// Required for any non-loopback `--web-bind`. Prefer
    /// `--web-auth-token-env`: a literal value here is visible to anything that
    /// can inspect this process's arguments.
    #[arg(long, conflicts_with = "web_auth_token_env")]
    pub web_auth_token: Option<String>,

    /// Environment variable holding the bearer token for the `/api/v2` API.
    #[arg(long, conflicts_with = "web_auth_token")]
    pub web_auth_token_env: Option<String>,

    /// Exact additional origin allowed to make cross-origin `/api/v2` requests.
    ///
    /// Repeatable. Exact `scheme://host[:port]` values only — wildcards are
    /// rejected, and forwarded headers never widen this list, so a reverse proxy
    /// that changes the external origin must name it here.
    #[arg(long = "web-allowed-origin", value_name = "ORIGIN")]
    pub web_allowed_origins: Vec<String>,

    /// Path for the local `/api/v2` Unix-domain socket.
    ///
    /// Overrides the default `${GIT_COMMON_DIR}/cflx-api.sock`, which every
    /// linked worktree of one repository shares. Mutually exclusive with
    /// `--no-web-unix-socket`.
    #[arg(long, value_name = "PATH", conflicts_with = "no_web_unix_socket")]
    pub web_unix_socket: Option<PathBuf>,

    /// Do not serve `/api/v2` on a Unix-domain socket.
    ///
    /// The Unix socket is the only listener a web-enabled build starts without
    /// `--web`, so opting out leaves the process API-free unless `--web` adds
    /// the TCP listener.
    #[arg(long, conflicts_with = "web_unix_socket")]
    pub no_web_unix_socket: bool,

    /// Push completed TUI change branches to a remote instead of merging to base.
    #[arg(long, num_args = 0..=1, default_missing_value = "origin", value_parser = parse_push_remote)]
    pub push: Option<String>,

    /// Publish every completed change's verified cumulative base to the selected
    /// remote's same-name branch before that change succeeds.
    ///
    /// Same contract as `cflx run -u`: `-u` and value-less `--integrate-upstream`
    /// select `origin`, a named remote requires `--integrate-upstream=<remote>`,
    /// and `--upstream-verify-command` is mandatory. Local TUI only.
    #[arg(
        long,
        num_args = 0..=1,
        require_equals = true,
        default_missing_value = crate::upstream::DEFAULT_UPSTREAM_REMOTE,
        value_parser = crate::upstream::options::parse_upstream_remote
    )]
    pub integrate_upstream: Option<String>,

    /// Publish to `origin`; short value-less spelling of `--integrate-upstream`.
    ///
    /// A named remote is available only as `--integrate-upstream=<remote>`, so
    /// `-u` takes no value at all and `-u=<remote>` is a parse error.
    #[arg(short = 'u', action = clap::ArgAction::SetTrue, conflicts_with = "integrate_upstream")]
    pub integrate_upstream_default_remote: bool,

    /// Complete repository verification command run before every publication.
    ///
    /// Requires `-u`/`--integrate-upstream`; rejected without it.
    #[arg(long)]
    pub upstream_verify_command: Option<String>,

    #[command(subcommand)]
    pub command: Option<Commands>,
}

/// Rejection of a top-level upstream option that an explicit subcommand ignores.
///
/// The top-level `-u` / `--integrate-upstream` / `--upstream-verify-command`
/// options exist only to give bare `cflx` the same contract as `cflx tui`. When
/// an explicit subcommand follows, the subcommand parses its own options and the
/// top-level values are never read — so accepting them would silently drop an
/// opt-in whose publication is part of the success contract.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TopLevelUpstreamOptionError {
    /// Spelling the operator used, as it must be repositioned.
    pub option: &'static str,
    /// Subcommand that would have ignored it.
    pub subcommand: &'static str,
}

impl std::fmt::Display for TopLevelUpstreamOptionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} must follow the '{}' subcommand: 'cflx {} {}' applies to the subcommand, while 'cflx {} {}' would be ignored",
            self.option, self.subcommand, self.subcommand, self.option, self.option, self.subcommand
        )
    }
}

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

impl Cli {
    /// Name of the subcommand for diagnostics, when one was given.
    fn subcommand_name(&self) -> Option<&'static str> {
        match self.command.as_ref()? {
            Commands::Run(_) => Some("run"),
            Commands::Tui(_) => Some("tui"),
            Commands::Init(_) => Some("init"),
            Commands::CheckConflicts(_) => Some("check-conflicts"),
            Commands::InstallSkills(_) => Some("install-skills"),
            Commands::Logs(_) => Some("logs"),
            Commands::JudgeEval(_) => Some("judge-eval"),
            Commands::Openspec(_) => Some("openspec"),
            Commands::Client(_) => Some("client"),
            Commands::Openapi => Some("openapi"),
            Commands::Completion(_) => Some("completion"),
            Commands::Complete(_) => Some("__complete"),
        }
    }

    /// Reject top-level upstream options that an explicit subcommand would drop.
    ///
    /// Called before any orchestration, logging, or workspace mutation.
    pub fn validate_upstream_option_placement(
        &self,
    ) -> std::result::Result<(), TopLevelUpstreamOptionError> {
        let Some(subcommand) = self.subcommand_name() else {
            return Ok(());
        };
        let option = if self.integrate_upstream_default_remote {
            "-u"
        } else if self.integrate_upstream.is_some() {
            "--integrate-upstream"
        } else if self.upstream_verify_command.is_some() {
            "--upstream-verify-command"
        } else {
            return Ok(());
        };
        Err(TopLevelUpstreamOptionError { option, subcommand })
    }
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Run the OpenSpec change orchestration loop (non-interactive)
    Run(RunArgs),

    /// Launch the interactive TUI dashboard
    ///
    /// Key bindings: Space (select), F5 (start by default), Esc (stop), Tab (switch view), q (quit).
    /// Override the default start key in ~/.config/cflx/tui.jsonc.
    Tui(TuiArgs),

    /// Generate project overrides for required commands missing globally
    Init(InitArgs),

    /// Check for conflicts between spec delta files across changes
    CheckConflicts(CheckConflictsArgs),

    /// Install agent skills into .agents/skills or .claude/skills
    ///
    /// Installs bundled agent skills into the standard target location.
    ///
    /// EXAMPLES:
    ///   cflx install-skills                    # Install bundled skills to .agents (project scope)
    ///   cflx install-skills --global           # Install bundled skills to .agents (global scope)
    ///   cflx install-skills --claude           # Install bundled skills to .claude (project scope)
    ///   cflx install-skills --claude --global  # Install bundled skills to .claude (global scope)
    #[command(name = "install-skills")]
    InstallSkills(InstallSkillsArgs),

    /// View persistent Conflux logs without creating, appending, or cleaning log files
    ///
    /// EXAMPLES:
    ///   cflx logs --path                    # Print selected log file path
    ///   cflx logs --last 50                 # Print the last 50 log lines
    ///   cflx logs --follow                  # Print recent lines, then stream appended lines
    ///   cflx logs --today --project my-slug # Select today's log for an explicit project
    Logs(LogsArgs),

    /// Inspect opt-in shadow judge evaluation records, read-only
    ///
    /// Reads only the dedicated `<state-root>/evaluations` store — never the
    /// ordinary log root — and mutates nothing: it creates no directory, no
    /// installation salt, and no record file, initializes no operational
    /// logging, and runs no retention. Records exist only where
    /// `judge_commands.parallel_dependency.evaluation.enabled` was explicitly
    /// turned on; everywhere else this reports an empty summary.
    ///
    /// The metrics are promotion evidence — precision, recall, specificity,
    /// outcome rates, latency percentiles, and token totals — and nothing here
    /// feeds routing, Acceptance, Archive, or any lifecycle decision.
    ///
    /// EXAMPLES:
    ///   cflx judge-eval summary --purpose parallel_dependency
    ///   cflx judge-eval summary --purpose parallel_dependency --json
    ///   cflx judge-eval summary --purpose parallel_dependency --since-days 7
    ///   cflx judge-eval summary --purpose parallel_dependency --project my-slug
    #[command(name = "judge-eval")]
    JudgeEval(JudgeEvalArgs),

    /// OpenSpec utility commands for repository-scoped operations
    ///
    /// Provides native subcommands for listing, inspecting, validating, and
    /// archiving OpenSpec changes and specs — replacing the former Python helper.
    ///
    /// EXAMPLES:
    ///   cflx openspec list                          # List active changes
    ///   cflx openspec list --specs                  # List canonical specs
    ///   cflx openspec show my-change                # Show change details
    ///   cflx openspec show my-change --json         # JSON output
    ///   cflx openspec validate --strict             # Validate all changes
    ///   cflx openspec archive my-change --yes       # Archive a change
    Openspec(OpenspecArgs),

    /// Operate an existing Conflux owner as a client, without becoming one
    ///
    /// `cflx client` talks to the process that already holds this repository —
    /// a TUI, or a `cflx run` for read-only observation — over its local
    /// `/api/v2` Unix socket. It never takes the repository lock, binds a
    /// listener, starts orchestration, or launches an AI subprocess, which is
    /// exactly what separates it from `cflx run`: `run` *is* an owner of a
    /// finite explicit-target run, while `client` only speaks to one.
    ///
    /// Control, not protocol: the verbs are the operator's own. `mark` and
    /// `unmark` write one proposal's execution mark and preserve every unrelated
    /// one; `start` is the F5 equivalent that consumes the owner's authoritative
    /// mark set. No caller constructs a revision, an idempotency key, a command
    /// type, or a queue intent, and no client command decides admission — the
    /// owner's own settlement does.
    ///
    /// `subscribe` manages completion callbacks for named proposals. Because it
    /// is keyed by the proposal rather than by an execution episode, it can be
    /// registered before anything is admitted, and each new episode of a
    /// subscribed proposal delivers once. Delivery notifies; it never resumes an
    /// agent. The callback is an argv after `--`, never shell source.
    ///
    /// EXAMPLES:
    ///   cflx client status --json               # Read the owner without mutating it
    ///   cflx client mark alpha beta --json      # Select proposals; admission stays the owner's
    ///   cflx client start --json                # F5 equivalent over the authoritative marks
    ///   cflx client stop --json                 # Graceful stop; force-stop for the immediate one
    ///   cflx client force-stop-change ID --json # Kill exactly one proposal now
    ///   cflx client wait alpha                  # Observe until verified completion; no deadline
    ///   cflx client wait alpha --timeout 30m    # Give up after an explicit deadline instead
    ///   cflx client subscribe set alpha --instance-id ID --json -- /absolute/callback
    ///   cflx client subscribe get alpha --instance-id ID --json     # Read the registration
    ///   cflx client subscribe clear alpha --instance-id ID --json   # Remove it
    ///   cflx client mcp                         # Serve the same controls over stdio MCP
    Client(ClientArgs),

    /// Print the generated /api/v2 OpenAPI 3.1 schema to standard output
    ///
    /// Read-only export of the same document `GET /api/v2/openapi.yaml` serves.
    /// It needs no Git repository and starts no logging, listeners, lifecycle
    /// adapters, AI subprocesses, or orchestration. Standard output carries only
    /// the schema, so redirecting it produces a valid standalone document;
    /// diagnostics go to standard error and failures exit non-zero.
    ///
    /// EXAMPLES:
    ///   cflx openapi                   # Print the schema
    ///   cflx openapi > openapi.yaml    # Export it for client generation
    Openapi,

    /// Generate shell completion scripts
    Completion(CompletionArgs),

    /// Hidden internal completion candidate commands
    #[command(name = "__complete", hide = true)]
    Complete(InternalCompleteArgs),
}

/// Supported shells for generated completion scripts.
#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum CompletionShell {
    Bash,
    Fish,
    #[value(name = "powershell")]
    PowerShell,
    Zsh,
}

impl From<CompletionShell> for Shell {
    fn from(shell: CompletionShell) -> Self {
        match shell {
            CompletionShell::Bash => Shell::Bash,
            CompletionShell::Fish => Shell::Fish,
            CompletionShell::PowerShell => Shell::PowerShell,
            CompletionShell::Zsh => Shell::Zsh,
        }
    }
}

/// Arguments for the completion subcommand
#[derive(Parser, Debug)]
pub struct CompletionArgs {
    /// Shell to generate completions for
    #[arg(value_enum)]
    pub shell: CompletionShell,
}

/// Hidden internal completion candidate commands.
#[derive(Parser, Debug)]
pub struct InternalCompleteArgs {
    #[command(subcommand)]
    pub command: InternalCompleteCommands,
}

#[derive(Subcommand, Debug)]
pub enum InternalCompleteCommands {
    /// Print OpenSpec change ID completion candidates, one per line
    #[command(name = "change-ids")]
    ChangeIds(ChangeIdCompletionArgs),
}

#[derive(Parser, Debug)]
pub struct ChangeIdCompletionArgs {
    /// Include active OpenSpec changes
    #[arg(long)]
    pub active: bool,

    /// Include archived OpenSpec changes
    #[arg(long)]
    pub archived: bool,

    /// Only include candidates beginning with this prefix
    #[arg(long)]
    pub prefix: Option<String>,
}

/// Arguments for the logs subcommand
#[derive(Parser, Debug)]
#[command(
    long_about = "View persistent Conflux log files without initializing runtime logging.

By default, prints the last 200 lines from the latest existing log for the current project.
Use --path to inspect the selected path without requiring the file to exist.

EXAMPLES:
  cflx logs --path
  cflx logs --last 50
  cflx logs --follow
  cflx logs --today --project conflux-a1b2c3d4"
)]
pub struct LogsArgs {
    /// Print the selected log path instead of reading log content
    #[arg(long)]
    pub path: bool,

    /// Print at most the last N lines from the selected log file
    #[arg(long, value_name = "N")]
    pub last: Option<usize>,

    /// Print the selected tail and then stream appended lines until interrupted
    #[arg(long)]
    pub follow: bool,

    /// Prefer today's log file instead of the latest existing dated log file
    #[arg(long)]
    pub today: bool,

    /// Select an explicit log project slug under the Conflux log root
    #[arg(long, value_name = "SLUG")]
    pub project: Option<String>,
}

// ============================================================================
// Judge evaluation records
// ============================================================================

/// Largest accepted `--since-days`, matching the configuration's own retention
/// ceiling. A parse bound, not a policy: it turns a typo into a usage error
/// rather than an arithmetic surprise deep inside a date computation.
const MAX_JUDGE_EVAL_SINCE_DAYS: u32 = 3_650;

fn parse_since_days(value: &str) -> std::result::Result<u32, String> {
    let days: u32 = value
        .parse()
        .map_err(|_| format!("`{value}` is not a whole number of days"))?;
    if days == 0 {
        // Zero is not "no window" here: an empty window would report an empty
        // summary that looks exactly like "nothing was ever recorded".
        return Err("--since-days must be at least 1".to_string());
    }
    if days > MAX_JUDGE_EVAL_SINCE_DAYS {
        return Err(format!(
            "--since-days must be at most {MAX_JUDGE_EVAL_SINCE_DAYS}"
        ));
    }
    Ok(days)
}

/// Judgment purposes that have an evaluation store.
///
/// A closed enum rather than a free string: naming a purpose that records
/// nothing should be a usage error, not an empty summary indistinguishable
/// from an unused judge.
#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum JudgeEvalPurpose {
    #[value(name = "parallel_dependency")]
    ParallelDependency,
}

impl JudgeEvalPurpose {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::ParallelDependency => "parallel_dependency",
        }
    }
}

/// Arguments for the `judge-eval` subcommand namespace.
#[derive(Parser, Debug)]
pub struct JudgeEvalArgs {
    #[command(subcommand)]
    pub command: JudgeEvalCommands,
}

#[derive(Subcommand, Debug)]
pub enum JudgeEvalCommands {
    /// Summarize recorded evaluation evidence without modifying anything
    ///
    /// This change exposes the read-only summary alone. Export and purge are
    /// separate reviewable commands, so nothing here can delete a record.
    Summary(JudgeEvalSummaryArgs),
}

/// Arguments for `cflx judge-eval summary`.
#[derive(Parser, Debug)]
#[command(long_about = "Summarize opt-in shadow judge evaluation records.

Reads only <state-root>/evaluations. It creates no directory, salt, or record,
initializes no operational logging, and runs no retention, so inspecting the
store never changes it.

Malformed lines and records carrying an unsupported schema version are counted
as skipped and excluded from every metric, rather than silently dropped or
guessed at. Precision, recall, and specificity are null — not zero — when their
denominator is empty, because \"never right\" and \"never asked\" are different
findings.

EXAMPLES:
  cflx judge-eval summary --purpose parallel_dependency
  cflx judge-eval summary --purpose parallel_dependency --json
  cflx judge-eval summary --purpose parallel_dependency --since-days 7
  cflx judge-eval summary --purpose parallel_dependency --project conflux-a1b2c3d4")]
pub struct JudgeEvalSummaryArgs {
    /// Judgment purpose whose evaluation store is summarized
    #[arg(long, value_enum)]
    pub purpose: JudgeEvalPurpose,

    /// Include only records dated within the last N days, today inclusive
    ///
    /// Defaults to the configured retention window when one is available,
    /// otherwise 30 days.
    #[arg(long, value_name = "N", value_parser = parse_since_days)]
    pub since_days: Option<u32>,

    /// Select one exact project slug under the evaluation root
    #[arg(long, value_name = "SLUG")]
    pub project: Option<String>,

    /// Emit exactly one versioned JSON object instead of human-readable text
    #[arg(long)]
    pub json: bool,
}

/// Arguments for the run subcommand
#[derive(Parser, Debug)]
#[command(
    group(
        ArgGroup::new("run_target")
            .required(true)
            .multiple(false)
            .args(["all", "change", "changes"])
    ),
    long_about = "Execute the OpenSpec change orchestration loop in non-interactive mode.

This mode requires an explicit target: --all for every current change, positional
change IDs for selected changes, or legacy --change for comma-separated IDs.

EXECUTION MODEL:
  Every run executes changes in managed git worktrees. Changes are analyzed for
  dependencies and executed in optimal concurrent groups. There is no execution
  mode to select; a usable git repository is required.

LOCAL API:
  /api/v2 is served on ${GIT_COMMON_DIR}/cflx-api.sock by default, with no TCP
  port. Use --web-unix-socket PATH for another location, or --no-web-unix-socket
  to serve no Unix socket at all.

WEB MONITORING:
  --web additionally enables remote monitoring via HTTP. Access progress from
  any browser while orchestration runs in background.

EXAMPLES:
  cflx run --all                           # Process all current changes
  cflx run my-feature other-change         # Process selected changes
  cflx run --change my-feature,other-change  # Legacy selected changes
  cflx run --all --max-concurrent 5        # Run with 5 concurrent workspaces
  cflx run my-feature --dry-run            # Preview the selected execution plan
  cflx run --all --web --web-port 8080     # Enable web monitoring on port 8080"
)]
pub struct RunArgs {
    /// Process all current eligible changes explicitly
    #[arg(long)]
    pub all: bool,

    /// Process only the specified changes (comma-separated, e.g., --change a,b,c)
    #[arg(long, value_delimiter = ',')]
    pub change: Option<Vec<String>>,

    /// Positional change IDs to process
    pub changes: Vec<String>,

    /// Path to custom configuration file (JSONC format)
    #[arg(long, short = 'c')]
    pub config: Option<PathBuf>,

    /// Maximum number of iterations for the orchestration loop (overrides config, 0 = no limit)
    #[arg(long)]
    pub max_iterations: Option<u32>,

    /// Push completed change branches to a remote instead of merging to base.
    #[arg(long, num_args = 0..=1, default_missing_value = "origin", value_parser = parse_push_remote)]
    pub push: Option<String>,

    /// Maximum number of concurrent workspaces
    #[arg(long)]
    pub max_concurrent: Option<usize>,

    /// Preview dependency execution groups without executing (dry run)
    #[arg(long)]
    pub dry_run: bool,

    /// VCS backend: auto or git
    /// Default: auto (detects git repository)
    #[arg(long, default_value = "auto")]
    pub vcs: String,

    /// Disable automatic workspace resume. When set, always create new
    /// workspaces instead of reusing existing ones from interrupted runs.
    #[arg(long)]
    pub no_resume: bool,

    /// Enable web monitoring server for remote status viewing
    #[arg(long)]
    pub web: bool,

    /// Port for web monitoring server (default: 0 = auto-assign by OS)
    #[arg(long, default_value = "0")]
    pub web_port: u16,

    /// Bind address for web monitoring server (default: 127.0.0.1)
    #[arg(long, default_value = "127.0.0.1")]
    pub web_bind: String,

    /// Literal bearer token for the `/api/v2` remote-control API.
    ///
    /// Required for any non-loopback `--web-bind`. Prefer
    /// `--web-auth-token-env`: a literal value here is visible to anything that
    /// can inspect this process's arguments.
    #[arg(long, conflicts_with = "web_auth_token_env")]
    pub web_auth_token: Option<String>,

    /// Environment variable holding the bearer token for the `/api/v2` API.
    #[arg(long, conflicts_with = "web_auth_token")]
    pub web_auth_token_env: Option<String>,

    /// Exact additional origin allowed to make cross-origin `/api/v2` requests.
    ///
    /// Repeatable. Exact `scheme://host[:port]` values only — wildcards are
    /// rejected, and forwarded headers never widen this list, so a reverse proxy
    /// that changes the external origin must name it here.
    #[arg(long = "web-allowed-origin", value_name = "ORIGIN")]
    pub web_allowed_origins: Vec<String>,

    /// Path for the local `/api/v2` Unix-domain socket.
    ///
    /// Overrides the default `${GIT_COMMON_DIR}/cflx-api.sock`, which every
    /// linked worktree of one repository shares. Mutually exclusive with
    /// `--no-web-unix-socket`.
    #[arg(long, value_name = "PATH", conflicts_with = "no_web_unix_socket")]
    pub web_unix_socket: Option<PathBuf>,

    /// Do not serve `/api/v2` on a Unix-domain socket.
    ///
    /// The Unix socket is the only listener a web-enabled build starts without
    /// `--web`, so opting out leaves the process API-free unless `--web` adds
    /// the TCP listener.
    #[arg(long, conflicts_with = "web_unix_socket")]
    pub no_web_unix_socket: bool,

    /// Integrate the selected remote's same-name base branch into the cumulative
    /// base during the run, and push the verified result once at completion.
    ///
    /// `-u` and value-less `--integrate-upstream` select `origin`. A named remote
    /// requires `=`, as in `--integrate-upstream=upstream`; `-u <remote>` is not
    /// supported and never consumes a following positional change ID.
    ///
    /// Requires `--upstream-verify-command`.
    #[arg(
        long,
        num_args = 0..=1,
        require_equals = true,
        default_missing_value = crate::upstream::DEFAULT_UPSTREAM_REMOTE,
        value_parser = crate::upstream::options::parse_upstream_remote
    )]
    pub integrate_upstream: Option<String>,

    /// Publish to `origin`; short value-less spelling of `--integrate-upstream`.
    ///
    /// A named remote is available only as `--integrate-upstream=<remote>`, so
    /// `-u` takes no value at all and `-u=<remote>` is a parse error.
    #[arg(short = 'u', action = clap::ArgAction::SetTrue, conflicts_with = "integrate_upstream")]
    pub integrate_upstream_default_remote: bool,

    /// Complete repository verification command run after every cumulative base
    /// tree change and immediately before the final push.
    ///
    /// Requires `-u`/`--integrate-upstream`; rejected without it.
    #[arg(long)]
    pub upstream_verify_command: Option<String>,
}

impl RunArgs {
    /// Resolve the invocation-scoped upstream integration configuration.
    ///
    /// Returns `Ok(None)` for the default-off path, which installs no upstream
    /// behavior at all.
    pub fn upstream_integration(
        &self,
    ) -> std::result::Result<
        Option<crate::upstream::UpstreamIntegrationConfig>,
        crate::upstream::UpstreamOptionError,
    > {
        let selected = crate::upstream::options::selected_upstream_remote(
            self.integrate_upstream_default_remote,
            self.integrate_upstream.as_deref(),
        );
        crate::upstream::options::resolve_frontend_upstream_config(
            selected.as_deref(),
            self.upstream_verify_command.as_deref(),
            self.push.as_deref(),
        )
    }

    /// Returns None for --all and Some(ids) for explicit selected targets.
    pub fn normalized_target_changes(&self) -> Option<Vec<String>> {
        if self.all {
            None
        } else if !self.changes.is_empty() {
            Some(self.changes.clone())
        } else {
            self.change.clone()
        }
    }
}

/// Arguments for the TUI subcommand
#[derive(Parser, Debug)]
#[command(long_about = "Launch the interactive Terminal UI dashboard.

The TUI provides real-time visualization of change processing with:
  • Change selection and queue management
  • Live progress tracking with task completion percentages
  • Streaming logs from AI agent execution

  • Git worktree visualization and management
  • Parallel execution monitoring

KEY BINDINGS:
  Space     Toggle change selection/queue status
  F5        Start/resume processing (default; override in ~/.config/cflx/tui.jsonc)
  Esc       Stop processing (press twice to force)
  Tab       Switch between Changes/Worktrees view
  q         Quit

TUI USER CONFIG:
  Set keybindings.start in ~/.config/cflx/tui.jsonc, for example:
    { \"keybindings\": { \"start\": [\"F5\", \"!\"] } }
  The help text documents defaults only and does not render dynamic user config values.

LOCAL API:
  /api/v2 is served on ${GIT_COMMON_DIR}/cflx-api.sock by default, with no TCP
  port. Use --web-unix-socket PATH for another location, or --no-web-unix-socket
  to serve no Unix socket at all.

WEB MONITORING:
  --web additionally enables simultaneous web-based monitoring alongside the TUI.

EXAMPLES:
  cflx tui                                        # Launch TUI (default when no subcommand)
  cflx tui --web                                  # TUI with web monitoring enabled")]
pub struct TuiArgs {
    /// Path to custom configuration file (JSONC format)
    #[arg(long, short = 'c')]
    pub config: Option<PathBuf>,

    /// Enable web monitoring server for remote status viewing
    #[arg(long)]
    pub web: bool,

    /// Port for web monitoring server (default: 0 = auto-assign by OS)
    #[arg(long, default_value = "0")]
    pub web_port: u16,

    /// Bind address for web monitoring server (default: 127.0.0.1)
    #[arg(long, default_value = "127.0.0.1")]
    pub web_bind: String,

    /// Literal bearer token for the `/api/v2` remote-control API.
    ///
    /// Required for any non-loopback `--web-bind`. Prefer
    /// `--web-auth-token-env`: a literal value here is visible to anything that
    /// can inspect this process's arguments.
    #[arg(long, conflicts_with = "web_auth_token_env")]
    pub web_auth_token: Option<String>,

    /// Environment variable holding the bearer token for the `/api/v2` API.
    #[arg(long, conflicts_with = "web_auth_token")]
    pub web_auth_token_env: Option<String>,

    /// Exact additional origin allowed to make cross-origin `/api/v2` requests.
    ///
    /// Repeatable. Exact `scheme://host[:port]` values only — wildcards are
    /// rejected, and forwarded headers never widen this list, so a reverse proxy
    /// that changes the external origin must name it here.
    #[arg(long = "web-allowed-origin", value_name = "ORIGIN")]
    pub web_allowed_origins: Vec<String>,

    /// Path for the local `/api/v2` Unix-domain socket.
    ///
    /// Overrides the default `${GIT_COMMON_DIR}/cflx-api.sock`, which every
    /// linked worktree of one repository shares. Mutually exclusive with
    /// `--no-web-unix-socket`.
    #[arg(long, value_name = "PATH", conflicts_with = "no_web_unix_socket")]
    pub web_unix_socket: Option<PathBuf>,

    /// Do not serve `/api/v2` on a Unix-domain socket.
    ///
    /// The Unix socket is the only listener a web-enabled build starts without
    /// `--web`, so opting out leaves the process API-free unless `--web` adds
    /// the TCP listener.
    #[arg(long, conflicts_with = "web_unix_socket")]
    pub no_web_unix_socket: bool,

    /// Push completed TUI change branches to a remote instead of merging to base.
    #[arg(long, num_args = 0..=1, default_missing_value = "origin", value_parser = parse_push_remote)]
    pub push: Option<String>,

    /// Publish every completed change's verified cumulative base to the selected
    /// remote's same-name branch before that change succeeds.
    ///
    /// Same contract as `cflx run -u`: `-u` and value-less `--integrate-upstream`
    /// select `origin`, a named remote requires `--integrate-upstream=<remote>`,
    /// and `--upstream-verify-command` is mandatory.
    #[arg(
        long,
        num_args = 0..=1,
        require_equals = true,
        default_missing_value = crate::upstream::DEFAULT_UPSTREAM_REMOTE,
        value_parser = crate::upstream::options::parse_upstream_remote
    )]
    pub integrate_upstream: Option<String>,

    /// Publish to `origin`; short value-less spelling of `--integrate-upstream`.
    ///
    /// A named remote is available only as `--integrate-upstream=<remote>`, so
    /// `-u` takes no value at all and `-u=<remote>` is a parse error.
    #[arg(short = 'u', action = clap::ArgAction::SetTrue, conflicts_with = "integrate_upstream")]
    pub integrate_upstream_default_remote: bool,

    /// Complete repository verification command run before every publication.
    ///
    /// Requires `-u`/`--integrate-upstream`; rejected without it.
    #[arg(long)]
    pub upstream_verify_command: Option<String>,
}

impl TuiArgs {
    /// Resolve the invocation-scoped upstream integration configuration.
    ///
    /// Identical normalization to [`RunArgs::upstream_integration`], plus the
    /// TUI-only `--push` rejection. Returns `Ok(None)` for the default-off path,
    /// which installs no upstream behavior.
    pub fn upstream_integration(
        &self,
    ) -> std::result::Result<
        Option<crate::upstream::UpstreamIntegrationConfig>,
        crate::upstream::UpstreamOptionError,
    > {
        let selected = crate::upstream::options::selected_upstream_remote(
            self.integrate_upstream_default_remote,
            self.integrate_upstream.as_deref(),
        );
        crate::upstream::options::resolve_frontend_upstream_config(
            selected.as_deref(),
            self.upstream_verify_command.as_deref(),
            self.push.as_deref(),
        )
    }
}

/// Template options for init command
#[derive(Debug, Clone, Copy, Default, clap::ValueEnum)]
pub enum Template {
    /// Claude Code agent (claude --dangerously-skip-permissions)
    #[default]
    Claude,
    /// OpenCode agent
    Opencode,
    /// Codex agent
    Codex,
}

/// Arguments for the init subcommand
#[derive(Parser, Debug)]
pub struct InitArgs {
    /// Template to use for required commands missing from global configuration
    #[arg(long, short = 't', value_enum, default_value_t = Template::Claude)]
    pub template: Template,

    /// Overwrite an existing project configuration with the missing-command template
    #[arg(long, short = 'f')]
    pub force: bool,
}

/// Arguments for the check-conflicts subcommand
#[derive(Parser, Debug)]
pub struct CheckConflictsArgs {
    /// Output results in JSON format
    #[arg(long, short = 'j')]
    pub json: bool,
}

/// Install target family for `install-skills`.
#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
pub enum InstallSkillsTarget {
    Agents,
    Claude,
}

/// Arguments for the `install-skills` subcommand
#[derive(Parser, Debug)]
#[command(
    long_about = "Install bundled agent skills into the standard skills location.

Skills are embedded into the cflx binary at compile time and installed directly
without requiring a skills/ directory to be present. When no embedded skills are
available (uncommon), the command falls back to discovering skills from a local
skills/ directory at the project root.

TARGETS:
  Default target: .agents (existing behavior)
  --claude:       .claude

SCOPE (.agents target):
  Project scope (default): installs to ./.agents/skills
                            lock file:  ./.agents/.skill-lock.json
  Global scope (--global):  installs to ~/.agents/skills
                            lock file:  ~/.agents/.skill-lock.json

SCOPE (.claude target):
  Project scope (default): installs to ./.claude/skills
                            lock file:  ./.claude/.skill-lock.json
  Global scope (--global):  installs to ~/.claude/skills
                            lock file:  ~/.claude/.skill-lock.json

EXAMPLES:
  cflx install-skills
  cflx install-skills --global
  cflx install-skills --claude
  cflx install-skills --claude --global"
)]
pub struct InstallSkillsArgs {
    /// Install into global scope (~/.agents/skills or ~/.claude/skills) instead of project scope
    #[arg(long)]
    pub global: bool,

    /// Install bundled skills into .claude/skills instead of .agents/skills
    #[arg(long, default_value = "false")]
    pub claude: bool,

    /// Hidden positional argument to detect and reject legacy source forms (e.g. "self", "local:...").
    #[arg(hide = true)]
    pub legacy_source: Option<String>,
}

impl InstallSkillsArgs {
    pub fn target(&self) -> InstallSkillsTarget {
        if self.claude {
            InstallSkillsTarget::Claude
        } else {
            InstallSkillsTarget::Agents
        }
    }
}

/// Return a migration guidance error message when a legacy source argument is detected.
pub fn install_skills_legacy_error(src: &str) -> String {
    format!(
        "error: unrecognized argument '{src}'\n\n\
         The source argument is no longer accepted.\n\
         Use:\n  \
         cflx install-skills           # project scope\n  \
         cflx install-skills --global  # global scope"
    )
}

// ============================================================================
// Existing-owner client namespace
// ============================================================================

/// Smallest accepted *positive* `--timeout`, so a `50ms` typo cannot turn a wait
/// into a probe.
///
/// Sub-second values are accepted because the deadline is a safety valve, not a
/// latency budget: a scripted caller that wants "check once and give up" should
/// be able to say so without inventing a second flag. Zero is not a small
/// deadline but the absence of one, so it is handled before this bound applies.
const MIN_CLIENT_TIMEOUT_MILLIS: u64 = 100;

/// Largest accepted `--timeout`: 7 days.
///
/// Not a policy about how long work may take — it is a parse bound, so an
/// accidental `--timeout 99999999999h` fails as usage rather than as an overflow
/// deep inside a deadline computation.
const MAX_CLIENT_TIMEOUT_MILLIS: u64 = 7 * 24 * 60 * 60 * 1000;

/// Longest accepted change ID.
const MAX_CHANGE_ID_LEN: usize = 128;

/// How long a `cflx client wait` may run before it gives up.
///
/// A newtype rather than a bare `Duration` because the interesting value is the
/// one a `Duration` cannot hold: "no operation deadline at all". Representing
/// that as `Duration::ZERO` and comparing everywhere is how an unbounded wait
/// turns into an instant timeout the first time someone forgets the special
/// case.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WaitTimeout(Option<std::time::Duration>);

impl WaitTimeout {
    /// Wait until the question is answered, however long that takes.
    pub const UNBOUNDED: Self = Self(None);

    /// The explicitly requested operation deadline, if there is one.
    ///
    /// `None` is the unbounded default, and the only form that never produces
    /// the `timeout` outcome.
    pub fn deadline(self) -> Option<std::time::Duration> {
        self.0
    }
}

/// Parse a `--timeout` value as a strict duration, or as the unbounded sentinel.
///
/// Accepted spellings are `<n>`, `<n>ms`, `<n>s`, `<n>m`, and `<n>h`; a bare
/// number is seconds. Deliberately strict: a silently-ignored suffix would turn
/// `30m` into thirty seconds and make a wait report `timeout` on work that was
/// fine. `ms` is matched before `m` for the same reason.
///
/// Every spelling whose magnitude is exactly zero — `0`, `0s`, `0ms`, `0m`, `0h`
/// — means "no operation deadline", uniformly, because a caller who wrote a zero
/// in any unit asked the same question. It is a sentinel and not a bound, so the
/// minimum below applies only to positive values.
pub fn parse_client_timeout(value: &str) -> std::result::Result<WaitTimeout, String> {
    let trimmed = value.trim();
    let (digits, multiplier) = if let Some(digits) = trimmed.strip_suffix("ms") {
        (digits, 1)
    } else if let Some(digits) = trimmed.strip_suffix('s') {
        (digits, 1_000)
    } else if let Some(digits) = trimmed.strip_suffix('m') {
        (digits, 60_000)
    } else if let Some(digits) = trimmed.strip_suffix('h') {
        (digits, 3_600_000)
    } else {
        (trimmed, 1_000)
    };
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return Err(format!(
            "'{value}' is not a duration: use a whole number optionally suffixed with ms, s, m, or h (for example 500ms, 30s, 45m, 2h)"
        ));
    }
    let magnitude: u64 = digits
        .parse()
        .map_err(|_| format!("'{value}' is out of range: the maximum timeout is 7d"))?;
    let millis = magnitude
        .checked_mul(multiplier)
        .ok_or_else(|| format!("'{value}' is out of range: the maximum timeout is 7d"))?;
    // Checked before the range, because zero is not a duration this command is
    // being asked to honour — it is the caller declining to name one.
    if millis == 0 {
        return Ok(WaitTimeout::UNBOUNDED);
    }
    if !(MIN_CLIENT_TIMEOUT_MILLIS..=MAX_CLIENT_TIMEOUT_MILLIS).contains(&millis) {
        return Err(format!(
            "'{value}' is out of range: the timeout must be 0 (wait indefinitely) or between {MIN_CLIENT_TIMEOUT_MILLIS}ms and 7d"
        ));
    }
    Ok(WaitTimeout(Some(std::time::Duration::from_millis(millis))))
}

/// Parse a change ID as an ordinary managed identifier.
///
/// Change IDs reach a socket path join, a Git ref derivation, and a URL query,
/// so the accepted shape is narrow on purpose: a leading dot, a separator, or a
/// percent sign is rejected as usage rather than escaped somewhere downstream.
pub fn parse_change_id(value: &str) -> std::result::Result<String, String> {
    let invalid = |reason: &str| {
        Err(format!(
            "'{value}' is not a change ID: {reason}. Change IDs are 1-{MAX_CHANGE_ID_LEN} characters of [A-Za-z0-9._-] and may not start with '.' or '-'"
        ))
    };
    if value.is_empty() {
        return invalid("it is empty");
    }
    if value.len() > MAX_CHANGE_ID_LEN {
        return invalid("it is too long");
    }
    if value.starts_with('.') || value.starts_with('-') {
        return invalid("it starts with a reserved character");
    }
    if !value
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
    {
        return invalid("it contains characters outside [A-Za-z0-9._-]");
    }
    Ok(value.to_string())
}

/// Longest process-local identifier this CLI will forward to an owner.
///
/// The owner mints these as 32 hex digits, so the ceiling is slack rather than a
/// format assertion: a future widening stays acceptable, an unbounded argument
/// does not.
const MAX_PROCESS_LOCAL_ID_LEN: usize = 128;

/// Parse an owner-minted process-local identifier (execution or instance).
///
/// These are opaque to the caller — an execution ID names one admitted episode
/// and an instance ID names one owner incarnation — but they still reach a URL
/// path segment and a query value, so an empty, oversized, or
/// separator-carrying value is rejected as usage here rather than escaped into
/// a request that would come back as an unrelated `execution_not_found`.
pub fn parse_process_local_id(value: &str) -> std::result::Result<String, String> {
    let invalid = |reason: &str| {
        Err(format!(
            "'{value}' is not an owner-issued identifier: {reason}. These are 1-{MAX_PROCESS_LOCAL_ID_LEN} characters of [A-Za-z0-9._-] and may not start with '.' or '-'"
        ))
    };
    if value.is_empty() {
        return invalid("it is empty");
    }
    if value.len() > MAX_PROCESS_LOCAL_ID_LEN {
        return invalid("it is too long");
    }
    if value.starts_with('.') || value.starts_with('-') {
        return invalid("it starts with a reserved character");
    }
    if !value
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
    {
        return invalid("it contains characters outside [A-Za-z0-9._-]");
    }
    Ok(value.to_string())
}

/// Arguments for the `client` subcommand group.
#[derive(Parser, Debug)]
#[command(
    about = "Operate an existing Conflux owner without becoming one",
    long_about = "Client-only namespace for one existing repository owner.

Connects to the owner's local /api/v2 Unix socket, which defaults to
${GIT_COMMON_DIR}/cflx-api.sock — the same repository identity the orchestration
lock uses, so every linked worktree of one repository reaches one owner.

No client command acquires the repository lock, binds a listener, starts an
orchestration run, launches a lifecycle adapter or an AI subprocess, or writes
to the workspace. `status` and `wait` submit no command at all.

Machine output: --json prints exactly one versioned envelope on stdout and sends
every diagnostic to stderr. Outcomes and exit statuses are stable.

Secrets are never accepted in argv: --auth-token-env names an environment
variable that holds the bearer token, and the token is never printed.

EXAMPLES:
  cflx client status --json
  cflx client mark alpha beta --json
  cflx client unmark alpha --json
  cflx client start --json
  cflx client stop --json
  cflx client force-stop --json
  cflx client wait alpha --json                    # Wait indefinitely (the default)
  cflx client wait alpha --timeout 45m --json      # Give up after an explicit deadline
  cflx client subscribe set alpha beta --instance-id <owner-instance> --json -- /absolute/callback --flag value
  cflx client subscribe get alpha --instance-id <owner-instance> --json
  cflx client subscribe clear alpha beta --instance-id <owner-instance> --json
  cflx client mcp
  cflx client --unix-socket /tmp/cflx-api.sock status"
)]
pub struct ClientArgs {
    /// Absolute directory inside the project whose owner to talk to
    ///
    /// The normal explicit route. Conflux resolves the directory's Git working
    /// tree, then uses that project's canonical repository root as completion
    /// evidence and `<git-common-dir>/cflx-api.sock` as the owner socket — so
    /// one client invocation can name any project without knowing where its
    /// socket lives. A linked worktree, a submodule, or a directory below the
    /// working-tree root all resolve. Conflicts with `--unix-socket`.
    #[arg(
        long,
        value_name = "ABSOLUTE_PATH",
        global = true,
        conflicts_with = "unix_socket"
    )]
    pub project_dir: Option<PathBuf>,

    /// Path to the owner's `/api/v2` Unix socket
    ///
    /// The low-level override, for diagnostics, tests, and transports that are
    /// not a repository. Overrides the default
    /// `${GIT_COMMON_DIR}/cflx-api.sock`. Prefer `--project-dir`, which names
    /// the stable identity of the work rather than one owner incarnation's
    /// transport. Required when the working directory is not inside a Git
    /// repository and no `--project-dir` is given, because there is no
    /// repository identity to derive a default from.
    #[arg(long, value_name = "PATH", global = true)]
    pub unix_socket: Option<PathBuf>,

    /// Name of the environment variable holding the bearer token
    ///
    /// The token value itself is never accepted as an argument: anything that
    /// can read this process's arguments would see it.
    #[arg(long, value_name = "NAME", global = true)]
    pub auth_token_env: Option<String>,

    #[command(subcommand)]
    pub command: ClientCommands,
}

/// Subcommands for `cflx client`.
#[derive(Subcommand, Debug)]
pub enum ClientCommands {
    /// Read the existing owner without mutating it
    ///
    /// Reports the owner incarnation, application mode, scheduler and activity
    /// state, execution contract, and per-change authoritative status — but only
    /// once the separate reads reconcile at one incarnation and revision. A
    /// snapshot that cannot be reconciled is reported as `observation_conflict`
    /// rather than stitched together.
    Status(ClientStatusArgs),

    /// Set the execution mark on one or more proposals
    ///
    /// Target-scoped desired-state write, exactly like Space in the TUI. It
    /// preserves every unrelated mark, submits only the shared
    /// `SetExecutionMark` intent, and returns once the commands settle.
    ///
    /// A mark is operator selection, not admission. It does not construct queue
    /// intent, start a run, retry anything, or create an execution episode, and
    /// it does not wait to see whether the owner later admitted the work: the
    /// owner's own mark settlement and analysis decide that.
    ///
    /// EXAMPLES:
    ///   cflx client mark alpha
    ///   cflx client mark alpha beta gamma --json
    Mark(ClientMarkArgs),

    /// Clear the execution mark on one or more proposals
    ///
    /// The mirror of `mark`, and just as narrowly scoped: unmarking `alpha`
    /// leaves `beta` marked, and it neither stops nor dequeues work that is
    /// already admitted or active.
    Unmark(ClientMarkArgs),

    /// Start the owner against its authoritative mark set — F5 / `!` equivalent
    ///
    /// Submits the shared Start intent a keypress submits. There is no target
    /// list: Start consumes the marks the owner already holds, and a
    /// caller-supplied replacement set is something the shared transaction does
    /// not offer. Mark what you want first.
    Start(ClientLifecycleArgs),

    /// Request a graceful stop
    ///
    /// Submits the shared Stop intent. The run stops at its next boundary; this
    /// command does not infer termination before settlement.
    Stop(ClientLifecycleArgs),

    /// Stop immediately
    ///
    /// Submits the shared ForceStop intent, which applies the same runtime
    /// classification the TUI's immediate stop applies. The client does not
    /// classify or terminate work itself.
    ForceStop(ClientLifecycleArgs),

    /// Kill one named proposal immediately and dequeue it
    ///
    /// The target-scoped counterpart of `force-stop`, and the only control that
    /// bypasses the graceful SIGTERM escalation window `stop` gives a change:
    /// the owner sends SIGKILL straight to the managed process group that
    /// proposal owns, waits for confirmed reaping, then clears its queue
    /// admission and execution mark together so later mark settlement cannot
    /// redispatch it.
    ///
    /// Exactly one proposal, always. Unrelated changes keep their processes,
    /// marks, queue intent, execution IDs, and subscriptions, and the
    /// process-wide run mode, scheduler state, and stop state do not change.
    /// Completed worktree effects — an Apply commit that already landed — are
    /// preserved; the settled result reports `effects_rolled_back: false`.
    ///
    /// The successful outcome is `stopped`, not `accepted`: one settled command
    /// ended one execution episode. A target that owns no live managed process
    /// but is admitted is dequeued outright; a terminal, unadmitted, merge-wait,
    /// or resolve-wait target is refused with `target_ineligible`.
    ///
    /// EXAMPLES:
    ///   cflx client force-stop-change add-my-change
    ///   cflx client force-stop-change add-my-change --json
    ForceStopChange(ClientForceStopChangeArgs),

    /// Observe one change until verified completion or a typed failure
    ///
    /// Observation only: it submits no start, retry, queue, resolve, archive,
    /// merge, or cleanup command. Success requires current repository evidence
    /// for the owner's terminal mode; a change merely disappearing from the
    /// snapshot is never completion.
    ///
    /// It observes while the owner can still advance the change on its own —
    /// `not queued`, `queued`, `blocked`, and the active phases — and releases
    /// as soon as the row is one only a new operator action can move: `error`,
    /// `merge wait`, `stopped`, and `stalled` return `change_requires_action`
    /// with exit status 27 and the observed status in `detail`, while `rejected`
    /// keeps `change_rejected`. `blocked` is the one status split by its
    /// structured blocker: a dependency wait keeps observing, while a validated
    /// external prerequisite releases the same way, publishing the blocker's
    /// `unblock_condition` and `prerequisite_owner` in `detail.blocker`.
    /// Releasing is not repairing; nothing is submitted on the way out. The same
    /// classification runs on the first observation, so waiting on an
    /// already-parked change reports it rather than hanging.
    ///
    /// There is no deadline unless one is asked for: `--timeout` defaults to 0,
    /// which waits for as long as the work takes. `--timeout D` adds one
    /// operation deadline whose expiry is the typed `timeout` outcome. Either
    /// way each owner request and each Git subprocess keeps its own bound, so an
    /// unbounded wait never becomes an unbounded child process.
    ///
    /// A `timeout` reports what it was waiting on rather than only that it gave
    /// up: `detail` carries `timeout_ms`, the measured `wait_elapsed_ms`,
    /// `commands_submitted: 0`, and a stable `timeout_stage` —
    /// `initial_observation`, `observing_owner`, `repository_certification`, or
    /// `remote_verification`. `detail.last_observation` is the latest coherent
    /// observation completed before the deadline, projected onto this proposal
    /// alone: the observation's `observed_at`, `state_revision`, and
    /// `event_sequence`, the change's own row, and its matching execution facts.
    /// Nothing is read after expiry, so a wait whose first observation never
    /// completed reports `last_observation: null` and names no `instance_id`.
    /// Timing out is observation-only like every other release: no command is
    /// submitted, no repository state changes, and the proposal's lifecycle
    /// status is untouched.
    Wait(ClientWaitArgs),

    /// Manage explicit completion subscriptions for named proposals
    ///
    /// Observability only: a subscription submits no workflow command, creates
    /// no command record, advances no revision, and cannot move a proposal.
    ///
    /// Keyed by the proposal rather than by an execution episode, so it can be
    /// registered before the owner admits anything. Whenever a subscribed
    /// proposal enters a new execution episode, the owner binds that episode and
    /// delivers its first typed terminal classification — completed, failed, or
    /// stopped — once. `--blocked` opts into the non-terminal attention edge.
    /// Re-admission after a retry is a distinct episode and a distinct
    /// notification.
    ///
    /// What fires is execution completion, not process completion: a resident
    /// TUI stays alive after the work finishes, so its exit was never the
    /// signal, and a lifecycle adapter's `idle` describes the process rather
    /// than your proposal.
    ///
    /// Delivery is notification, never control: Conflux runs the registered argv
    /// and resumes no agent. It does not start or message a session either, and
    /// a callback's exit status cannot change any workflow outcome.
    ///
    /// Every operation names the owner incarnation it expects. Subscriptions are
    /// process-local, so an owner restart invalidates all of them and a caller
    /// naming the old incarnation is told `owner_restarted` rather than silently
    /// registering against a process that never saw its work.
    ///
    /// The callback is an argv vector given after `--`, never shell source: no
    /// `sh -c`, no quoting, no expansion, and every argument boundary is
    /// preserved exactly as typed. The owner replaces the callback's environment
    /// with exactly CFLX_EVENT_PATH, CFLX_EVENT_TYPE, CFLX_EXECUTION_ID,
    /// CFLX_CHANGE_ID, and CFLX_INSTANCE_ID.
    ///
    /// Setting and clearing store or remove an argv this owner will execute, so
    /// they are accepted only over the owner's Unix socket; a TCP client is
    /// refused with `transport_not_permitted` and is not told a registered argv
    /// on a read either.
    ///
    /// EXAMPLES:
    ///   cflx client subscribe set alpha --instance-id ID -- /absolute/callback --flag value
    ///   cflx client subscribe set alpha beta --instance-id ID --blocked --json -- /absolute/callback
    ///   cflx client subscribe get alpha --instance-id ID --json
    ///   cflx client subscribe clear alpha beta --instance-id ID --json
    Subscribe(ClientSubscribeArgs),

    /// Serve the same client intents to an MCP host over stdio
    ///
    /// A stdio Model Context Protocol server over exactly this namespace. It
    /// stays a client — no repository lock, no listener, no orchestration run —
    /// and exposes no raw `/api/v2` command construction, so a model cannot name
    /// a command type, an expected revision, an idempotency key, queue intent,
    /// or shell source.
    ///
    /// Three closed tools: cflx_status, cflx_control, and cflx_subscribe.
    /// cflx_control takes one action — mark, unmark, start, stop, force_stop, or
    /// force_stop_change — and calls the same client boundary the matching
    /// command does, so routing and typed outcomes are shared rather than
    /// reimplemented. force_stop_change names exactly one proposal in
    /// change_ids; the three process-wide lifecycle actions accept none.
    ///
    /// cflx_wait is deliberately absent from MCP: a completion wait stays open
    /// for as long as the work takes, which is not the shape of a tool call.
    /// `cflx client wait` remains the CLI completion oracle — unbounded by
    /// default, with `--timeout D` available when a caller does want a deadline
    /// — and an MCP host that wants asynchronous completion registers an
    /// explicit callback with cflx_subscribe.
    ///
    /// Connection defaults come from this namespace's --project-dir /
    /// --unix-socket and --auth-token-env, and each tool may override them per
    /// call. A token value is never accepted in argv or in a tool argument: only
    /// the name of an environment variable holding it.
    ///
    /// stdout carries JSON-RPC frames and nothing else; diagnostics go to stderr.
    Mcp(ClientMcpArgs),
}

/// Arguments for `cflx client mcp`.
///
/// Empty on purpose: the connection options are the namespace's globals, and a
/// protocol server has no per-invocation output mode to select.
#[derive(Parser, Debug)]
pub struct ClientMcpArgs {}

/// Arguments for `cflx client status`.
#[derive(Parser, Debug)]
pub struct ClientStatusArgs {
    /// Emit one versioned JSON envelope on stdout
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `cflx client mark` and `cflx client unmark`.
///
/// One struct for both because they are the same write with opposite desired
/// states, and a caller that can name targets for one names them for the other.
#[derive(Parser, Debug)]
pub struct ClientMarkArgs {
    /// Proposals whose execution mark to set, 1 through 64 and all distinct
    #[arg(required = true, num_args = 1.., value_parser = parse_change_id)]
    pub change_ids: Vec<String>,

    /// Emit one versioned JSON envelope on stdout
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `cflx client force-stop-change`.
///
/// Exactly one proposal, and no `--all`, no glob, and no target list: widening
/// an immediate kill is what process-wide `force-stop` is for, and the two must
/// never be reachable by adding an argument to the other.
#[derive(Parser, Debug)]
pub struct ClientForceStopChangeArgs {
    /// The one proposal to kill immediately and dequeue
    #[arg(value_parser = parse_change_id)]
    pub change_id: String,

    /// Emit one versioned JSON envelope on stdout
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `cflx client start`, `stop`, and `force-stop`.
///
/// No target list, deliberately: these submit the shared lifecycle intent
/// against the marks the owner already holds, which is the only thing the shared
/// transaction — and the TUI — can express.
#[derive(Parser, Debug)]
pub struct ClientLifecycleArgs {
    /// Emit one versioned JSON envelope on stdout
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `cflx client wait`.
#[derive(Parser, Debug)]
pub struct ClientWaitArgs {
    /// Change ID to observe
    #[arg(value_parser = parse_change_id)]
    pub change_id: String,

    /// How long to observe before giving up; 0 (the default) waits indefinitely
    ///
    /// A positive duration — 500ms, 30s, 45m, 2h — creates one operation
    /// deadline whose expiry is the typed `timeout` outcome. Zero, in any unit,
    /// creates none: the wait ends at verified completion, a typed failure,
    /// owner replacement, or cancellation, and never because a clock ran out.
    /// Per-request transport limits and per-subprocess Git limits stay in force
    /// either way.
    #[arg(long, value_name = "DURATION", default_value = "0", value_parser = parse_client_timeout)]
    pub timeout: WaitTimeout,

    /// Emit one versioned JSON envelope on stdout
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `cflx client subscribe`.
///
/// A group rather than an operation: the help a caller reads lives on the
/// [`ClientCommands::Subscribe`] variant, the way every other subcommand's does.
#[derive(Parser, Debug)]
pub struct ClientSubscribeArgs {
    #[command(subcommand)]
    pub command: ClientSubscribeCommands,
}

/// Subcommands for `cflx client subscribe`.
#[derive(Subcommand, Debug)]
pub enum ClientSubscribeCommands {
    /// Register or replace the named proposals' completion callback
    ///
    /// The argv after `--` is executed directly, never as shell source, and each
    /// argument boundary is preserved exactly as typed. Registering after the
    /// proposal's latest execution episode already settled delivers that
    /// terminal event immediately, once — which is what stops a start/registration
    /// race from losing a notification, without replaying anything this owner
    /// already delivered.
    ///
    /// Registration is not delivery and delivery is not workflow state: a
    /// callback that fails, hangs, or exits non-zero cannot roll back, retry, or
    /// re-classify anything, and it never resumes an agent.
    ///
    /// EXAMPLES:
    ///   cflx client subscribe set alpha --instance-id ID -- /absolute/callback --flag value
    ///   cflx client subscribe set alpha beta --instance-id ID --blocked --json -- /absolute/callback
    Set(ClientSubscribeSetArgs),

    /// Read the named proposals' current subscriptions
    ///
    /// Reports whether a subscription exists, the latest bound execution
    /// episode, its state, and the events already delivered. The registered argv
    /// itself comes back only over the owner's own Unix socket.
    ///
    /// Named targets only: there is no list-all, because an unbounded read of
    /// every registration is not something one request should answer.
    Get(ClientSubscribeRefArgs),

    /// Remove the named proposals' subscriptions
    ///
    /// Removes only those subscriptions; every other proposal is untouched.
    /// Delivery that has not started is cancelled; a callback process already
    /// running keeps its own bounds and finishes.
    Clear(ClientSubscribeRefArgs),
}

/// Arguments for `cflx client subscribe set`.
#[derive(Parser, Debug)]
pub struct ClientSubscribeSetArgs {
    /// Proposals to subscribe, 1 through 64 and all distinct
    #[arg(required = true, num_args = 1.., value_parser = parse_change_id)]
    pub change_ids: Vec<String>,

    /// Owner incarnation the subscription is registered against
    ///
    /// Required, because a subscription is process-local: a request that named
    /// no incarnation would be asking to register against whichever owner
    /// happens to answer the socket. `cflx client status` reports the current
    /// one.
    #[arg(long, value_name = "ID", required = true, value_parser = parse_process_local_id)]
    pub instance_id: String,

    /// Also deliver the non-terminal `blocked` attention edge
    #[arg(long)]
    pub blocked: bool,

    /// Emit one versioned JSON envelope on stdout
    #[arg(long)]
    pub json: bool,

    /// Callback argv, given after `--` and executed directly
    ///
    /// Never shell source: no `sh -c`, no quoting, no expansion. Every argument
    /// after `--` is one argv element, exactly as typed.
    #[arg(last = true, required = true, num_args = 1.., value_name = "COMMAND")]
    pub command: Vec<String>,
}

/// Arguments for `cflx client subscribe get` and `cflx client subscribe clear`.
///
/// One struct for both because a read and a removal name the same thing: neither
/// carries a callback, and a caller that can name proposals for one can name them
/// for the other.
#[derive(Parser, Debug)]
pub struct ClientSubscribeRefArgs {
    /// Proposals to address, 1 through 64 and all distinct
    #[arg(required = true, num_args = 1.., value_parser = parse_change_id)]
    pub change_ids: Vec<String>,

    /// Owner incarnation the subscriptions belong to
    #[arg(long, value_name = "ID", required = true, value_parser = parse_process_local_id)]
    pub instance_id: String,

    /// Emit one versioned JSON envelope on stdout
    #[arg(long)]
    pub json: bool,
}

/// Arguments for the `openspec` subcommand group
#[derive(Parser, Debug)]
#[command(about = "OpenSpec utility commands")]
pub struct OpenspecArgs {
    #[command(subcommand)]
    pub command: OpenspecCommands,
}

/// Subcommands for `cflx openspec`
#[derive(Subcommand, Debug)]
pub enum OpenspecCommands {
    /// List active changes or canonical specs
    List(OpenspecListArgs),

    /// Show detailed information about a change
    Show(OpenspecShowArgs),

    /// Validate change structure and spec deltas
    ///
    /// Use `--archive-gate` to run the local archive-readiness equivalent
    /// (`--strict --evidence error`) so evidence findings fail before archive.
    Validate(OpenspecValidateArgs),

    /// Archive a deployed change and promote spec deltas
    Archive(OpenspecArchiveArgs),

    /// Run a change's repository-local verifications under runtime supervision
    ///
    /// The Conflux runtime — not the calling agent — starts the declared argv,
    /// waits for it, and records a sidecar bound to the current commit, tree,
    /// automation blob, and executable. Acceptance may reuse that record only
    /// while every one of those bindings still matches, so a command whose
    /// evidence is stale, dirty, or absent is simply run again.
    ///
    /// EXAMPLES:
    ///   cflx openspec verify my-change              # Run what cannot be reused
    ///   cflx openspec verify my-change --plan       # Show reuse decisions only
    ///   cflx openspec verify my-change --verification-id local-tests --json
    Verify(OpenspecVerifyArgs),
}

/// Arguments for `cflx openspec verify`
#[derive(Parser, Debug)]
pub struct OpenspecVerifyArgs {
    /// Change ID whose declared verifications to run
    pub change_id: String,

    /// Run only this declared verification ID
    #[arg(long)]
    pub verification_id: Option<String>,

    /// Report reuse decisions without executing anything
    #[arg(long)]
    pub plan: bool,

    /// Output as JSON
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `cflx openspec list`
#[derive(Parser, Debug)]
pub struct OpenspecListArgs {
    /// List canonical specs instead of changes
    #[arg(long)]
    pub specs: bool,
}

/// Arguments for `cflx openspec show`
#[derive(Parser, Debug)]
pub struct OpenspecShowArgs {
    /// Change ID to show
    pub change_id: String,

    /// Output as JSON
    #[arg(long)]
    pub json: bool,

    /// Show only spec deltas
    #[arg(long)]
    pub deltas_only: bool,
}

/// Evidence checking mode for validation
#[derive(Debug, Clone, Copy, Default, clap::ValueEnum)]
pub enum EvidenceMode {
    /// Do not check for evidence hints
    #[default]
    Off,
    /// Warn on missing evidence hints
    Warn,
    /// Error on missing evidence hints
    Error,
}

/// Arguments for `cflx openspec validate`
#[derive(Parser, Debug)]
pub struct OpenspecValidateArgs {
    /// Change ID to validate (omit to validate all)
    pub change_id: Option<String>,

    /// Enable strict validation mode
    #[arg(long)]
    pub strict: bool,

    /// Run archive-readiness validation locally (`--strict --evidence error`)
    #[arg(long)]
    pub archive_gate: bool,

    /// How to treat missing implementation evidence in tasks.md
    #[arg(long, value_enum, default_value_t = EvidenceMode::Off)]
    pub evidence: EvidenceMode,
}

/// Arguments for `cflx openspec archive`
#[derive(Parser, Debug)]
pub struct OpenspecArchiveArgs {
    /// Change ID to archive
    pub change_id: String,

    /// Skip confirmation prompt
    #[arg(long)]
    pub yes: bool,

    /// Skip spec updates during archive
    #[arg(long)]
    pub skip_specs: bool,
}

/// Check if git directory exists
pub fn check_git_directory() -> bool {
    std::path::Path::new(".git").exists()
}

/// Check if git CLI is available
pub fn check_git_available() -> bool {
    debug!(
        module = module_path!(),
        "Executing git command: git --version (cwd: {:?})",
        std::env::current_dir().ok()
    );
    std::process::Command::new("git")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Check whether this workspace can run worktree orchestration at all.
///
/// Both facts are required: a repository to cut worktrees from, and the `git`
/// command that cuts them.
pub fn check_git_workspace_usable() -> bool {
    check_git_directory() && check_git_available()
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::{CommandFactory, Parser};

    fn run_args(argv: &[&str]) -> RunArgs {
        match Cli::parse_from(argv).command {
            Some(Commands::Run(args)) => args,
            _ => panic!("expected run subcommand for {:?}", argv),
        }
    }

    #[test]
    fn upstream_integration_is_absent_by_default() {
        let args = run_args(&["cflx", "run", "--all"]);
        assert_eq!(args.integrate_upstream, None);
        assert_eq!(args.upstream_verify_command, None);
        assert_eq!(args.upstream_integration().unwrap(), None);
    }

    #[test]
    fn upstream_integration_short_and_long_aliases_are_equivalent() {
        let short = run_args(&[
            "cflx",
            "run",
            "--all",
            "-u",
            "--upstream-verify-command",
            "cargo test",
        ]);
        let long = run_args(&[
            "cflx",
            "run",
            "--all",
            "--integrate-upstream",
            "--upstream-verify-command",
            "cargo test",
        ]);
        // `-u` is its own value-less argument, so equivalence is asserted on the
        // remote both spellings select rather than on one shared raw field.
        assert!(short.integrate_upstream_default_remote);
        assert_eq!(short.integrate_upstream, None);
        assert_eq!(long.integrate_upstream.as_deref(), Some("origin"));
        assert_eq!(
            short.upstream_integration().unwrap(),
            long.upstream_integration().unwrap()
        );
        assert_eq!(
            short.upstream_integration().unwrap(),
            Some(crate::upstream::UpstreamIntegrationConfig::new(
                "origin",
                "cargo test"
            ))
        );
    }

    #[test]
    fn upstream_integration_short_option_does_not_consume_change_id() {
        let args = run_args(&[
            "cflx",
            "run",
            "-u",
            "--upstream-verify-command",
            "cargo test",
            "my-change",
        ]);
        assert!(args.integrate_upstream_default_remote);
        assert_eq!(args.changes, vec!["my-change".to_string()]);
        assert_eq!(
            args.normalized_target_changes(),
            Some(vec!["my-change".to_string()])
        );
    }

    #[test]
    fn upstream_integration_named_remote_requires_equals() {
        let args = run_args(&[
            "cflx",
            "run",
            "--all",
            "--integrate-upstream=upstream",
            "--upstream-verify-command",
            "cargo test",
        ]);
        assert_eq!(args.integrate_upstream.as_deref(), Some("upstream"));
        assert_eq!(
            args.upstream_integration().unwrap(),
            Some(crate::upstream::UpstreamIntegrationConfig::new(
                "upstream",
                "cargo test"
            ))
        );

        // Space-separated values are not option values; they stay positional.
        let spaced = run_args(&[
            "cflx",
            "run",
            "--integrate-upstream",
            "upstream",
            "--upstream-verify-command",
            "cargo test",
        ]);
        assert_eq!(spaced.integrate_upstream.as_deref(), Some("origin"));
        assert_eq!(spaced.changes, vec!["upstream".to_string()]);
    }

    #[test]
    fn upstream_integration_rejects_invalid_remote_value() {
        let err = Cli::try_parse_from(["cflx", "run", "--all", "--integrate-upstream=origin:main"])
            .unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation);
    }

    #[test]
    fn upstream_integration_requires_verify_command() {
        let args = run_args(&["cflx", "run", "--all", "-u"]);
        assert_eq!(
            args.upstream_integration(),
            Err(crate::upstream::UpstreamOptionError::MissingVerifyCommand)
        );
    }

    #[test]
    fn upstream_integration_verify_command_alone_is_rejected() {
        let args = run_args(&[
            "cflx",
            "run",
            "--all",
            "--upstream-verify-command",
            "cargo test",
        ]);
        assert_eq!(
            args.upstream_integration(),
            Err(crate::upstream::UpstreamOptionError::VerifyCommandWithoutOption)
        );
    }

    fn tui_args(argv: &[&str]) -> TuiArgs {
        match Cli::parse_from(argv).command {
            Some(Commands::Tui(args)) => args,
            _ => panic!("expected tui subcommand for {:?}", argv),
        }
    }

    /// Bare `cflx` has no subcommand; it forwards its own options into `TuiArgs`,
    /// exactly as `main` does.
    pub(super) fn bare_tui_args(argv: &[&str]) -> TuiArgs {
        let cli = Cli::parse_from(argv);
        assert!(cli.command.is_none(), "expected bare invocation");
        TuiArgs {
            config: cli.config,
            web: cli.web,
            web_port: cli.web_port,
            web_bind: cli.web_bind,
            web_auth_token: cli.web_auth_token,
            web_auth_token_env: cli.web_auth_token_env,
            web_allowed_origins: cli.web_allowed_origins,
            web_unix_socket: cli.web_unix_socket,
            no_web_unix_socket: cli.no_web_unix_socket,
            push: cli.push,
            integrate_upstream: cli.integrate_upstream,
            integrate_upstream_default_remote: cli.integrate_upstream_default_remote,
            upstream_verify_command: cli.upstream_verify_command,
        }
    }

    #[test]
    fn per_change_upstream_is_absent_by_default_for_tui() {
        let bare = bare_tui_args(&["cflx"]);
        assert_eq!(bare.integrate_upstream, None);
        assert_eq!(bare.upstream_verify_command, None);
        assert_eq!(bare.upstream_integration().unwrap(), None);

        let explicit = tui_args(&["cflx", "tui"]);
        assert_eq!(explicit.upstream_integration().unwrap(), None);
    }

    #[test]
    fn per_change_upstream_run_bare_tui_and_explicit_tui_are_equivalent() {
        let run = run_args(&[
            "cflx",
            "run",
            "--all",
            "-u",
            "--upstream-verify-command",
            "cargo test",
        ]);
        let bare = bare_tui_args(&["cflx", "-u", "--upstream-verify-command", "cargo test"]);
        let explicit = tui_args(&[
            "cflx",
            "tui",
            "-u",
            "--upstream-verify-command",
            "cargo test",
        ]);

        let expected = Some(crate::upstream::UpstreamIntegrationConfig::new(
            "origin",
            "cargo test",
        ));
        assert_eq!(run.upstream_integration().unwrap(), expected);
        assert_eq!(bare.upstream_integration().unwrap(), expected);
        assert_eq!(explicit.upstream_integration().unwrap(), expected);
    }

    #[test]
    fn per_change_upstream_tui_accepts_explicit_remote_with_equals_only() {
        let explicit = tui_args(&[
            "cflx",
            "tui",
            "--integrate-upstream=upstream",
            "--upstream-verify-command",
            "cargo test",
        ]);
        assert_eq!(
            explicit.upstream_integration().unwrap(),
            Some(crate::upstream::UpstreamIntegrationConfig::new(
                "upstream",
                "cargo test"
            ))
        );

        let bare = bare_tui_args(&[
            "cflx",
            "--integrate-upstream=upstream",
            "--upstream-verify-command",
            "cargo test",
        ]);
        assert_eq!(bare.integrate_upstream.as_deref(), Some("upstream"));
        assert_eq!(bare.push, None, "upstream must not configure push mode");

        // A space-separated remote is not an option value for the value-less alias.
        let spaced = tui_args(&[
            "cflx",
            "tui",
            "--integrate-upstream",
            "--upstream-verify-command",
            "cargo test",
        ]);
        assert_eq!(spaced.integrate_upstream.as_deref(), Some("origin"));
    }

    #[test]
    fn per_change_upstream_tui_rejects_push() {
        let with_push = tui_args(&[
            "cflx",
            "tui",
            "-u",
            "--upstream-verify-command",
            "cargo test",
            "--push",
        ]);
        assert_eq!(
            with_push.upstream_integration(),
            Err(crate::upstream::UpstreamOptionError::ConflictsWithPush)
        );

        let bare_push = bare_tui_args(&[
            "cflx",
            "-u",
            "--upstream-verify-command",
            "cargo test",
            "--push",
        ]);
        assert_eq!(
            bare_push.upstream_integration(),
            Err(crate::upstream::UpstreamOptionError::ConflictsWithPush)
        );
    }

    #[test]
    fn per_change_upstream_tui_requires_verify_command() {
        let missing = tui_args(&["cflx", "tui", "-u"]);
        assert_eq!(
            missing.upstream_integration(),
            Err(crate::upstream::UpstreamOptionError::MissingVerifyCommand)
        );

        let orphan_command = tui_args(&["cflx", "tui", "--upstream-verify-command", "cargo test"]);
        assert_eq!(
            orphan_command.upstream_integration(),
            Err(crate::upstream::UpstreamOptionError::VerifyCommandWithoutOption)
        );
    }

    #[test]
    fn per_change_upstream_run_rejects_push_combination_at_parse_time() {
        let args = run_args(&[
            "cflx",
            "run",
            "--all",
            "-u",
            "--upstream-verify-command",
            "cargo test",
            "--push",
        ]);
        assert_eq!(
            args.upstream_integration(),
            Err(crate::upstream::UpstreamOptionError::ConflictsWithPush)
        );
    }

    #[test]
    fn per_change_upstream_short_flag_never_carries_a_remote() {
        // A named remote is spec-restricted to `--integrate-upstream=<remote>`,
        // so the short spelling must take no value on any of the three
        // entrypoints while the long spelling keeps accepting one.
        for argv in [
            vec!["cflx", "run", "--all", "-u=upstream"],
            vec!["cflx", "-u=upstream"],
            vec!["cflx", "tui", "-u=upstream"],
        ] {
            let err = Cli::try_parse_from(&argv)
                .err()
                .unwrap_or_else(|| panic!("-u must not accept a remote value: {:?}", argv));
            assert_ne!(
                err.kind(),
                clap::error::ErrorKind::DisplayHelp,
                "rejection must be a parse error, not help: {:?}",
                argv
            );
        }

        // The equals form still parses everywhere and selects the named remote.
        let run = run_args(&[
            "cflx",
            "run",
            "--all",
            "--integrate-upstream=upstream",
            "--upstream-verify-command",
            "cargo test",
        ]);
        let bare = bare_tui_args(&[
            "cflx",
            "--integrate-upstream=upstream",
            "--upstream-verify-command",
            "cargo test",
        ]);
        let explicit = tui_args(&[
            "cflx",
            "tui",
            "--integrate-upstream=upstream",
            "--upstream-verify-command",
            "cargo test",
        ]);
        let expected = Some(crate::upstream::UpstreamIntegrationConfig::new(
            "upstream",
            "cargo test",
        ));
        assert_eq!(run.upstream_integration().unwrap(), expected);
        assert_eq!(bare.upstream_integration().unwrap(), expected);
        assert_eq!(explicit.upstream_integration().unwrap(), expected);
    }

    #[test]
    fn per_change_upstream_short_flag_still_selects_the_default_remote() {
        // Removing the short alias from the valued argument must not change what
        // a value-less `-u` resolves to.
        for args in [
            run_args(&[
                "cflx",
                "run",
                "--all",
                "-u",
                "--upstream-verify-command",
                "cargo test",
            ])
            .upstream_integration(),
            bare_tui_args(&["cflx", "-u", "--upstream-verify-command", "cargo test"])
                .upstream_integration(),
            tui_args(&[
                "cflx",
                "tui",
                "-u",
                "--upstream-verify-command",
                "cargo test",
            ])
            .upstream_integration(),
        ] {
            assert_eq!(
                args.unwrap(),
                Some(crate::upstream::UpstreamIntegrationConfig::new(
                    "origin",
                    "cargo test"
                ))
            );
        }
    }

    #[test]
    fn per_change_upstream_top_level_options_are_rejected_before_a_subcommand() {
        // `cflx -u run ...` parses, but `Commands::Run` reads its own options, so
        // the opt-in would be dropped and the run would succeed in merged mode.
        for (argv, option) in [
            (vec!["cflx", "-u", "run", "--all"], "-u"),
            (
                vec!["cflx", "--integrate-upstream=upstream", "run", "--all"],
                "--integrate-upstream",
            ),
            (
                vec![
                    "cflx",
                    "--upstream-verify-command",
                    "cargo test",
                    "run",
                    "--all",
                ],
                "--upstream-verify-command",
            ),
            (vec!["cflx", "-u", "tui"], "-u"),
        ] {
            let cli = Cli::try_parse_from(&argv)
                .unwrap_or_else(|e| panic!("expected {:?} to parse: {e}", argv));
            let error = cli
                .validate_upstream_option_placement()
                .expect_err(&format!("{:?} must not silently drop the opt-in", argv));
            assert_eq!(error.option, option, "{:?}", argv);
            assert!(
                error.to_string().contains(error.subcommand),
                "the diagnostic must name the subcommand: {error}"
            );
        }
    }

    #[test]
    fn per_change_upstream_top_level_options_stay_valid_for_bare_invocation() {
        let bare = Cli::try_parse_from(["cflx", "-u", "--upstream-verify-command", "cargo test"])
            .expect("bare invocation parses");
        assert_eq!(bare.validate_upstream_option_placement(), Ok(()));

        let plain_subcommand = Cli::try_parse_from(["cflx", "run", "--all"]).expect("run parses");
        assert_eq!(
            plain_subcommand.validate_upstream_option_placement(),
            Ok(())
        );
    }

    #[test]
    fn per_change_upstream_verify_command_help_states_it_is_rejected_alone() {
        use clap::CommandFactory;
        let mut command = Cli::command();
        let run = command
            .find_subcommand_mut("run")
            .expect("run subcommand")
            .render_long_help()
            .to_string();
        let tui = command
            .find_subcommand_mut("tui")
            .expect("tui subcommand")
            .render_long_help()
            .to_string();
        let top = Cli::command().render_long_help().to_string();

        for (entrypoint, help) in [("run", &run), ("tui", &tui), ("bare", &top)] {
            assert!(
                help.contains("Requires `-u`/`--integrate-upstream`; rejected without it."),
                "{entrypoint} help must not claim the verification command is ignored: {help}"
            );
            assert!(
                !help.contains("ignored otherwise"),
                "{entrypoint} help retains the stale wording: {help}"
            );
        }
    }

    #[test]
    fn per_change_upstream_is_exposed_in_tui_help() {
        use clap::CommandFactory;
        let help = Cli::command()
            .find_subcommand_mut("tui")
            .expect("tui subcommand")
            .render_long_help()
            .to_string();
        assert!(help.contains("--integrate-upstream"), "help: {}", help);
        assert!(help.contains("--upstream-verify-command"), "help: {}", help);

        let top = Cli::command().render_long_help().to_string();
        assert!(top.contains("--integrate-upstream"), "help: {}", top);
    }

    #[test]
    fn test_completion_subcommand_supported_shells() {
        for (shell_name, expected) in [
            ("zsh", CompletionShell::Zsh),
            ("bash", CompletionShell::Bash),
            ("fish", CompletionShell::Fish),
            ("powershell", CompletionShell::PowerShell),
        ] {
            let cli = Cli::parse_from(["cflx", "completion", shell_name]);
            match cli.command {
                Some(Commands::Completion(args)) => assert_eq!(args.shell, expected),
                _ => panic!("Expected Completion subcommand for {shell_name}"),
            }
        }
    }

    #[test]
    fn test_completion_subcommand_rejects_unsupported_shell() {
        for shell in ["tcsh", "elvish"] {
            let err = Cli::try_parse_from(["cflx", "completion", shell]).unwrap_err();
            assert_eq!(err.kind(), clap::error::ErrorKind::InvalidValue);
        }
    }

    #[test]
    fn test_internal_change_id_completion_defaults() {
        let cli = Cli::parse_from(["cflx", "__complete", "change-ids"]);
        match cli.command {
            Some(Commands::Complete(args)) => match args.command {
                InternalCompleteCommands::ChangeIds(change_args) => {
                    assert!(!change_args.active);
                    assert!(!change_args.archived);
                    assert_eq!(change_args.prefix, None);
                }
            },
            _ => panic!("Expected hidden Complete subcommand"),
        }
    }

    #[test]
    fn test_internal_change_id_completion_flags() {
        let cli = Cli::parse_from([
            "cflx",
            "__complete",
            "change-ids",
            "--active",
            "--archived",
            "--prefix",
            "add-",
        ]);
        match cli.command {
            Some(Commands::Complete(args)) => match args.command {
                InternalCompleteCommands::ChangeIds(change_args) => {
                    assert!(change_args.active);
                    assert!(change_args.archived);
                    assert_eq!(change_args.prefix.as_deref(), Some("add-"));
                }
            },
            _ => panic!("Expected hidden Complete subcommand"),
        }
    }

    #[test]
    fn test_internal_complete_rejects_invalid_mode() {
        let err = Cli::try_parse_from(["cflx", "__complete", "spec-ids"]).unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::InvalidSubcommand);
    }

    #[test]
    fn test_logs_subcommand_flags() {
        let cli = Cli::parse_from([
            "cflx",
            "logs",
            "--path",
            "--last",
            "50",
            "--follow",
            "--today",
            "--project",
            "conflux-test",
        ]);

        match cli.command {
            Some(Commands::Logs(args)) => {
                assert!(args.path);
                assert_eq!(args.last, Some(50));
                assert!(args.follow);
                assert!(args.today);
                assert_eq!(args.project.as_deref(), Some("conflux-test"));
            }
            _ => panic!("Expected Logs subcommand"),
        }
    }

    #[test]
    fn test_logs_help_documents_flags() {
        let err = Cli::try_parse_from(["cflx", "logs", "--help"]).unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
        let help = err.to_string();
        assert!(help.contains("--path"));
        assert!(help.contains("--last <N>"));
        assert!(help.contains("--follow"));
        assert!(help.contains("--today"));
        assert!(help.contains("--project <SLUG>"));
    }

    #[test]
    fn test_logs_subcommand_default_mode() {
        let cli = Cli::parse_from(["cflx", "logs"]);

        match cli.command {
            Some(Commands::Logs(args)) => {
                assert!(!args.path);
                assert_eq!(args.last, None);
                assert!(!args.follow);
                assert!(!args.today);
                assert!(args.project.is_none());
            }
            _ => panic!("Expected Logs subcommand"),
        }
    }

    #[test]
    fn test_run_subcommand_config_option() {
        let cli = Cli::parse_from(["cflx", "run", "--all", "--config", "/path/to/config.jsonc"]);

        match cli.command {
            Some(Commands::Run(args)) => {
                assert_eq!(args.config, Some(PathBuf::from("/path/to/config.jsonc")));
            }
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn test_run_subcommand_change_option() {
        let cli = Cli::parse_from(["cflx", "run", "--change", "add-feature-x"]);

        match cli.command {
            Some(Commands::Run(args)) => {
                assert_eq!(args.change, Some(vec!["add-feature-x".to_string()]));
            }
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn test_run_subcommand_multiple_changes_comma_separated() {
        let cli = Cli::parse_from(["cflx", "run", "--change", "a,b,c"]);

        match cli.command {
            Some(Commands::Run(args)) => {
                assert_eq!(
                    args.change,
                    Some(vec!["a".to_string(), "b".to_string(), "c".to_string()])
                );
            }
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn test_run_subcommand_multiple_changes_with_spaces() {
        // Test that spaces around commas are handled
        let cli = Cli::parse_from(["cflx", "run", "--change", "a, b, c"]);

        match cli.command {
            Some(Commands::Run(args)) => {
                // clap preserves spaces - trimming should be done by application logic if needed
                assert!(args.change.is_some());
                let changes = args.change.unwrap();
                assert_eq!(changes.len(), 3);
            }
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn test_run_subcommand_requires_explicit_target() {
        let err = Cli::try_parse_from(["cflx", "run"]).unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
    }

    #[test]
    fn test_run_subcommand_all_target() {
        let cli = Cli::parse_from(["cflx", "run", "--all"]);

        match cli.command {
            Some(Commands::Run(args)) => {
                assert!(args.all);
                assert_eq!(args.normalized_target_changes(), None);
            }
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn test_run_subcommand_positional_changes() {
        let cli = Cli::parse_from(["cflx", "run", "a", "b"]);

        match cli.command {
            Some(Commands::Run(args)) => {
                assert_eq!(args.changes, vec!["a".to_string(), "b".to_string()]);
                assert_eq!(
                    args.normalized_target_changes(),
                    Some(vec!["a".to_string(), "b".to_string()])
                );
            }
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn test_run_subcommand_rejects_target_mode_combinations() {
        for argv in [
            vec!["cflx", "run", "--all", "a"],
            vec!["cflx", "run", "--all", "--change", "a"],
            vec!["cflx", "run", "--change", "a", "b"],
        ] {
            let err = Cli::try_parse_from(argv).unwrap_err();
            assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
        }
    }

    #[test]
    fn test_no_subcommand() {
        let cli = Cli::parse_from(["cflx"]);
        assert!(cli.command.is_none());
    }

    #[test]
    fn tui_default_push_defaults_to_origin() {
        let cli = Cli::parse_from(["cflx", "--push"]);
        assert!(cli.command.is_none());
        assert_eq!(cli.push.as_deref(), Some("origin"));
    }

    #[test]
    fn tui_default_push_accepts_remote_name() {
        let cli = Cli::parse_from(["cflx", "--push", "upstream"]);
        assert!(cli.command.is_none());
        assert_eq!(cli.push.as_deref(), Some("upstream"));
    }

    #[test]
    fn tui_default_push_rejects_branch_selection() {
        let err = Cli::try_parse_from(["cflx", "--push", "origin:main"]).unwrap_err();
        assert!(err
            .to_string()
            .contains("branch selection is not supported"));
    }

    #[test]
    fn tui_subcommand_push_defaults_to_origin() {
        let cli = Cli::parse_from(["cflx", "tui", "--push"]);
        match cli.command {
            Some(Commands::Tui(args)) => assert_eq!(args.push.as_deref(), Some("origin")),
            _ => panic!("Expected Tui subcommand"),
        }
    }

    #[test]
    fn tui_subcommand_push_accepts_remote_name() {
        let cli = Cli::parse_from(["cflx", "tui", "--push", "upstream"]);
        match cli.command {
            Some(Commands::Tui(args)) => assert_eq!(args.push.as_deref(), Some("upstream")),
            _ => panic!("Expected Tui subcommand"),
        }
    }

    #[test]
    fn tui_subcommand_push_rejects_branch_selection() {
        let err = Cli::try_parse_from(["cflx", "tui", "--push", "origin:main"]).unwrap_err();
        assert!(err
            .to_string()
            .contains("branch selection is not supported"));
    }

    #[test]
    fn test_init_subcommand_default_template() {
        let cli = Cli::parse_from(["cflx", "init"]);

        match cli.command {
            Some(Commands::Init(args)) => {
                assert!(matches!(args.template, Template::Claude));
                assert!(!args.force);
            }
            _ => panic!("Expected Init subcommand"),
        }
    }

    #[test]
    fn test_init_subcommand_opencode_template() {
        let cli = Cli::parse_from(["cflx", "init", "--template", "opencode"]);

        match cli.command {
            Some(Commands::Init(args)) => {
                assert!(matches!(args.template, Template::Opencode));
            }
            _ => panic!("Expected Init subcommand"),
        }
    }

    #[test]
    fn test_init_subcommand_claude_template() {
        let cli = Cli::parse_from(["cflx", "init", "--template", "claude"]);

        match cli.command {
            Some(Commands::Init(args)) => {
                assert!(matches!(args.template, Template::Claude));
            }
            _ => panic!("Expected Init subcommand"),
        }
    }

    #[test]
    fn test_init_subcommand_codex_template() {
        let cli = Cli::parse_from(["cflx", "init", "--template", "codex"]);

        match cli.command {
            Some(Commands::Init(args)) => {
                assert!(matches!(args.template, Template::Codex));
            }
            _ => panic!("Expected Init subcommand"),
        }
    }

    #[test]
    fn test_init_subcommand_short_template_flag() {
        let cli = Cli::parse_from(["cflx", "init", "-t", "opencode"]);

        match cli.command {
            Some(Commands::Init(args)) => {
                assert!(matches!(args.template, Template::Opencode));
            }
            _ => panic!("Expected Init subcommand"),
        }
    }

    #[test]
    fn test_init_subcommand_force_flag() {
        let cli = Cli::parse_from(["cflx", "init", "--force"]);

        match cli.command {
            Some(Commands::Init(args)) => {
                assert!(args.force);
            }
            _ => panic!("Expected Init subcommand"),
        }
    }

    #[test]
    fn test_init_subcommand_short_force_flag() {
        let cli = Cli::parse_from(["cflx", "init", "-f"]);

        match cli.command {
            Some(Commands::Init(args)) => {
                assert!(args.force);
            }
            _ => panic!("Expected Init subcommand"),
        }
    }

    #[test]
    fn test_version_flag_exits_with_display_version() {
        // --version flag should cause parse to return an error (DisplayVersion)
        let result = Cli::try_parse_from(["cflx", "--version"]);
        assert!(result.is_err());

        let err = result.unwrap_err();
        // clap returns DisplayVersion error kind for --version
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion);
    }

    #[test]
    fn test_short_version_flag() {
        // -V flag should also display version
        let result = Cli::try_parse_from(["cflx", "-V"]);
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion);
    }

    #[test]
    fn test_run_subcommand_max_iterations_default() {
        let cli = Cli::parse_from(["cflx", "run", "--all"]);

        match cli.command {
            Some(Commands::Run(args)) => {
                assert!(args.max_iterations.is_none());
            }
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn test_run_subcommand_max_iterations_custom() {
        let cli = Cli::parse_from(["cflx", "run", "--all", "--max-iterations", "100"]);

        match cli.command {
            Some(Commands::Run(args)) => {
                assert_eq!(args.max_iterations, Some(100));
            }
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn test_run_subcommand_max_iterations_zero() {
        let cli = Cli::parse_from(["cflx", "run", "--all", "--max-iterations", "0"]);

        match cli.command {
            Some(Commands::Run(args)) => {
                assert_eq!(args.max_iterations, Some(0));
            }
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn test_run_subcommand_execution_options_default() {
        let cli = Cli::parse_from(["cflx", "run", "--all"]);

        match cli.command {
            Some(Commands::Run(args)) => {
                assert!(args.max_concurrent.is_none());
                assert!(!args.dry_run);
            }
            _ => panic!("Expected Run subcommand"),
        }
    }

    /// Worktree orchestration is the only execution model, so the retired mode
    /// selector must be a parse error rather than an accepted no-op, and help
    /// output must not advertise it.
    #[test]
    fn retired_parallel_flag_is_rejected_and_unadvertised() {
        let error = Cli::try_parse_from(["cflx", "run", "--all", "--parallel"])
            .expect_err("--parallel must not parse");
        assert_eq!(
            error.kind(),
            clap::error::ErrorKind::UnknownArgument,
            "the retired flag must fail as an unknown argument, got: {error}"
        );

        let help = Cli::command()
            .find_subcommand_mut("run")
            .expect("run subcommand")
            .render_long_help()
            .to_string();
        assert!(
            !help.contains("--parallel"),
            "run help must not advertise the retired flag, got: {help}"
        );

        let root_help = Cli::command().render_long_help().to_string();
        assert!(
            !root_help.contains("--parallel"),
            "root help must not advertise the retired flag, got: {root_help}"
        );
    }

    #[test]
    fn cli_push_defaults_to_origin() {
        let cli = Cli::parse_from(["cflx", "run", "--all", "--push"]);
        match cli.command {
            Some(Commands::Run(args)) => assert_eq!(args.push.as_deref(), Some("origin")),
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn cli_push_accepts_remote_name() {
        let cli = Cli::parse_from(["cflx", "run", "--all", "--push", "upstream"]);
        match cli.command {
            Some(Commands::Run(args)) => assert_eq!(args.push.as_deref(), Some("upstream")),
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn cli_push_rejects_branch_selection() {
        let err =
            Cli::try_parse_from(["cflx", "run", "--all", "--push", "origin:main"]).unwrap_err();
        assert!(err
            .to_string()
            .contains("branch selection is not supported"));
    }

    #[test]
    fn test_run_subcommand_max_concurrent() {
        let cli = Cli::parse_from(["cflx", "run", "--all", "--max-concurrent", "5"]);

        match cli.command {
            Some(Commands::Run(args)) => {
                assert_eq!(args.max_concurrent, Some(5));
            }
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn test_run_subcommand_dry_run() {
        let cli = Cli::parse_from(["cflx", "run", "--all", "--dry-run"]);

        match cli.command {
            Some(Commands::Run(args)) => {
                assert!(args.dry_run);
            }
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn test_run_subcommand_web_port_default_auto_assign() {
        let cli = Cli::parse_from(["cflx", "run", "--all", "--web"]);

        match cli.command {
            Some(Commands::Run(args)) => {
                assert!(args.web);
                assert_eq!(args.web_port, 0); // Default: OS auto-assigns port
                assert_eq!(args.web_bind, "127.0.0.1");
            }
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn test_run_subcommand_web_port_explicit() {
        let cli = Cli::parse_from(["cflx", "run", "--all", "--web", "--web-port", "9000"]);

        match cli.command {
            Some(Commands::Run(args)) => {
                assert!(args.web);
                assert_eq!(args.web_port, 9000);
            }
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn test_tui_subcommand_web_port_default_auto_assign() {
        let cli = Cli::parse_from(["cflx", "tui", "--web"]);

        match cli.command {
            Some(Commands::Tui(args)) => {
                assert!(args.web);
                assert_eq!(args.web_port, 0); // Default: OS auto-assigns port
                assert_eq!(args.web_bind, "127.0.0.1");
            }
            _ => panic!("Expected Tui subcommand"),
        }
    }

    #[test]
    fn test_no_subcommand_with_web() {
        // Note: Current CLI design requires explicit subcommand for web options.
        // The --web flag is only valid with 'run' or 'tui' subcommands.
        // This test verifies that web options work correctly with TUI subcommand.

        let cli = Cli::parse_from(["cflx", "tui", "--web"]);

        match cli.command {
            Some(Commands::Tui(args)) => {
                assert!(args.web);
                assert_eq!(args.web_port, 0); // Default: OS auto-assigns port
                assert_eq!(args.web_bind, "127.0.0.1");
            }
            _ => panic!("Expected Tui subcommand"),
        }
    }

    #[test]
    fn test_check_conflicts_subcommand_default() {
        let cli = Cli::parse_from(["cflx", "check-conflicts"]);

        match cli.command {
            Some(Commands::CheckConflicts(args)) => {
                assert!(!args.json);
            }
            _ => panic!("Expected CheckConflicts subcommand"),
        }
    }

    #[test]
    fn test_check_conflicts_subcommand_json_flag() {
        let cli = Cli::parse_from(["cflx", "check-conflicts", "--json"]);

        match cli.command {
            Some(Commands::CheckConflicts(args)) => {
                assert!(args.json);
            }
            _ => panic!("Expected CheckConflicts subcommand"),
        }
    }

    #[test]
    fn test_check_conflicts_subcommand_short_json_flag() {
        let cli = Cli::parse_from(["cflx", "check-conflicts", "-j"]);

        match cli.command {
            Some(Commands::CheckConflicts(args)) => {
                assert!(args.json);
            }
            _ => panic!("Expected CheckConflicts subcommand"),
        }
    }

    // Removed multi-project server surfaces must fail at parse time.
    //
    // Clap rejection is the whole contract: an operator who still has the old
    // flags in a script gets a usage error before any logging, repository lock,
    // network connection, or orchestration side effect can run.
    #[test]
    fn removed_top_level_server_options_are_rejected() {
        for argv in [
            vec!["cflx", "--server", "http://127.0.0.1:39876"],
            vec!["cflx", "--server-token", "mytoken"],
            vec!["cflx", "--server-token-env", "MY_TOKEN_VAR"],
        ] {
            let err = Cli::try_parse_from(&argv)
                .expect_err("removed top-level server option must not parse");
            assert_eq!(
                err.kind(),
                clap::error::ErrorKind::UnknownArgument,
                "unexpected error for {:?}: {}",
                argv,
                err
            );
        }
    }

    #[test]
    fn removed_tui_server_options_are_rejected() {
        for argv in [
            vec!["cflx", "tui", "--server", "http://127.0.0.1:39876"],
            vec!["cflx", "tui", "--server-token", "mytoken"],
            vec!["cflx", "tui", "--server-token-env", "MY_TOKEN_VAR"],
        ] {
            let err =
                Cli::try_parse_from(&argv).expect_err("removed tui server option must not parse");
            assert_eq!(
                err.kind(),
                clap::error::ErrorKind::UnknownArgument,
                "unexpected error for {:?}: {}",
                argv,
                err
            );
        }
    }

    #[test]
    fn removed_server_service_and_project_subcommands_are_rejected() {
        for argv in [
            vec!["cflx", "server"],
            vec!["cflx", "server", "--port", "39876"],
            vec!["cflx", "service", "install"],
            vec!["cflx", "service", "status"],
            vec!["cflx", "project", "status"],
            vec!["cflx", "project", "add", "https://github.com/org/repo.git"],
            vec!["cflx", "project", "sync", "--all"],
        ] {
            let err = Cli::try_parse_from(&argv).expect_err("removed subcommand must not parse");
            assert_eq!(
                err.kind(),
                clap::error::ErrorKind::InvalidSubcommand,
                "unexpected error for {:?}: {}",
                argv,
                err
            );
        }
    }

    #[test]
    fn help_no_longer_advertises_removed_server_surfaces() {
        let mut cmd = <Cli as clap::CommandFactory>::command();
        let long_help = cmd.render_long_help().to_string();
        for needle in [
            "--server",
            "--server-token",
            "--server-token-env",
            "cflx server",
            "cflx project",
            "cflx service",
        ] {
            assert!(
                !long_help.contains(needle),
                "top-level help still advertises '{}'",
                needle
            );
        }

        let mut tui = cmd
            .find_subcommand_mut("tui")
            .expect("tui subcommand")
            .clone();
        let tui_help = tui.render_long_help().to_string();
        for needle in ["--server", "--server-token", "--server-token-env"] {
            assert!(
                !tui_help.contains(needle),
                "tui help still advertises '{}'",
                needle
            );
        }
        // The retained local web surface must still be advertised.
        assert!(tui_help.contains("--web"));
        assert!(tui_help.contains("--web-auth-token"));
    }

    // Additional tests for web flag parsing behavior
    #[test]
    fn test_case_1_cflx() {
        // Case 1: cflx -> No subcommand (will trigger parse_tui_args in main.rs)
        let cli = Cli::try_parse_from(["cflx"]).unwrap();
        assert!(cli.command.is_none());
        println!("Case 1: 'cflx' -> No subcommand (TUI with web=false via parse_tui_args)");
    }

    #[test]
    fn test_case_2_cflx_web() {
        // Case 2: cflx --web -> No subcommand (--web is a top-level flag, should succeed)
        let cli = Cli::try_parse_from(["cflx", "--web"]).unwrap();
        assert!(cli.web);
        assert!(cli.command.is_none());
        println!("Case 2: 'cflx --web' -> No subcommand with web=true (TUI with web)");
    }

    #[test]
    fn test_case_3_cflx_tui_web() {
        // Case 3: cflx tui --web -> TUI subcommand with web=true
        let cli = Cli::try_parse_from(["cflx", "tui", "--web"]).unwrap();
        match &cli.command {
            Some(Commands::Tui(args)) => {
                assert!(args.web);
                println!("Case 3: 'cflx tui --web' -> TuiArgs with web=true");
            }
            _ => panic!("Expected Tui subcommand"),
        }
    }

    #[test]
    fn test_case_4_cflx_run_web() {
        // Case 4: cflx run --web -> Run subcommand with web=true
        let cli = Cli::try_parse_from(["cflx", "run", "--all", "--web"]).unwrap();
        match &cli.command {
            Some(Commands::Run(args)) => {
                assert!(args.web);
                println!("Case 4: 'cflx run --web' -> RunArgs with web=true");
            }
            _ => panic!("Expected Run subcommand"),
        }
    }

    #[test]
    fn test_parse_tui_args_with_web_simulation() {
        // Simulate parse_tui_args logic for "cflx --web" from main.rs
        // This is what happens when Cli::parse() returns None
        // Note: TuiArgs is a subcommand struct, so it expects arguments starting with program name
        // The parse_tui_args function prepends "cflx", "tui" to simulate this behavior

        let args: Vec<String> = vec!["--web".to_string()];
        let full_args = {
            let mut v = vec!["cflx".to_string(), "tui".to_string()];
            v.extend(args);
            v
        };

        // Parse via full CLI path (simulating the behavior)
        let cli_result = Cli::try_parse_from(full_args.clone());
        match cli_result {
            Ok(cli) => match &cli.command {
                Some(Commands::Tui(tui_args)) => {
                    assert!(tui_args.web);
                    println!("Case 5 (parse_tui_args simulation): 'cflx --web' -> via Cli -> TuiArgs with web=true");
                }
                _ => panic!("Expected Tui subcommand"),
            },
            Err(e) => {
                panic!("Expected successful parse: {}", e);
            }
        }
    }

    // ── install-skills subcommand tests ──────────────────────────────────────

    #[test]
    fn test_install_skills_no_args() {
        let cli = Cli::parse_from(["cflx", "install-skills"]);
        match cli.command {
            Some(Commands::InstallSkills(args)) => {
                assert!(!args.global);
                assert!(!args.claude);
                assert_eq!(args.target(), InstallSkillsTarget::Agents);
            }
            _ => panic!("Expected InstallSkills subcommand"),
        }
    }

    #[test]
    fn test_install_skills_global_flag() {
        let cli = Cli::parse_from(["cflx", "install-skills", "--global"]);
        match cli.command {
            Some(Commands::InstallSkills(args)) => {
                assert!(args.global);
                assert!(!args.claude);
                assert_eq!(args.target(), InstallSkillsTarget::Agents);
            }
            _ => panic!("Expected InstallSkills subcommand"),
        }
    }

    #[test]
    fn test_install_skills_claude_flag() {
        let cli = Cli::parse_from(["cflx", "install-skills", "--claude"]);
        match cli.command {
            Some(Commands::InstallSkills(args)) => {
                assert!(!args.global);
                assert!(args.claude);
                assert_eq!(args.target(), InstallSkillsTarget::Claude);
            }
            _ => panic!("Expected InstallSkills subcommand"),
        }
    }

    #[test]
    fn test_install_skills_claude_and_global_flags() {
        let cli = Cli::parse_from(["cflx", "install-skills", "--claude", "--global"]);
        match cli.command {
            Some(Commands::InstallSkills(args)) => {
                assert!(args.global);
                assert!(args.claude);
                assert_eq!(args.target(), InstallSkillsTarget::Claude);
            }
            _ => panic!("Expected InstallSkills subcommand"),
        }
    }

    #[test]
    fn test_install_skills_legacy_self_arg_captured() {
        // Legacy "self" positional argument is captured so we can emit migration guidance
        let cli = Cli::parse_from(["cflx", "install-skills", "self"]);
        match cli.command {
            Some(Commands::InstallSkills(args)) => {
                assert_eq!(args.legacy_source.as_deref(), Some("self"));
                let msg = install_skills_legacy_error("self");
                assert!(
                    msg.contains("cflx install-skills"),
                    "Migration guidance must mention 'cflx install-skills'"
                );
                assert!(
                    msg.contains("--global"),
                    "Migration guidance must mention '--global'"
                );
            }
            _ => panic!("Expected InstallSkills subcommand"),
        }
    }

    #[test]
    fn test_install_skills_legacy_local_arg_captured() {
        // Legacy "local:..." positional argument is captured so we can emit migration guidance
        let cli = Cli::parse_from(["cflx", "install-skills", "local:../my-skills"]);
        match cli.command {
            Some(Commands::InstallSkills(args)) => {
                assert_eq!(args.legacy_source.as_deref(), Some("local:../my-skills"));
                let msg = install_skills_legacy_error("local:../my-skills");
                assert!(
                    msg.contains("cflx install-skills"),
                    "Migration guidance must mention 'cflx install-skills'"
                );
                assert!(
                    msg.contains("--global"),
                    "Migration guidance must mention '--global'"
                );
            }
            _ => panic!("Expected InstallSkills subcommand"),
        }
    }

    // ── openspec subcommand tests ──────────────────────────────────────────

    #[test]
    fn test_openspec_list_default() {
        let cli = Cli::parse_from(["cflx", "openspec", "list"]);
        match cli.command {
            Some(Commands::Openspec(args)) => match args.command {
                super::OpenspecCommands::List(list_args) => {
                    assert!(!list_args.specs);
                }
                _ => panic!("Expected List subcommand"),
            },
            _ => panic!("Expected Openspec subcommand"),
        }
    }

    #[test]
    fn test_openspec_list_specs_flag() {
        let cli = Cli::parse_from(["cflx", "openspec", "list", "--specs"]);
        match cli.command {
            Some(Commands::Openspec(args)) => match args.command {
                super::OpenspecCommands::List(list_args) => {
                    assert!(list_args.specs);
                }
                _ => panic!("Expected List subcommand"),
            },
            _ => panic!("Expected Openspec subcommand"),
        }
    }

    #[test]
    fn test_openspec_show_basic() {
        let cli = Cli::parse_from(["cflx", "openspec", "show", "my-change"]);
        match cli.command {
            Some(Commands::Openspec(args)) => match args.command {
                super::OpenspecCommands::Show(show_args) => {
                    assert_eq!(show_args.change_id, "my-change");
                    assert!(!show_args.json);
                    assert!(!show_args.deltas_only);
                }
                _ => panic!("Expected Show subcommand"),
            },
            _ => panic!("Expected Openspec subcommand"),
        }
    }

    #[test]
    fn test_openspec_show_json_deltas_only() {
        let cli = Cli::parse_from([
            "cflx",
            "openspec",
            "show",
            "my-change",
            "--json",
            "--deltas-only",
        ]);
        match cli.command {
            Some(Commands::Openspec(args)) => match args.command {
                super::OpenspecCommands::Show(show_args) => {
                    assert_eq!(show_args.change_id, "my-change");
                    assert!(show_args.json);
                    assert!(show_args.deltas_only);
                }
                _ => panic!("Expected Show subcommand"),
            },
            _ => panic!("Expected Openspec subcommand"),
        }
    }

    #[test]
    fn test_openspec_validate_all_default() {
        let cli = Cli::parse_from(["cflx", "openspec", "validate"]);
        match cli.command {
            Some(Commands::Openspec(args)) => match args.command {
                super::OpenspecCommands::Validate(val_args) => {
                    assert!(val_args.change_id.is_none());
                    assert!(!val_args.strict);
                    assert!(!val_args.archive_gate);
                    assert!(matches!(val_args.evidence, super::EvidenceMode::Off));
                }
                _ => panic!("Expected Validate subcommand"),
            },
            _ => panic!("Expected Openspec subcommand"),
        }
    }

    #[test]
    fn test_openspec_validate_strict_with_change() {
        let cli = Cli::parse_from(["cflx", "openspec", "validate", "my-change", "--strict"]);
        match cli.command {
            Some(Commands::Openspec(args)) => match args.command {
                super::OpenspecCommands::Validate(val_args) => {
                    assert_eq!(val_args.change_id, Some("my-change".to_string()));
                    assert!(val_args.strict);
                }
                _ => panic!("Expected Validate subcommand"),
            },
            _ => panic!("Expected Openspec subcommand"),
        }
    }

    #[test]
    fn test_openspec_validate_evidence_modes() {
        for (flag, expected) in [("off", "Off"), ("warn", "Warn"), ("error", "Error")] {
            let cli = Cli::parse_from(["cflx", "openspec", "validate", "--evidence", flag]);
            match cli.command {
                Some(Commands::Openspec(args)) => match args.command {
                    super::OpenspecCommands::Validate(val_args) => {
                        let actual = format!("{:?}", val_args.evidence);
                        assert_eq!(
                            actual, expected,
                            "Evidence mode mismatch for flag '{}'",
                            flag
                        );
                    }
                    _ => panic!("Expected Validate subcommand"),
                },
                _ => panic!("Expected Openspec subcommand"),
            }
        }
    }

    #[test]
    fn test_openspec_validate_rejects_strict_as_evidence_mode_name() {
        use clap::Parser;

        let parsed = Cli::try_parse_from(["cflx", "openspec", "validate", "--evidence", "strict"]);

        assert!(parsed.is_err(), "strict evidence mode should be rejected");
    }

    #[test]
    fn test_openspec_validate_archive_gate_flag() {
        let cli = Cli::parse_from([
            "cflx",
            "openspec",
            "validate",
            "my-change",
            "--archive-gate",
        ]);
        match cli.command {
            Some(Commands::Openspec(args)) => match args.command {
                super::OpenspecCommands::Validate(val_args) => {
                    assert_eq!(val_args.change_id, Some("my-change".to_string()));
                    assert!(val_args.archive_gate);
                }
                _ => panic!("Expected Validate subcommand"),
            },
            _ => panic!("Expected Openspec subcommand"),
        }
    }

    #[test]
    fn test_openspec_archive_basic() {
        let cli = Cli::parse_from(["cflx", "openspec", "archive", "my-change", "--yes"]);
        match cli.command {
            Some(Commands::Openspec(args)) => match args.command {
                super::OpenspecCommands::Archive(arc_args) => {
                    assert_eq!(arc_args.change_id, "my-change");
                    assert!(arc_args.yes);
                    assert!(!arc_args.skip_specs);
                }
                _ => panic!("Expected Archive subcommand"),
            },
            _ => panic!("Expected Openspec subcommand"),
        }
    }

    #[test]
    fn test_openspec_archive_skip_specs() {
        let cli = Cli::parse_from([
            "cflx",
            "openspec",
            "archive",
            "my-change",
            "--yes",
            "--skip-specs",
        ]);
        match cli.command {
            Some(Commands::Openspec(args)) => match args.command {
                super::OpenspecCommands::Archive(arc_args) => {
                    assert_eq!(arc_args.change_id, "my-change");
                    assert!(arc_args.yes);
                    assert!(arc_args.skip_specs);
                }
                _ => panic!("Expected Archive subcommand"),
            },
            _ => panic!("Expected Openspec subcommand"),
        }
    }

    #[test]
    fn test_tui_help_displays_key_bindings() {
        // Regression test: Ensure TUI help output contains key bindings
        use clap::CommandFactory;

        let app = Cli::command();
        let tui_subcommand = app
            .find_subcommand("tui")
            .expect("tui subcommand should exist");

        // Get the long help text
        let mut help_output = Vec::new();
        tui_subcommand
            .clone()
            .write_long_help(&mut help_output)
            .unwrap();
        let help_text = String::from_utf8(help_output).unwrap();

        // Verify key bindings are documented
        assert!(help_text.contains("Space"), "Help should mention Space key");
        assert!(help_text.contains("F5"), "Help should mention F5 key");
        assert!(
            help_text.contains("~/.config/cflx/tui.jsonc"),
            "Help should mention TUI user config path"
        );
        assert!(help_text.contains("Esc"), "Help should mention Esc key");
        assert!(help_text.contains("Tab"), "Help should mention Tab key");
        assert!(help_text.contains("q"), "Help should mention q key");

        // Verify the key binding section is present
        assert!(
            help_text.contains("Key bindings"),
            "Help should have 'Key bindings' section"
        );
    }
}

/// Parser coverage for the `/api/v2` remote-control web options.
///
/// Named for the capability rather than for `cli` so the change's verification
/// filter (`cargo test --lib remote_control_api`) reaches the CLI surface too:
/// a config that only fails at runtime is not a safety property.
#[cfg(test)]
mod remote_control_api_cli_tests {
    use super::*;
    use clap::{CommandFactory, Parser};

    fn parse(args: &[&str]) -> Cli {
        Cli::try_parse_from(args).unwrap_or_else(|e| panic!("{args:?} must parse: {e}"))
    }

    fn parse_err(args: &[&str]) -> String {
        Cli::try_parse_from(args)
            .err()
            .unwrap_or_else(|| panic!("{args:?} must be rejected"))
            .to_string()
    }

    #[test]
    fn web_auth_options_default_to_absent_in_every_web_enabled_scope() {
        let root = parse(&["cflx", "--web"]);
        assert_eq!(root.web_auth_token, None);
        assert_eq!(root.web_auth_token_env, None);
        assert!(root.web_allowed_origins.is_empty());

        match parse(&["cflx", "run", "--all", "--web"]).command {
            Some(Commands::Run(args)) => {
                assert_eq!(args.web_auth_token, None);
                assert_eq!(args.web_auth_token_env, None);
                assert!(args.web_allowed_origins.is_empty());
            }
            other => panic!("expected run, got {other:?}"),
        }

        match parse(&["cflx", "tui", "--web"]).command {
            Some(Commands::Tui(args)) => {
                assert_eq!(args.web_auth_token, None);
                assert_eq!(args.web_auth_token_env, None);
                assert!(args.web_allowed_origins.is_empty());
            }
            other => panic!("expected tui, got {other:?}"),
        }
    }

    #[test]
    fn a_literal_token_parses_in_every_web_enabled_scope() {
        assert_eq!(
            parse(&["cflx", "--web", "--web-auth-token", "abc"]).web_auth_token,
            Some("abc".to_string())
        );
        match parse(&["cflx", "run", "--all", "--web", "--web-auth-token", "abc"]).command {
            Some(Commands::Run(args)) => assert_eq!(args.web_auth_token, Some("abc".to_string())),
            other => panic!("expected run, got {other:?}"),
        }
        match parse(&["cflx", "tui", "--web", "--web-auth-token", "abc"]).command {
            Some(Commands::Tui(args)) => assert_eq!(args.web_auth_token, Some("abc".to_string())),
            other => panic!("expected tui, got {other:?}"),
        }
    }

    #[test]
    fn the_environment_form_parses_in_every_web_enabled_scope() {
        assert_eq!(
            parse(&["cflx", "--web", "--web-auth-token-env", "CFLX_TOKEN"]).web_auth_token_env,
            Some("CFLX_TOKEN".to_string())
        );
        match parse(&[
            "cflx",
            "run",
            "--all",
            "--web",
            "--web-auth-token-env",
            "CFLX_TOKEN",
        ])
        .command
        {
            Some(Commands::Run(args)) => {
                assert_eq!(args.web_auth_token_env, Some("CFLX_TOKEN".to_string()))
            }
            other => panic!("expected run, got {other:?}"),
        }
        match parse(&["cflx", "tui", "--web", "--web-auth-token-env", "CFLX_TOKEN"]).command {
            Some(Commands::Tui(args)) => {
                assert_eq!(args.web_auth_token_env, Some("CFLX_TOKEN".to_string()))
            }
            other => panic!("expected tui, got {other:?}"),
        }
    }

    #[test]
    fn token_sources_are_mutually_exclusive_in_every_web_enabled_scope() {
        for prefix in [
            vec!["cflx"],
            vec!["cflx", "run", "--all"],
            vec!["cflx", "tui"],
        ] {
            let mut args = prefix.clone();
            args.extend([
                "--web",
                "--web-auth-token",
                "a",
                "--web-auth-token-env",
                "V",
            ]);
            let error = parse_err(&args);
            assert!(
                error.contains("cannot be used with"),
                "{prefix:?} must reject both token sources, got: {error}"
            );
        }
    }

    #[test]
    fn allowed_origins_are_repeatable_in_every_web_enabled_scope() {
        let root = parse(&[
            "cflx",
            "--web",
            "--web-allowed-origin",
            "https://ops.example.com",
            "--web-allowed-origin",
            "http://localhost:5173",
        ]);
        assert_eq!(
            root.web_allowed_origins,
            vec![
                "https://ops.example.com".to_string(),
                "http://localhost:5173".to_string()
            ]
        );

        match parse(&[
            "cflx",
            "run",
            "--all",
            "--web",
            "--web-allowed-origin",
            "https://a.example",
            "--web-allowed-origin",
            "https://b.example",
        ])
        .command
        {
            Some(Commands::Run(args)) => assert_eq!(args.web_allowed_origins.len(), 2),
            other => panic!("expected run, got {other:?}"),
        }

        match parse(&[
            "cflx",
            "tui",
            "--web",
            "--web-allowed-origin",
            "https://a.example",
            "--web-allowed-origin",
            "https://b.example",
        ])
        .command
        {
            Some(Commands::Tui(args)) => assert_eq!(args.web_allowed_origins.len(), 2),
            other => panic!("expected tui, got {other:?}"),
        }
    }

    #[test]
    fn help_documents_the_literal_token_exposure_and_the_recommended_form() {
        let help = Cli::command().render_long_help().to_string();
        assert!(help.contains("--web-auth-token"));
        assert!(help.contains("--web-auth-token-env"));
        assert!(help.contains("--web-allowed-origin"));
        assert!(
            help.contains("inspect this process's arguments"),
            "the literal-token exposure must be documented where an operator will read it"
        );
        assert!(
            help.contains("wildcards are\nrejected") || help.contains("wildcards are rejected"),
            "the exact-origin rule must be documented"
        );
    }

    /// `WebConfig` only exists under `web-monitoring`, so the wiring assertion is
    /// gated while the parser assertions above stay feature-independent.
    #[test]
    #[cfg(feature = "web-monitoring")]
    fn parsed_web_options_flow_into_a_validated_web_config() {
        let args = parse(&[
            "cflx",
            "--web",
            "--web-bind",
            "0.0.0.0",
            "--web-port",
            "9000",
            "--web-auth-token",
            "abc",
            "--web-allowed-origin",
            "https://ops.example.com",
        ]);
        let config = crate::web::WebConfig::enabled(args.web_port, args.web_bind.clone())
            .with_auth(
                args.web_auth_token.clone(),
                args.web_auth_token_env.clone(),
                args.web_allowed_origins.clone(),
            );
        assert!(config.validate().is_ok());
        assert_eq!(config.resolve_auth_token().as_deref(), Some("abc"));

        let unsafe_args = parse(&["cflx", "--web", "--web-bind", "0.0.0.0"]);
        let unsafe_config =
            crate::web::WebConfig::enabled(unsafe_args.web_port, unsafe_args.web_bind.clone())
                .with_auth(None, None, Vec::new());
        assert!(
            unsafe_config.validate().is_err(),
            "a routable bind without credentials must never reach a listener"
        );
    }

    /// A UDS-only process never becomes reachable from the network, so a bind
    /// address it will not use must not be able to refuse its startup.
    #[test]
    #[cfg(feature = "web-monitoring")]
    fn a_routable_bind_only_matters_when_the_tcp_listener_participates() {
        let config = crate::web::WebConfig::enabled(0, "0.0.0.0".to_string())
            .with_tcp_enabled(false)
            .with_auth(None, None, Vec::new());
        assert!(config.validate().is_ok());
        assert!(config
            .with_tcp_enabled(true)
            .validate()
            .is_err_and(|e| e.contains("non-loopback")));
    }

    // ── Unix socket selection ──────────────────────────────────────────────

    fn unix_options(args: &[&str]) -> (Option<PathBuf>, bool) {
        let cli = parse(args);
        match cli.command {
            None => (cli.web_unix_socket, cli.no_web_unix_socket),
            Some(Commands::Run(run)) => (run.web_unix_socket, run.no_web_unix_socket),
            Some(Commands::Tui(tui)) => (tui.web_unix_socket, tui.no_web_unix_socket),
            other => panic!("unexpected command {other:?}"),
        }
    }

    /// Every invocation shape that owns local orchestration.
    const UNIX_SCOPES: [&[&str]; 3] = [&["cflx"], &["cflx", "tui"], &["cflx", "run", "--all"]];

    #[test]
    fn unix_socket_options_default_to_the_repository_default_in_every_scope() {
        for scope in UNIX_SCOPES {
            assert_eq!(
                unix_options(scope),
                (None, false),
                "scope={scope:?} must default to neither override nor opt-out"
            );
        }
    }

    #[test]
    fn an_explicit_unix_path_parses_in_every_scope() {
        for scope in UNIX_SCOPES {
            let mut args = scope.to_vec();
            args.extend_from_slice(&["--web-unix-socket", "/run/user/1000/custom.sock"]);
            assert_eq!(
                unix_options(&args),
                (Some(PathBuf::from("/run/user/1000/custom.sock")), false),
                "scope={scope:?}"
            );
        }
    }

    #[test]
    fn the_unix_opt_out_parses_in_every_scope() {
        for scope in UNIX_SCOPES {
            let mut args = scope.to_vec();
            args.push("--no-web-unix-socket");
            assert_eq!(unix_options(&args), (None, true), "scope={scope:?}");
        }
    }

    #[test]
    fn the_unix_override_and_opt_out_are_mutually_exclusive_in_every_scope() {
        for scope in UNIX_SCOPES {
            let mut args = scope.to_vec();
            args.extend_from_slice(&["--web-unix-socket", "/tmp/a.sock", "--no-web-unix-socket"]);
            let error = parse_err(&args);
            assert!(
                error.contains("cannot be used with"),
                "scope={scope:?} must report a conflict, got {error}"
            );
        }
    }

    /// `--web` adds TCP; it never turns the Unix listener off.
    #[test]
    fn the_web_flag_leaves_the_unix_selection_alone() {
        for scope in UNIX_SCOPES {
            let mut args = scope.to_vec();
            args.push("--web");
            assert_eq!(unix_options(&args), (None, false), "scope={scope:?}");
        }
    }

    /// Bare `cflx` forwards its own Unix options into `TuiArgs` exactly as
    /// `main` does, so the default TUI is not a second, weaker contract.
    #[test]
    fn bare_invocation_forwards_its_unix_options_to_the_tui_args() {
        let bare = super::tests::bare_tui_args(&["cflx", "--web-unix-socket", "/tmp/bare.sock"]);
        assert_eq!(bare.web_unix_socket, Some(PathBuf::from("/tmp/bare.sock")));
        assert!(!bare.no_web_unix_socket);

        let opted_out = super::tests::bare_tui_args(&["cflx", "--no-web-unix-socket"]);
        assert_eq!(opted_out.web_unix_socket, None);
        assert!(opted_out.no_web_unix_socket);
    }

    #[test]
    fn help_documents_both_unix_socket_choices() {
        for help in [
            Cli::command().render_long_help().to_string(),
            Cli::command()
                .find_subcommand_mut("run")
                .expect("run subcommand")
                .render_long_help()
                .to_string(),
            Cli::command()
                .find_subcommand_mut("tui")
                .expect("tui subcommand")
                .render_long_help()
                .to_string(),
        ] {
            assert!(help.contains("--web-unix-socket"), "help={help}");
            assert!(help.contains("--no-web-unix-socket"), "help={help}");
            assert!(
                help.contains("cflx-api.sock"),
                "the default socket name must be discoverable from help, help={help}"
            );
        }
    }

    /// The parsed options must reach the resolver that decides the actual path,
    /// including the non-Git refusal an operator will hit outside a repository.
    #[test]
    #[cfg(all(unix, feature = "web-monitoring"))]
    fn parsed_unix_options_flow_into_socket_resolution() {
        use crate::web::unix_socket::{resolve_unix_socket, UnixSocketSelection};
        use std::path::Path;

        let (explicit, opt_out) = unix_options(&["cflx", "run", "--all"]);
        assert_eq!(
            resolve_unix_socket(explicit.as_deref(), opt_out, Some(Path::new("/repo/.git")))
                .unwrap(),
            UnixSocketSelection::Bind(PathBuf::from("/repo/.git/cflx-api.sock"))
        );
        assert!(
            resolve_unix_socket(explicit.as_deref(), opt_out, None).is_err(),
            "outside Git the default must be refused rather than guessed"
        );

        let (explicit, opt_out) =
            unix_options(&["cflx", "tui", "--web-unix-socket", "/tmp/x.sock"]);
        assert_eq!(
            resolve_unix_socket(explicit.as_deref(), opt_out, None).unwrap(),
            UnixSocketSelection::Bind(PathBuf::from("/tmp/x.sock"))
        );

        let (explicit, opt_out) = unix_options(&["cflx", "--no-web-unix-socket"]);
        assert_eq!(
            resolve_unix_socket(explicit.as_deref(), opt_out, None).unwrap(),
            UnixSocketSelection::Disabled
        );
    }

    /// Parsing of the read-only `judge-eval` namespace.
    mod judge_evaluation_cli {
        use super::*;

        fn summary(argv: &[&str]) -> JudgeEvalSummaryArgs {
            match Cli::parse_from(argv).command {
                Some(Commands::JudgeEval(args)) => match args.command {
                    JudgeEvalCommands::Summary(summary) => summary,
                },
                other => panic!("expected judge-eval summary, got {other:?} for {argv:?}"),
            }
        }

        #[test]
        fn summary_parses_its_selectors() {
            let args = summary(&[
                "cflx",
                "judge-eval",
                "summary",
                "--purpose",
                "parallel_dependency",
                "--since-days",
                "7",
                "--project",
                "conflux-a1b2c3d4",
                "--json",
            ]);

            assert_eq!(args.purpose, JudgeEvalPurpose::ParallelDependency);
            assert_eq!(args.purpose.as_str(), "parallel_dependency");
            assert_eq!(args.since_days, Some(7));
            assert_eq!(args.project.as_deref(), Some("conflux-a1b2c3d4"));
            assert!(args.json);
        }

        #[test]
        fn every_selector_except_purpose_is_optional() {
            let args = summary(&[
                "cflx",
                "judge-eval",
                "summary",
                "--purpose",
                "parallel_dependency",
            ]);

            assert_eq!(args.since_days, None, "the window is defaulted downstream");
            assert_eq!(args.project, None);
            assert!(!args.json, "human output is the default");
        }

        #[test]
        fn purpose_is_required_and_closed() {
            // Required: a store cannot be chosen without naming one.
            assert!(
                Cli::try_parse_from(["cflx", "judge-eval", "summary"]).is_err(),
                "--purpose must be required"
            );
            // Closed: an unrecorded purpose is a usage error rather than an
            // empty summary indistinguishable from an unused judge.
            assert!(
                Cli::try_parse_from([
                    "cflx",
                    "judge-eval",
                    "summary",
                    "--purpose",
                    "some_other_purpose",
                ])
                .is_err(),
                "an unknown purpose must not parse"
            );
        }

        #[test]
        fn since_days_rejects_zero_negative_and_oversized_windows() {
            for bad in ["0", "-1", "3651", "seven", "1.5", ""] {
                assert!(
                    Cli::try_parse_from([
                        "cflx",
                        "judge-eval",
                        "summary",
                        "--purpose",
                        "parallel_dependency",
                        "--since-days",
                        bad,
                    ])
                    .is_err(),
                    "--since-days {bad} must be a usage error"
                );
            }

            for good in ["1", "30", "3650"] {
                let args = summary(&[
                    "cflx",
                    "judge-eval",
                    "summary",
                    "--purpose",
                    "parallel_dependency",
                    "--since-days",
                    good,
                ]);
                assert_eq!(args.since_days, Some(good.parse().expect("bound")));
            }
        }

        #[test]
        fn the_namespace_exposes_only_the_read_only_summary() {
            // Export, purge, and any other mutation are separate reviewable
            // changes; none of them may be reachable from this build.
            for verb in ["export", "purge", "delete", "clear", "prune"] {
                assert!(
                    Cli::try_parse_from(["cflx", "judge-eval", verb]).is_err(),
                    "`judge-eval {verb}` must not exist"
                );
            }
            assert!(
                Cli::try_parse_from(["cflx", "judge-eval"]).is_err(),
                "a subcommand is required"
            );
        }

        #[test]
        fn judge_eval_is_named_for_diagnostics_like_every_other_subcommand() {
            let cli = Cli::parse_from([
                "cflx",
                "judge-eval",
                "summary",
                "--purpose",
                "parallel_dependency",
            ]);
            assert_eq!(cli.subcommand_name(), Some("judge-eval"));
            // And it is a real subcommand rather than a hidden one.
            assert!(Cli::command()
                .get_subcommands()
                .any(|sub| sub.get_name() == "judge-eval" && !sub.is_hide_set()));
        }
    }
}