loopflow 0.12.19

Run steps and flows with coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
use std::path::PathBuf;

use clap::{Args, Parser, Subcommand};

pub mod commands;
pub mod discovery;
pub mod output;

#[derive(Parser, Debug, Default)]
#[command(name = "lf")]
#[command(about = "Open Loopflow or run its CLI")]
#[command(version = crate::build_info::BUILD_VERSION)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Commands>,

    /// List the skill and flow catalog
    #[arg(short, long)]
    pub list: bool,

    /// Direction(s) to apply (repeatable or comma-separated)
    #[arg(
        short = 'd',
        long = "direction",
        value_delimiter = ',',
        short_alias = 'D'
    )]
    pub direction: Vec<String>,

    /// Exclude config default directions
    #[arg(long = "no-direction")]
    pub no_direction: bool,

    /// Docs paths, globs, or directories to include in context
    #[arg(long = "docs", value_delimiter = ',')]
    pub docs: Vec<String>,

    /// Include clipboard content in prompt
    #[arg(short = 'c', long = "clipboard", short_alias = 'C')]
    pub clipboard: bool,

    /// Model to use (harness or harness:model)
    #[arg(short = 'm', long = "model", short_alias = 'M')]
    pub model: Option<String>,

    /// Prefer this managed provider login before the normal route. Repeat to
    /// select provider-qualified preferences such as `claude=jack@`.
    /// Logins spend; a profile is only the Chrome venue accounts log in
    /// through, so it is never a run-time selector.
    #[arg(
        id = "preferred_provider_account",
        long = "account",
        value_name = "SELECTOR",
        conflicts_with = "restricted_provider_account"
    )]
    pub account: Vec<String>,

    /// Restrict this invocation and its children to exactly these managed
    /// provider logins. Providers without a selection are unavailable.
    #[arg(
        id = "restricted_provider_account",
        long = "only-account",
        value_name = "SELECTOR",
        conflicts_with = "preferred_provider_account"
    )]
    pub only_account: Vec<String>,

    /// Internal SSH compatibility and broker-connectivity probe.
    #[arg(long = "__account-lease-probe", hide = true)]
    pub account_lease_probe: bool,

    /// Skip permission prompts
    #[arg(long)]
    pub yolo: bool,

    /// Run interactively
    #[arg(short = 'i', long = "interactive", short_alias = 'I')]
    pub interactive: bool,

    /// Run in batch/headless mode
    #[arg(short = 'b', long = "batch", short_alias = 'B')]
    pub batch: bool,

    /// Hand off Claude, Codex, or OpenCode to the terminal (overrides session.launch)
    #[arg(long, conflicts_with = "ide")]
    pub tui: bool,

    /// Hand off Claude or Codex to the vendor app (overrides session.launch)
    #[arg(long)]
    pub ide: bool,

    /// Enable Chrome integration (Claude)
    #[arg(long)]
    pub chrome: bool,

    /// Disable Chrome integration (Claude)
    #[arg(long = "no-chrome", overrides_with = "chrome")]
    pub no_chrome: bool,

    /// Include files changed on branch
    #[arg(long = "diff-files")]
    pub diff_files: bool,

    /// Exclude files changed on branch
    #[arg(long = "no-diff-files", overrides_with = "diff_files")]
    pub no_diff_files: bool,

    /// Include raw git diff
    #[arg(long = "diff")]
    pub diff: bool,

    /// Exclude raw git diff
    #[arg(long = "no-diff", overrides_with = "diff")]
    pub no_diff: bool,

    /// Maximum agent turns for this invocation
    #[arg(long = "max-turns")]
    pub max_turns: Option<u32>,

    /// Select Wave Work, or qualify a selected Project or Task
    #[arg(short = 'w', long = "wave", short_alias = 'W')]
    pub wave: Option<String>,

    /// Select Project Work, or qualify a selected Task
    #[arg(long = "project", value_name = "SELECTOR")]
    pub project: Option<String>,

    /// Select Task Work
    #[arg(long = "task", value_name = "ISSUE")]
    pub task: Option<String>,

    /// Select one Work for a direct Skill or inline prompt
    #[arg(
        long = "as",
        value_name = "WORK",
        conflicts_with_all = ["wave", "project", "task"]
    )]
    pub as_work: Option<String>,

    /// Keep a Work-bound internal launch in this exact checkout.
    #[arg(long = "__cwd", value_name = "PATH", hide = true)]
    pub bound_cwd: Option<PathBuf>,

    /// Exclude loopflow operating guidance
    #[arg(long = "no-loopflow")]
    pub no_loopflow: bool,
}

impl Cli {
    fn toggle_setting(enabled: bool, disabled: bool) -> Option<bool> {
        if enabled {
            Some(true)
        } else if disabled {
            Some(false)
        } else {
            None
        }
    }

    /// Get chrome setting: Some(true) if --chrome, Some(false) if --no-chrome, None if neither.
    pub fn chrome_setting(&self) -> Option<bool> {
        Self::toggle_setting(self.chrome, self.no_chrome)
    }

    /// Get diff_files setting: Some(true) if --diff-files, Some(false) if --no-diff-files, None if neither.
    pub fn diff_files_setting(&self) -> Option<bool> {
        Self::toggle_setting(self.diff_files, self.no_diff_files)
    }

    /// Get diff setting: Some(true) if --diff, Some(false) if --no-diff, None if neither.
    pub fn diff_setting(&self) -> Option<bool> {
        Self::toggle_setting(self.diff, self.no_diff)
    }

    /// The most specific Work selected for a direct skill Run.
    pub fn work_subject_selector(&self) -> Option<String> {
        self.as_work.clone().or_else(|| {
            self.task
                .as_ref()
                .map(|task| format!("task:{task}"))
                .or_else(|| {
                    self.project
                        .as_ref()
                        .map(|project| format!("project:{project}"))
                })
                .or_else(|| self.wave.as_ref().map(|wave| format!("wave:{wave}")))
        })
    }
}

#[derive(Args, Debug, Clone)]
pub struct ScreenshotArgs {
    /// URL or local HTML file to capture
    pub source: String,

    /// PNG destination
    #[arg(short = 'o', long = "output")]
    pub output: PathBuf,

    /// Viewport width in pixels
    #[arg(long, default_value_t = 1440)]
    pub width: u32,

    /// Viewport height in pixels
    #[arg(long, default_value_t = 900)]
    pub height: u32,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Run an inline prompt
    #[command(name = ":")]
    Inline {
        #[arg(trailing_var_arg = true)]
        prompt: Vec<String>,
    },
    /// Open or focus Loopflow.app
    Desktop,
    /// Capture a URL or local HTML file without claiming the user's browser
    Screenshot {
        #[command(flatten)]
        screenshot: ScreenshotArgs,
    },
    /// Internal owner-loss supervisor for one browser capture.
    #[command(name = "__screenshot-supervisor", hide = true)]
    ScreenshotSupervisor {
        #[command(flatten)]
        screenshot: ScreenshotArgs,
    },
    /// Internal provider callback that records one native interactive session.
    #[command(name = "__provider-session", hide = true)]
    ProviderSession,
    /// Open a durable human session and wait for the human to complete it
    Ask {
        #[command(flatten)]
        ask: AskArgs,
    },
    /// Inspect and continue Sessions
    Session {
        #[command(subcommand)]
        cmd: SessionCommand,
    },
    /// Internal installer transaction entry point.
    #[command(hide = true)]
    Install {
        #[command(subcommand)]
        cmd: InstallCommand,
    },
    /// Pull request lifecycle
    Pr {
        #[command(subcommand)]
        cmd: Option<PrCommand>,
    },
    /// Worktree operations
    Wt {
        #[command(subcommand)]
        cmd: WtCommand,
    },
    /// Rebase current branch onto target (default: main)
    Rebase {
        /// Print the planned rebase strategy without mutating git
        #[arg(long, conflicts_with_all = ["manual", "continue_rebase", "abort"])]
        plan: bool,
        /// Keep the rebase local and leave conflicts for this process to resolve
        #[arg(long, conflicts_with_all = ["plan", "continue_rebase", "abort"])]
        manual: bool,
        /// Stage resolved conflict paths and continue the local rebase
        #[arg(long = "continue", conflicts_with_all = ["plan", "manual", "abort"])]
        continue_rebase: bool,
        /// Abort the local rebase in progress
        #[arg(long, conflicts_with_all = ["plan", "manual", "continue_rebase"])]
        abort: bool,
        /// Explicitly claim a raw rebase that has no Loopflow owner
        #[arg(long, conflicts_with_all = ["plan", "manual"])]
        adopt: bool,
        /// Branch to rebase onto
        onto: Option<String>,
    },
    /// Commit changes
    Commit {
        #[arg(short = 'm', long = "message", short_alias = 'M')]
        message: Option<String>,
        #[arg(short = 'p', long = "push", short_alias = 'P')]
        push: bool,
        #[arg(long = "no-add")]
        no_add: bool,
    },
    /// Provider authentication for local lf skills and ops
    Auth {
        #[command(subcommand)]
        cmd: AuthCommand,
    },
    /// Chrome access venues used during provider login ceremonies
    Profile {
        #[command(subcommand)]
        cmd: ProfileCommand,
    },
    /// Route providers through ordered managed accounts
    Route {
        #[command(subcommand)]
        cmd: RouteCommand,
    },
    /// Release operations (run, check, notes, bump, tag, status)
    Release {
        #[command(subcommand)]
        cmd: ReleaseCommand,
    },
    /// Linear Initiatives, Projects, and tasks for waves
    Pm {
        #[command(subcommand)]
        cmd: PmCommand,
    },
    /// Inspect this Home and observe routes to other Homes
    Home {
        #[command(subcommand)]
        cmd: HomeCommand,
    },
    /// Compile loopflow skills into your home vendor Skills directories.
    #[command(name = "sync-skills", hide = true)]
    SyncSkills {
        /// Confirm writes under ~/ without prompting
        #[arg(short = 'y', long = "yes")]
        yes: bool,
        /// Keep stale loopflow-generated skills
        #[arg(long = "no-prune")]
        no_prune: bool,
    },
    /// Local launchd jobs that run lf commands on a schedule
    Cron {
        #[command(subcommand)]
        cmd: CronCommand,
    },
    /// Run a Wave's listener, thread, and residency. Steerable.
    ///
    /// By convention this is the wave loop's entrypoint — a served mind is one
    /// you can chat with while it runs.
    Wave {
        /// Wave name
        name: String,
        /// Take over even if another live Wave is registered
        #[arg(long)]
        force: bool,
    },
    /// Start one or more Waves on this machine.
    Start {
        /// Wave names. With none, starts eligible Waves in the current repo.
        waves: Vec<String>,
        /// Internal identity bindings carried by an explicit Home SSH hop.
        #[arg(long = "wave-id", value_name = "NAME=ID", hide = true)]
        wave_ids: Vec<String>,
        #[arg(long)]
        json: bool,
    },
    /// Stop a served wave gracefully
    Stop {
        /// Wave name
        name: String,
    },
    /// Pause new turns while keeping the Wave listener available.
    Pause {
        /// Wave name
        name: String,
        /// Emit the resulting turn intent as JSON
        #[arg(long)]
        json: bool,
    },
    /// Resume new turns for a paused Wave.
    Resume {
        /// Wave name
        name: String,
        /// Emit the resulting turn intent as JSON
        #[arg(long)]
        json: bool,
    },
    /// Internal: the resident body a listener spawns for its own wave. Never
    /// booted by hand — `lf wave` owns the listener half.
    #[command(name = "__resident", hide = true)]
    Resident {
        /// Wave name
        name: String,
    },
    /// Internal resident primitive: execute one expanded top-level flow step.
    #[command(name = "__flow-step", hide = true)]
    FlowStep {
        flow: String,
        index: usize,
        seed: String,
    },
    /// Project lifecycle operations
    Project {
        #[command(subcommand)]
        cmd: ProjectCommand,
    },
    /// Linear-backed Task lifecycle
    Task {
        #[command(subcommand)]
        cmd: TaskCommand,
    },
    /// Inspect and control stable Wave, Project, or Task Work
    Work {
        #[command(subcommand)]
        cmd: WorkCommand,
    },
    /// Internal: run a Project or Task body under the ambient Run context
    #[command(name = "__work", hide = true)]
    WorkRunner {
        #[arg(value_parser = ["project", "task"])]
        kind: String,
        work_id: String,
    },
    /// Measure this codebase: lines and tokens per directory (tracked files only)
    Tokens {
        /// Emit as JSON
        #[arg(long)]
        json: bool,
        /// Walk git history instead: the codebase's size on each day it changed
        #[arg(long, value_name = "DAYS")]
        days: Option<u32>,
    },
    /// Show direct provider-authored usage from Home-local Run records
    Usage {
        /// Emit Run usage evidence as JSON
        #[arg(long)]
        json: bool,
        /// Run window, in days (zero means all time)
        #[arg(long, default_value_t = 30)]
        days: u32,
        /// Limit to Runs attributed to one Wave
        #[arg(long)]
        wave: Option<String>,
        /// Limit to Runs attributed to one Project
        #[arg(long)]
        project: Option<String>,
        /// Limit to Runs attributed to one Task
        #[arg(long)]
        task: Option<String>,
    },
    /// Internal: render the repository maintainer scorecard for telemetry-daily
    #[command(name = "__telemetry-scorecard", hide = true)]
    TelemetryScorecard {
        /// Emit structured JSON for operator automation
        #[arg(long)]
        json: bool,
    },
    /// Show how failed CI is detected, repaired, and landed across this Home
    Ci {
        /// Relative window (7d, 24h, 30m) or RFC3339 start
        #[arg(long, default_value = "7d")]
        since: String,
        /// Scope to one Wave
        #[arg(long)]
        wave: Option<String>,
        /// Scope to one GitHub owner/repo
        #[arg(long)]
        repo: Option<String>,
        /// Emit the complete incident report as JSON
        #[arg(long)]
        json: bool,
    },
    /// Print one parseable snapshot of live Loopflow call trees
    Ps {
        /// Emit the versioned activity snapshot as JSON
        #[arg(long)]
        json: bool,
    },
    /// Refresh live Loopflow call trees on a terminal; print once when redirected
    Top {
        /// Emit one versioned activity snapshot as JSON
        #[arg(long)]
        json: bool,
    },
    /// Reap registered orphan providers and remove dead process receipts
    Prune {
        /// Show exact targets without changing process or receipt state
        #[arg(long)]
        dry_run: bool,
        /// Emit the versioned prune report as JSON
        #[arg(long)]
        json: bool,
    },
    /// Audit the local run ledger: continuity, vocabulary, attribution, identity, lineage, coverage
    Doctor {
        /// Emit the audit as JSON
        #[arg(long)]
        json: bool,
    },
    /// List available skills and flows, including authored and collapsed flows
    List,
    /// List every wave in the registry (running and stopped), marking which
    /// have a live server. Local-only query over the shared ledger.
    Ls {
        /// Emit the wave snapshot as JSON (Loopflow's dashboard snapshot)
        #[arg(long)]
        json: bool,
        /// List Waves from every repository on this machine, not just the
        /// current repository (worktrees collapse to their main checkout).
        #[arg(long)]
        all: bool,
    },
    /// Show one Wave's Project/Task hierarchy, Runs, and live loop
    /// state from the registry. Defaults to the ambient wave (`LF_WAVE_ID`).
    Status {
        /// Wave name (default: the ambient wave)
        wave: Option<String>,
        /// Emit the status snapshot as JSON
        #[arg(long)]
        json: bool,
    },
    /// Show the current repository's roadmap: every open Task across the repo's
    /// Waves, joined to live evidence and bucketed into Now / Waiting /
    /// Available / Later. `--wave` scopes it; `--all` spans every repository on
    /// this machine. Local-only, deterministic.
    Roadmap {
        /// Scope to one Wave (default: every Wave in the current repository)
        #[arg(long)]
        wave: Option<String>,
        /// Emit the roadmap snapshot as JSON
        #[arg(long)]
        json: bool,
        /// Span every repository on this machine, not just the current one.
        #[arg(long)]
        all: bool,
    },
    /// Show one ordered record of durable Work, Run, PR, and Steer facts
    Activity {
        /// Relative window (7d, 24h, 30m) or RFC3339 start
        #[arg(long, default_value = "7d")]
        since: String,
        /// Maximum rows after Work filters (1-200)
        #[arg(long, default_value_t = 50)]
        limit: usize,
        /// Scope to one Wave by name
        #[arg(long)]
        wave: Option<String>,
        /// Scope to one Project by slug
        #[arg(long)]
        project: Option<String>,
        /// Scope to one Task by Linear identifier
        #[arg(long)]
        task: Option<String>,
        /// Emit the typed activity snapshot as JSON
        #[arg(long)]
        json: bool,
    },
    /// Show recent agent-backed skill runs with context and token evidence
    Runs {
        /// Inspect one Run by full id or unambiguous displayed prefix
        #[arg(conflicts_with_all = ["task", "project", "wave"])]
        run: Option<String>,
        /// Print the Run's append-only event stream verbatim
        #[arg(long, requires = "run", conflicts_with_all = ["json", "resume"])]
        events: bool,
        /// Resume the Run's provider-native interactive session
        #[arg(long, requires = "run", conflicts_with_all = ["events", "json"])]
        resume: bool,
        /// Drill to one roadmap Task by its Linear issue identifier (e.g. W2-122)
        #[arg(long)]
        task: Option<String>,
        /// Drill to one roadmap Project by slug
        #[arg(long)]
        project: Option<String>,
        /// Scope to one Wave by name
        #[arg(long)]
        wave: Option<String>,
        /// Emit the run history as JSON
        #[arg(long)]
        json: bool,
    },
    /// Launch the exact provider request recorded by a prior Run as a child Run.
    Replay {
        /// Full Run id or an unambiguous displayed prefix
        run: String,
    },
    /// Observe wave-chat message(s) and print a reply only if one is warranted.
    /// A direct capability: no listener, resident, or governance loop.
    Reply {
        /// Wave name
        wave: String,
        /// Recent message text (reads stdin when omitted)
        #[arg(trailing_var_arg = true)]
        text: Vec<String>,
        /// Override the provider (e.g. `claude`, `codex`); default is configured
        #[arg(long)]
        agent: Option<String>,
        /// Cap provider turns for the reply
        #[arg(long)]
        max_turns: Option<u32>,
    },
    /// Converse with a served mind's thread; --follow replays it and --steer
    /// reaches the live body.
    Chat {
        /// Message text (reads stdin when omitted unless --follow or --history)
        #[arg(trailing_var_arg = true)]
        text: Vec<String>,
        /// Replay and follow the thread while typed lines post into it.
        #[arg(long, conflicts_with_all = ["text", "history", "json", "limit"])]
        follow: bool,
        /// Inject into a live steer-capable turn; otherwise queue.
        #[arg(long, conflicts_with_all = ["parent", "history", "json", "limit"])]
        steer: bool,
        /// Read the latest durable turns without requiring a live listener.
        #[arg(long, conflicts_with = "text")]
        history: bool,
        /// Emit the durable history snapshot as JSON.
        #[arg(long, requires = "history")]
        json: bool,
        /// Maximum durable turns to return (default: 12).
        #[arg(long, requires = "history")]
        limit: Option<usize>,
        /// Select one immutable conversation epoch.
        #[arg(long, requires = "history")]
        epoch: Option<String>,
        #[command(flatten)]
        target: WaveTargetArgs,
    },
    // architecture-shim: retired-op
    // Same reservation for the retired `lf op` namespace, which held every
    // operation before the runtime collapsed to waves, projects, and tasks.
    // Without it, `lf op land` reports a missing skill named `op` instead of
    // naming the command that replaced it.
    #[command(
        name = "op",
        hide = true,
        about = "Removed; the operations are top-level (`lf pr`, `lf rebase`, `lf wt`, `lf pm`)",
        arg_required_else_help = true
    )]
    RetiredOp {
        #[arg(required = true, value_name = "COMMAND", value_parser = reject_retired_op)]
        removed: String,
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        rest: Vec<String>,
    },
    /// Run lf on a Home or SSH host carrying your local credentials.
    ///
    /// Resolves local credentials and forwards a foreground account lease over
    /// SSH; Loopflow writes no managed provider credential on the remote. The
    /// Doppler token is never forwarded — name specific secrets with `--secret`
    /// to resolve them locally. Example: `lf ssh <home-id> pr open`.
    Ssh {
        /// Prefer this origin account when the remote lf chooses a provider.
        #[arg(
            id = "ssh_preferred_provider_account",
            long = "account",
            value_name = "SELECTOR",
            conflicts_with = "ssh_restricted_provider_account"
        )]
        origin_account: Vec<String>,
        /// Restrict remote provider launches to these origin accounts.
        #[arg(
            id = "ssh_restricted_provider_account",
            long = "only-account",
            value_name = "SELECTOR",
            conflicts_with = "ssh_preferred_provider_account"
        )]
        origin_only_account: Vec<String>,
        /// HomeId (preferred), SSH alias, or user@host
        target: String,
        /// Repository path on the remote, relative to $HOME
        #[arg(long = "repo")]
        repo: Option<String>,
        /// Doppler secret to resolve locally and forward as an env var
        /// (repeatable). The Doppler token itself is never forwarded.
        #[arg(long = "secret")]
        secret: Vec<String>,
        /// Forward the ssh-agent (`ssh -A`). Off by default: git pushes use the
        /// forwarded GH_TOKEN over HTTPS, so agent forwarding is unneeded risk.
        #[arg(long = "forward-agent")]
        forward_agent: bool,
        /// Arguments for the remote lf. The target is the boundary: every
        /// argument after it belongs to the remote invocation.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        lf_args: Vec<String>,
    },
    /// Run a flow by name — the explicit form for names that collide with a
    /// built-in command
    Flow {
        /// Flow name
        name: String,
        /// Message for the flow
        #[arg(trailing_var_arg = true)]
        args: Vec<String>,
    },
    /// Run a skill (skill) by name — the explicit form
    Skill {
        /// Skill name
        name: String,
        /// Message for the skill
        #[arg(trailing_var_arg = true)]
        args: Vec<String>,
    },
    /// External: skill/flow name (when no subcommand matches)
    #[command(external_subcommand)]
    External(Vec<String>),
}

#[derive(Args, Debug, Default)]
pub struct AskArgs {
    /// What the human-facing session should work through
    #[arg(trailing_var_arg = true, value_name = "QUESTION")]
    pub question: Vec<String>,
}

#[derive(Subcommand, Debug)]
pub enum SessionCommand {
    /// List Sessions
    List {
        #[arg(long)]
        json: bool,
        /// Include waiting steps from every repository on this machine
        #[arg(long)]
        all: bool,
    },
    /// Open or resume one session in this terminal
    Open {
        id: String,
        #[arg(long)]
        json: bool,
        /// Stop Loopflow-owned clients before resuming here
        #[arg(long, conflicts_with = "try_open")]
        replace: bool,
        /// Ask the provider to resume even when another client is active
        #[arg(long = "try", conflicts_with = "replace")]
        try_open: bool,
    },
    /// Complete an interactive or ad-hoc Ask session
    Complete { id: String },
    /// Mark the active session ready for human action
    Ready {
        #[arg(value_name = "SUMMARY", required = true, num_args = 1..)]
        summary: Vec<String>,
    },
    /// Approve a ready Task FlowStep and continue the Task
    Approve {
        id: String,
        #[arg(value_name = "SUMMARY", required = true, num_args = 1..)]
        summary: Vec<String>,
    },
    /// Iterate on a Task FlowStep with new direction
    Iterate {
        id: String,
        #[arg(value_name = "DIRECTION", required = true, num_args = 1..)]
        direction: Vec<String>,
    },
    /// Run the exact human skill in its durable terminal
    #[command(name = "serve-flow", hide = true)]
    ServeFlow {
        task_id: crate::work::task::TaskId,
        flow: String,
        node_id: String,
        skill: String,
        iteration: u32,
    },
    /// Run one ad-hoc human Ask in its durable terminal
    #[command(name = "serve-ask", hide = true)]
    ServeAsk { id: String },
    /// Stop one exact native provider Run after its human boundary settles
    #[command(name = "stop-run", hide = true)]
    StopRun { run_id: crate::durable::RunId },
}

#[derive(Subcommand, Debug)]
pub enum WorkCommand {
    /// Show current Work state and placement
    Status {
        #[arg(value_parser = ["wave", "project", "task"])]
        kind: String,
        id: String,
        #[arg(long)]
        json: bool,
    },
    /// Record Wave Work's Home
    Place {
        #[arg(value_parser = ["wave"])]
        kind: String,
        id: String,
        home_id: crate::durable::HomeId,
        #[arg(long)]
        json: bool,
    },
    /// Rename or rehome stopped Wave Work without changing its identity
    Relocate {
        #[arg(value_parser = ["wave"])]
        kind: String,
        id: String,
        #[arg(long)]
        repo: Option<PathBuf>,
        #[arg(long)]
        name: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Allow this Home to pursue Work
    Enable {
        #[arg(value_parser = ["wave", "project", "task"])]
        kind: String,
        id: String,
        #[arg(long)]
        json: bool,
    },
    /// Prevent this Home from starting new pursuit of Work
    Disable {
        #[arg(value_parser = ["wave", "project", "task"])]
        kind: String,
        id: String,
        #[arg(long)]
        json: bool,
    },
    /// Append authored direction with User or generic Run provenance
    Steer {
        #[arg(value_parser = ["wave", "project", "task"])]
        kind: String,
        id: String,
        message: String,
        #[arg(long)]
        json: bool,
    },
    /// Refuse interruption until Work has an exact process owner
    Interrupt {
        #[arg(value_parser = ["wave", "project", "task"])]
        kind: String,
        id: String,
        #[arg(long)]
        json: bool,
    },
    /// Abandon the Work
    Abandon {
        #[arg(value_parser = ["wave", "project", "task"])]
        kind: String,
        id: String,
        #[arg(long)]
        reason: String,
        #[arg(long)]
        json: bool,
    },
}

/// Name the surviving spelling for each retired `lf op` verb. Prompts, `.lf/`
/// adaptations, and older installed binaries still say `lf op …`; a caller who
/// types it should learn where the operation went, not that a skill named `op`
/// is missing. Nothing here executes — it only fails with a memory.
fn reject_retired_op(sub: &str) -> Result<String, String> {
    let hint = match sub {
        // Ephemeral rotation is gone, not renamed: a worker forks from and
        // targets its parent branch, so no branch rotates through a worktree.
        "next" | "advance" => {
            "it has no replacement — dispatch work with `lf task run <issue-id>`, \
             and the worker forks from and targets its parent branch"
                .to_string()
        }
        "pr" => "use `lf pr open`".to_string(),
        "submit" => "use `lf pr submit`".to_string(),
        "land" => "use `lf pr land`".to_string(),
        "dispatch" => "use `lf task run <issue-id>`".to_string(),
        "auth" | "commit" | "cron" | "doctor" | "pm" | "rebase" | "release" | "sync-skills"
        | "wt" => format!("use `lf {sub}`"),
        _ => "the operations are top-level now — see `lf --help`".to_string(),
    };
    Err(format!("`lf op {sub}` was removed; {hint}"))
}

/// Wave targeting for `lf chat`: default is the invoking context's wave
/// (`LF_WAVE_ID` env, else the worktree name).
#[derive(Args, Debug, Clone, Default)]
pub struct WaveTargetArgs {
    /// Target wave by name
    #[arg(short = 'w', long = "wave", conflicts_with = "parent")]
    pub wave: Option<String>,
    /// Target the invoking wave's parent (escalation up the wave tree)
    #[arg(long)]
    pub parent: bool,
}

#[derive(Subcommand, Debug)]
pub enum ProjectCommand {
    /// Ensure tracked Project Work without starting a controller
    Prepare {
        /// Linear Project UUID or unique slug
        project_id: String,
        #[arg(long)]
        directive: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Create a Linear Project first, then start its durable Project
    Start {
        title: String,
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
        #[arg(long)]
        directive: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Start or resume the current Work for an existing Linear Project
    Run {
        /// Linear Project UUID or unique slug
        project_id: String,
        #[arg(long)]
        directive: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Show durable Project state and Home-owned liveness evidence
    Status {
        /// Linear Project UUID, unique slug, or historical Project id
        project_id: String,
        #[arg(long)]
        json: bool,
    },
    /// Redirect Project Work now, relaunching its provider when needed
    Steer {
        project_id: String,
        message: String,
        #[arg(long)]
        json: bool,
    },
    /// Interrupt the active Project turn
    Interrupt {
        project_id: String,
        #[arg(long)]
        json: bool,
    },
    /// Wait without polling an LM
    Wait {
        project_id: String,
        #[arg(long, default_value = "terminal", value_parser = ["waiting", "terminal"])]
        until: String,
        #[arg(long)]
        timeout: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Resume the same Project, optionally handing its next body to another agent
    Resume {
        project_id: String,
        #[arg(long)]
        model: Option<String>,
        #[arg(long, requires = "model")]
        reason: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Attach to the writable Project control terminal
    Attach { project_id: String },
    /// End Project pursuit without deleting its durable history
    Abandon {
        project_id: String,
        #[arg(long)]
        reason: String,
        #[arg(long)]
        json: bool,
    },
    /// Promote a project into a resident child wave through the authored flow
    Promote {
        /// Linear Project slug under the parent wave
        slug: String,
        /// Parent wave (default: ambient wave)
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
    },
}

#[derive(Subcommand, Debug)]
pub enum TaskCommand {
    /// Ensure tracked Task Work and its worktree without starting a controller
    Prepare {
        issue: String,
        #[arg(long)]
        name: Option<String>,
        /// Fork this Task's worktree from another Task's active PR
        #[arg(long = "stack-on", value_name = "PARENT_TASK")]
        stack_on: Option<String>,
        #[arg(long)]
        directive: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Ensure its Project, then start or return the existing Linear task
    Run {
        issue: String,
        #[arg(long)]
        name: Option<String>,
        /// Fix cycle: first incident, finally ship-demo (human gates at the demo)
        #[arg(long, conflicts_with = "feature")]
        fix: bool,
        /// Feature cycle: design review first, configured-path demo before settlement
        #[arg(long, alias = "feat", conflicts_with = "fix")]
        feature: bool,
        /// Override the Project's first flow for a new Task
        #[arg(long, value_name = "FLOW")]
        first: Option<String>,
        /// Override the Project's loop flow for a new Task
        #[arg(long = "loop", value_name = "FLOW")]
        loop_: Option<String>,
        /// Override the Project's finally flow for a new Task
        #[arg(long, value_name = "FLOW")]
        finally: Option<String>,
        /// Fork this Task's worktree from another Task's active PR
        #[arg(long = "stack-on", value_name = "PARENT_TASK")]
        stack_on: Option<String>,
        #[arg(long)]
        directive: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Create a Linear task, ensure its Project, then start its Task
    Start {
        /// Required Linear Project id or slug
        project_id: String,
        /// Task title; omitted when stdin supplies the report and first line
        title: Option<String>,
        #[arg(long)]
        name: Option<String>,
        /// Fix cycle: first incident, finally ship-demo (human gates at the demo)
        #[arg(long, conflicts_with = "feature")]
        fix: bool,
        /// Feature cycle: design review first, configured-path demo before settlement
        #[arg(long, alias = "feat", conflicts_with = "fix")]
        feature: bool,
        /// Override the Project's first flow
        #[arg(long, value_name = "FLOW")]
        first: Option<String>,
        /// Override the Project's loop flow
        #[arg(long = "loop", value_name = "FLOW")]
        loop_: Option<String>,
        /// Override the Project's finally flow
        #[arg(long, value_name = "FLOW")]
        finally: Option<String>,
        /// Fork this Task's worktree from another Task's active PR
        #[arg(long = "stack-on", value_name = "PARENT_TASK")]
        stack_on: Option<String>,
        #[arg(long)]
        directive: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Show durable state and Home-owned liveness evidence
    Status {
        issue: String,
        #[arg(long)]
        json: bool,
    },
    /// List files changed from this Task's recorded base commit
    Changes {
        issue: String,
        #[arg(long)]
        json: bool,
    },
    /// Show this Task's patch, optionally limited to one changed file
    Diff {
        issue: String,
        path: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Read one file from this Task's worktree
    File {
        issue: String,
        path: String,
        #[arg(long)]
        json: bool,
    },
    /// Complete a Task without requiring another pull request
    Complete {
        issue: String,
        #[arg(long)]
        summary: String,
        #[arg(long)]
        json: bool,
    },
    /// Redirect the active provider turn, interrupting when live steer is unavailable
    Steer {
        issue: String,
        message: String,
        #[arg(long)]
        json: bool,
    },
    /// Interrupt the active provider turn
    Interrupt {
        issue: String,
        #[arg(long)]
        json: bool,
    },
    /// Wait without polling an LM
    Wait {
        issue: String,
        #[arg(long, default_value = "terminal", value_parser = ["submitted", "terminal"])]
        until: String,
        #[arg(long)]
        timeout: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Resume the same Task, optionally handing its next body to another agent
    Resume {
        issue: String,
        #[arg(long)]
        model: Option<String>,
        #[arg(long, requires = "model")]
        reason: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Begin a new Task kickoff in a fresh provider session
    Restart {
        issue: String,
        advice: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Explicitly recover an abandoned Task on the same worktree (User only)
    Recover {
        issue: String,
        #[arg(long)]
        reason: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Explicitly end a Task without merging
    Abandon {
        issue: String,
        #[arg(long)]
        reason: String,
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum InstallCommand {
    /// Continue one interrupted machine install switch from its pinned candidate.
    #[command(hide = true)]
    RecoverSwitch {
        /// The fixed machine switch receipt to continue.
        #[arg(long)]
        switch: String,
    },
    /// Preview whether this build may replace the global lf (read-only).
    /// Reads the shared store's migration frontier and validates executable
    /// planning references against this binary; mutates nothing and exits
    /// non-zero on refusal so a caller can gate on it.
    #[command(hide = true)]
    Preflight {
        /// Emit the structured PromotionPreview as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Validate this exact local candidate against one receipt-selected store.
    #[command(hide = true)]
    LocalPreflight {
        #[arg(long)]
        store: PathBuf,
        #[arg(long)]
        json: bool,
    },
    /// Advance the receipt-selected store with this exact candidate's registry.
    #[command(hide = true)]
    AdvanceSwitch {
        #[arg(long)]
        switch: String,
    },
    /// Promote this build to the global CLI: content-address it into ~/.lf/bin
    /// and atomically repoint the target symlink, under the exclusive promotion
    /// lock. Refuses — leaving every target unchanged — on incompatible
    /// schema or persisted executable evidence.
    #[command(hide = true)]
    Promote {
        /// Promote this exact unpublished local lf into a disposable installed Home.
        #[arg(long)]
        from_build: Option<PathBuf>,
        /// Candidate delegated to the receipt-pinned active coordinator.
        #[arg(long, hide = true)]
        coordinated_build: Option<PathBuf>,
        /// Abandon an incompatible disposable Home and fork published data again.
        #[arg(long, requires = "from_build")]
        fresh: bool,
        /// The global CLI symlink to replace (e.g. ~/.local/bin/lf).
        #[arg(long)]
        cli_target: PathBuf,
        /// The staged lfd built from the same candidate source.
        #[arg(long)]
        daemon_source: PathBuf,
        /// The global lfd symlink to replace (e.g. ~/.local/bin/lfd).
        #[arg(long)]
        daemon_target: PathBuf,
        /// A staged Loopflow.app bundle to install alongside the CLI.
        #[arg(long)]
        app_source: Option<PathBuf>,
        /// The global Loopflow.app path to replace atomically.
        #[arg(long)]
        app_target: Option<PathBuf>,
        /// A retired app bundle to remove after the new app commits.
        #[arg(long)]
        legacy_app_target: Option<PathBuf>,
        /// Regenerate global skills after the promotion commits.
        #[arg(long)]
        sync_skills: bool,
        /// Validate and print the preview but change nothing.
        #[arg(long)]
        preview: bool,
    },
    /// Repoint the global CLI at retained prior bytes only after that binary's
    /// own preflight proves it recognizes the current store frontier.
    #[command(hide = true)]
    Rollback {
        /// The global CLI symlink to replace (e.g. ~/.local/bin/lf).
        #[arg(long)]
        cli_target: PathBuf,
        /// The immutable content-addressed prior executable to activate.
        #[arg(long)]
        candidate: PathBuf,
        /// The global lfd symlink to restore with the CLI.
        #[arg(long)]
        daemon_target: PathBuf,
        /// The retained immutable lfd binary paired with the CLI candidate.
        #[arg(long)]
        daemon_candidate: PathBuf,
    },
}

#[derive(Debug, Subcommand)]
pub enum PrCommand {
    /// Show current branch's PR state
    Status,
    /// After an out-of-band merge, rotate this Task to its next serial PR,
    /// carrying committed and uncommitted follow-up onto the new branch.
    Next {
        /// Name the next serial branch (defaults to the settled PR's next slug,
        /// then the sequence number).
        slug: Option<String>,
    },
    /// Publish a PR headlessly: push, create or refresh, print state + URL.
    /// Opens no review surface.
    Publish {
        #[arg(short = 'm', long = "model", short_alias = 'M')]
        model: Option<String>,
        #[arg(long = "title")]
        title: Option<String>,
        #[arg(long = "body")]
        body: Option<String>,
    },
    /// Publish a PR, then open it for review (the GitHub page in the browser).
    /// The explicit human review action.
    Open {
        #[arg(short = 'm', long = "model", short_alias = 'M')]
        model: Option<String>,
        #[arg(long = "title")]
        title: Option<String>,
        #[arg(long = "body")]
        body: Option<String>,
    },
    /// Prepare a PR to land: rebase, clear scratch, mark ready, and assign it
    /// to you. Nothing merges until you click merge on GitHub.
    Submit {
        #[arg(long)]
        strict: bool,
        #[arg(short = 'p', long = "create-pr")]
        create_pr: bool,
        #[arg(short = 'c', long)]
        complete: bool,
        #[arg(long = "next")]
        next: Option<String>,
        #[arg(short = 'w', long = "worktree")]
        worktree: Option<String>,
        #[arg(short = 'm', long = "message")]
        message: Option<String>,
        #[arg(long = "title")]
        title: Option<String>,
        #[arg(long = "body")]
        body: Option<String>,
    },
    /// Prepare a PR, request exact-head auto-merge, and return without watching.
    Arm {
        #[arg(long)]
        strict: bool,
        #[arg(long)]
        local: bool,
        #[arg(short = 'c', long)]
        complete: bool,
        #[arg(long = "next")]
        next: Option<String>,
        #[arg(short = 'w', long = "worktree")]
        worktree: Option<String>,
        #[arg(short = 'm', long = "message")]
        message: Option<String>,
        #[arg(long = "title")]
        title: Option<String>,
        #[arg(long = "body")]
        body: Option<String>,
    },
    /// Arm and watch a PR through CI repair and authoritative merge.
    Land {
        #[arg(long)]
        strict: bool,
        #[arg(long)]
        local: bool,
        #[arg(short = 'c', long)]
        complete: bool,
        #[arg(long = "next")]
        next: Option<String>,
        #[arg(short = 'w', long = "worktree")]
        worktree: Option<String>,
        #[arg(short = 'm', long = "message")]
        message: Option<String>,
        #[arg(long = "title")]
        title: Option<String>,
        #[arg(long = "body")]
        body: Option<String>,
    },
    /// Abandon branch: close PR, remove worktree, delete branch
    Abandon {
        /// Branch to abandon (default: current)
        branch: Option<String>,
        #[arg(short = 'f', long)]
        force: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum CronCommand {
    /// Install or replace a scheduled lf invocation
    Add {
        /// Wave name passed to `lf <flow> --wave <wave>` (ambient if omitted)
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
        /// Flow or skill name to run
        #[arg(long = "flow")]
        flow: String,
        /// Fixed-daily cron expression, or the `daily` alias
        #[arg(long = "schedule", default_value = "daily")]
        schedule: String,
    },
    /// List installed loopflow cron jobs
    List {
        /// Only jobs for this Wave
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
        /// Emit machine-readable job state
        #[arg(long)]
        json: bool,
    },
    /// Validate Home authority and declared jobs without changing launchd
    Preflight {
        /// Wave whose GOAL.md `crons:` are validated
        #[arg(short = 'w', long = "wave")]
        wave: String,
    },
    /// Reconcile installed launchd jobs to match a wave's declared `crons:`
    Sync {
        /// Wave whose GOAL.md `crons:` drive the installed jobs
        #[arg(short = 'w', long = "wave")]
        wave: String,
    },
    /// Execute one installed cron job and persist its terminal receipt
    #[command(hide = true)]
    Run {
        /// Wave whose installed declaration is executed
        #[arg(short = 'w', long = "wave")]
        wave: String,
        /// Flow or skill name to run
        #[arg(long = "flow")]
        flow: String,
        /// Mark a launchd-owned invocation
        #[arg(long, hide = true)]
        scheduled: bool,
    },
    /// Show durable cron receipts
    History {
        /// Wave whose receipts are shown
        #[arg(short = 'w', long = "wave")]
        wave: String,
        /// Only receipts for this flow or skill
        #[arg(long = "flow")]
        flow: Option<String>,
        /// Receipt window in days
        #[arg(long, default_value_t = 35)]
        days: u32,
        /// Emit machine-readable receipts
        #[arg(long)]
        json: bool,
    },
    /// Ask launchd to fire an installed job
    Trigger {
        /// Wave whose installed job is fired
        #[arg(short = 'w', long = "wave")]
        wave: String,
        /// Flow or skill name to run
        #[arg(long = "flow")]
        flow: String,
        /// Wait for and return the scheduled receipt
        #[arg(long)]
        wait: bool,
        /// Maximum wait for a receipt
        #[arg(long, default_value = "15m")]
        timeout: String,
    },
    /// Uninstall a scheduled lf invocation
    Remove {
        /// Wave name passed to `lf <flow> --wave <wave>`
        #[arg(short = 'w', long = "wave")]
        wave: String,
        /// Flow or skill name to remove
        #[arg(long = "flow")]
        flow: String,
    },
}

#[derive(Subcommand, Debug)]
pub enum PmCommand {
    /// Connect a Wave to its Initiative and the repository's Team (Task prefix)
    Init {
        /// Wave name (auto-detected if omitted)
        wave: Option<String>,
        /// Wave name (flag form; same as positional wave)
        #[arg(short = 'w', long = "wave", conflicts_with_all = ["wave", "all"])]
        wave_flag: Option<String>,
        /// Recursively initialize every Wave under wave/
        #[arg(long, conflicts_with_all = ["wave", "wave_flag"])]
        all: bool,
        /// Repository Team key = Task prefix (e.g. LOO). Defaults from the repository name.
        #[arg(long = "team-key")]
        team_key: Option<String>,
        /// Repository Team display name. Defaults to the repository name.
        #[arg(long = "team-name")]
        team_name: Option<String>,
    },
    /// Read the wave's local Project and task snapshot
    Show {
        /// Wave name (auto-detected if omitted)
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
        /// Linear Project slug
        #[arg(short = 'p', long = "project")]
        project: Option<String>,
        /// Emit the task snapshot as JSON
        #[arg(long)]
        json: bool,
        /// Force a refresh from Linear before reading
        #[arg(long = "sync", conflicts_with = "no_sync")]
        sync: bool,
        /// Read the local cache only; never contact Linear
        #[arg(long = "no-sync")]
        no_sync: bool,
    },
    /// Show local PM status for linked waves
    Status {
        /// Wave name (all PM-enabled waves if omitted)
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
    },
    /// Compare Linear with local wave bindings
    Doctor,
    /// Move every linked wave onto the repository's one Linear team
    Reteam {
        /// Execute the moves; without it, `reteam` only prints the plan (dry run)
        #[arg(long)]
        apply: bool,
    },
    /// Refresh the local PM snapshot from Linear
    Sync {
        /// Wave name (all linked waves if omitted)
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
        /// Compare without writing the SQLite snapshot
        #[arg(long = "plan")]
        plan: bool,
    },
    /// Rename the Linear Initiative backing a wave
    Rename {
        /// Wave name (auto-detected if omitted)
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
        /// Linear Initiative title
        #[arg(long = "title")]
        title: String,
    },
    /// Linear task operations
    Task {
        #[command(subcommand)]
        cmd: PmTaskCommand,
    },
    /// Linear Project operations
    Project {
        #[command(subcommand)]
        cmd: PmProjectCommand,
    },
    /// Linear webhook receiver: stream human edits into Tasks
    Webhook {
        #[command(subcommand)]
        cmd: PmWebhookCommand,
    },
}

#[derive(Subcommand, Debug)]
pub enum PmWebhookCommand {
    /// Run the receiver that turns Linear edits into Task direction. Reads the
    /// signing secret from LF_LINEAR_WEBHOOK_SECRET (source it from Doppler).
    Serve {
        /// Address to bind (a reverse proxy gives Linear the public HTTPS URL)
        #[arg(long, default_value = "127.0.0.1:8899")]
        addr: String,
    },
    /// Register the Issue/Comment webhook with Linear (one-time). Reads the
    /// signing secret from LF_LINEAR_WEBHOOK_SECRET.
    Register {
        /// Public HTTPS URL Linear will POST deliveries to
        #[arg(long)]
        url: String,
    },
}

#[derive(Subcommand, Debug)]
pub enum PmProjectCommand {
    /// Create a Linear Project in the wave's Initiative
    Create {
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
        #[arg(long = "title")]
        title: String,
        #[arg(long = "definition")]
        definition: String,
        /// Key result; repeat for each KR. Prefix with `[x] ` when it holds.
        #[arg(long = "kr", required = true)]
        krs: Vec<String>,
        /// Flow run once when each Task starts
        #[arg(long)]
        first: Option<String>,
        /// Flow repeated while each Task makes progress
        #[arg(long = "loop")]
        loop_: Option<String>,
        /// Flow run to gate, learn from, and land each Task
        #[arg(long)]
        finally: Option<String>,
    },
    /// Update a Linear Project's content or Task flows
    Update {
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
        #[arg(short = 'p', long = "project")]
        project: String,
        #[arg(long = "title")]
        title: Option<String>,
        #[arg(long = "definition")]
        definition: Option<String>,
        /// Replace KRs; repeat for each KR. Prefix with `[x] ` when it holds.
        #[arg(long = "kr")]
        krs: Vec<String>,
        /// Flow run once when each Task starts
        #[arg(long)]
        first: Option<String>,
        /// Flow repeated while each Task makes progress
        #[arg(long = "loop")]
        loop_: Option<String>,
        /// Flow run to gate, learn from, and land each Task
        #[arg(long)]
        finally: Option<String>,
    },
    /// Archive a Linear Project and refresh the wave snapshot
    Archive {
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
        #[arg(short = 'p', long = "project")]
        project: String,
    },
}

#[derive(Subcommand, Debug)]
pub enum PmTaskCommand {
    /// Create a Linear task
    Create {
        /// Wave name (auto-detected if omitted)
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
        /// Linear Project slug
        #[arg(short = 'p', long = "project")]
        project: String,
        /// Task title
        #[arg(long = "title")]
        title: String,
        /// Task notes/description
        #[arg(long = "notes")]
        notes: Option<String>,
    },
    /// Update a Linear task
    Update {
        /// Existing task id to edit
        #[arg(long = "id")]
        id: String,
        /// Wave name (auto-detected if omitted)
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
        /// Linear Project slug
        #[arg(short = 'p', long = "project")]
        project: Option<String>,
        /// Task title
        #[arg(long = "title")]
        title: Option<String>,
        /// Task notes/description
        #[arg(long = "notes")]
        notes: Option<String>,
    },
    /// Close a Linear task and optionally link the shipped PR
    Done {
        /// Existing task id to close
        #[arg(long = "id")]
        id: String,
        /// Wave name (auto-detected if omitted)
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
        /// PR URL to attach as a comment
        #[arg(long = "pr")]
        pr: Option<String>,
    },
    /// Move a task into a wave's Linear Project
    Move {
        /// Existing task id to move
        #[arg(long = "id")]
        id: String,
        /// Destination wave
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
        /// Destination Linear Project slug
        #[arg(short = 'p', long = "project")]
        project: String,
    },
}

/// Inspect and observe durable Homes.
#[derive(Debug, Subcommand)]
pub enum HomeCommand {
    /// Print this machine's stable local Home identity.
    Id {
        #[arg(long)]
        json: bool,
    },
    /// Record the current route for a known Home identity.
    Observe {
        home_id: crate::durable::HomeId,
        route: String,
        #[arg(long)]
        json: bool,
    },
    /// Probe a Wave's Home for liveness and the one contextual action.
    ///
    /// Prints the Home route, its state (unreachable/stopped/running/unknown)
    /// with the evidence, the attach endpoint when running, and the action to
    /// offer. `--json` emits the `HomeRuntimeDto` a UI consumes.
    Probe {
        /// Wave name; defaults to the ambient wave.
        wave: Option<String>,
        #[arg(long)]
        json: bool,
    },
}

#[derive(Debug, Subcommand)]
pub enum AuthCommand {
    /// Show authentication status for local credentials
    Status {
        /// Provider name (optional)
        provider: Option<String>,
    },
    /// Disconnect a provider from local lf credentials
    Disconnect {
        /// Provider name
        provider: String,
        /// Disconnect one managed OAuth login
        #[arg(long)]
        email: Option<String>,
    },
    /// Store an API key from the provider's environment variable
    Configure {
        /// Provider name
        provider: String,
    },
    /// Start a provider auth flow explicitly
    Connect {
        /// Provider name
        provider: String,
        /// Login email or an unambiguous prefix
        email: Option<String>,
        /// Bootstrap through this Chrome directory, name, or signed-in email
        #[arg(long, requires = "email")]
        chrome_profile: Option<String>,
    },
    /// Adopt an existing Claude login
    Import {
        provider: String,
        /// Verified login email
        #[arg(long)]
        email: String,
        /// Chrome profile directory, name, or signed-in email
        #[arg(long)]
        chrome_profile: Option<String>,
    },
    /// Manage the ordered Chrome venues that can log in an account
    Access {
        #[command(subcommand)]
        cmd: AuthAccessCommand,
    },
    /// List managed Claude and Codex OAuth accounts
    Accounts {
        /// Provider name (optional)
        provider: Option<String>,
        /// Ask each provider now instead of reporting only cached state
        #[arg(long)]
        verify: bool,
    },
    /// Record provider-specific account identity, routing, and billing state
    Set {
        provider: String,
        /// Login email or an unambiguous prefix
        email: String,
        #[arg(long)]
        login_email: Option<String>,
        /// automatic, explicit-only, or disabled
        #[arg(long)]
        routing: Option<String>,
        #[arg(long, conflicts_with = "clear_plan")]
        plan: Option<String>,
        #[arg(long)]
        clear_plan: bool,
        /// Last paid day, as YYYY-MM-DD
        #[arg(long, conflicts_with = "clear_paid_through")]
        paid_through: Option<String>,
        #[arg(long)]
        clear_paid_through: bool,
    },
    /// Clear observed utilization and cooldown for an account
    Reset {
        provider: String,
        /// Login email or an unambiguous prefix
        email: String,
    },
    /// External: provider name (so `lf auth linear` works)
    #[command(external_subcommand)]
    External(Vec<String>),
}

#[derive(Debug, Subcommand)]
pub enum ProfileCommand {
    /// Record a Chrome access venue
    Create {
        /// Chrome profile directory, name, or signed-in email on this host
        #[arg(long)]
        chrome_profile: String,
        /// Stable venue name; defaults to the Chrome directory
        #[arg(long = "as")]
        name: Option<String>,
        /// Expected signed-in email; defaults to Chrome's current login
        #[arg(long)]
        expects: Option<String>,
    },
    /// List Chrome venues and the accounts that reference them
    List,
}

#[derive(Debug, Subcommand)]
pub enum AuthAccessCommand {
    /// Atomically replace an account's ordered access venues
    Set {
        provider: String,
        /// Login email or an unambiguous prefix
        email: String,
        #[arg(long = "profile", required = true)]
        profiles: Vec<String>,
    },
    /// Append one access venue
    Add {
        provider: String,
        /// Login email or an unambiguous prefix
        email: String,
        #[arg(long = "profile")]
        profile: String,
    },
    /// Remove one access venue
    Rm {
        provider: String,
        /// Login email or an unambiguous prefix
        email: String,
        #[arg(long = "profile")]
        profile: String,
    },
}

#[derive(Debug, Subcommand)]
pub enum RouteCommand {
    /// Atomically replace one provider's route for a repository
    Set {
        provider: String,
        #[arg(required = true)]
        accounts: Vec<String>,
        /// Repository owner/name; defaults to the current repository
        #[arg(long)]
        repo: Option<String>,
    },
    /// Configure the store-wide fallback route
    Default {
        #[command(subcommand)]
        cmd: DefaultRouteCommand,
    },
    /// Show repo routes or the defaults they fall back to
    Show {
        /// Repository owner/name; defaults to the current repository
        #[arg(long)]
        repo: Option<String>,
    },
}

#[derive(Debug, Subcommand)]
pub enum DefaultRouteCommand {
    /// Atomically replace one provider's store-wide route
    Set {
        provider: String,
        #[arg(required = true)]
        accounts: Vec<String>,
    },
}

#[derive(Subcommand, Debug)]
pub enum ReleaseCommand {
    /// Run the full release workflow end-to-end
    Run {
        /// Version to release: patch|minor|major|X.Y.Z (default: patch)
        version: Option<String>,
        #[arg(short = 't', long = "target")]
        target: Option<String>,
    },
    /// Check if PRs have merged since the last tag
    Check {
        #[arg(short = 't', long = "target")]
        target: Option<String>,
    },
    /// Generate release notes for a version
    Notes {
        /// Version (e.g. 0.9.6)
        version: String,
        #[arg(long = "prev-tag")]
        prev_tag: Option<String>,
        #[arg(short = 't', long = "target")]
        target: Option<String>,
    },
    /// Bump version in manifest files
    Bump {
        /// Version to bump to (e.g. 0.9.6)
        version: String,
        #[arg(short = 't', long = "target")]
        target: Option<String>,
    },
    /// Create a git tag and push it
    Tag {
        /// Version to tag (e.g. 0.9.6)
        version: String,
        #[arg(short = 't', long = "target")]
        target: Option<String>,
    },
    /// Stage or publish a GitHub Release
    Publish {
        /// Release tag (for example v0.12.4)
        tag: String,
        /// Release notes used while creating or updating the draft
        #[arg(long)]
        notes: Option<PathBuf>,
        /// Asset to upload; repeat for multiple files
        #[arg(long = "asset")]
        assets: Vec<PathBuf>,
        /// Publish the existing draft and mark it latest
        #[arg(long)]
        finalize: bool,
    },
    /// Check release workflow status
    Status {
        #[arg(short = 't', long = "target")]
        target: Option<String>,
    },
}

#[derive(Subcommand, Debug)]
pub enum WtCommand {
    /// Create a low-level sibling worktree
    Create {
        /// Worktree name
        name: String,
        /// Print the placement plan without creating a worktree
        #[arg(long)]
        plan: bool,
    },
    /// Switch to a worktree by name, identity leaf, or full branch
    Switch {
        /// Worktree name or full branch name to switch to
        name: String,
    },
    /// List worktrees (read-only; reflects the last-synced main)
    List {
        #[arg(long)]
        format: Option<String>,
        #[arg(long)]
        full: bool,
        /// Fetch origin and fast-forward main before listing (mutates the
        /// canonical checkout). Off by default so a list never touches it.
        #[arg(long)]
        sync: bool,
    },
    /// Remove clean terminal or inactive worktrees
    Prune {
        /// Show what would be pruned without removing anything
        #[arg(long)]
        dry_run: bool,
    },
    /// Remove a worktree
    #[command(alias = "rm")]
    Remove {
        /// Worktree name to remove
        name: String,
        #[arg(short = 'f', long = "force")]
        force: bool,
    },
    /// Show CI status for current branch
    Ci {
        #[arg(short = 'w', long = "watch")]
        watch: bool,
        #[arg(short = 'l', long = "logs")]
        logs: bool,
    },
}

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

    #[test]
    fn version_output_uses_the_embedded_build_identity() {
        let error = Cli::try_parse_from(["lf", "--version"]).expect_err("version exits");
        assert_eq!(error.kind(), clap::error::ErrorKind::DisplayVersion);
        assert_eq!(
            error.to_string(),
            format!("lf {}\n", crate::build_info::BUILD_VERSION)
        );
    }

    #[test]
    fn screenshot_requires_an_output_and_accepts_a_viewport() {
        let cli = Cli::try_parse_from([
            "lf",
            "screenshot",
            "page.html",
            "--output",
            "capture.png",
            "--width",
            "390",
            "--height",
            "844",
        ])
        .expect("parse screenshot");
        let Some(Commands::Screenshot { screenshot }) = cli.command else {
            panic!("expected screenshot command");
        };
        assert_eq!(screenshot.source, "page.html");
        assert_eq!(screenshot.output, PathBuf::from("capture.png"));
        assert_eq!((screenshot.width, screenshot.height), (390, 844));
        assert!(Cli::try_parse_from(["lf", "screenshot", "page.html"]).is_err());
    }

    #[test]
    fn installer_transport_is_hidden_and_has_no_status_surface() {
        let help = Cli::command().render_long_help().to_string();
        assert!(!help.contains("install"));
        assert!(Cli::try_parse_from(["lf", "install", "status"]).is_err());
        assert!(Cli::try_parse_from(["lf", "install", "preflight"]).is_ok());
    }

    #[test]
    fn catalog_accepts_command_and_flag_forms_without_claiming_ls() {
        let command = Cli::try_parse_from(["lf", "list"]).expect("parse list command");
        assert!(matches!(command.command, Some(Commands::List)));

        let flag = Cli::try_parse_from(["lf", "-l"]).expect("parse list flag");
        assert!(flag.list);

        let waves = Cli::try_parse_from(["lf", "ls", "--json"]).expect("parse wave list");
        assert!(matches!(
            waves.command,
            Some(Commands::Ls {
                json: true,
                all: false
            })
        ));
    }

    #[test]
    fn hierarchical_work_selectors_choose_the_most_specific_subject() {
        let before = Cli::try_parse_from([
            "lf",
            "--wave",
            "intelligence",
            "--project",
            "context",
            "--task",
            "LOO-123",
            "implement",
        ])
        .expect("parse selectors before skill");
        assert_eq!(before.wave.as_deref(), Some("intelligence"));
        assert_eq!(before.project.as_deref(), Some("context"));
        assert_eq!(before.task.as_deref(), Some("LOO-123"));
        assert_eq!(
            before.work_subject_selector().as_deref(),
            Some("task:LOO-123")
        );
        assert!(matches!(before.command, Some(Commands::External(_))));
    }

    #[test]
    fn direct_work_selector_accepts_an_inline_question() {
        let cli = Cli::try_parse_from([
            "lf",
            "--batch",
            "--as",
            "project:mac-surface-ux",
            ":",
            "Which KR matters?",
        ])
        .expect("parse bound inline prompt");

        assert_eq!(cli.as_work.as_deref(), Some("project:mac-surface-ux"));
        assert!(matches!(
            cli.command,
            Some(Commands::Inline { prompt }) if prompt == vec!["Which KR matters?"]
        ));
    }

    #[test]
    fn ci_report_accepts_machine_wide_filters() {
        let cli = Cli::try_parse_from([
            "lf",
            "ci",
            "--since",
            "24h",
            "--wave",
            "infrastructure",
            "--repo",
            "loopflowstudio/loopflow",
            "--json",
        ])
        .expect("parse CI report");
        assert!(matches!(
            cli.command,
            Some(Commands::Ci {
                since,
                wave: Some(wave),
                repo: Some(repo),
                json: true,
            }) if since == "24h" && wave == "infrastructure" && repo == "loopflowstudio/loopflow"
        ));
    }

    #[test]
    fn activity_accepts_composed_work_filters() {
        let cli = Cli::try_parse_from([
            "lf",
            "activity",
            "--since",
            "24h",
            "--limit",
            "100",
            "--wave",
            "live",
            "--project",
            "control-room",
            "--task",
            "W2-140",
            "--json",
        ])
        .expect("parse Activity query");
        assert!(matches!(
            cli.command,
            Some(Commands::Activity {
                since,
                limit: 100,
                wave: Some(wave),
                project: Some(project),
                task: Some(task),
                json: true,
            }) if since == "24h"
                && wave == "live"
                && project == "control-room"
                && task == "W2-140"
        ));
    }

    #[test]
    fn runs_resume_requires_one_run_and_excludes_record_output() {
        let cli = Cli::try_parse_from(["lf", "runs", "abc123", "--resume"])
            .expect("parse provider session resume");
        assert!(matches!(
            cli.command,
            Some(Commands::Runs {
                run: Some(run),
                resume: true,
                events: false,
                json: false,
                ..
            }) if run == "abc123"
        ));
        assert!(Cli::try_parse_from(["lf", "runs", "--resume"]).is_err());
        assert!(Cli::try_parse_from(["lf", "runs", "abc123", "--resume", "--events"]).is_err());
    }

    #[test]
    fn auth_help_exposes_managed_account_flows() {
        let command = Cli::command();
        let auth = command
            .find_subcommand("auth")
            .expect("auth subcommand exists");

        for flow in [
            "connect",
            "import",
            "accounts",
            "set",
            "reset",
            "disconnect",
        ] {
            assert!(
                auth.find_subcommand(flow).is_some(),
                "auth help is missing {flow}"
            );
        }
        let connect = auth
            .find_subcommand("connect")
            .expect("connect flow exists");
        assert!(connect
            .get_arguments()
            .any(|argument| argument.get_id() == "email"));
        assert!(connect
            .get_arguments()
            .any(|argument| argument.get_long() == Some("chrome-profile")));
        assert!(!connect
            .get_arguments()
            .any(|argument| argument.get_long() == Some("profile")));
    }

    #[test]
    fn route_accepts_a_provider_specific_account_order() {
        let cli = Cli::try_parse_from(["lf", "route", "set", "claude", "loopflow", "primary"])
            .expect("parse account route");

        assert!(matches!(
            cli.command,
            Some(Commands::Route {
                cmd: RouteCommand::Set {
                    provider,
                    accounts,
                    repo: None,
                }
            }) if provider == "claude" && accounts == vec!["loopflow", "primary"]
        ));
    }

    #[test]
    fn account_preference_and_restriction_are_distinct_repeatable_flags() {
        let preferred = Cli::try_parse_from([
            "lf",
            "--account",
            "claude=personal",
            "--account",
            "codex=reserve",
            "skill",
            "implement",
        ])
        .expect("parse account preferences");
        assert_eq!(preferred.account, vec!["claude=personal", "codex=reserve"]);
        assert!(preferred.only_account.is_empty());

        let restricted = Cli::try_parse_from([
            "lf",
            "--only-account",
            "claude=personal",
            "--only-account",
            "codex=reserve",
            "skill",
            "implement",
        ])
        .expect("parse account restrictions");
        assert_eq!(
            restricted.only_account,
            vec!["claude=personal", "codex=reserve"]
        );

        assert!(Cli::try_parse_from([
            "lf",
            "--account",
            "reserve",
            "--only-account",
            "reserve",
            "skill",
            "implement",
        ])
        .is_err());
    }

    #[test]
    fn account_lease_probe_is_parseable_but_hidden() {
        let cli = Cli::try_parse_from(["lf", "--__account-lease-probe"])
            .expect("parse internal account lease probe");
        assert!(cli.account_lease_probe);
        assert!(!Cli::command()
            .render_long_help()
            .to_string()
            .contains("__account-lease-probe"));
    }

    #[test]
    fn telemetry_scorecard_is_parseable_but_hidden() {
        let cli = Cli::try_parse_from(["lf", "__telemetry-scorecard", "--json"])
            .expect("parse internal telemetry scorecard");
        assert!(matches!(
            cli.command,
            Some(Commands::TelemetryScorecard { json: true })
        ));
        assert!(!Cli::command()
            .render_long_help()
            .to_string()
            .contains("__telemetry-scorecard"));
    }

    #[test]
    fn ssh_parser_respects_the_internal_target_boundary() {
        let cli = Cli::try_parse_from([
            "lf",
            "ssh",
            "--account",
            "reserve",
            "mini",
            "--",
            "task",
            "pursue",
        ])
        .expect("parse origin SSH account preference");

        assert!(cli.account.is_empty());
        assert!(matches!(
            cli.command,
            Some(Commands::Ssh { origin_account, lf_args, .. })
                if origin_account == vec!["reserve"]
                    && lf_args == vec!["task", "pursue"]
        ));

        let after_host = Cli::try_parse_from([
            "lf",
            "ssh",
            "mini",
            "--",
            "--account",
            "reserve",
            "task",
            "pursue",
        ])
        .expect("parse remote account preference");
        assert!(after_host.account.is_empty());
        assert!(matches!(
            after_host.command,
            Some(Commands::Ssh { lf_args, .. })
                if lf_args == vec!["--account", "reserve", "task", "pursue"]
        ));
    }

    #[test]
    fn profile_create_accepts_a_host_local_chrome_profile() {
        let cli = Cli::try_parse_from([
            "lf",
            "profile",
            "create",
            "--chrome-profile",
            "Profile 8",
            "--as",
            "engineering",
            "--expects",
            "engineering@example.com",
        ])
        .expect("parse profile Chrome binding");

        assert!(matches!(
            cli.command,
            Some(Commands::Profile {
                cmd: ProfileCommand::Create {
                    chrome_profile,
                    name: Some(name),
                    expects: Some(expects),
                }
            }) if chrome_profile == "Profile 8"
                && name == "engineering"
                && expects == "engineering@example.com"
        ));
    }

    #[test]
    fn auth_access_set_accepts_ordered_profiles() {
        let cli = Cli::try_parse_from([
            "lf",
            "auth",
            "access",
            "set",
            "claude",
            "operator@",
            "--profile",
            "personal",
            "--profile",
            "engineering",
        ])
        .expect("parse account access order");

        assert!(cli.account.is_empty());
        assert!(matches!(
            cli.command,
            Some(Commands::Auth {
                cmd: AuthCommand::Access {
                    cmd: AuthAccessCommand::Set {
                        provider,
                        email,
                        profiles,
                    }
                }
            }) if provider == "claude"
                && email == "operator@"
                && profiles == vec!["personal", "engineering"]
        ));
    }

    #[test]
    fn auth_connect_addresses_an_account_and_optional_bootstrap_venue() {
        let cli = Cli::try_parse_from([
            "lf",
            "auth",
            "connect",
            "claude",
            "operator@",
            "--chrome-profile",
            "Profile 9",
        ])
        .expect("parse account connection");

        assert!(cli.account.is_empty());
        assert!(matches!(
            cli.command,
            Some(Commands::Auth {
                cmd: AuthCommand::Connect {
                    provider,
                    email: Some(email),
                    chrome_profile: Some(chrome_profile),
                }
            }) if provider == "claude"
                && email == "operator@"
                && chrome_profile == "Profile 9"
        ));
    }

    #[test]
    fn auth_import_accepts_managed_account_and_chrome_profile() {
        let cli = Cli::try_parse_from([
            "lf",
            "auth",
            "import",
            "claude",
            "--email",
            "jack@example.com",
            "--chrome-profile",
            "jack@example.com",
        ])
        .expect("parse existing login import");

        assert!(cli.account.is_empty());
        assert!(matches!(
            cli.command,
            Some(Commands::Auth {
                cmd: AuthCommand::Import {
                    provider,
                    email,
                    chrome_profile: Some(chrome_profile),
                }
            }) if provider == "claude"
                && email == "jack@example.com"
                && chrome_profile == "jack@example.com"
        ));
    }

    #[test]
    fn auth_set_accepts_provider_specific_billing_and_routing_state() {
        let cli = Cli::try_parse_from([
            "lf",
            "auth",
            "set",
            "codex",
            "loopflow-eng@",
            "--login-email",
            "engineering@example.com",
            "--routing",
            "automatic",
            "--plan",
            "max",
            "--paid-through",
            "2026-08-14",
        ])
        .expect("parse provider account lifecycle");

        assert!(cli.account.is_empty());
        assert!(matches!(
            cli.command,
            Some(Commands::Auth {
                cmd: AuthCommand::Set {
                    provider,
                    email,
                    login_email: Some(login_email),
                    routing: Some(routing),
                    plan: Some(plan),
                    paid_through: Some(paid_through),
                    clear_plan: false,
                    clear_paid_through: false,
                }
            }) if provider == "codex"
                && email == "loopflow-eng@"
                && login_email == "engineering@example.com"
                && routing == "automatic"
                && plan == "max"
                && paid_through == "2026-08-14"
        ));
    }

    #[test]
    fn pm_init_accepts_positional_wave() {
        let cli = Cli::try_parse_from(["lf", "pm", "init", "pm"]).expect("parse");
        let Some(Commands::Pm {
            cmd:
                PmCommand::Init {
                    wave,
                    wave_flag,
                    all,
                    ..
                },
        }) = cli.command
        else {
            panic!("expected pm init command");
        };

        assert_eq!(wave.as_deref(), Some("pm"));
        assert_eq!(wave_flag, None);
        assert!(!all);
    }

    #[test]
    fn task_run_accepts_linear_identifier_and_json() {
        let cli = Cli::try_parse_from([
            "lf",
            "task",
            "run",
            "INF-123",
            "--name",
            "release-scoped-migrations",
            "--stack-on",
            "INF-122",
            "--json",
        ])
        .expect("parse task run");
        let Some(Commands::Task {
            cmd:
                TaskCommand::Run {
                    issue,
                    name,
                    stack_on,
                    json,
                    ..
                },
        }) = cli.command
        else {
            panic!("expected task run command");
        };
        assert_eq!(issue, "INF-123");
        assert_eq!(name.as_deref(), Some("release-scoped-migrations"));
        assert_eq!(stack_on.as_deref(), Some("INF-122"));
        assert!(json);
    }

    #[test]
    fn task_prepare_accepts_worktree_options_without_controller_flows() {
        let cli = Cli::try_parse_from([
            "lf",
            "task",
            "prepare",
            "INF-123",
            "--name",
            "runtime-research",
            "--stack-on",
            "INF-122",
            "--directive",
            "collect both reports",
            "--json",
        ])
        .expect("parse task prepare");
        let Some(Commands::Task {
            cmd:
                TaskCommand::Prepare {
                    issue,
                    name,
                    stack_on,
                    directive,
                    json,
                },
        }) = cli.command
        else {
            panic!("expected task prepare command");
        };
        assert_eq!(issue, "INF-123");
        assert_eq!(name.as_deref(), Some("runtime-research"));
        assert_eq!(stack_on.as_deref(), Some("INF-122"));
        assert_eq!(directive.as_deref(), Some("collect both reports"));
        assert!(json);
    }

    #[test]
    fn project_prepare_accepts_existing_planning_identity() {
        let cli = Cli::try_parse_from([
            "lf",
            "project",
            "prepare",
            "runtime-model",
            "--directive",
            "collect evidence",
            "--json",
        ])
        .expect("parse project prepare");
        let Some(Commands::Project {
            cmd:
                ProjectCommand::Prepare {
                    project_id,
                    directive,
                    json,
                },
        }) = cli.command
        else {
            panic!("expected project prepare command");
        };
        assert_eq!(project_id, "runtime-model");
        assert_eq!(directive.as_deref(), Some("collect evidence"));
        assert!(json);
    }

    #[test]
    fn task_run_accepts_lifecycle_flow_overrides() {
        let cli = Cli::try_parse_from([
            "lf",
            "task",
            "run",
            "INF-123",
            "--first",
            "incident",
            "--loop",
            "ship-5whys",
            "--finally",
            "ship",
        ])
        .expect("parse task lifecycle overrides");
        let Some(Commands::Task {
            cmd:
                TaskCommand::Run {
                    first,
                    loop_,
                    finally,
                    ..
                },
        }) = cli.command
        else {
            panic!("expected task run command");
        };
        assert_eq!(first.as_deref(), Some("incident"));
        assert_eq!(loop_.as_deref(), Some("ship-5whys"));
        assert_eq!(finally.as_deref(), Some("ship"));
    }

    #[test]
    fn task_run_rejects_design_only_outcome() {
        assert!(Cli::try_parse_from(["lf", "task", "run", "INF-123", "--design-only"]).is_err());
    }

    #[test]
    fn task_run_rejects_retired_reviewer_flag() {
        assert!(
            Cli::try_parse_from(["lf", "task", "run", "INF-123", "--reviewer", "parent"]).is_err()
        );
    }

    #[test]
    fn task_start_requires_project_and_allows_piped_title_omission() {
        let cli = Cli::try_parse_from(["lf", "task", "start", "incident-management"])
            .expect("parse Task start with required Project");
        let Some(Commands::Task {
            cmd: TaskCommand::Start {
                project_id, title, ..
            },
        }) = cli.command
        else {
            panic!("expected task start command");
        };
        assert_eq!(project_id, "incident-management");
        assert_eq!(title, None);
        assert!(Cli::try_parse_from(["lf", "task", "start"]).is_err());
    }

    #[test]
    fn task_run_rejects_retired_headless_flag() {
        let error = Cli::try_parse_from(["lf", "task", "run", "INF-123", "--headless"])
            .expect_err("--headless must not remain as an alias");
        assert!(error
            .to_string()
            .contains("unexpected argument '--headless'"));
    }

    #[test]
    fn task_completion_and_pr_dispositions_parse() {
        let complete = Cli::try_parse_from([
            "lf",
            "task",
            "complete",
            "INF-123",
            "--summary",
            "Root cause recorded",
        ])
        .expect("parse task complete");
        assert!(matches!(
            complete.command,
            Some(Commands::Task {
                cmd: TaskCommand::Complete { issue, summary, .. }
            }) if issue == "INF-123" && summary == "Root cause recorded"
        ));

        let land = Cli::try_parse_from(["lf", "pr", "land", "-c"]).expect("parse completing land");
        assert!(matches!(
            land.command,
            Some(Commands::Pr {
                cmd: Some(PrCommand::Land {
                    complete: true,
                    next: None,
                    ..
                })
            })
        ));

        let submit =
            Cli::try_parse_from(["lf", "pr", "submit", "--next", "released-upgrade-proof"])
                .expect("parse continuation submit");
        assert!(matches!(
            submit.command,
            Some(Commands::Pr {
                cmd: Some(PrCommand::Submit {
                    complete: false,
                    next: Some(next),
                    ..
                })
            }) if next == "released-upgrade-proof"
        ));
    }

    #[test]
    fn top_is_a_first_class_machine_dashboard() {
        let cli = Cli::try_parse_from(["lf", "top"]).expect("parse top");
        assert!(matches!(cli.command, Some(Commands::Top { json: false })));

        let cli = Cli::try_parse_from(["lf", "ps", "--json"]).expect("parse ps");
        assert!(matches!(cli.command, Some(Commands::Ps { json: true })));
        assert!(Cli::try_parse_from(["lf", "ps", "--sort", "tokens"]).is_err());

        let cli = Cli::try_parse_from(["lf", "prune", "--dry-run", "--json"])
            .expect("parse process prune");
        assert!(matches!(
            cli.command,
            Some(Commands::Prune {
                dry_run: true,
                json: true,
            })
        ));
    }

    #[test]
    fn usage_exposes_the_direct_run_window_and_work_drill() {
        let cli =
            Cli::try_parse_from(["lf", "usage", "--days", "7", "--task", "LOO-265", "--json"])
                .expect("parse direct usage");
        assert!(matches!(
            cli.command,
            Some(Commands::Usage {
                json: true,
                days: 7,
                wave: None,
                project: None,
                task: Some(task),
            })
                if task == "LOO-265"
        ));
        assert!(Cli::try_parse_from(["lf", "usage", "--refresh"]).is_err());
        assert!(Cli::try_parse_from(["lf", "usage", "--cached"]).is_err());
    }

    #[test]
    fn task_workspace_commands_address_the_task_then_optional_file() {
        let changes = Cli::try_parse_from(["lf", "task", "changes", "INF-123", "--json"])
            .expect("parse task changes");
        assert!(matches!(
            changes.command,
            Some(Commands::Task {
                cmd: TaskCommand::Changes { issue, json: true }
            }) if issue == "INF-123"
        ));

        let diff =
            Cli::try_parse_from(["lf", "task", "diff", "INF-123", "src/parser.rs", "--json"])
                .expect("parse task diff");
        assert!(matches!(
            diff.command,
            Some(Commands::Task {
                cmd: TaskCommand::Diff {
                    issue,
                    path: Some(path),
                    json: true,
                }
            }) if issue == "INF-123" && path == "src/parser.rs"
        ));

        let file =
            Cli::try_parse_from(["lf", "task", "file", "INF-123", "src/parser.rs", "--json"])
                .expect("parse task file");
        assert!(matches!(
            file.command,
            Some(Commands::Task {
                cmd: TaskCommand::File { issue, path, json: true }
            }) if issue == "INF-123" && path == "src/parser.rs"
        ));
    }

    #[test]
    fn task_interrupt_authors_no_direction() {
        let cli = Cli::try_parse_from(["lf", "task", "interrupt", "INF-123"])
            .expect("parse task interrupt");
        let Some(Commands::Task {
            cmd: TaskCommand::Interrupt { issue, json },
        }) = cli.command
        else {
            panic!("expected task interrupt command");
        };
        assert_eq!(issue, "INF-123");
        assert!(!json);
        assert!(Cli::try_parse_from([
            "lf",
            "task",
            "interrupt",
            "INF-123",
            "--message",
            "take the smaller approach",
        ])
        .is_err());
    }

    #[test]
    fn task_steer_is_the_only_authored_direction_command() {
        let steer = Cli::try_parse_from([
            "lf",
            "task",
            "steer",
            "INF-123",
            "take the smaller approach",
        ])
        .expect("parse task steer");
        let Some(Commands::Task {
            cmd:
                TaskCommand::Steer {
                    issue,
                    message,
                    json,
                },
        }) = steer.command
        else {
            panic!("expected task steer command");
        };
        assert_eq!(issue, "INF-123");
        assert_eq!(message, "take the smaller approach");
        assert!(!json);

        for removed in ["follow-up", "acknowledge", "decide", "request-decision"] {
            assert!(
                Cli::try_parse_from(["lf", "task", removed, "INF-123"]).is_err(),
                "{removed} must not remain as a compatibility command"
            );
        }
    }

    #[test]
    fn project_start_accepts_title_wave_and_json() {
        let cli = Cli::try_parse_from([
            "lf",
            "project",
            "start",
            "Release stability",
            "--wave",
            "infrastructure",
            "--json",
        ])
        .expect("parse project start");
        let Some(Commands::Project {
            cmd: ProjectCommand::Start {
                title, wave, json, ..
            },
        }) = cli.command
        else {
            panic!("expected project start command");
        };
        assert_eq!(title, "Release stability");
        assert_eq!(wave.as_deref(), Some("infrastructure"));
        assert!(json);
    }

    #[test]
    fn project_steer_parses() {
        let steer = Cli::try_parse_from([
            "lf",
            "project",
            "steer",
            "project-uuid",
            "prioritize the CLI path",
            "--json",
        ])
        .expect("parse project steer");
        assert!(matches!(
            steer.command,
            Some(Commands::Project {
                cmd: ProjectCommand::Steer {
                    project_id,
                    message,
                    json: true,
                },
            }) if project_id == "project-uuid" && message == "prioritize the CLI path"
        ));
    }

    #[test]
    fn task_and_project_resume_accept_audited_model_handoffs() {
        let task = Cli::try_parse_from([
            "lf",
            "task",
            "resume",
            "W2-135",
            "--model",
            "codex",
            "--reason",
            "Claude quota exhausted",
            "--json",
        ])
        .expect("parse Task body handoff");
        assert!(matches!(
            task.command,
            Some(Commands::Task {
                cmd: TaskCommand::Resume {
                    issue,
                    model: Some(model),
                    reason: Some(reason),
                    json: true,
                    ..
                }
            }) if issue == "W2-135" && model == "codex" && reason == "Claude quota exhausted"
        ));

        let project = Cli::try_parse_from([
            "lf",
            "project",
            "resume",
            "loopflow-api",
            "--model",
            "claude:opus",
        ])
        .expect("parse Project body handoff");
        assert!(matches!(
            project.command,
            Some(Commands::Project {
                cmd: ProjectCommand::Resume {
                    project_id,
                    model: Some(model),
                    reason: None,
                    ..
                }
            }) if project_id == "loopflow-api" && model == "claude:opus"
        ));

        assert!(Cli::try_parse_from([
            "lf",
            "task",
            "resume",
            "W2-135",
            "--reason",
            "quota exhausted",
        ])
        .is_err());
    }

    #[test]
    fn task_restart_accepts_optional_advice() {
        let cli = Cli::try_parse_from([
            "lf",
            "task",
            "restart",
            "LOO-267",
            "replace the old runtime model",
            "--json",
        ])
        .expect("parse Task restart");
        assert!(matches!(
            cli.command,
            Some(Commands::Task {
                cmd: TaskCommand::Restart {
                    issue,
                    advice: Some(advice),
                    json: true,
                }
            }) if issue == "LOO-267" && advice == "replace the old runtime model"
        ));
    }

    #[test]
    fn task_recover_accepts_an_optional_audited_reason() {
        let cli = Cli::try_parse_from([
            "lf",
            "task",
            "recover",
            "PRD-9",
            "--reason",
            "the abandoned work is still valid",
            "--json",
        ])
        .expect("parse Task recovery");
        assert!(matches!(
            cli.command,
            Some(Commands::Task {
                cmd: TaskCommand::Recover {
                    issue,
                    reason: Some(reason),
                    json: true,
                }
            }) if issue == "PRD-9" && reason == "the abandoned work is still valid"
        ));
    }
    #[test]
    fn cli_parses_stable_work_controls() {
        let cli = Cli::try_parse_from([
            "lf",
            "work",
            "steer",
            "task",
            "task_1",
            "inspect the failure",
            "--json",
        ])
        .expect("parse Work steer");
        assert!(matches!(
            cli.command,
            Some(Commands::Work {
                cmd: WorkCommand::Steer {
                    kind,
                    id,
                    message,
                    json: true,
                }
            }) if kind == "task" && id == "task_1" && message == "inspect the failure"
        ));

        assert!(Cli::try_parse_from(["lf", "work", "continue", "task", "task_1"]).is_err());
        assert!(Cli::try_parse_from(["lf", "work", "escalate", "task", "task_1"]).is_err());

        let place = Cli::try_parse_from([
            "lf",
            "work",
            "place",
            "wave",
            "wave_00000000000000000000000000000001",
            "home_00000000000000000000000000000001",
            "--json",
        ])
        .expect("parse Work placement");
        assert!(matches!(
            place.command,
            Some(Commands::Work {
                cmd: WorkCommand::Place { kind, id, json: true, .. }
            }) if kind == "wave" && id == "wave_00000000000000000000000000000001"
        ));
        assert!(Cli::try_parse_from([
            "lf",
            "work",
            "place",
            "task",
            "task_00000000000000000000000000000001",
            "home_00000000000000000000000000000001",
        ])
        .is_err());

        let disable = Cli::try_parse_from([
            "lf",
            "work",
            "disable",
            "task",
            "task_00000000000000000000000000000001",
            "--json",
        ])
        .expect("parse Work disable");
        assert!(matches!(
            disable.command,
            Some(Commands::Work {
                cmd: WorkCommand::Disable { kind, id, json: true }
            }) if kind == "task" && id == "task_00000000000000000000000000000001"
        ));
    }

    #[test]
    fn cli_separates_ask_completion_from_flow_decisions() {
        let ask = Cli::try_parse_from(["lf", "ask", "Review", "this", "branch"])
            .expect("parse human Ask");
        assert!(matches!(
            ask.command,
            Some(Commands::Ask { ask }) if ask.question == ["Review", "this", "branch"]
        ));

        let ready = Cli::try_parse_from(["lf", "session", "ready", "Ready for review"])
            .expect("parse session readiness");
        assert!(matches!(
            ready.command,
            Some(Commands::Session {
                cmd: SessionCommand::Ready { summary }
            }) if summary == ["Ready for review"]
        ));

        let approve = Cli::try_parse_from(["lf", "session", "approve", "task_flow", "Verified"])
            .expect("parse explicit FlowStep decision");
        assert!(matches!(
            approve.command,
            Some(Commands::Session {
                cmd: SessionCommand::Approve { id, summary }
            }) if id == "task_flow" && summary == ["Verified"]
        ));

        let iterate = Cli::try_parse_from([
            "lf",
            "session",
            "iterate",
            "task_flow",
            "Needs another pass",
        ])
        .expect("parse explicit FlowStep iteration");
        assert!(matches!(
            iterate.command,
            Some(Commands::Session {
                cmd: SessionCommand::Iterate { id, direction }
            }) if id == "task_flow" && direction == ["Needs another pass"]
        ));

        for args in [
            vec!["lf", "session", "ready"],
            vec!["lf", "session", "approve", "task_flow"],
            vec!["lf", "session", "iterate", "task_flow"],
        ] {
            assert!(Cli::try_parse_from(args).is_err());
        }

        let open = Cli::try_parse_from(["lf", "session", "open", "run_123", "--replace"])
            .expect("parse replacement open");
        assert!(matches!(
            open.command,
            Some(Commands::Session {
                cmd: SessionCommand::Open {
                    id,
                    replace: true,
                    try_open: false,
                    json: false,
                }
            }) if id == "run_123"
        ));
        assert!(
            Cli::try_parse_from(["lf", "session", "open", "run_123", "--replace", "--try",])
                .is_err()
        );

        let complete = Cli::try_parse_from(["lf", "session", "complete", "run_123"])
            .expect("parse interactive completion");
        assert!(matches!(
            complete.command,
            Some(Commands::Session {
                cmd: SessionCommand::Complete { id }
            }) if id == "run_123"
        ));
    }

    #[test]
    fn retired_loop_and_stack_surfaces_are_not_first_class_commands() {
        let loop_cli = Cli::try_parse_from(["lf", "loop", "infrastructure"])
            .expect("unknown names remain eligible for skill discovery");
        assert!(matches!(loop_cli.command, Some(Commands::External(_))));
        assert!(Cli::try_parse_from(["lf", "wt", "create", "child", "--stack"]).is_err());
        assert!(Cli::try_parse_from(["lf", "wt", "create", "child", "--child"]).is_err());
        assert!(Cli::try_parse_from(["lf", "wt", "up"]).is_err());
        assert!(Cli::try_parse_from(["lf", "wt", "down"]).is_err());
        assert!(Cli::try_parse_from(["lf", "pr", "stack"]).is_err());
    }

    #[test]
    fn rebase_manual_recovery_modes_are_explicit_and_exclusive() {
        let manual = Cli::try_parse_from(["lf", "rebase", "--manual", "origin/main"])
            .expect("parse manual rebase");
        assert!(matches!(
            manual.command,
            Some(Commands::Rebase {
                manual: true,
                continue_rebase: false,
                abort: false,
                onto: Some(ref onto),
                ..
            }) if onto == "origin/main"
        ));

        assert!(Cli::try_parse_from(["lf", "rebase", "--continue", "--abort"]).is_err());
        assert!(Cli::try_parse_from(["lf", "rebase", "--plan", "--manual"]).is_err());
    }

    #[test]
    fn install_promote_requires_a_local_build_for_fresh_forks() {
        let cli = Cli::try_parse_from([
            "lf",
            "install",
            "promote",
            "--from-build",
            "/tmp/lf",
            "--fresh",
            "--cli-target",
            "/tmp/bin/lf",
            "--daemon-source",
            "/tmp/lfd",
            "--daemon-target",
            "/tmp/bin/lfd",
        ])
        .expect("parse local promotion");
        assert!(matches!(
            cli.command,
            Some(Commands::Install {
                cmd: InstallCommand::Promote {
                    from_build: Some(_),
                    fresh: true,
                    ..
                }
            })
        ));
        assert!(Cli::try_parse_from([
            "lf",
            "install",
            "promote",
            "--fresh",
            "--cli-target",
            "/tmp/bin/lf",
            "--daemon-source",
            "/tmp/lfd",
            "--daemon-target",
            "/tmp/bin/lfd",
        ])
        .is_err());
    }

    #[test]
    fn pm_init_accepts_all_flag() {
        let cli = Cli::try_parse_from(["lf", "pm", "init", "--all"]).expect("parse");
        let Some(Commands::Pm {
            cmd:
                PmCommand::Init {
                    wave,
                    wave_flag,
                    all,
                    team_key,
                    team_name,
                },
        }) = cli.command
        else {
            panic!("expected pm init command");
        };

        assert_eq!(wave, None);
        assert_eq!(wave_flag, None);
        assert!(all);
        assert_eq!(team_key, None);
        assert_eq!(team_name, None);
    }

    #[test]
    fn pm_init_accepts_team_key_and_name() {
        let cli = Cli::try_parse_from([
            "lf",
            "pm",
            "init",
            "--wave",
            "product",
            "--team-key",
            "PRD",
            "--team-name",
            "Product",
        ])
        .expect("parse");
        let Some(Commands::Pm {
            cmd:
                PmCommand::Init {
                    team_key,
                    team_name,
                    ..
                },
        }) = cli.command
        else {
            panic!("expected pm init command");
        };

        assert_eq!(team_key.as_deref(), Some("PRD"));
        assert_eq!(team_name.as_deref(), Some("Product"));
    }

    #[test]
    fn pm_reteam_defaults_to_dry_run() {
        let cli = Cli::try_parse_from(["lf", "pm", "reteam"]).expect("parse");
        let Some(Commands::Pm {
            cmd: PmCommand::Reteam { apply },
        }) = cli.command
        else {
            panic!("expected pm reteam command");
        };
        assert!(!apply);

        let cli = Cli::try_parse_from(["lf", "pm", "reteam", "--apply"]).expect("parse apply");
        let Some(Commands::Pm {
            cmd: PmCommand::Reteam { apply },
        }) = cli.command
        else {
            panic!("expected pm reteam command");
        };
        assert!(apply);
    }

    #[test]
    fn pm_project_archive_accepts_wave_and_project() {
        let cli = Cli::try_parse_from([
            "lf",
            "pm",
            "project",
            "archive",
            "--wave",
            "product",
            "--project",
            "wave-chat",
        ])
        .expect("parse");
        let Some(Commands::Pm {
            cmd:
                PmCommand::Project {
                    cmd: PmProjectCommand::Archive { wave, project },
                },
        }) = cli.command
        else {
            panic!("expected pm project archive command");
        };

        assert_eq!(wave.as_deref(), Some("product"));
        assert_eq!(project, "wave-chat");
    }

    #[test]
    fn pm_show_parses_refresh_modes() {
        let cli = Cli::try_parse_from(["lf", "pm", "show", "--wave", "goals"]).expect("parse");
        let Some(Commands::Pm {
            cmd:
                PmCommand::Show {
                    wave,
                    project,
                    json,
                    sync,
                    no_sync,
                },
        }) = cli.command
        else {
            panic!("expected pm show command");
        };
        assert_eq!(wave.as_deref(), Some("goals"));
        assert_eq!(project, None);
        assert!(!json);
        assert!(!sync);
        assert!(!no_sync);

        let cli = Cli::try_parse_from(["lf", "pm", "show", "--sync"]).expect("force sync");
        let Some(Commands::Pm {
            cmd: PmCommand::Show { sync, no_sync, .. },
        }) = cli.command
        else {
            panic!("expected pm show command");
        };
        assert!(sync);
        assert!(!no_sync);

        let cli = Cli::try_parse_from(["lf", "pm", "show", "--no-sync"]).expect("cache-only read");
        let Some(Commands::Pm {
            cmd: PmCommand::Show { sync, no_sync, .. },
        }) = cli.command
        else {
            panic!("expected pm show command");
        };
        assert!(!sync);
        assert!(no_sync);

        assert!(Cli::try_parse_from(["lf", "pm", "show", "--sync", "--no-sync"]).is_err());
    }

    #[test]
    fn chat_parses_text_and_targeting() {
        let cli = Cli::try_parse_from(["lf", "chat", "shipped", "the", "parser"]).expect("parse");
        let Some(Commands::Chat {
            text,
            follow,
            steer,
            target,
            ..
        }) = cli.command
        else {
            panic!("expected chat command");
        };
        assert_eq!(text, vec!["shipped", "the", "parser"]);
        assert!(!follow);
        assert!(!steer);
        assert_eq!(target.wave, None);
        assert!(!target.parent);

        // No text: stdin is the body. Flags come before the trailing text.
        let cli = Cli::try_parse_from(["lf", "chat", "--parent"]).expect("parse");
        let Some(Commands::Chat { text, target, .. }) = cli.command else {
            panic!("expected chat command");
        };
        assert!(text.is_empty());
        assert!(target.parent);

        let cli = Cli::try_parse_from(["lf", "chat", "--wave", "goals", "hi"]).expect("parse");
        let Some(Commands::Chat { text, target, .. }) = cli.command else {
            panic!("expected chat command");
        };
        assert_eq!(text, vec!["hi"]);
        assert_eq!(target.wave.as_deref(), Some("goals"));

        let cli =
            Cli::try_parse_from(["lf", "chat", "--steer", "change course"]).expect("parse steer");
        let Some(Commands::Chat { text, steer, .. }) = cli.command else {
            panic!("expected chat command");
        };
        assert_eq!(text, vec!["change course"]);
        assert!(steer);

        assert!(Cli::try_parse_from(["lf", "chat", "--steer", "--parent", "x"]).is_err());

        // --wave and --parent are mutually exclusive.
        assert!(Cli::try_parse_from(["lf", "chat", "--wave", "goals", "--parent", "x"]).is_err());

        let cli = Cli::try_parse_from(["lf", "chat", "--follow", "--wave", "goals"])
            .expect("parse follow");
        let Some(Commands::Chat {
            text,
            follow,
            steer,
            target,
            ..
        }) = cli.command
        else {
            panic!("expected chat command");
        };
        assert!(text.is_empty());
        assert!(follow);
        assert!(!steer);
        assert_eq!(target.wave.as_deref(), Some("goals"));

        assert!(Cli::try_parse_from(["lf", "chat", "--follow", "hello"]).is_err());

        let cli = Cli::try_parse_from([
            "lf",
            "chat",
            "--history",
            "--json",
            "--limit",
            "20",
            "--epoch",
            "chat-epoch-2",
            "--wave",
            "goals",
        ])
        .expect("parse durable history");
        let Some(Commands::Chat {
            history,
            json,
            limit,
            epoch,
            target,
            ..
        }) = cli.command
        else {
            panic!("expected chat command");
        };
        assert!(history);
        assert!(json);
        assert_eq!(limit, Some(20));
        assert_eq!(epoch.as_deref(), Some("chat-epoch-2"));
        assert_eq!(target.wave.as_deref(), Some("goals"));

        assert!(Cli::try_parse_from(["lf", "chat", "--json", "--wave", "goals"]).is_err());
        assert!(Cli::try_parse_from(["lf", "chat", "--epoch", "chat-epoch-2"]).is_err());
        assert!(Cli::try_parse_from([
            "lf",
            "chat",
            "--history",
            "--json",
            "--follow",
            "--wave",
            "goals"
        ])
        .is_err());
        assert!(Cli::command().find_subcommand("wavechat").is_none());
    }

    #[test]
    fn radio_is_not_a_first_class_command() {
        assert!(Cli::command().find_subcommand("radio").is_none());
        assert!(matches!(
            Cli::try_parse_from(["lf", "radio", "pub", "status"])
                .expect("unknown names remain eligible for skill discovery")
                .command,
            Some(Commands::External(parts)) if parts[0] == "radio"
        ));
    }

    #[test]
    fn evidence_receipt_command_is_absent() {
        assert!(Cli::command().find_subcommand("receipt").is_none());
        let cli = Cli::try_parse_from(["lf", "receipt", "show", "chat_turn:turn-3"])
            .expect("unknown names remain eligible for skill discovery");
        assert!(matches!(cli.command, Some(Commands::External(_))));
    }

    #[test]
    fn pr_open_accepts_model_override() {
        let cli = Cli::try_parse_from(["lf", "pr", "open", "-m", "codex"]).expect("parse");
        let Some(Commands::Pr {
            cmd: Some(PrCommand::Open { model, title, body }),
        }) = cli.command
        else {
            panic!("expected pr command");
        };

        assert_eq!(model.as_deref(), Some("codex"));
        assert_eq!(title, None);
        assert_eq!(body, None);
    }

    #[test]
    fn top_level_model_reaches_pr_open() {
        let cli = Cli::try_parse_from(["lf", "-m", "codex", "pr", "open"]).expect("parse");
        let Some(Commands::Pr {
            cmd: Some(PrCommand::Open { model, title, body }),
        }) = cli.command
        else {
            panic!("expected pr command");
        };

        assert_eq!(cli.model.as_deref(), Some("codex"));
        assert_eq!(model, None);
        assert_eq!(title, None);
        assert_eq!(body, None);
    }
}