cli-engine 0.9.3

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

mod builtins;
mod completion;
mod help;
mod tree_render;

use clap::{Arg, ArgMatches, Command, builder::PossibleValuesParser};

use crate::{
    ActivityEmitter, Auditor, AuthProvider, Authorizer, CliCoreError, CommandMeta, CommandSpec,
    FeatureFlag, GroupSpec, GuideEntry, Middleware, MiddlewareRequest, Result, RuntimeCommandSpec,
    RuntimeGroupSpec,
    auth::commands::auth_command_group,
    command::{
        CommandContext, StreamSender, command_args_from_matches, command_path_from_matches,
        leaf_matches,
    },
    error::exit_code_for_error,
    feature_flags::{FlagEntry, FlagPolicy, FlagRegistry, Stage},
    flags::{
        GlobalFlags, derive_bool_flags, derive_value_flags, extract_command_path,
        extract_output_format, global_flags_from_matches, has_true_schema_flag, min_stage_env_var,
        output_env_var, register_global_flags, register_reason_flag, resolve_default_output_format,
    },
    guide::{guide_content, render_guide_human},
    module::{Module, ModuleContext},
    output::{
        FieldInfo, HumanViewDef, HumanViewRegistry, NextAction, SchemaRegistry,
        format_help_section, global_human_view_registry_snapshot, global_schema_registry_snapshot,
    },
    search::{SearchDocument, SearchIndex},
};

use builtins::{
    completion_args, completion_command, guide_args, guide_command, help_args, help_command,
    search_args, search_command,
};
use help::{GROUP_HELP_TEMPLATE, ROOT_HELP_TEMPLATE};
pub use help::{ModuleHelpEntry, build_root_long, render_next_actions_human};

/// Build metadata shown by the root `--version` flag.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct BuildInfo {
    /// Semantic version or other release label.
    pub version: String,
    /// Optional source control commit identifier.
    pub commit: Option<String>,
    /// Optional build date string.
    pub date: Option<String>,
}

impl BuildInfo {
    /// Creates build metadata with only a version string.
    #[must_use]
    pub fn new(version: impl Into<String>) -> Self {
        Self {
            version: version.into(),
            commit: None,
            date: None,
        }
    }

    /// Adds a commit identifier to the version string shown by `--version`.
    #[must_use]
    pub fn with_commit(mut self, commit: impl Into<String>) -> Self {
        self.commit = Some(commit.into());
        self
    }

    /// Adds a build date to the version string shown by `--version`.
    #[must_use]
    pub fn with_date(mut self, date: impl Into<String>) -> Self {
        self.date = Some(date.into());
        self
    }

    /// Returns the rendered version string used by the root `--version` flag.
    #[must_use]
    pub fn version_string(&self) -> String {
        let commit = self.commit.as_deref().unwrap_or_default();
        let date = self.date.as_deref().unwrap_or_default();

        if commit.is_empty() && date.is_empty() {
            self.version.clone()
        } else {
            format!("{} (commit {commit}, built {date})", self.version)
        }
    }
}

/// Late dependency initializer run once before real command execution.
pub type InitDeps = Arc<dyn Fn(&mut Middleware) -> Result<()> + Send + Sync>;
/// Hook used to add application-specific global flags to the root `clap` command.
pub type RegisterFlags = Arc<dyn Fn(Command) -> Command + Send + Sync>;
/// Hook used to copy parsed application-specific flags into middleware.
pub type ApplyFlags = Arc<dyn Fn(&ArgMatches, &mut Middleware) -> Result<()> + Send + Sync>;
/// Hook run immediately before executable commands and built-ins.
pub type PreRun =
    Arc<dyn Fn(&mut Middleware, &str, &crate::middleware::ValueMap) -> Result<()> + Send + Sync>;
/// Hook used to adjust command metadata globally before middleware executes.
pub type ResolveMeta = Arc<dyn Fn(&str, CommandMeta) -> CommandMeta + Send + Sync>;
/// Hook called after a CLI run completes.
pub type OnShutdown = Arc<dyn Fn() + Send + Sync>;
/// Hook that contributes extra root-scope `search` documents.
pub type ExtraSearchDocs = Arc<dyn Fn() -> Vec<SearchDocument> + Send + Sync>;
/// Hook that supplies the suggested next actions shown when the CLI is invoked
/// with no subcommand (bare root). The same actions drive a human "Next actions"
/// section and the JSON discovery envelope.
pub type RootNextActions = Arc<dyn Fn() -> Vec<NextAction> + Send + Sync>;

/// Default name for the admin help category, under which the engine files the
/// built-in `auth` command when a consumer does not override it via
/// [`CliConfig::with_admin_category`].
const DEFAULT_ADMIN_CATEGORY: &str = "Admin";

/// Maximum number of chained `argv0` dispatch hand-offs before the engine
/// refuses to recurse further. Real multi-call nesting is zero or one level;
/// this bounds a pathologically long explicit `argv0 … argv0 …` chain so it
/// errors cleanly instead of overflowing the stack.
const MAX_ARGV0_DEPTH: usize = 16;

/// How the engine behaves when invoked under a registered alternative `argv[0]`
/// name (busybox/git-style multi-call dispatch).
///
/// A route is selected when the binary's `argv[0]` basename — or the name given
/// to the hidden `argv0` command — matches a key registered via
/// [`CliConfig::with_argv0_alias`] or [`CliConfig::with_argv0_personality`]. An
/// `argv[0]` that matches no route falls through to the default CLI, so existing
/// applications that register no routes are unaffected.
///
/// Non-exhaustive: more route kinds may be added in future releases. Register
/// routes through the [`CliConfig`] builders rather than matching on variants.
#[derive(Clone)]
#[non_exhaustive]
pub enum Argv0Route {
    /// Rewrite the invocation into these canonical subcommand tokens and run it
    /// through the normal command tree, with the real argument tail appended.
    ///
    /// For example, an `Alias(vec!["project".into(), "list".into()])` registered
    /// under `pl` makes `pl --team x` behave exactly like `project list --team x`.
    Alias(Vec<String>),
    /// Run an entirely separate CLI application built from the returned
    /// [`CliConfig`] (its own root name, commands, flags, and auth). The
    /// configuration is built lazily, only when the route is actually dispatched,
    /// so registering a personality costs nothing for invocations that never hit it.
    Personality(Arc<dyn Fn() -> CliConfig + Send + Sync>),
}

impl std::fmt::Debug for Argv0Route {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Alias(tokens) => formatter.debug_tuple("Alias").field(tokens).finish(),
            Self::Personality(_) => formatter.write_str("Personality(..)"),
        }
    }
}

/// On-disk mechanism used by [`Cli::create_link`] to materialize an alternative
/// `argv[0]` name so the binary can be invoked under it.
///
/// Installers pick the mechanism that suits the platform and environment;
/// self-healing code can re-run [`Cli::create_link`] to restore a deleted link.
///
/// Non-exhaustive: more link mechanisms may be added in future releases.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Argv0LinkMethod {
    /// A symbolic link to the target executable (`<name>` on Unix, `<name>.exe`
    /// on Windows). On Windows this may require Developer Mode or elevation.
    SoftLink,
    /// A hard link to the target executable (`<name>` on Unix, `<name>.exe` on
    /// Windows). The link must live on the same volume as the target.
    HardLink,
    /// A small shim script that forwards to the target via the `argv0` command:
    /// a `<name>.cmd` batch file on Windows, or an executable `<name>` shell
    /// script on Unix. Useful when links are unavailable or inconvenient.
    Script,
}

/// Top-level subcommand names that are reserved by the engine and must not be
/// used as module group names.  [`Cli::add_module_group`] rejects a group whose
/// name matches a reserved name so the engine's built-in command always wins.
pub(crate) const BUILTIN_COMMAND_NAMES: [&str; 5] =
    ["help", "guide", "tree", "completion", "search"];

/// Declarative configuration for a CLI application.
///
/// Use [`CliConfig::new`] for the common path and chain `with_*` methods for
/// modules, auth providers, guides, views, and lifecycle hooks. Direct struct
/// literals remain available for advanced setup and tests.
#[derive(Clone, Default)]
pub struct CliConfig {
    /// Root command name shown in usage output.
    pub name: String,
    /// One-line root command description.
    pub short: String,
    /// Optional longer root command description. Defaults to `short`.
    pub long: Option<String>,
    /// Version/build metadata for `--version`.
    pub build: BuildInfo,
    /// Application id stored in middleware and output metadata.
    pub app_id: String,
    /// Fallback auth provider when a command does not select one explicitly.
    pub default_auth_provider: Option<String>,
    /// Domain modules mounted under the root command.
    pub modules: Vec<Module>,
    /// Additional top-level runtime commands.
    pub commands: Vec<RuntimeCommandSpec>,
    /// Additional commands mounted as siblings of the built-in `auth`
    /// group's `login`/`status`/`logout` (e.g. `auth scopes`). Populate via
    /// [`CliConfig::with_auth_extra_commands`]; folded in internally after
    /// the built-in group is built, so the built-ins are never lost or
    /// overwritten.
    pub auth_extra_commands: Vec<RuntimeCommandSpec>,
    /// Global guide entries mounted under `guide`.
    pub guides: Vec<GuideEntry>,
    /// Global human output views.
    pub views: Vec<HumanViewDef>,
    /// Providers registered before command execution starts.
    pub auth_providers: Vec<Arc<dyn AuthProvider>>,
    /// Optional override for the process-wide outbound User-Agent. When unset,
    /// the engine derives `name/version` from this config. See
    /// [`CliConfig::user_agent_string`].
    pub user_agent: Option<String>,
    /// Extra HTTP header names to redact in `--debug transport` output, on top
    /// of the built-in sensitive set (`authorization`, `proxy-authorization`,
    /// `cookie`, `set-cookie`, `x-api-key`). Set CLI-specific secret-bearing
    /// headers here — e.g. a custom API-key header an auth injector adds.
    /// Populate via [`CliConfig::with_redacted_debug_headers`].
    pub redacted_debug_headers: Vec<String>,
    /// Optional authorization gatekeeper injected into middleware.
    pub authz: Option<Arc<dyn Authorizer>>,
    /// Optional audit recorder injected into middleware.
    pub auditor: Option<Arc<dyn Auditor>>,
    /// Optional activity event sink injected into middleware.
    pub activity: Option<Arc<dyn ActivityEmitter>>,
    /// Optional late initializer for runtime dependencies.
    pub init_deps: Option<InitDeps>,
    /// Optional hook for adding application-specific global flags.
    pub register_flags: Option<RegisterFlags>,
    /// Optional hook for applying parsed application-specific flags.
    pub apply_flags: Option<ApplyFlags>,
    /// Optional hook run before executable commands and built-ins.
    pub pre_run: Option<PreRun>,
    /// Optional hook for global command metadata adjustments.
    pub meta_resolver: Option<ResolveMeta>,
    /// Optional hook called after each run.
    pub on_shutdown: Option<OnShutdown>,
    /// Optional root-scope search document provider.
    pub extra_search_docs: Option<ExtraSearchDocs>,
    /// Optional provider for the bare-root suggested next actions.
    pub root_next_actions: Option<RootNextActions>,
    /// Name of the admin help category. The engine files its built-in `auth`
    /// command under this heading; apps should use the same name for their own
    /// admin modules (e.g. godaddy's `env`). When unset, defaults to `"Admin"`;
    /// set it to match a consumer's own taxonomy (e.g. gdx's "Administration").
    pub admin_category: Option<String>,
    /// Whether to mount the built-in `config` command group (`config
    /// get`/`set`/`path`/`list`). Off by default to avoid colliding with a
    /// consumer's own `config` noun. Enable via
    /// [`CliConfig::with_config_commands`].
    pub config_commands: bool,
    /// Alternative `argv[0]` names this binary may be invoked as, mapped to the
    /// behavior the engine should take (busybox/git-style multi-call dispatch).
    ///
    /// Keyed by the bare alternative name (no path, no extension). Empty by
    /// default, in which case argv0 dispatch is inert and behavior is identical
    /// to a binary that never opted in. Populate via [`CliConfig::with_argv0_alias`]
    /// and [`CliConfig::with_argv0_personality`].
    pub argv0_routes: BTreeMap<String, Argv0Route>,
    /// Optional first-class environment system.
    ///
    /// Registered via [`CliConfig::with_environments`]. When set, the engine
    /// registers a global `--env` flag, seeds the active environment into
    /// middleware, and exposes it to handlers through
    /// [`CommandContext::environment`](crate::command::CommandContext::environment).
    pub environments: Option<Arc<crate::environments::Environments>>,
    /// Explicit argv override for [`Cli::new`]'s startup `--env` prescan,
    /// mainly used to make tests hermetic.
    pub startup_args: Option<Vec<std::ffi::OsString>>,
    /// Minimum feature stage required for a flagged command, group, or module
    /// to remain mounted.
    ///
    /// Defaults to [`Stage::Ga`] via [`Stage`]'s own `Default`, which combined
    /// with an empty [`feature_overrides`](Self::feature_overrides) is the
    /// zero-config behavior: nothing is gated unless a command/group/module
    /// opts in with `.with_feature_flag(...)`, and even then it stays visible
    /// until this is lowered. Lower it (e.g. to [`Stage::Beta`] or
    /// [`Stage::Experimental`]) to opt a build or environment into
    /// pre-release commands. Set via [`CliConfig::with_min_stage`].
    pub min_stage: Stage,
    /// Per-key stage overrides that substitute a forced stage for a flag
    /// key's own declared stage before comparing against
    /// [`min_stage`](Self::min_stage).
    ///
    /// Empty by default. Populate via [`CliConfig::with_feature_override`] to
    /// force one named flag to a specific effective stage — e.g. forcing a
    /// single flag to [`Stage::Ga`] to turn it on for internal testing without
    /// lowering [`min_stage`](Self::min_stage) for every other flagged
    /// command, or forcing it to [`Stage::Experimental`] to disable it even
    /// under a permissive `min_stage`. See [`FlagPolicy::visible`] for the
    /// exact comparison.
    pub feature_overrides: BTreeMap<String, Stage>,
    /// Whether to auto-enable interactive mode when a TTY is detected.
    ///
    /// When `false` (the default), commands only run interactively if the user
    /// passes `--interactive` explicitly. When `true`, the engine auto-detects
    /// a TTY (stdin + stderr) and defaults to interactive mode — meaning
    /// missing required arguments will be prompted for instead of erroring.
    ///
    /// Set via [`CliConfig::with_auto_interactive`]. Start with `false` for
    /// backwards compatibility; flip to `true` once the CLI's commands have
    /// been tested under interactive prompting.
    pub auto_interactive: bool,
}

impl CliConfig {
    /// Creates the minimum useful CLI configuration.
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        short: impl Into<String>,
        app_id: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            short: short.into(),
            app_id: app_id.into(),
            ..Self::default()
        }
    }

    /// Sets root long help text.
    #[must_use]
    pub fn with_long(mut self, long: impl Into<String>) -> Self {
        self.long = Some(long.into());
        self
    }

    /// Sets build metadata used by `--version`.
    #[must_use]
    pub fn with_build(mut self, build: BuildInfo) -> Self {
        self.build = build;
        self
    }

    /// Sets the fallback auth provider for commands that do not name one.
    #[must_use]
    pub fn with_default_auth_provider(mut self, provider: impl Into<String>) -> Self {
        self.default_auth_provider = Some(provider.into());
        self
    }

    /// Registers a first-class environment system.
    ///
    /// When set, [`Cli::new`] registers a global `--env` flag, seeds the active
    /// environment into middleware (explicit `--env` > persisted active >
    /// configured default), and exposes the resolved environment to handlers via
    /// [`CommandContext::environment`](crate::command::CommandContext::environment).
    ///
    /// The [`Environments`](crate::environments::Environments) is stored as-is, so
    /// the consumer is responsible for configuring it before wrapping it in an
    /// `Arc`:
    ///
    /// - Call
    ///   [`Environments::with_app_id`](crate::environments::Environments::with_app_id)
    ///   with the **same** `app_id` passed to [`CliConfig::new`], so the config
    ///   file and active-environment persistence resolve to the application's
    ///   config directory. (An empty `app_id` makes
    ///   [`Environments::config_file_path`](crate::environments::Environments::config_file_path)
    ///   return `None`, silently disabling the `environments.toml` file layer.)
    /// - Call
    ///   [`Environments::with_config_file(true)`](crate::environments::Environments::with_config_file)
    ///   if the application loads a user-editable `environments.toml`.
    /// - **Share the same `Arc`** with any `PkceAuthProvider::with_environments`
    ///   (available with the `pkce-auth` feature):
    ///   the provider's OAuth file layer and active-environment persistence must
    ///   resolve against the identical, `app_id`-stamped instance the engine sees,
    ///   or a file-defined environment (or a file override of a compiled
    ///   environment's `client_id`) will be visible to `env info` yet invisible to
    ///   the actual OAuth login.
    #[must_use]
    pub fn with_environments(
        mut self,
        environments: Arc<crate::environments::Environments>,
    ) -> Self {
        self.environments = Some(environments);
        self
    }

    /// Overrides the argv [`Cli::new`] prescans for `--env` before pruning the
    /// command tree, instead of the real process argv.
    ///
    /// Only meaningful alongside [`with_environments`](Self::with_environments)
    /// — otherwise `Cli::new` never registers `--env` or does the prescan at
    /// all, so this is silently unused. Element `0` is treated as the program
    /// name and skipped, the same convention [`Cli::run`]/[`Cli::execute_from`]
    /// use for their own `args` parameter.
    ///
    /// This matters beyond tests: tree pruning is decided once, at `Cli::new`
    /// time, from either this override or real process argv — never from the
    /// `args` a later [`Cli::run`]/[`Cli::execute_from`] call receives. Any
    /// caller that builds the `Cli` once and later runs it with a synthetic
    /// argv (e.g. a wrapper binary invoking it programmatically, or a fixed
    /// argument list unrelated to `std::env::args_os()`) should pass the same
    /// `--env` here too, or an environment named only in the later call's
    /// argv won't have been consulted for pruning, and a flagged command that
    /// environment would reveal (or hide) can disagree with what actually
    /// dispatches. A test that configures `with_environments` should call
    /// this (even with an empty iterator) to keep construction hermetic;
    /// without it, `Cli::new` reads whatever real argv the test binary itself
    /// was invoked with.
    #[must_use]
    pub fn with_startup_args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<std::ffi::OsString>,
    {
        self.startup_args = Some(args.into_iter().map(Into::into).collect());
        self
    }

    /// Sets the minimum feature stage required for a flagged command, group,
    /// or module to remain mounted.
    ///
    /// See [`min_stage`](Self::min_stage) for the default and [`FlagPolicy`]
    /// for how it combines with [`feature_overrides`](Self::feature_overrides)
    /// during command-tree pruning.
    #[must_use]
    pub fn with_min_stage(mut self, stage: Stage) -> Self {
        self.min_stage = stage;
        self
    }

    /// Enables auto-interactive mode: when a TTY is detected, the CLI
    /// defaults to interactive prompting for missing required arguments.
    ///
    /// Off by default for backwards compatibility. Enable once commands have
    /// been tested under interactive prompting. `--interactive` still works as
    /// an explicit override regardless of this setting.
    #[must_use]
    pub fn with_auto_interactive(mut self, enabled: bool) -> Self {
        self.auto_interactive = enabled;
        self
    }

    /// Adds (or replaces) a per-key feature-flag stage override.
    ///
    /// See [`feature_overrides`](Self::feature_overrides) for how the
    /// override participates in the [`FlagPolicy::visible`] comparison.
    #[must_use]
    pub fn with_feature_override(mut self, key: impl Into<String>, stage: Stage) -> Self {
        self.feature_overrides.insert(key.into(), stage);
        self
    }

    /// Builds the merged [`FlagPolicy`] used for command-tree pruning from
    /// this config's `min_stage` and `feature_overrides`.
    fn flag_policy(&self) -> FlagPolicy {
        FlagPolicy {
            min_stage: self.min_stage,
            overrides: self.feature_overrides.clone(),
        }
    }

    /// Overrides the outbound User-Agent string for all HTTP traffic.
    ///
    /// When unset, the engine derives `name/version` from this config (see
    /// [`CliConfig::user_agent_string`]). Set this when the upstream APIs expect
    /// a specific product token. The resolved value is applied process-wide on
    /// execution via [`crate::transport::set_default_user_agent`], so it reaches
    /// both command [`HttpClient`](crate::transport::HttpClient)s and the
    /// engine's own OAuth token requests.
    #[must_use]
    pub fn with_user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = Some(user_agent.into());
        self
    }

    /// Adds HTTP header names to redact in `--debug transport` output, on top of
    /// the built-in sensitive set.
    ///
    /// Use this for CLI-specific secret-bearing headers that are not standard
    /// auth headers — for example a custom API-key header that an
    /// [`AuthInjector`](crate::transport::AuthInjector) sets. Matching is
    /// case-insensitive and additive: the built-in set is always redacted.
    /// Calls accumulate. Names are trimmed and empty entries are dropped, so a
    /// mistyped value with stray whitespace cannot silently disable redaction.
    #[must_use]
    pub fn with_redacted_debug_headers(
        mut self,
        names: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.redacted_debug_headers
            .extend(names.into_iter().filter_map(|name| {
                let name = name.into().trim().to_owned();
                (!name.is_empty()).then_some(name)
            }));
        self
    }

    /// Returns the outbound User-Agent string the CLI presents on HTTP requests.
    ///
    /// Resolution order:
    /// 1. an explicit [`with_user_agent`](Self::with_user_agent) override;
    /// 2. otherwise `name/version` (for example `gdx/1.2.3`);
    /// 3. otherwise just `name` when no build version is set.
    #[must_use]
    pub fn user_agent_string(&self) -> String {
        if let Some(user_agent) = &self.user_agent {
            return user_agent.clone();
        }
        if self.build.version.is_empty() {
            self.name.clone()
        } else {
            format!("{}/{}", self.name, self.build.version)
        }
    }

    /// Adds one domain module.
    ///
    /// # Reserved group names
    ///
    /// The top-level group names `help`, `guide`, `tree`, and `completion` are
    /// reserved by the engine.  A module whose root group uses one of these
    /// names will be rejected at registration time (logged as a warning) so
    /// the engine's own built-in always takes precedence in the command tree.
    #[must_use]
    pub fn with_module(mut self, module: Module) -> Self {
        self.modules.push(module);
        self
    }

    /// Adds several domain modules.
    ///
    /// See [`with_module`](Self::with_module) for the list of reserved group names.
    #[must_use]
    pub fn with_modules(mut self, modules: impl IntoIterator<Item = Module>) -> Self {
        self.modules.extend(modules);
        self
    }

    /// Adds a top-level runtime command outside a module.
    #[must_use]
    pub fn with_command(mut self, command: RuntimeCommandSpec) -> Self {
        self.commands.push(command);
        self
    }

    /// Adds commands mounted as siblings of the built-in `auth` group's
    /// `login`/`status`/`logout`.
    ///
    /// Use this to extend `auth` with consumer-specific subcommands (e.g.
    /// `auth scopes`) without losing or duplicating the built-ins — unlike
    /// pre-registering an `auth` [`Module`], which either drops the built-ins
    /// entirely or has them silently overwrite any extra command added this
    /// way, these are folded in additively after building the built-in group.
    #[must_use]
    pub fn with_auth_extra_commands(
        mut self,
        commands: impl IntoIterator<Item = RuntimeCommandSpec>,
    ) -> Self {
        self.auth_extra_commands.extend(commands);
        self
    }

    /// Adds one global guide.
    #[must_use]
    pub fn with_guide(mut self, guide: GuideEntry) -> Self {
        self.guides.push(guide);
        self
    }

    /// Adds several global guides.
    #[must_use]
    pub fn with_guides(mut self, guides: impl IntoIterator<Item = GuideEntry>) -> Self {
        self.guides.extend(guides);
        self
    }

    /// Adds one global human view.
    #[must_use]
    pub fn with_view(mut self, view: HumanViewDef) -> Self {
        self.views.push(view);
        self
    }

    /// Registers one auth provider.
    #[must_use]
    pub fn with_auth_provider(mut self, provider: Arc<dyn AuthProvider>) -> Self {
        self.auth_providers.push(provider);
        self
    }

    /// Sets the authorization gatekeeper.
    #[must_use]
    pub fn with_authz(mut self, authz: Arc<dyn Authorizer>) -> Self {
        self.authz = Some(authz);
        self
    }

    /// Sets the audit recorder.
    #[must_use]
    pub fn with_auditor(mut self, auditor: Arc<dyn Auditor>) -> Self {
        self.auditor = Some(auditor);
        self
    }

    /// Sets the activity event sink.
    #[must_use]
    pub fn with_activity(mut self, activity: Arc<dyn ActivityEmitter>) -> Self {
        self.activity = Some(activity);
        self
    }

    /// Sets the late dependency initializer.
    #[must_use]
    pub fn with_init_deps(mut self, init_deps: InitDeps) -> Self {
        self.init_deps = Some(init_deps);
        self
    }

    /// Sets the application-specific global flag registration hook.
    #[must_use]
    pub fn with_register_flags(mut self, register_flags: RegisterFlags) -> Self {
        self.register_flags = Some(register_flags);
        self
    }

    /// Sets the application-specific parsed flag application hook.
    #[must_use]
    pub fn with_apply_flags(mut self, apply_flags: ApplyFlags) -> Self {
        self.apply_flags = Some(apply_flags);
        self
    }

    /// Sets the pre-run hook.
    #[must_use]
    pub fn with_pre_run(mut self, pre_run: PreRun) -> Self {
        self.pre_run = Some(pre_run);
        self
    }

    /// Sets the command metadata resolver hook.
    #[must_use]
    pub fn with_meta_resolver(mut self, meta_resolver: ResolveMeta) -> Self {
        self.meta_resolver = Some(meta_resolver);
        self
    }

    /// Sets the shutdown hook.
    #[must_use]
    pub fn with_on_shutdown(mut self, on_shutdown: OnShutdown) -> Self {
        self.on_shutdown = Some(on_shutdown);
        self
    }

    /// Sets the provider for additional root-scope search documents.
    #[must_use]
    pub fn with_extra_search_docs(mut self, extra_search_docs: ExtraSearchDocs) -> Self {
        self.extra_search_docs = Some(extra_search_docs);
        self
    }

    /// Sets the provider for the bare-root suggested next actions.
    #[must_use]
    pub fn with_root_next_actions(mut self, root_next_actions: RootNextActions) -> Self {
        self.root_next_actions = Some(root_next_actions);
        self
    }

    /// Sets the name of the admin help category. The engine files the built-in
    /// `auth` command there; apps should use the same name for their own admin
    /// modules (e.g. godaddy's `env`). Optional: defaults to `"Admin"`.
    #[must_use]
    pub fn with_admin_category(mut self, category: impl Into<String>) -> Self {
        self.admin_category = Some(category.into());
        self
    }

    /// Mounts the built-in `config` command group (`config get`/`set`/`path`/
    /// `list`) for reading and writing the per-application config file.
    ///
    /// Off by default so it never collides with a consumer's own `config` noun;
    /// the group is filed under the admin help category when enabled.
    #[must_use]
    pub fn with_config_commands(mut self) -> Self {
        self.config_commands = true;
        self
    }

    /// Registers an alternative `argv[0]` name that acts as a shortcut to a
    /// command path on this same CLI.
    ///
    /// When the binary is invoked under `name` (via symlink, hardlink, copy, or
    /// the hidden `argv0` command), the engine behaves as if the user had typed
    /// `command_path` followed by the real argument tail, routed through the
    /// normal command tree. For example:
    ///
    /// ```
    /// use cli_engine::CliConfig;
    ///
    /// // Invoking the binary as `pl --team platform` runs `project list --team platform`.
    /// let config = CliConfig::new("my-cli", "Team CLI", "my-cli")
    ///     .with_argv0_alias("pl", ["project", "list"]);
    /// ```
    ///
    /// `name` must be a simple token: non-empty and composed only of ASCII
    /// letters, digits, `-`, or `_` (no dots, spaces, path separators, or shell
    /// metacharacters), and it must differ from the CLI's own name. These are
    /// debug-asserted. The restriction keeps the name usable as a link/shim
    /// filename and an `argv[0]` basename (which is matched with its extension
    /// stripped, so a dot would break matching).
    #[must_use]
    pub fn with_argv0_alias(
        mut self,
        name: impl Into<String>,
        command_path: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        let name = name.into();
        debug_assert!(
            is_valid_argv0_name(&name),
            "argv0 route name {name:?} must be non-empty and contain only ASCII letters, digits, '-', or '_'"
        );
        debug_assert!(
            name != self.name,
            "argv0 route name {name:?} must differ from the CLI's own name {:?}",
            self.name
        );
        let tokens = command_path.into_iter().map(Into::into).collect();
        self.argv0_routes.insert(name, Argv0Route::Alias(tokens));
        self
    }

    /// Registers an alternative `argv[0]` name that runs an entirely separate CLI
    /// application.
    ///
    /// When the binary is invoked under `name`, the engine builds a fresh
    /// [`CliConfig`] from `build` and runs that application instead — its own root
    /// name, commands, flags, and auth. The closure runs lazily, only when the
    /// route is dispatched, so unused personalities cost nothing. The personality
    /// presents the name from its own [`CliConfig`] in help and usage output.
    ///
    /// ```
    /// use cli_engine::CliConfig;
    ///
    /// let config = CliConfig::new("my-cli", "Team CLI", "my-cli")
    ///     .with_argv0_personality("legacy-tool", || {
    ///         CliConfig::new("legacy-tool", "Legacy compatibility shim", "legacy-tool")
    ///     });
    /// ```
    ///
    /// `name` follows the same contract as [`CliConfig::with_argv0_alias`]: a
    /// simple `[A-Za-z0-9_-]` token, differing from the CLI's own name
    /// (debug-asserted).
    #[must_use]
    pub fn with_argv0_personality(
        mut self,
        name: impl Into<String>,
        build: impl Fn() -> CliConfig + Send + Sync + 'static,
    ) -> Self {
        let name = name.into();
        debug_assert!(
            is_valid_argv0_name(&name),
            "argv0 route name {name:?} must be non-empty and contain only ASCII letters, digits, '-', or '_'"
        );
        debug_assert!(
            name != self.name,
            "argv0 route name {name:?} must differ from the CLI's own name {:?}",
            self.name
        );
        self.argv0_routes
            .insert(name, Argv0Route::Personality(Arc::new(build)));
        self
    }
}

impl std::fmt::Debug for CliConfig {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("CliConfig")
            .field("name", &self.name)
            .field("short", &self.short)
            .field("long", &self.long)
            .field("build", &self.build)
            .field("app_id", &self.app_id)
            .field("default_auth_provider", &self.default_auth_provider)
            .field("modules", &self.modules)
            .field("commands", &self.commands)
            .field("guides", &self.guides)
            .field("views", &self.views)
            .field("auth_providers_len", &self.auth_providers.len())
            .field("has_authz", &self.authz.is_some())
            .field("has_auditor", &self.auditor.is_some())
            .field("has_activity", &self.activity.is_some())
            .field("has_init_deps", &self.init_deps.is_some())
            .field("has_register_flags", &self.register_flags.is_some())
            .field("has_apply_flags", &self.apply_flags.is_some())
            .field("has_pre_run", &self.pre_run.is_some())
            .field("has_meta_resolver", &self.meta_resolver.is_some())
            .field("has_on_shutdown", &self.on_shutdown.is_some())
            .field("has_extra_search_docs", &self.extra_search_docs.is_some())
            .field("has_root_next_actions", &self.root_next_actions.is_some())
            .field("admin_category", &self.admin_category)
            .field(
                "argv0_routes",
                &self.argv0_routes.keys().collect::<Vec<_>>(),
            )
            .field("min_stage", &self.min_stage)
            .field("feature_overrides", &self.feature_overrides)
            .finish()
    }
}

/// Captured result of running a CLI in tests or embedding contexts.
#[derive(Clone, Debug, PartialEq)]
pub struct CliRunOutput {
    /// Process-style exit code.
    pub exit_code: i32,
    /// Rendered stdout or stderr payload.
    pub rendered: String,
}

impl From<crate::middleware::MiddlewareOutput> for CliRunOutput {
    fn from(o: crate::middleware::MiddlewareOutput) -> Self {
        Self {
            exit_code: o.exit_code,
            rendered: o.rendered,
        }
    }
}

/// Configured CLI application.
///
/// A `Cli` owns the `clap` command tree, middleware, registered runtime
/// commands, guides, schemas, and built-ins. Consumer binaries normally create
/// one `Cli` and call [`Cli::execute`].
#[derive(Clone)]
pub struct Cli {
    config: CliConfig,
    middleware: Middleware,
    root: Command,
    commands: BTreeMap<String, RuntimeCommandSpec>,
    module_entries: Vec<ModuleHelpEntry>,
    guide_entries: Vec<GuideEntry>,
    init_deps: Option<InitDeps>,
    apply_flags: Option<ApplyFlags>,
    pre_run: Option<PreRun>,
    meta_resolver: Option<ResolveMeta>,
    on_shutdown: Option<OnShutdown>,
    extra_search_docs: Option<ExtraSearchDocs>,
    root_next_actions: Option<RootNextActions>,
    init_state: Arc<Mutex<Option<std::result::Result<Middleware, InitFailure>>>>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct InitFailure {
    message: String,
    code: String,
    system: String,
    request_id: String,
    fix: Option<String>,
    exit_code: i32,
}

impl InitFailure {
    fn capture(err: &CliCoreError) -> Self {
        let envelope = crate::output::build_error_envelope(err, "");
        let (code, system, request_id) = envelope.error.map_or_else(
            || ("ERROR".to_owned(), String::new(), String::new()),
            |error| (error.code, error.system, error.request_id),
        );
        Self {
            message: err.to_string(),
            code,
            system,
            request_id,
            fix: envelope.fix,
            exit_code: exit_code_for_error(err),
        }
    }

    fn into_error(self) -> CliCoreError {
        let message = CliCoreError::SystemMessage {
            message: self.message,
            system: self.system,
            code: self.code,
            request_id: self.request_id,
        };
        CliCoreError::with_exit_code(
            self.exit_code,
            CliCoreError::with_fix(self.fix.unwrap_or_default(), message),
        )
    }
}

impl std::fmt::Debug for Cli {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Cli")
            .field("config", &self.config)
            .field("middleware", &self.middleware)
            .field("root", &self.root)
            .field("commands", &self.commands)
            .field("module_entries", &self.module_entries)
            .field("guide_entries", &self.guide_entries)
            .field("has_init_deps", &self.init_deps.is_some())
            .field("has_apply_flags", &self.apply_flags.is_some())
            .field("has_pre_run", &self.pre_run.is_some())
            .field("has_meta_resolver", &self.meta_resolver.is_some())
            .field("has_on_shutdown", &self.on_shutdown.is_some())
            .field("has_extra_search_docs", &self.extra_search_docs.is_some())
            .field("has_root_next_actions", &self.root_next_actions.is_some())
            .finish()
    }
}

impl Cli {
    /// Builds a CLI application from declarative configuration.
    #[must_use]
    pub fn new(config: CliConfig) -> Self {
        let auth_providers = config.auth_providers.clone();
        let guides = config.guides.clone();
        let views = config.views.clone();
        let modules = config.modules.clone();
        let commands = config.commands.clone();
        let init_deps = config.init_deps.clone();
        let apply_flags = config.apply_flags.clone();
        let pre_run = config.pre_run.clone();
        let meta_resolver = config.meta_resolver.clone();
        let on_shutdown = config.on_shutdown.clone();
        let extra_search_docs = config.extra_search_docs.clone();
        let root_next_actions = config.root_next_actions.clone();
        let mut root = Command::new(config.name.clone())
            .about(config.short.clone())
            .disable_help_subcommand(true)
            .version(config.build.version_string());
        if let Some(long) = &config.long
            && !long.is_empty()
        {
            root = root.long_about(long.clone());
        }
        root = register_global_flags(root)
            .subcommand(help_command())
            .subcommand(guide_command())
            .subcommand(Command::new("tree").about("Display full command tree"))
            .subcommand(completion_command())
            .subcommand(search_command());
        if let Some(register_flags) = &config.register_flags {
            root = register_flags(root);
        }
        // `--reason` is only meaningful when something actually consumes it —
        // an authorizer, auditor, or activity emitter. Apps with none of those
        // registered never see the flag at all, rather than a flag whose value
        // is captured and silently discarded. This checks the eager `CliConfig`
        // fields only: an authorizer/auditor/activity emitter installed later via
        // `init_deps` runs per-request, after flag registration, so it can't be
        // observed here. Apps that want `--reason` must set `authz`/`auditor`/
        // `activity` directly on `CliConfig`, not exclusively through `init_deps`.
        if config.authz.is_some() || config.auditor.is_some() || config.activity.is_some() {
            root = register_reason_flag(root);
        }
        if config.environments.is_some() {
            root = root.arg(
                Arg::new("env")
                    .long("env")
                    .global(true)
                    .value_name("ENV")
                    .display_order(crate::flags::global_flag_order::ENV)
                    .help("Override the active environment (see: env list)"),
            );
        }
        let intro = config
            .long
            .as_deref()
            .filter(|long| !long.is_empty())
            .unwrap_or(config.short.as_str());
        root = root
            .long_about(build_root_long(intro, &[], false))
            .help_template(ROOT_HELP_TEMPLATE);

        let mut middleware = Middleware::new();
        middleware.app_id = config.app_id.clone();
        // One-time, macOS-only: move any pre-existing $HOME/.config/<app_id>
        // contents to $HOME/Library/Application Support/<app_id> before the
        // config file below is loaded from its (possibly new) location.
        crate::fs::migrate_macos_config_dir(&config.app_id);
        // Load the per-application config file once at startup; cloned into each
        // per-run middleware so handlers and module registration share it.
        middleware.config = Arc::new(crate::config::ConfigFile::load(&config.app_id));
        middleware.default_auth_provider = config.default_auth_provider.clone().unwrap_or_default();
        middleware.authz = config.authz.clone();
        middleware.auditor = config.auditor.clone();
        middleware.activity = config.activity.clone();
        middleware
            .schema_registry
            .merge(&global_schema_registry_snapshot());
        middleware
            .human_views
            .merge(&global_human_view_registry_snapshot());
        if let Some(environments) = &config.environments {
            // Seed the sticky/default active environment now, but let a
            // startup `--env` win over it if one is present: `prescan_env_flag`
            // scans `startup_args` (or, when unset, the real process argv) the
            // same way `apply_env_flag` will parse it for real per invocation
            // — this is what lets a same-invocation `--env <name>` affect the
            // `flag_policy` computed below (and therefore which flagged
            // commands get pruned), not just `middleware.env`. The real,
            // per-invocation value used for dispatch still comes from
            // `apply_env_flag`'s clap parse in `run_with_depth`; this prescan
            // only decides tree shape earlier than clap otherwise could,
            // since that decision can't be revisited once the tree is built.
            let startup_args = config
                .startup_args
                .clone()
                .unwrap_or_else(|| std::env::args_os().collect());
            let startup_env_flag = prescan_env_flag(
                startup_args
                    .iter()
                    .skip(1) // argv[0] is the program name, same convention `run`/`execute_from` use
                    .map(|arg| arg.to_string_lossy().into_owned()),
            );
            // The same `Arc` the consumer shared with any `PkceAuthProvider` is
            // reused, so the file layer and active-env persistence resolve
            // consistently.
            middleware.env =
                environments.effective_active(startup_env_flag.as_deref(), &middleware.config);
            middleware.environments = Some(Arc::clone(environments));
        }
        let mut flag_policy = config.flag_policy();
        if let Some(min_stage) = global_min_stage_override(&config.app_id) {
            flag_policy.min_stage = min_stage;
        }
        if let Some(environments) = &middleware.environments
            && let Ok(source) = environments.source(&middleware.env)
        {
            let chain = crate::env_config::SourceChain::new().push(&source);
            match crate::env_config::resolve_field::<Stage>(
                &chain,
                "min_stage",
                "min_stage",
                None,
                false,
                crate::env_config::default_from_toml::<Stage>,
                |_raw: &str| -> std::result::Result<Stage, String> { Err(String::new()) },
            ) {
                Ok(Some(min_stage)) => flag_policy.min_stage = min_stage,
                Ok(None) => {}
                Err(err) => {
                    tracing::warn!(env = %middleware.env, error = %err, "ignoring invalid environment min_stage");
                }
            }
            match crate::env_config::resolve_field::<BTreeMap<String, Stage>>(
                &chain,
                "feature_overrides",
                "feature_overrides",
                None,
                false,
                crate::env_config::default_from_toml::<BTreeMap<String, Stage>>,
                |_raw: &str| -> std::result::Result<BTreeMap<String, Stage>, String> {
                    Err(String::new())
                },
            ) {
                Ok(Some(overrides)) => flag_policy.overrides.extend(overrides),
                Ok(None) => {}
                Err(err) => {
                    tracing::warn!(env = %middleware.env, error = %err, "ignoring invalid environment feature_overrides");
                }
            }
        }
        middleware.flag_policy = flag_policy;

        let mut cli = Self {
            config,
            middleware,
            root,
            commands: BTreeMap::new(),
            module_entries: Vec::new(),
            guide_entries: Vec::new(),
            init_deps,
            apply_flags,
            pre_run,
            meta_resolver,
            on_shutdown,
            extra_search_docs,
            root_next_actions,
            init_state: Arc::new(Mutex::new(None)),
        };
        for provider in auth_providers {
            cli.register_auth_provider(provider);
        }
        if cli.middleware.default_auth_provider.is_empty()
            && let Some(provider) = cli.middleware.auth.registered_names().first()
        {
            cli.middleware.default_auth_provider = provider.clone();
        }
        if !cli.middleware.default_auth_provider.is_empty() {
            cli.ensure_auth_command();
        }
        for view in views {
            cli.middleware.human_views.register(view);
        }
        cli.add_guides(guides);
        for module in modules {
            cli.add_module(module);
        }
        for command in commands {
            cli.add_command(command);
        }
        if cli.config.config_commands {
            cli.ensure_config_command();
        }
        if cli.config.environments.is_some() {
            cli.ensure_env_command();
        }
        cli.ensure_flags_command();
        cli
    }

    /// Lists the auto-registered `auth` command under the admin help category so
    /// it is never uncategorized once clap's auto subcommand list is suppressed.
    /// Defaults to [`DEFAULT_ADMIN_CATEGORY`]; `admin_category` overrides it to
    /// align with a consumer's own taxonomy.
    fn register_auth_help_entry(&mut self) {
        let category = self
            .config
            .admin_category
            .clone()
            .unwrap_or_else(|| DEFAULT_ADMIN_CATEGORY.to_owned());
        let already_listed = self.module_entries.iter().any(|entry| entry.name == "auth");
        let short = self
            .root
            .find_subcommand("auth")
            .filter(|auth| !auth.is_hide_set())
            .map(|auth| {
                auth.get_about()
                    .map(ToString::to_string)
                    .unwrap_or_default()
            });
        if !already_listed && let Some(short) = short {
            self.module_entries.push(ModuleHelpEntry {
                category,
                name: "auth".to_owned(),
                short,
            });
        }
        self.refresh_root_long();
    }

    /// Returns the shared middleware template.
    #[must_use]
    pub fn middleware(&self) -> &Middleware {
        &self.middleware
    }

    /// Returns mutable middleware for advanced application setup.
    pub fn middleware_mut(&mut self) -> &mut Middleware {
        &mut self.middleware
    }

    /// Executes the CLI with process arguments and process stdout/stderr.
    pub async fn execute(&self) -> ExitCode {
        let mut stdout = std::io::stdout().lock();
        let mut stderr = std::io::stderr().lock();
        match self
            .execute_from(std::env::args_os(), &mut stdout, &mut stderr)
            .await
        {
            Ok(code) => code,
            Err(err) => {
                drop(writeln!(stderr, "{err}"));
                ExitCode::from(1)
            }
        }
    }

    /// Executes the CLI with caller-provided args and output writers.
    ///
    /// If `args` carries a synthetic `--env` unrelated to real process argv
    /// (or to whatever [`CliConfig::with_startup_args`] this `Cli` was built
    /// with), command-tree pruning — decided once, at construction time —
    /// won't reflect it; see `with_startup_args`'s doc for why.
    pub async fn execute_from<I, S, O, E>(
        &self,
        args: I,
        stdout: &mut O,
        stderr: &mut E,
    ) -> std::io::Result<ExitCode>
    where
        I: IntoIterator<Item = S>,
        S: Into<std::ffi::OsString> + Clone,
        O: Write,
        E: Write,
    {
        self.execute_from_until_signal(args, stdout, stderr, shutdown_signal())
            .await
    }

    /// Executes the CLI until either command completion or a shutdown signal future resolves.
    pub async fn execute_from_until_signal<I, S, O, E, Shutdown>(
        &self,
        args: I,
        stdout: &mut O,
        stderr: &mut E,
        shutdown: Shutdown,
    ) -> std::io::Result<ExitCode>
    where
        I: IntoIterator<Item = S>,
        S: Into<std::ffi::OsString> + Clone,
        O: Write,
        E: Write,
        Shutdown: Future<Output = ()>,
    {
        self.install_default_user_agent();
        let output = run_until_signal(self.run(args), shutdown).await;
        if output.exit_code == 130
            && output.rendered == "command interrupted\n"
            && let Some(on_shutdown) = &self.on_shutdown
        {
            on_shutdown();
        }
        if output.exit_code == 0 {
            stdout.write_all(output.rendered.as_bytes())?;
        } else {
            stderr.write_all(output.rendered.as_bytes())?;
        }
        Ok(process_exit_code(output.exit_code))
    }

    /// Publishes the configured outbound User-Agent process-wide so that
    /// command [`HttpClient`](crate::transport::HttpClient)s and the engine's
    /// own OAuth token requests share it.
    ///
    /// Called from the execution entrypoints rather than [`Cli::new`] so that
    /// merely constructing a `Cli` (as tests do in bulk) does not mutate global
    /// state. See [`CliConfig::user_agent_string`] for resolution order.
    fn install_default_user_agent(&self) {
        crate::transport::set_default_user_agent(self.config.user_agent_string());
    }

    /// Registers an auth provider after construction.
    pub fn register_auth_provider(&mut self, provider: Arc<dyn AuthProvider>) -> &mut Self {
        self.middleware.auth.register(provider);
        self.ensure_auth_command();
        self.refresh_root_long();
        self
    }

    /// Returns the built `clap` root command.
    #[must_use]
    pub fn root_command(&self) -> &Command {
        &self.root
    }

    /// Adds one runtime module group after construction.
    pub fn add_module_group(
        &mut self,
        category: impl Into<String>,
        group: RuntimeGroupSpec,
    ) -> &mut Self {
        self.add_module_group_inner(category, group, None)
    }

    /// Shared implementation behind [`add_module_group`](Self::add_module_group)
    /// and [`add_module`](Self::add_module). `inherited` is the effective
    /// feature flag the group's enclosing module declared (if any), so a
    /// module-level flag cascades down to the group even though
    /// `add_module_group` itself has no concept of a module.
    fn add_module_group_inner(
        &mut self,
        category: impl Into<String>,
        group: RuntimeGroupSpec,
        inherited: Option<FeatureFlag>,
    ) -> &mut Self {
        // Prevent consumer modules from shadowing engine built-ins in the clap
        // command tree.  A reserved group name would override the engine's own
        // subcommand (last-writer-wins in clap) and corrupt the dispatch path.
        if BUILTIN_COMMAND_NAMES.contains(&group.group.name.as_str()) {
            tracing::warn!(
                name = %group.group.name,
                "module group name is reserved by cli-engine built-ins; the group will not be registered"
            );
            return self;
        }

        let mut prefix = Vec::new();
        let Some(group) = prune_feature_flag_tree(
            group,
            inherited.as_ref(),
            &self.middleware.flag_policy,
            &mut prefix,
            &mut self.middleware.flag_registry,
        ) else {
            return self;
        };

        let category = category.into();
        if !group.group.hidden {
            self.module_entries.push(ModuleHelpEntry {
                category,
                name: group.group.name.clone(),
                short: group.group.short.clone(),
            });
        }

        let mut prefix = Vec::new();
        register_runtime_group_metadata(
            &group,
            &mut prefix,
            &mut self.middleware.schema_registry,
            &mut self.middleware.human_views,
        );
        let mut prefix = Vec::new();
        group.register_commands(&mut prefix, &mut self.commands);
        let mut prefix = Vec::new();
        let clap_group = runtime_group_clap_command_with_schema_help(
            &group,
            &mut prefix,
            &self.middleware.schema_registry,
        );
        self.root = self.root.clone().subcommand(clap_group);
        self.refresh_root_long();
        self
    }

    /// Adds one module after construction.
    pub fn add_module(&mut self, module: Module) -> &mut Self {
        for view in module.views.clone() {
            self.middleware.human_views.register(view);
        }
        self.add_guides(module.guides.clone());
        let mut context = ModuleContext::new(&mut self.middleware);
        let group = (module.register)(&mut context);
        let (guides, views) = context.into_parts();
        for view in views {
            self.middleware.human_views.register(view);
        }
        self.add_guides(guides);
        self.add_module_group_inner(module.category, group, module.feature_flag.clone())
    }

    /// Adds one top-level runtime command after construction.
    pub fn add_command(&mut self, command: RuntimeCommandSpec) -> &mut Self {
        let name = command.spec.name.clone();
        register_command_schema(&command.spec, &name, &mut self.middleware.schema_registry);
        self.commands.insert(name, command.clone());
        self.root = self
            .root
            .clone()
            .subcommand(command_clap_command_with_schema_help(
                &command.spec,
                &command.spec.name,
                &self.middleware.schema_registry,
            ));
        self
    }

    /// Controls whether the built-in `guide` command is advertised.
    pub fn set_has_guide(&mut self, has_guide: bool) -> &mut Self {
        if has_guide && self.guide_entries.is_empty() && !has_subcommand(&self.root, "guide") {
            self.root = self.root.clone().subcommand(guide_command());
        }
        self.sync_guide_topic_values();
        self.refresh_root_long();
        self
    }

    /// Adds guide entries after construction.
    pub fn add_guides(&mut self, entries: impl IntoIterator<Item = GuideEntry>) -> &mut Self {
        let mut seen = self
            .guide_entries
            .iter()
            .map(|entry| entry.name.clone())
            .collect::<BTreeSet<_>>();
        for entry in entries {
            if seen.insert(entry.name.clone()) {
                self.guide_entries.push(entry);
            }
        }
        if !self.guide_entries.is_empty() && !has_subcommand(&self.root, "guide") {
            self.root = self.root.clone().subcommand(guide_command());
        }
        self.sync_guide_topic_values();
        self.refresh_root_long();
        self
    }

    /// Re-attaches the `guide` subcommand's `topic` arg possible values from
    /// the current [`Self::guide_entries`], so shell completion knows about
    /// guide names, which are not all registered up front.
    fn sync_guide_topic_values(&mut self) {
        if self.guide_entries.is_empty() {
            return;
        }
        let names = self
            .guide_entries
            .iter()
            .map(|entry| entry.name.clone())
            .collect::<Vec<_>>();
        if let Some(guide_cmd) = self.root.find_subcommand_mut("guide") {
            let taken = std::mem::replace(guide_cmd, Command::new("guide"));
            *guide_cmd = taken.mut_arg("topic", |arg| {
                arg.value_parser(PossibleValuesParser::new(names))
            });
        }
    }

    /// Resolves busybox/git-style `argv[0]` dispatch before the normal pipeline.
    ///
    /// Returns [`Argv0Outcome::Proceed`] with the (possibly rewritten) argument
    /// vector to feed the normal command pipeline, or [`Argv0Outcome::Handled`]
    /// with a fully rendered result when a personality ran or an explicit `argv0`
    /// invocation was rejected. When no routes are registered this is inert and
    /// returns the arguments unchanged. `depth` counts chained hand-offs and
    /// bounds recursion via [`MAX_ARGV0_DEPTH`].
    async fn resolve_argv0(&self, text_args: Vec<String>, depth: usize) -> Argv0Outcome {
        if self.config.argv0_routes.is_empty() {
            return Argv0Outcome::Proceed(text_args);
        }

        if depth > MAX_ARGV0_DEPTH {
            return Argv0Outcome::Handled(
                self.render_argv0_error(&text_args, "argv0 dispatch recursion limit exceeded"),
            );
        }

        // The hidden `argv0` meta-command (`<bin> argv0 <name> [args...]`) forces
        // a route without an actual symlink. It is recognized positionally as the
        // first argument after the program name and is never registered with clap,
        // so it stays absent from `--help`, `tree`, and the `search` command.
        let explicit = text_args.get(1).map(String::as_str) == Some("argv0");
        let (name, rest) = if explicit {
            match text_args.get(2) {
                None => {
                    return Argv0Outcome::Handled(self.render_argv0_error(
                        &text_args,
                        "the argv0 command requires a name to dispatch as",
                    ));
                }
                // Normalize the explicit name the same way as a symlink basename
                // so a route registered as `whatever` matches whether the caller
                // passed `whatever`, `whatever.exe`, or a `.cmd` shim's `whatever.cmd`.
                Some(name) => (
                    program_basename(name),
                    text_args
                        .get(3..)
                        .map(<[String]>::to_vec)
                        .unwrap_or_default(),
                ),
            }
        } else {
            let name = text_args
                .first()
                .map(|arg| program_basename(arg))
                .unwrap_or_default();
            let rest = text_args
                .get(1..)
                .map(<[String]>::to_vec)
                .unwrap_or_default();
            (name, rest)
        };

        match self.config.argv0_routes.get(&name) {
            Some(Argv0Route::Alias(tokens)) => {
                // Rewrite as `<canonical-name> <tokens...> <rest...>`. Element 0 is
                // the canonical name so the downstream program-name skip applies.
                let mut rewritten = Vec::with_capacity(1 + tokens.len() + rest.len());
                rewritten.push(self.config.name.clone());
                rewritten.extend(tokens.iter().cloned());
                rewritten.extend(rest);
                Argv0Outcome::Proceed(rewritten)
            }
            Some(Argv0Route::Personality(build)) => {
                // Hand off to an independent CLI built lazily from the route. Its
                // own config name leads so its help/usage and program-name skip
                // render correctly. `Box::pin` breaks the recursive `async fn`;
                // `depth + 1` bounds a pathological chain of hand-offs.
                let config = build();
                let bin = config.name.clone();
                let alt = Self::new(config);
                let mut alt_args = Vec::with_capacity(1 + rest.len());
                alt_args.push(bin);
                alt_args.extend(rest);
                Argv0Outcome::Handled(Box::pin(alt.run_with_depth(alt_args, depth + 1)).await)
            }
            None if explicit => Argv0Outcome::Handled(self.render_argv0_error(
                &text_args,
                format!(
                    "{name:?} is not a registered argv0 name; known names: {}",
                    self.known_argv0_names()
                ),
            )),
            None => {
                // Unregistered name (e.g. the binary renamed to something we do not
                // recognize): fall through to the default CLI. Normalizing element 0
                // to the canonical name lets a renamed binary parse as the default
                // application instead of treating its name as a command token.
                let mut rewritten = Vec::with_capacity(1 + rest.len());
                rewritten.push(self.config.name.clone());
                rewritten.extend(rest);
                Argv0Outcome::Proceed(rewritten)
            }
        }
    }

    /// Computes the default output format for this run — the fallback used
    /// when no explicit `--output`/`--json`/`--human`/`--toon` is given.
    fn resolve_run_output_format(&self) -> String {
        use std::io::IsTerminal;

        let env = std::env::var(output_env_var(&self.config.app_id)).ok();
        let engine_config = self.middleware.config.engine();
        resolve_default_output_format(
            env.as_deref(),
            engine_config.output.format.as_deref(),
            std::io::stdout().is_terminal(),
        )
    }

    /// Comma-separated, sorted list of registered alternative `argv[0]` names,
    /// used in the error shown for an unknown explicit `argv0` invocation.
    fn known_argv0_names(&self) -> String {
        self.config
            .argv0_routes
            .keys()
            .cloned()
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// Renders an `argv0`-dispatch error through the engine's structured error
    /// envelope so it honors `--output` (parsed from the raw args, since dispatch
    /// runs before clap) and the shared exit-code mapping, matching every other
    /// CLI error rather than emitting bare text.
    fn render_argv0_error(&self, text_args: &[String], message: impl Into<String>) -> CliRunOutput {
        let mut middleware = self.middleware.clone();
        middleware.output_format =
            extract_output_format(text_args, &self.resolve_run_output_format());
        let err = CliCoreError::message(message);
        self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id))
    }

    /// Returns the registered alternative `argv[0]` names, sorted.
    ///
    /// Useful for install or self-healing code that iterates the names and calls
    /// [`Cli::create_link`] for each.
    #[must_use]
    pub fn argv0_names(&self) -> Vec<&str> {
        self.config
            .argv0_routes
            .keys()
            .map(String::as_str)
            .collect()
    }

    /// Creates an on-disk link in `dir` that lets the binary be invoked under the
    /// registered alternative `argv[0]` name `name`, using `method`.
    ///
    /// `target` is the executable the link points at; pass `None` to use the
    /// current executable ([`std::env::current_exe`]), which is the common choice
    /// for install and self-healing code. The file name follows the platform and
    /// method: a symlink or hard link is `<name>` on Unix and `<name>.exe` on
    /// Windows; a [`Argv0LinkMethod::Script`] shim is `<name>.cmd` on Windows and
    /// an executable `<name>` shell script on Unix.
    ///
    /// The call ensures the desired state idempotently: if the destination already
    /// matches what would be created (a symlink to `target`, a hard link with the
    /// same contents, or a shim with identical contents) it is left untouched and
    /// its path returned; if it exists but differs (wrong kind, stale target, or
    /// edited shim) it is replaced. This makes the call safe to re-run as install
    /// or self-healing code, restoring both deleted and corrupted links. The
    /// directory is created if necessary.
    ///
    /// # Errors
    ///
    /// Returns an error if `name` is not a registered route, if the current
    /// executable cannot be resolved (when `target` is `None`), or if the
    /// directory or link cannot be created or replaced (e.g. insufficient
    /// privilege for a Windows symlink, or a hard link across volumes).
    pub fn create_link(
        &self,
        name: &str,
        dir: impl AsRef<Path>,
        target: Option<&Path>,
        method: Argv0LinkMethod,
    ) -> std::io::Result<PathBuf> {
        if !self.config.argv0_routes.contains_key(name) {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!("{name:?} is not a registered argv0 name"),
            ));
        }

        let dir = dir.as_ref();
        std::fs::create_dir_all(dir)?;
        let link = dir.join(argv0_link_file_name(name, method));

        // Resolve the target up front so an existing entry can be compared against it.
        let resolved_target;
        let target = match target {
            Some(target) => target,
            None => {
                resolved_target = std::env::current_exe()?;
                resolved_target.as_path()
            }
        };

        // Ensure-desired-state. `symlink_metadata` does not follow links, so a
        // present-but-dangling link still counts as existing. A matching entry is
        // left untouched (idempotent); a differing one is removed and recreated.
        if std::fs::symlink_metadata(&link).is_ok() {
            if argv0_link_matches(&link, target, name, method)? {
                return Ok(link);
            }
            std::fs::remove_file(&link)?;
        }

        match method {
            Argv0LinkMethod::SoftLink => create_symlink(target, &link)?,
            Argv0LinkMethod::HardLink => std::fs::hard_link(target, &link)?,
            Argv0LinkMethod::Script => {
                std::fs::write(&link, argv0_script_contents(target, name))?;
                make_executable(&link)?;
            }
        }
        Ok(link)
    }

    /// Runs the CLI with provided args and captures the rendered result.
    ///
    /// Same `--env`/tree-pruning caveat as [`Cli::execute_from`]: see
    /// [`CliConfig::with_startup_args`].
    pub async fn run<I, S>(&self, args: I) -> CliRunOutput
    where
        I: IntoIterator<Item = S>,
        S: Into<std::ffi::OsString> + Clone,
    {
        self.run_with_depth(args, 0).await
    }

    /// Runs the CLI like [`Cli::run`], threading the `argv0` dispatch recursion
    /// `depth` so a chain of personality hand-offs is bounded by [`MAX_ARGV0_DEPTH`].
    async fn run_with_depth<I, S>(&self, args: I, depth: usize) -> CliRunOutput
    where
        I: IntoIterator<Item = S>,
        S: Into<std::ffi::OsString> + Clone,
    {
        let raw_args = args
            .into_iter()
            .map(Into::into)
            .collect::<Vec<std::ffi::OsString>>();
        let text_args = raw_args
            .iter()
            .map(|arg| arg.to_string_lossy().into_owned())
            .collect::<Vec<_>>();
        let text_args = match self.resolve_argv0(text_args, depth).await {
            Argv0Outcome::Handled(output) => return output,
            Argv0Outcome::Proceed(args) => args,
        };
        let mut clap_args = normalize_optional_global_flags_before_command(&self.root, &text_args);
        if has_root_version_flag(&text_args, &self.root, &self.config.name) {
            return self.finish_run(CliRunOutput {
                exit_code: 0,
                rendered: format!(
                    "{} version {}\n",
                    self.config.name,
                    self.config.build.version_string()
                ),
            });
        }
        if let Some(output) = self.try_run_schema_bypass(&text_args) {
            return output;
        }
        // Resolve the positional command path once and share it between the
        // group-help rewrite and the unknown-command check below.
        let bool_flags = derive_bool_flags(&self.root);
        let value_flags = derive_value_flags(&self.root);
        let positionals =
            positional_command_tokens(&text_args, &self.config.name, &bool_flags, &value_flags);
        let command_keyword_count =
            command_keyword_count(&text_args, &self.config.name, &bool_flags, &value_flags);
        if let Some(parts) =
            group_help_target_parts(&self.root, &positionals, command_keyword_count)
        {
            // Rewrite `<group> help [sub...]` into the canonical
            // `help <group> [sub...]` so it flows through the curated root
            // `help` command, which also runs global-flag parsing and the
            // `pre_run` hook (matching `help <group>` and bare-group help).
            // Only the positional command tokens are reordered; every flag and
            // its value is preserved in place so e.g. `--output json` survives.
            clap_args = rewrite_group_help_args(
                &clap_args,
                &self.config.name,
                &bool_flags,
                &value_flags,
                &parts,
            );
        } else if let Some(unknown) =
            detect_unknown_group_command(&self.root, &positionals[..command_keyword_count])
        {
            // Hint/re-dispatch only when the whole path resolves to one command.
            if let Some(corrections) =
                full_command_correction(&self.root, &positionals[..command_keyword_count])
            {
                let display = correction_display(
                    &self.config.name,
                    &positionals[..command_keyword_count],
                    &corrections,
                );
                let full_fix_message = format_did_you_mean(&unknown.base, &display);
                match crate::prompt::confirm_command_correction(
                    &clap_args,
                    &display,
                    self.config.auto_interactive,
                ) {
                    crate::prompt::CommandCorrection::Accepted => {
                        for (index, replacement) in &corrections {
                            clap_args = replace_positional_command_token(
                                &clap_args,
                                &self.config.name,
                                &bool_flags,
                                &value_flags,
                                *index,
                                replacement,
                            );
                        }
                        clap_args = rewrite_group_help_if_needed(
                            &self.root,
                            &clap_args,
                            &self.config.name,
                            &bool_flags,
                            &value_flags,
                        );
                    }
                    crate::prompt::CommandCorrection::Declined => {
                        return self.finish_run(CliRunOutput {
                            exit_code: 1,
                            rendered: full_fix_message,
                        });
                    }
                    crate::prompt::CommandCorrection::Cancelled => {
                        return self.finish_run(CliRunOutput {
                            exit_code: 130,
                            rendered: "Cancelled.".to_owned(),
                        });
                    }
                }
            } else {
                return self.finish_run(CliRunOutput {
                    exit_code: 1,
                    rendered: unknown.base,
                });
            }
        }

        let matches = match self.root.clone().try_get_matches_from(&clap_args) {
            Ok(matches) => matches,
            Err(err) => {
                // Attempt interactive recovery for missing required arguments.
                if let Some(recovery) = crate::prompt::try_recover_missing_args(
                    &err,
                    &clap_args,
                    &self.root,
                    &self.config.name,
                    self.config.auto_interactive,
                ) {
                    match recovery {
                        crate::prompt::RecoveryResult::Recovered { args } => {
                            match self.root.clone().try_get_matches_from(args) {
                                Ok(m) => m,
                                Err(retry_err) => {
                                    return self.finish_run(CliRunOutput {
                                        exit_code: retry_err.exit_code(),
                                        rendered: retry_err.to_string(),
                                    });
                                }
                            }
                        }
                        crate::prompt::RecoveryResult::Cancelled { resume } => {
                            return self.finish_run(CliRunOutput {
                                exit_code: 130,
                                rendered: format!("Cancelled. Resume with:\n  {resume}\n"),
                            });
                        }
                    }
                } else {
                    return self.finish_run(CliRunOutput {
                        exit_code: err.exit_code(),
                        rendered: err.to_string(),
                    });
                }
            }
        };

        let default_format = self.resolve_run_output_format();
        let flags =
            global_flags_from_matches(&matches, &default_format, self.config.auto_interactive);
        // Publish the --credential-store override so auth providers resolving
        // their storage backend see it at the top of the precedence chain.
        crate::config::set_credential_store_flag(flags.credential_store);
        let command_timeout = match parse_command_timeout(&flags.timeout) {
            Ok(timeout) => timeout,
            Err(err) => {
                return self.finish_run(render_cli_error(
                    &self.middleware,
                    &err,
                    &self.config.app_id,
                ));
            }
        };
        let mut middleware = self.middleware.clone();
        apply_global_flags(&mut middleware, &flags, command_timeout);
        install_debug_transport_logger(&flags.debug, &self.config.redacted_debug_headers);
        if let Err(err) = self.apply_config_flags(&matches, &mut middleware) {
            return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
        }
        // Validate and apply `--env` for built-in paths (help/tree/guide/group
        // help) so they reflect the selected environment and reject unknowns.
        if let Err(err) = self.apply_env_flag(&matches, &mut middleware) {
            return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
        }

        let command_path = command_path_from_matches(&self.config.name, &matches);
        if command_path == "help" {
            if let Err(err) = self.run_pre_run(&mut middleware, &command_path, &help_args(&matches))
            {
                return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
            }
            return self.finish_run(self.render_help_command(&matches));
        }
        if command_path == "tree" {
            if let Err(err) = self.run_pre_run(
                &mut middleware,
                &command_path,
                &crate::middleware::ValueMap::new(),
            ) {
                return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
            }
            return self.finish_run(tree_render::render_tree(
                &self.root,
                &self.config.app_id,
                &middleware,
            ));
        }
        if command_path == "guide" {
            if let Err(err) =
                self.run_pre_run(&mut middleware, &command_path, &guide_args(&matches))
            {
                return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
            }
            return self.finish_run(self.render_guide(&matches, &flags.output_format));
        }
        if command_path == "search" {
            let args = search_args(&matches);
            if let Err(err) = self.run_pre_run(&mut middleware, &command_path, &args) {
                return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
            }
            let query = args
                .get("query")
                .and_then(|v| v.as_str())
                .unwrap_or_default();
            let scope_path = args
                .get("scope")
                .and_then(|v| v.as_str())
                .unwrap_or_default();
            let scope = self.resolve_search_scope(scope_path);
            return self.finish_run(self.render_search(query, &scope, &flags.output_format));
        }
        if command_path == "completion" {
            let args = completion_args(&matches);
            if let Err(err) = self.run_pre_run(&mut middleware, &command_path, &args) {
                return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
            }
            let install = args
                .get("install")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            let shell_opt = args
                .get("shell")
                .and_then(|v| v.as_str())
                .map(str::to_owned);
            if install {
                use crate::cli::completion::{detect_shell, parse_shell};
                let shell = match shell_opt {
                    Some(ref s) => match parse_shell(s) {
                        Ok(s) => s,
                        Err(e) => {
                            return self.finish_run(render_cli_error(
                                &middleware,
                                &e,
                                &self.config.app_id,
                            ));
                        }
                    },
                    None => match detect_shell() {
                        Ok(s) => s,
                        Err(e) => {
                            return self.finish_run(render_cli_error(
                                &middleware,
                                &e,
                                &self.config.app_id,
                            ));
                        }
                    },
                };
                return self.finish_run(
                    completion::install(&self.root, &self.config.name, shell)
                        .await
                        .unwrap_or_else(|e| render_cli_error(&middleware, &e, &self.config.app_id)),
                );
            }
            return self.finish_run(self.render_completion_print(shell_opt, &middleware));
        }
        let Some(command) = self.commands.get(&command_path) else {
            if !command_path.is_empty()
                && let Some(group) = find_command_by_colon_path(&self.root, &command_path)
                && group.get_subcommands().next().is_some()
            {
                if let Err(err) = self.run_pre_run(
                    &mut middleware,
                    &command_path,
                    &crate::middleware::ValueMap::new(),
                ) {
                    return self.finish_run(render_cli_error(
                        &middleware,
                        &err,
                        &self.config.app_id,
                    ));
                }
                return self.finish_run(self.render_bare_group_discovery(
                    group,
                    &command_path,
                    &middleware,
                ));
            }
            if command_path.is_empty()
                && let Some(root_next_actions) = &self.root_next_actions
            {
                // Bare-root discovery is static (help text / metadata + action
                // pointers) and must always be available as a cold-start entry
                // point, so we skip `pre_run` here — matching the no-hook
                // bare-root path below, which also renders help without it.
                let actions = root_next_actions();
                return self.finish_run(self.render_root(&middleware, actions));
            }
            return self.finish_run(CliRunOutput {
                exit_code: if command_path.is_empty() { 0 } else { 1 },
                rendered: if command_path.is_empty() {
                    self.root.clone().render_long_help().to_string()
                } else {
                    format!("unknown command {command_path:?}")
                },
            });
        };

        let mut middleware = match self.initialized_middleware() {
            Ok(middleware) => middleware,
            Err(err) => {
                return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
            }
        };
        apply_global_flags(&mut middleware, &flags, command_timeout);
        install_debug_transport_logger(&flags.debug, &self.config.redacted_debug_headers);
        if let Err(err) = self.apply_config_flags(&matches, &mut middleware) {
            return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
        }
        // The global `--env` flag overrides the seeded active environment for
        // this invocation; an unknown name surfaces as an error envelope.
        if let Err(err) = self.apply_env_flag(&matches, &mut middleware) {
            return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
        }

        let leaf = leaf_matches(&matches);
        apply_pagination_flags(&mut middleware, &command.spec, leaf);
        let args = command_args_from_matches(leaf, &command.spec, false);
        let user_args = command_args_from_matches(leaf, &command.spec, true);
        let pagination_command = command.spec.pagination.is_some().then(|| {
            pagination_command_base(
                &self.config.name,
                &command_path,
                &command.spec,
                &user_args,
                &flags,
            )
        });
        if let Err(err) = self.run_pre_run(&mut middleware, &command_path, &args) {
            return self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id));
        }
        let meta = self.resolve_meta(&command_path, command.spec.metadata());
        let default_fields = command.spec.default_fields.clone().unwrap_or_default();
        let system = command.spec.system.clone().unwrap_or_default();
        // The human view this command declared: an explicit shared id wins;
        // otherwise an inline `with_view` was registered under the command path
        // at build time, so reference it by that path. `None` renders generic
        // human output.
        let view_id = command
            .spec
            .view_id
            .clone()
            .or_else(|| (!command.spec.view_columns.is_empty()).then(|| command_path.clone()));

        if let Some(streaming_handler) = command.streaming_handler.clone() {
            let result = run_with_timeout(
                command_timeout,
                &flags.timeout,
                run_streaming_command(
                    &middleware,
                    MiddlewareRequest {
                        meta,
                        command_path: &command_path,
                        system: &system,
                        user_args,
                        args,
                        default_fields: &default_fields,
                        view_id: view_id.as_deref(),
                        auth: command.spec.auth,
                        raw_output: command.spec.raw_output,
                        pagination_command,
                    },
                    Arc::new(leaf.clone()),
                    streaming_handler,
                ),
            )
            .await;
            return self.finish_run(match result {
                Ok(output) => output,
                Err(err) => render_cli_error(&middleware, &err, &self.config.app_id),
            });
        }

        let handler = command.handler.clone();
        let args_for_handler = args.clone();
        let user_args_for_handler = user_args.clone();
        let handler_path = command_path.clone();
        let middleware_for_handler = middleware.clone();
        let raw_matches_for_handler = Arc::new(leaf.clone());
        let result = run_with_timeout(
            command_timeout,
            &flags.timeout,
            middleware.run(
                MiddlewareRequest {
                    meta,
                    command_path: &command_path,
                    system: &system,
                    user_args,
                    args,
                    default_fields: &default_fields,
                    view_id: view_id.as_deref(),
                    auth: command.spec.auth,
                    raw_output: command.spec.raw_output,
                    pagination_command,
                },
                async move |credential| {
                    handler(CommandContext {
                        credential,
                        args: args_for_handler,
                        user_args: user_args_for_handler,
                        command_path: handler_path,
                        middleware: middleware_for_handler,
                        raw_matches: raw_matches_for_handler,
                    })
                    .await
                },
            ),
        )
        .await;

        match result {
            Ok(output) => self.finish_run(output.into()),
            Err(err) => self.finish_run(render_cli_error(&middleware, &err, &self.config.app_id)),
        }
    }

    fn try_run_schema_bypass(&self, args: &[String]) -> Option<CliRunOutput> {
        if !has_true_schema_flag(args) {
            return None;
        }
        let bool_flags = derive_bool_flags(&self.root);
        let value_flags = derive_value_flags(&self.root);
        let command_path =
            self.canonical_command_path(&extract_command_path(args, &bool_flags, &value_flags));
        // `--schema` is an inspection flag and must not require the command's own
        // arguments, so it short-circuits before clap validates them. Only fire
        // for a real leaf command, though: unknown paths and groups fall through
        // so clap and `detect_unknown_group_command` can report them as usual.
        let command = find_command_by_colon_path(&self.root, &command_path)?;
        if command.get_subcommands().next().is_some() {
            return None;
        }
        let output_format = extract_output_format(args, &self.resolve_run_output_format());
        // When no schema is registered, report that rather than running the
        // command — matching the middleware's no-schema response so the public
        // path and the lower layer agree even when required args are missing.
        match self.middleware.schema_registry.get_by_path(&command_path) {
            Some(schema) => Some(self.render_schema(schema, &output_format)),
            None => Some(self.render_schema(
                crate::output::no_schema_response(&command_path),
                &output_format,
            )),
        }
    }

    fn render_schema(&self, data: impl serde::Serialize, output_format: &str) -> CliRunOutput {
        let format: crate::output::OutputFormat = match output_format.parse() {
            Ok(format) => format,
            Err(err) => {
                return CliRunOutput {
                    exit_code: exit_code_for_error(&err),
                    rendered: err.to_string(),
                };
            }
        };
        let envelope =
            crate::Envelope::success(data, self.config.app_id.clone()).prepare_for_render("");
        match crate::output::render(format, &envelope) {
            Ok(rendered) => CliRunOutput {
                exit_code: 0,
                rendered,
            },
            Err(err) => CliRunOutput {
                exit_code: exit_code_for_error(&err),
                rendered: err.to_string(),
            },
        }
    }

    /// Renders a bare group invocation (no subcommand given).
    ///
    /// Human output keeps the existing clap help text; every other format,
    /// explicit `--output json`/`--toon`, or the non-TTY default an agent
    /// sees with no `--output` flag at all — gets an explicit JSON
    /// command-tree subset scoped to this group, built with the same
    /// [`crate::tree`] machinery as the top-level `tree` command.
    fn render_bare_group_discovery(
        &self,
        group: &Command,
        command_path: &str,
        middleware: &Middleware,
    ) -> CliRunOutput {
        let format: crate::output::OutputFormat = match middleware.output_format.parse() {
            Ok(format) => format,
            Err(err) => {
                return CliRunOutput {
                    exit_code: exit_code_for_error(&err),
                    rendered: err.to_string(),
                };
            }
        };
        if format == crate::output::OutputFormat::Human {
            return CliRunOutput {
                exit_code: 0,
                rendered: group.clone().render_long_help().to_string(),
            };
        }
        let path = format!("{} {}", self.config.name, command_path.replace(':', " "));
        let tree = crate::tree::build_tree_from_clap_with_path(group, path);
        tree_render::render_tree_envelope(tree, &self.config.app_id, middleware, format)
    }

    fn render_search(&self, query: &str, scope: &str, output_format: &str) -> CliRunOutput {
        let format: crate::output::OutputFormat = match output_format.parse() {
            Ok(format) => format,
            Err(err) => {
                return CliRunOutput {
                    exit_code: exit_code_for_error(&err),
                    rendered: err.to_string(),
                };
            }
        };
        let docs = self.search_documents(scope);
        let results = SearchIndex::new(docs).search(query, 10);
        let envelope =
            crate::Envelope::success(results, self.config.app_id.clone()).prepare_for_render("");
        match crate::output::render(format, &envelope) {
            Ok(rendered) => CliRunOutput {
                exit_code: 0,
                rendered,
            },
            Err(err) => CliRunOutput {
                exit_code: exit_code_for_error(&err),
                rendered: err.to_string(),
            },
        }
    }

    /// Renders the bare-root response. For human output, renders long help plus
    /// a "Next actions" section so a human invoking the CLI with no arguments
    /// gets readable guidance; for machine-readable output, emits a discovery
    /// envelope (light metadata + next actions). The output format has already
    /// resolved the TTY/env/flag policy, so this just branches on it.
    fn render_root(&self, middleware: &Middleware, actions: Vec<NextAction>) -> CliRunOutput {
        // Reject an invalid explicit `--output` here too, matching the normal
        // command path (`Middleware::render_envelope`). `OutputFormat::from_str`
        // is infallible and would otherwise silently coerce an unrecognized
        // value (e.g. `--output yaml`) to JSON instead of reporting the error.
        if !crate::output::is_valid_output_format(&middleware.output_format) {
            let err = CliCoreError::InvalidOutputFormat(middleware.output_format.clone());
            return CliRunOutput {
                exit_code: exit_code_for_error(&err),
                rendered: err.to_string(),
            };
        }
        let format = middleware
            .output_format
            .parse()
            .unwrap_or(crate::output::OutputFormat::Json);
        if format == crate::output::OutputFormat::Human {
            // Fold the suggested actions into the root long-about so they render
            // alongside the other curated sections (before Usage) instead of
            // dangling beneath clap's options dump.
            let base_long = self
                .root
                .get_long_about()
                .map(ToString::to_string)
                .unwrap_or_default();
            let long = format!("{base_long}{}", render_next_actions_human(&actions));
            let rendered = self
                .root
                .clone()
                .long_about(long)
                .render_long_help()
                .to_string();
            return CliRunOutput {
                exit_code: 0,
                rendered,
            };
        }
        let description = self
            .config
            .long
            .as_deref()
            .filter(|long| !long.is_empty())
            .unwrap_or(self.config.short.as_str());
        let data = serde_json::json!({
            "description": description,
            "version": self.config.build.version,
        });
        let envelope = crate::Envelope::success(data, self.config.app_id.clone())
            .with_next_actions(actions)
            .prepare_for_render(&middleware.verbose);
        match crate::output::render(format, &envelope) {
            Ok(rendered) => CliRunOutput {
                exit_code: 0,
                rendered,
            },
            Err(err) => CliRunOutput {
                exit_code: exit_code_for_error(&err),
                rendered: err.to_string(),
            },
        }
    }

    fn search_documents(&self, scope: &str) -> Vec<SearchDocument> {
        let (scoped, mut prefix) = find_command_and_canonical_path_by_colon_path(&self.root, scope)
            .unwrap_or((&self.root, Vec::new()));
        let mut docs = Vec::new();
        let mut aliases = Vec::new();
        append_command_alias_terms(scoped, &mut aliases);
        collect_command_search_documents(scoped, &mut prefix, &mut aliases, &mut docs);
        if scope.is_empty() {
            for entry in &self.guide_entries {
                docs.push(SearchDocument {
                    id: format!("guide:{}", entry.name),
                    kind: "guide".to_owned(),
                    title: format!("guide {}", entry.name),
                    summary: entry.summary.clone(),
                    content: format!("{} {}", entry.summary, entry.content),
                });
            }
            if let Some(extra_search_docs) = &self.extra_search_docs {
                docs.extend(extra_search_docs());
            }
        }
        docs
    }

    /// Resolves `--scope`'s colon-separated path (e.g. `domain` or
    /// `domain:list`) to the canonical scope string [`Self::search_documents`]
    /// expects, matching aliases the same way a real command path would (via
    /// [`canonical_path_from_parts`]'s `find_subcommand` walk). An empty or
    /// unresolvable scope falls back to an unscoped (root) search rather than
    /// erroring — `search` staying permissive here matches how a typo in a
    /// search *query* just yields fewer results instead of a hard failure.
    /// An unresolvable (non-empty) scope prints a best-effort stderr hint
    /// first, so a typo like `--scope doamin` doesn't silently widen the
    /// search with no explanation for the extra results.
    fn resolve_search_scope(&self, scope_path: &str) -> String {
        if scope_path.is_empty() {
            return String::new();
        }
        let parts: Vec<String> = scope_path.split(':').map(str::to_owned).collect();
        match canonical_path_from_parts(&self.root, &parts) {
            Some(scope) => scope,
            None => {
                warn_unresolvable_search_scope(scope_path);
                String::new()
            }
        }
    }

    fn canonical_command_path(&self, command_path: &str) -> String {
        find_command_and_canonical_path_by_colon_path(&self.root, command_path).map_or_else(
            || command_path.to_owned(),
            |(_, canonical)| canonical.join(":"),
        )
    }

    fn render_guide(&self, matches: &ArgMatches, output_format: &str) -> CliRunOutput {
        use std::io::IsTerminal;

        // Reject an invalid explicit `--output` here too, matching the normal
        // command path and `render_root`; otherwise an unrecognized value (e.g.
        // `--output yaml`) would silently fall through and emit raw content.
        if !crate::output::is_valid_output_format(output_format) {
            let err = CliCoreError::InvalidOutputFormat(output_format.to_owned());
            return CliRunOutput {
                exit_code: exit_code_for_error(&err),
                rendered: err.to_string(),
            };
        }

        let leaf = leaf_matches(matches);
        let topic = leaf.get_one::<String>("topic").map(String::as_str);
        match guide_content(&self.guide_entries, topic) {
            Ok(rendered) => {
                // Only reflow an actual guide topic body, and only for human output.
                // The topic list is plain text (not markdown) and json/toon keep the
                // raw markdown so their output stays deterministic.
                let rendered = if topic.is_some() && output_format == "human" {
                    let is_tty = std::io::stdout().is_terminal();
                    render_guide_human(&rendered, crate::output::terminal_width(), is_tty)
                } else {
                    rendered
                };
                CliRunOutput {
                    exit_code: 0,
                    rendered,
                }
            }
            Err(err) => CliRunOutput {
                exit_code: 1,
                rendered: err,
            },
        }
    }

    fn render_completion_print(
        &self,
        shell_opt: Option<String>,
        middleware: &Middleware,
    ) -> CliRunOutput {
        use crate::cli::completion::{detect_shell, generate_script, parse_shell};
        let shell = match shell_opt {
            Some(s) => match parse_shell(&s) {
                Ok(s) => s,
                Err(e) => return render_cli_error(middleware, &e, &self.config.app_id),
            },
            None => match detect_shell() {
                Ok(s) => s,
                Err(e) => return render_cli_error(middleware, &e, &self.config.app_id),
            },
        };
        match generate_script(&self.root, &self.config.name, shell) {
            Ok(script) => CliRunOutput {
                exit_code: 0,
                rendered: script,
            },
            Err(e) => render_cli_error(middleware, &e, &self.config.app_id),
        }
    }

    fn render_help_command(&self, matches: &ArgMatches) -> CliRunOutput {
        let leaf = leaf_matches(matches);
        let parts = leaf
            .get_many::<String>("command")
            .map(|values| values.map(String::as_str).collect::<Vec<_>>())
            .unwrap_or_default();
        self.render_help_for_parts(&parts)
    }

    /// Renders the curated help text for a resolved command path.
    ///
    /// Empty `parts` render the root help. A path that resolves to a group or
    /// command renders that command's long help; an unresolved path returns the
    /// standard "unknown command" guidance with a non-zero exit code. Shared by
    /// the root `help <path>` command and the `<group> help` subcommand form.
    fn render_help_for_parts(&self, parts: &[&str]) -> CliRunOutput {
        if parts.is_empty() {
            return CliRunOutput {
                exit_code: 0,
                rendered: self.root.clone().render_long_help().to_string(),
            };
        }
        let Some(command) = find_help_target(&self.root, parts) else {
            return CliRunOutput {
                exit_code: 1,
                rendered: format!(
                    "unknown command {:?} — run '{} help' for available commands",
                    parts.join(" "),
                    self.config.name
                ),
            };
        };
        CliRunOutput {
            exit_code: 0,
            rendered: command.clone().render_long_help().to_string(),
        }
    }

    fn refresh_root_long(&mut self) {
        // Module-categorized entries, plus any visible top-level command that is
        // neither categorized nor an engine built-in, listed under a generic
        // "Commands" section. This keeps every command discoverable once clap's
        // auto subcommand list is suppressed by the root help template.
        let builtins = BUILTIN_COMMAND_NAMES;
        let categorized: BTreeSet<&str> = self
            .module_entries
            .iter()
            .map(|entry| entry.name.as_str())
            .collect();
        let mut generic: Vec<ModuleHelpEntry> = self
            .root
            .get_subcommands()
            .filter(|command| !command.is_hide_set())
            .filter(|command| !builtins.contains(&command.get_name()))
            .filter(|command| !categorized.contains(command.get_name()))
            .map(|command| ModuleHelpEntry {
                category: "Commands".to_owned(),
                name: command.get_name().to_owned(),
                short: command
                    .get_about()
                    .map(ToString::to_string)
                    .unwrap_or_default(),
            })
            .collect();
        generic.sort_by(|left, right| left.name.cmp(&right.name));

        let mut entries = self.module_entries.clone();
        entries.extend(generic);
        let has_guide = !self.guide_entries.is_empty() || has_subcommand(&self.root, "guide");
        let intro = self
            .config
            .long
            .as_deref()
            .filter(|long| !long.is_empty())
            .unwrap_or(self.config.short.as_str());
        self.root = self
            .root
            .clone()
            .long_about(build_root_long(intro, &entries, has_guide));
    }

    fn ensure_auth_command(&mut self) {
        let default_provider = self.default_auth_provider();
        let registered_names = self.middleware.auth.registered_names();
        if default_provider.is_empty() && registered_names.is_empty() {
            return;
        }
        let replacing_builtin = self.commands.contains_key("auth:login");
        if has_subcommand(&self.root, "auth") && !replacing_builtin {
            return;
        }
        let mut group = auth_command_group(&default_provider, &registered_names);
        let mut seen_names: std::collections::HashSet<String> =
            group.commands.iter().map(|c| c.spec.name.clone()).collect();
        for extra in self.config.auth_extra_commands.clone() {
            if !seen_names.insert(extra.spec.name.clone()) {
                tracing::warn!(
                    command = %extra.spec.name,
                    "auth_extra_commands entry collides with a built-in auth subcommand or an \
                     earlier auth_extra_commands entry; ignoring"
                );
                continue;
            }
            group = group.with_command(extra);
        }
        let mut prefix = Vec::new();
        register_runtime_group_metadata(
            &group,
            &mut prefix,
            &mut self.middleware.schema_registry,
            &mut self.middleware.human_views,
        );
        let mut prefix = Vec::new();
        group.register_commands(&mut prefix, &mut self.commands);
        let mut prefix = Vec::new();
        let clap_group = runtime_group_clap_command_with_schema_help(
            &group,
            &mut prefix,
            &self.middleware.schema_registry,
        );
        self.root = if replacing_builtin {
            self.root.clone().mut_subcommand("auth", |_| clap_group)
        } else {
            self.root.clone().subcommand(clap_group)
        };
        // Categorize `auth` wherever it is ensured (construction or a later
        // `register_auth_provider`), so it never falls into the generic
        // "Commands" bucket. Idempotent via the `already_listed` guard.
        self.register_auth_help_entry();
    }

    /// Mounts the built-in `config` command group and files it under the admin
    /// help category. Idempotent and yields to a consumer-defined `config`
    /// subcommand if one already exists.
    fn ensure_config_command(&mut self) {
        if has_subcommand(&self.root, "config") {
            return;
        }
        let group = crate::config_commands::config_command_group();
        let mut prefix = Vec::new();
        group.register_commands(&mut prefix, &mut self.commands);
        let mut prefix = Vec::new();
        let clap_group = runtime_group_clap_command_with_schema_help(
            &group,
            &mut prefix,
            &self.middleware.schema_registry,
        );
        self.root = self.root.clone().subcommand(clap_group);
        let category = self
            .config
            .admin_category
            .clone()
            .unwrap_or_else(|| DEFAULT_ADMIN_CATEGORY.to_owned());
        if !self
            .module_entries
            .iter()
            .any(|entry| entry.name == "config")
        {
            self.module_entries.push(ModuleHelpEntry {
                category,
                name: "config".to_owned(),
                short: "Read and write the CLI config file".to_owned(),
            });
        }
        self.refresh_root_long();
    }

    /// Mounts the built-in `env` command group and files it under the admin
    /// help category. Idempotent and yields to a consumer-defined `env`
    /// subcommand if one already exists.
    fn ensure_env_command(&mut self) {
        if has_subcommand(&self.root, "env") {
            return;
        }
        let group = crate::env_commands::env_command_group();
        let mut prefix = Vec::new();
        group.register_commands(&mut prefix, &mut self.commands);
        let mut prefix = Vec::new();
        let clap_group = runtime_group_clap_command_with_schema_help(
            &group,
            &mut prefix,
            &self.middleware.schema_registry,
        );
        self.root = self.root.clone().subcommand(clap_group);
        let category = self
            .config
            .admin_category
            .clone()
            .unwrap_or_else(|| DEFAULT_ADMIN_CATEGORY.to_owned());
        if !self.module_entries.iter().any(|e| e.name == "env") {
            self.module_entries.push(ModuleHelpEntry {
                category,
                name: "env".to_owned(),
                short: "Manage the active environment".to_owned(),
            });
        }
        self.refresh_root_long();
    }

    /// Mounts the built-in `flags` command group and files it under the admin
    /// help category. Idempotent and yields to a consumer-defined `flags`
    /// subcommand if one already exists. Unlike [`Self::ensure_env_command`],
    /// this is mounted unconditionally: feature-flag introspection does not
    /// depend on any opt-in system, so it is always available.
    fn ensure_flags_command(&mut self) {
        if has_subcommand(&self.root, "flags") {
            return;
        }
        let group = crate::flag_commands::flags_command_group();
        let mut prefix = Vec::new();
        group.register_commands(&mut prefix, &mut self.commands);
        let mut prefix = Vec::new();
        let clap_group = runtime_group_clap_command_with_schema_help(
            &group,
            &mut prefix,
            &self.middleware.schema_registry,
        );
        self.root = self.root.clone().subcommand(clap_group);
        let category = self
            .config
            .admin_category
            .clone()
            .unwrap_or_else(|| DEFAULT_ADMIN_CATEGORY.to_owned());
        if !self.module_entries.iter().any(|e| e.name == "flags") {
            self.module_entries.push(ModuleHelpEntry {
                category,
                name: "flags".to_owned(),
                short: "Inspect declared feature flags".to_owned(),
            });
        }
        self.refresh_root_long();
    }

    fn default_auth_provider(&self) -> String {
        if !self.middleware.default_auth_provider.is_empty() {
            return self.middleware.default_auth_provider.clone();
        }
        self.middleware
            .auth
            .registered_names()
            .into_iter()
            .next()
            .unwrap_or_default()
    }

    fn initialized_middleware(&self) -> Result<Middleware> {
        let Some(init_deps) = &self.init_deps else {
            return Ok(self.middleware.clone());
        };
        let mut guard = self
            .init_state
            .lock()
            .map_err(|_| CliCoreError::message("init deps lock poisoned"))?;
        if let Some(result) = guard.as_ref() {
            return result.clone().map_err(InitFailure::into_error);
        }
        let mut middleware = self.middleware.clone();
        let result = init_deps(&mut middleware)
            .map(|()| middleware)
            .map_err(|err| InitFailure::capture(&err));
        *guard = Some(result.clone());
        result.map_err(InitFailure::into_error)
    }

    fn apply_config_flags(&self, matches: &ArgMatches, middleware: &mut Middleware) -> Result<()> {
        if let Some(apply_flags) = &self.apply_flags {
            apply_flags(matches, middleware)?;
        }
        Ok(())
    }

    /// Applies the global `--env` override to a per-run middleware snapshot.
    ///
    /// The flag is only registered when environments are configured, so when it
    /// is present `middleware.environments` is set too. Validates the requested
    /// name against the registered environments and updates `middleware.env`,
    /// returning an error for an unknown environment.
    fn apply_env_flag(&self, matches: &ArgMatches, middleware: &mut Middleware) -> Result<()> {
        // Guard on the environment system FIRST. The `--env` arg is only
        // registered when environments are configured (the same condition that
        // sets `middleware.environments`); calling `matches.get_one("env")` for
        // an arg that was never registered panics in clap, which would break
        // every CLI that does not use environments.
        let Some(environments) = middleware.environments.as_ref() else {
            return Ok(());
        };
        if let Some(env) = matches.get_one::<String>("env") {
            environments.source(env)?;
            middleware.env = env.clone();
        }
        Ok(())
    }

    fn run_pre_run(
        &self,
        middleware: &mut Middleware,
        command_path: &str,
        args: &crate::middleware::ValueMap,
    ) -> Result<()> {
        if let Some(pre_run) = &self.pre_run {
            pre_run(middleware, command_path, args)?;
        }
        Ok(())
    }

    fn resolve_meta(&self, command_path: &str, meta: CommandMeta) -> CommandMeta {
        if let Some(resolver) = &self.meta_resolver {
            resolver(command_path, meta)
        } else {
            meta
        }
    }

    fn finish_run(&self, output: CliRunOutput) -> CliRunOutput {
        // Clear the per-thread credential-store flag so it does not leak into
        // subsequent sequential runs on the same thread.
        crate::config::clear_credential_store_flag();
        if let Some(on_shutdown) = &self.on_shutdown {
            on_shutdown();
        }
        output
    }
}

fn apply_global_flags(middleware: &mut Middleware, flags: &GlobalFlags, timeout: Option<Duration>) {
    middleware.output_format = flags.output_format.clone();
    middleware.verbose = flags.verbose.clone();
    middleware.dry_run = flags.dry_run;
    middleware.fields = flags.fields.clone();
    middleware.fields_explicit = flags.fields_explicit;
    middleware.filter = flags.filter.clone();
    middleware.expr = flags.expr.clone();
    middleware.reason = flags.reason.clone();
    middleware.schema = flags.schema;
    middleware.timeout = timeout;
    middleware.debug = flags.debug.clone();
    middleware.interactive = flags.interactive;
}

/// Sets `middleware.limit`/`middleware.offset` from a paginating command's own
/// `--limit`/`--offset`
fn apply_pagination_flags(middleware: &mut Middleware, spec: &CommandSpec, leaf: &ArgMatches) {
    let Some(pagination) = spec.pagination else {
        return;
    };
    middleware.limit = leaf
        .get_one::<i64>("limit")
        .copied()
        .unwrap_or(pagination.default_limit);
    middleware.offset = leaf.get_one::<i64>("offset").copied().unwrap_or(0);
}

/// Replays a paginating command's own explicit args, plus the global
/// `--filter`/`--expr`/`--fields` flags, as `--flag value` text, prefixed
/// with the CLI's binary name — the base a "view the next page"
/// [`crate::NextAction`] is built from once the response's
/// [`crate::PaginationMeta`] is known. Leading with the binary name keeps the
/// suggested command copy-pastable rather than a fragment starting at the
/// noun/verb path.
///
/// `--filter`/`--expr`/`--fields` sit in the same output pipeline as
/// pagination itself (filter -> paginate -> expr -> fields) and change what
/// data comes back, so dropping them would make the suggested next-page
/// command return different results than the command the user actually ran.
/// Other global flags (`--output`, `--verbose`, `--env`, ...) don't affect
/// *which* data is returned, so they're intentionally left out — the caller
/// is already running under them.
///
/// Best-effort, not a fully general clap-args reconstruction: it uses each
/// arg's real `get_long()`/`get_short()` name (never the value-map key,
/// which for derive-based args can differ from the flag — e.g. id
/// `page_size` vs flag `--page-size`), replays a multi-value arg as one
/// flag occurrence per value (round-trips correctly whether the arg is a
/// plain repeatable `ArgAction::Append` or also sets a `value_delimiter`),
/// and quotes/escapes values containing whitespace or shell metacharacters
/// (see `quote_pagination_value`). Deliberately omits `--limit`/`--offset` —
/// those are added by the caller once it knows the
/// next page's offset.
fn pagination_command_base(
    binary_name: &str,
    command_path: &str,
    spec: &CommandSpec,
    user_args: &crate::middleware::ValueMap,
    flags: &GlobalFlags,
) -> String {
    let mut parts = vec![
        quote_pagination_value(binary_name),
        command_path.replace(':', " "),
    ];
    for arg in &spec.args {
        let id = arg.get_id().as_str();
        if let Some(value) = user_args.get(id) {
            push_pagination_arg(&mut parts, arg, value);
        }
    }
    for (flag, value) in [
        ("--filter", &flags.filter),
        ("--expr", &flags.expr),
        ("--fields", &flags.fields),
    ] {
        if !value.is_empty() {
            parts.push(flag.to_owned());
            parts.push(quote_pagination_value(value));
        }
    }
    parts.join(" ")
}

fn push_pagination_arg(parts: &mut Vec<String>, arg: &Arg, value: &serde_json::Value) {
    let flag = arg
        .get_long()
        .map(|long| format!("--{long}"))
        .or_else(|| arg.get_short().map(|short| format!("-{short}")));
    match value {
        serde_json::Value::Bool(enabled) => {
            if matches!(
                arg.get_action(),
                clap::ArgAction::SetTrue | clap::ArgAction::SetFalse
            ) {
                // A switch-style flag's presence in `user_args` already means
                // the user typed exactly this flag — `SetTrue` implies `true`,
                // `SetFalse` implies `false` (e.g. a `--no-foo`-style arg) —
                // and neither accepts an explicit `=value` token, so replay
                // the bare flag rather than appending one.
                if let Some(flag) = flag {
                    parts.push(flag);
                }
            } else {
                // A custom bool-valued arg (`ArgAction::Set` with a bool
                // value parser) takes an explicit token, so replay it like
                // any other scalar.
                push_flagged_value(parts, flag, &enabled.to_string());
            }
        }
        serde_json::Value::Array(items) => {
            // Repeat the flag once per value rather than joining into one
            // comma-separated token: clap collects a repeatable flag
            // (`ArgAction::Append`, the common way a command declares a
            // multi-value arg) the same way whether or not it also sets
            // `value_delimiter(',')`, so `--scope a --scope b` round-trips
            // correctly either way. A single `--scope a,b` only works when
            // a delimiter was configured — for a plain `Append` arg it's
            // parsed as one literal value, changing the replay's meaning.
            for item in items {
                push_flagged_value(parts, flag.clone(), &pagination_arg_display(item));
            }
        }
        serde_json::Value::Null => {}
        other => push_flagged_value(parts, flag, &pagination_arg_display(other)),
    }
}

fn push_flagged_value(parts: &mut Vec<String>, flag: Option<String>, value: &str) {
    if let Some(flag) = flag {
        parts.push(flag);
    }
    parts.push(quote_pagination_value(value));
}

fn pagination_arg_display(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(text) => text.clone(),
        other => other.to_string(),
    }
}

/// Quotes a value for the suggested next-page command, if it contains
/// anything beyond a small safe-unquoted allowlist. Whitespace and shell
/// metacharacters (`|`, `&`, `;`, `<`, `>`, ...) all fall outside that
/// allowlist and so trigger quoting; once quoted, `\`, `"`, `$`, and `` ` ``
/// are backslash-escaped (backslash first, so escaping the others doesn't
/// re-escape the backslashes it just inserted) so the value can't break out
/// of the double quotes or trigger POSIX-shell expansion (`$VAR`, `$(...)`,
/// backticks) if the suggestion is copy-pasted into a shell.
fn quote_pagination_value(value: &str) -> String {
    let safe_unquoted =
        |c: char| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '/' | ':' | '@');
    if value.is_empty() || !value.chars().all(safe_unquoted) {
        let escaped = value
            .replace('\\', "\\\\")
            .replace('"', "\\\"")
            .replace('$', "\\$")
            .replace('`', "\\`");
        format!("\"{escaped}\"")
    } else {
        value.to_owned()
    }
}

/// Builds the transport debug logger implied by a parsed `--debug` pattern,
/// without publishing it anywhere.
///
/// Pure so tests can assert on the decision (`--debug` pattern -> enabled or
/// not) without touching the process-wide default logger, which every
/// [`Cli::run`] call republishes — including the many unrelated tests that
/// exercise `cli.run(...)` with no `--debug` flag and would otherwise race
/// with an assertion on the shared global.
fn debug_transport_logger_for(
    debug: &str,
    extra_redacted: &[String],
) -> Arc<dyn crate::transport::TransportLogger> {
    if crate::debug_component_enabled(debug, "transport") {
        Arc::new(
            crate::transport::StderrTransportLogger::new()
                .with_redacted_headers(extra_redacted.iter().cloned()),
        )
    } else {
        Arc::new(crate::transport::NoopTransportLogger)
    }
}

/// Installs (or clears) the process-wide transport debug logger from the parsed
/// `--debug` pattern.
///
/// When `--debug` selects the `transport` component the engine publishes a
/// [`StderrTransportLogger`](crate::transport::StderrTransportLogger) — extended
/// with any [`CliConfig::with_redacted_debug_headers`] entries — which every
/// [`HttpClient`](crate::transport::HttpClient) built afterward picks up
/// automatically, with no per-command wiring. The logger is reset to a noop when
/// `transport` is not selected so the explicit setting always reflects the
/// current invocation rather than a stale process-global from an earlier one.
fn install_debug_transport_logger(debug: &str, extra_redacted: &[String]) {
    crate::transport::set_default_transport_logger(debug_transport_logger_for(
        debug,
        extra_redacted,
    ));
}

async fn run_with_timeout<F, T>(
    timeout: Option<Duration>,
    timeout_label: &str,
    future: F,
) -> Result<T>
where
    F: Future<Output = Result<T>>,
{
    let Some(timeout) = timeout else {
        return future.await;
    };
    match tokio::time::timeout(timeout, future).await {
        Ok(result) => result,
        Err(_) => Err(CliCoreError::message(format!(
            "command timed out after {timeout_label}"
        ))),
    }
}

async fn run_until_signal<Run, Shutdown>(run: Run, shutdown: Shutdown) -> CliRunOutput
where
    Run: Future<Output = CliRunOutput>,
    Shutdown: Future<Output = ()>,
{
    tokio::pin!(run);
    tokio::pin!(shutdown);
    tokio::select! {
        output = &mut run => output,
        () = &mut shutdown => CliRunOutput {
            exit_code: 130,
            rendered: "command interrupted\n".to_owned(),
        },
    }
}

#[cfg(unix)]
async fn shutdown_signal() {
    let ctrl_c = tokio::signal::ctrl_c();
    match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
        Ok(mut sigterm) => {
            tokio::select! {
                _ = ctrl_c => {},
                _ = sigterm.recv() => {},
            }
        }
        Err(_) => {
            drop(ctrl_c.await);
        }
    }
}

#[cfg(not(unix))]
async fn shutdown_signal() {
    drop(tokio::signal::ctrl_c().await);
}

fn parse_command_timeout(raw: &str) -> Result<Option<Duration>> {
    let raw = raw.trim();
    if raw.is_empty() {
        return Ok(Some(Duration::from_secs(60)));
    }
    let Some(seconds) = parse_duration_seconds(raw) else {
        return Err(CliCoreError::message(format!(
            "invalid timeout {raw:?}: expected duration like 60s, 5m, or 0s"
        )));
    };
    if seconds <= 0.0 {
        Ok(None)
    } else {
        Ok(Some(Duration::from_secs_f64(seconds)))
    }
}

fn parse_duration_seconds(raw: &str) -> Option<f64> {
    for (suffix, seconds) in [
        ("ns", 0.000_000_001_f64),
        ("us", 0.000_001_f64),
        ("µs", 0.000_001_f64),
        ("ms", 0.001_f64),
        ("s", 1.0_f64),
        ("m", 60.0_f64),
        ("h", 3600.0_f64),
    ] {
        if let Some(number) = raw.strip_suffix(suffix) {
            let value = number.parse::<f64>().ok()?;
            if !value.is_finite() {
                return None;
            }
            return Some(value * seconds);
        }
    }
    None
}

/// Reads the global `${APP_ID}_MIN_STAGE` override (see [`min_stage_env_var`]).
///
/// Best-effort, like [`crate::config::ConfigFile::load`]'s handling of a
/// malformed config file: returns `None` when the var is unset, and also
/// `None` (after logging a warning) when it is set but fails to parse as a
/// [`Stage`], so a typo'd value cannot take the CLI down.
fn global_min_stage_override(app_id: &str) -> Option<Stage> {
    let var = min_stage_env_var(app_id);
    let value = std::env::var(&var).ok()?;
    value.parse::<Stage>().map_or_else(
        |err| {
            tracing::warn!(var = %var, value = %value, error = %err, "ignoring invalid min-stage override");
            None
        },
        Some,
    )
}

/// Pure scan over an arg iterator for the last `--env <value>`/`--env=<value>`
/// occurrence — used only to seed [`Cli::new`]'s `flag_policy` (and therefore
/// which flagged commands get pruned) before the command tree is built, since
/// that decision can't be revisited once real argv is parsed. The real,
/// per-invocation `--env` value used for dispatch still comes from
/// `apply_env_flag`'s clap-based parse, unchanged; this scan never replaces
/// it, only decides tree shape earlier than clap otherwise could
/// (clap's own [`clap::Command::ignore_errors`] does not help here — it
/// still requires the rest of the argv to parse against a *known* subcommand
/// structure, and at prescan time no domain modules are registered yet, so a
/// real command path makes it bail on capturing global flags too).
///
/// Scans the *entire* argv and keeps the *last* non-empty `--env`/`--env=`
/// value, rather than stopping at the first match — a global `--env` and a
/// command-local one sharing the same arg id can both appear in one
/// invocation, and whichever clap resolves as the effective value
/// (empirically, the last one) is the one this scan must agree with. An
/// empty value (`--env=` with nothing after the `=`, or `--env` immediately
/// followed by another flag with nothing captured) is ignored rather than
/// becoming a literal empty-string candidate.
fn prescan_env_flag(mut args: impl Iterator<Item = String>) -> Option<String> {
    let mut result = None;
    while let Some(arg) = args.next() {
        // clap's end-of-options sentinel: everything after a bare `--` is a
        // positional argument, never a flag, no matter what it looks like.
        // This scan must agree, or `app cmd -- --env dev` would be
        // misread as a real `--env` override.
        if arg == "--" {
            break;
        }
        let value = if let Some(v) = arg.strip_prefix("--env=") {
            Some(v.to_owned())
        } else if arg == "--env" {
            // A space-separated value that itself looks like another flag
            // (starts with `-`) is not a value at all — clap rejects this
            // outright ("a value is required for '--env <ENV>' but none was
            // supplied"), so this scan must not treat it as one either. An
            // explicit `--env=-foo` is unambiguous and still accepted, same
            // as clap's own disambiguation rule.
            args.next().filter(|v| !v.starts_with('-'))
        } else {
            None
        };
        if let Some(v) = value.filter(|v| !v.is_empty()) {
            result = Some(v);
        }
    }
    result
}

fn render_cli_error(
    middleware: &Middleware,
    err: &(dyn std::error::Error + 'static),
    system: &str,
) -> CliRunOutput {
    let format = middleware
        .output_format
        .parse::<crate::output::OutputFormat>()
        .unwrap_or(crate::output::OutputFormat::Json);
    let envelope =
        crate::output::build_error_envelope(err, system).prepare_for_render(&middleware.verbose);
    match crate::output::render(format, &envelope) {
        Ok(rendered) => CliRunOutput {
            exit_code: exit_code_for_error(err),
            rendered,
        },
        Err(render_err) => CliRunOutput {
            exit_code: exit_code_for_error(err),
            rendered: render_err.to_string(),
        },
    }
}

fn find_command_by_colon_path<'command>(
    root: &'command Command,
    path: &str,
) -> Option<&'command Command> {
    find_command_and_canonical_path_by_colon_path(root, path).map(|(command, _)| command)
}

fn find_help_target<'command>(
    root: &'command Command,
    parts: &[&str],
) -> Option<&'command Command> {
    let mut current = root;
    let mut matched_any = false;
    for part in parts {
        let Some(next) = current.find_subcommand(part) else {
            break;
        };
        current = next;
        matched_any = true;
    }
    matched_any.then_some(current)
}

fn find_command_and_canonical_path_by_colon_path<'command>(
    root: &'command Command,
    path: &str,
) -> Option<(&'command Command, Vec<String>)> {
    if path.is_empty() {
        return Some((root, Vec::new()));
    }
    let mut current = root;
    let mut canonical = Vec::new();
    for part in path.split(':') {
        current = current.find_subcommand(part)?;
        canonical.push(current.get_name().to_owned());
    }
    Some((current, canonical))
}

fn canonical_path_from_parts(root: &Command, parts: &[String]) -> Option<String> {
    if parts.is_empty() {
        return Some(String::new());
    }
    let mut current = root;
    let mut canonical = Vec::new();
    for part in parts {
        current = current.find_subcommand(part)?;
        canonical.push(current.get_name().to_owned());
    }
    Some(canonical.join(":"))
}

/// Best-effort stderr hint for a `--scope` value that didn't resolve to a
/// known command path — `resolve_search_scope` still searches everything
/// (matching a bare `search` with no `--scope` at all), so this is the only
/// signal the user gets that their scope was ignored rather than applied.
/// Written directly to a locked stderr handle (not `eprintln!`), matching
/// the transport module's own `StderrTransportLogger` convention for this
/// kind of side-channel diagnostic: best-effort, so a write failure is
/// discarded rather than surfaced as a command error.
fn warn_unresolvable_search_scope(scope_path: &str) {
    let mut stderr = std::io::stderr().lock();
    stderr
        .write_all(
            format!(
                "warning: --scope {scope_path:?} did not match a known command path; searching everything instead\n"
            )
            .as_bytes(),
        )
        .ok();
}

fn collect_command_search_documents(
    command: &Command,
    prefix: &mut Vec<String>,
    aliases: &mut Vec<String>,
    docs: &mut Vec<SearchDocument>,
) {
    if command.is_hide_set() || BUILTIN_COMMAND_NAMES.contains(&command.get_name()) {
        return;
    }
    if command.get_subcommands().next().is_some() {
        for child in command.get_subcommands() {
            prefix.push(child.get_name().to_owned());
            let alias_len = aliases.len();
            append_command_alias_terms(child, aliases);
            collect_command_search_documents(child, prefix, aliases, docs);
            aliases.truncate(alias_len);
            prefix.pop();
        }
        return;
    }
    if prefix.is_empty() {
        prefix.push(command.get_name().to_owned());
        append_command_alias_terms(command, aliases);
    }
    let path = prefix.join(" ");
    let alias_text = aliases.join(" ");
    docs.push(SearchDocument {
        id: format!("cmd:{path}"),
        kind: "command".to_owned(),
        title: path,
        summary: command
            .get_about()
            .map(ToString::to_string)
            .unwrap_or_default(),
        content: format!(
            "{} {} {} {}",
            command
                .get_about()
                .map(ToString::to_string)
                .unwrap_or_default(),
            command
                .get_long_about()
                .map(ToString::to_string)
                .unwrap_or_default(),
            command_flag_text(command),
            alias_text
        ),
    });
    if prefix.len() == 1 && prefix[0] == command.get_name() {
        prefix.pop();
    }
}

fn append_command_alias_terms(command: &Command, aliases: &mut Vec<String>) {
    aliases.extend(command.get_all_aliases().map(str::to_owned));
    aliases.extend(
        command
            .get_all_short_flag_aliases()
            .map(|alias| alias.to_string()),
    );
    aliases.extend(command.get_all_long_flag_aliases().map(str::to_owned));
}

fn command_flag_text(command: &Command) -> String {
    command
        .get_arguments()
        .filter(|arg| !arg.is_hide_set())
        .filter_map(|arg| {
            let mut names = Vec::new();
            if let Some(short) = arg.get_short() {
                names.push(format!("-{short}"));
            }
            if let Some(long) = arg.get_long() {
                names.push(format!("--{long}"));
            }
            if let Some(short_aliases) = arg.get_all_short_aliases() {
                names.extend(
                    short_aliases
                        .into_iter()
                        .map(|short_alias| format!("-{short_alias}")),
                );
            }
            if let Some(aliases) = arg.get_all_aliases() {
                names.extend(aliases.into_iter().map(|alias| format!("--{alias}")));
            }
            (!names.is_empty()).then(|| names.join(" "))
        })
        .collect::<Vec<_>>()
        .join(" ")
}

fn has_subcommand(command: &Command, name: &str) -> bool {
    command
        .get_subcommands()
        .any(|child| child.get_name() == name)
}

fn has_root_version_flag(args: &[String], root: &Command, root_name: &str) -> bool {
    let bool_flags = derive_bool_flags(root);
    let value_flags = derive_value_flags(root);
    let mut iter = args.iter().peekable();
    if iter
        .peek()
        .is_some_and(|arg| arg_matches_root_name(arg, root_name))
    {
        iter.next();
    }

    while let Some(arg) = iter.next() {
        match arg.as_str() {
            "--version" | "-v" => return true,
            "--" => return false,
            value if value.contains('=') || bool_flags.contains(value) => continue,
            value
                if value_flags.contains(value)
                    || unknown_flag_consumes_value(value, iter.peek()) =>
            {
                iter.next();
            }
            value if value.starts_with('-') => {}
            _ => return false,
        }
    }
    false
}

fn normalize_optional_global_flags_before_command(root: &Command, args: &[String]) -> Vec<String> {
    let optional_string_defaults = BTreeMap::from([("--verbose", "all"), ("--debug", "*")]);
    let optional_bool_defaults = BTreeMap::from([("--dry-run", "true"), ("--schema", "true")]);
    let mut normalized = Vec::with_capacity(args.len());
    let mut index = 0;
    let mut current = root;
    while index < args.len() {
        let arg = &args[index];
        if index == 0 && arg_matches_root_name(arg, root.get_name()) {
            normalized.push(arg.clone());
            index += 1;
            continue;
        }

        if let Some(default) = optional_bool_defaults.get(arg.as_str()) {
            normalized.push(format!("{arg}={default}"));
            index += 1;
            continue;
        }

        if let Some(default) = optional_string_defaults.get(arg.as_str()) {
            match args.get(index + 1) {
                None => {
                    normalized.push(format!("{arg}={default}"));
                    index += 1;
                    continue;
                }
                Some(next)
                    if current.get_name() == root.get_name()
                        || next.starts_with('-')
                        || direct_subcommand(current, next).is_some() =>
                {
                    normalized.push(format!("{arg}={default}"));
                    index += 1;
                    continue;
                }
                Some(next) => {
                    normalized.push(arg.clone());
                    normalized.push(next.clone());
                    index += 2;
                    continue;
                }
            }
        }

        normalized.push(arg.clone());
        if !arg.starts_with('-')
            && let Some(next_command) = direct_subcommand(current, arg)
        {
            current = next_command;
        }
        index += 1;
    }
    normalized
}

fn direct_subcommand<'command>(
    command: &'command Command,
    token: &str,
) -> Option<&'command Command> {
    command.get_subcommands().find(|child| {
        child.get_name() == token || child.get_all_aliases().any(|alias| alias == token)
    })
}

/// Appends a `— did you mean "…"?` suffix to an unknown-command error clause.
fn format_did_you_mean(base: &str, suggestion: &str) -> String {
    format!("{base} — did you mean {suggestion:?}?")
}

/// First unknown group token (`unknown command "X" for "Y"`, no hint suffix).
struct UnknownGroupCommand {
    base: String,
}

/// Reports the first unknown token under a group. `positionals` must be pre-`--`
/// command keywords (slice to `command_keyword_count` like the group-help path).
fn detect_unknown_group_command(
    root: &Command,
    positionals: &[String],
) -> Option<UnknownGroupCommand> {
    if positionals.is_empty() {
        return None;
    }

    let mut current = root;
    let mut path = vec![root.get_name().to_owned()];
    for token in positionals {
        if let Some(next) = current.find_subcommand(token) {
            current = next;
            path.push(next.get_name().to_owned());
            continue;
        }
        if current.get_subcommands().next().is_some() {
            let base = format!("unknown command {token:?} for {:?}", path.join(" "));
            return Some(UnknownGroupCommand { base });
        }
        return None;
    }
    None
}

/// Counts positional command tokens that precede any `--` separator.
fn command_keyword_count(
    args: &[String],
    root_name: &str,
    bool_flags: &BTreeSet<String>,
    value_flags: &BTreeSet<String>,
) -> usize {
    let positionals = positional_command_tokens(args, root_name, bool_flags, value_flags);
    match args.iter().position(|arg| arg == "--") {
        Some(end) => {
            positional_command_tokens(&args[..end], root_name, bool_flags, value_flags).len()
        }
        None => positionals.len(),
    }
}

/// Rewrites `<group> help [sub...]` into `help <group> [sub...]` when the form
/// is present; otherwise returns `clap_args` unchanged.
fn rewrite_group_help_if_needed(
    root: &Command,
    clap_args: &[String],
    root_name: &str,
    bool_flags: &BTreeSet<String>,
    value_flags: &BTreeSet<String>,
) -> Vec<String> {
    let positionals = positional_command_tokens(clap_args, root_name, bool_flags, value_flags);
    let keyword_count = command_keyword_count(clap_args, root_name, bool_flags, value_flags);
    let Some(parts) = group_help_target_parts(root, &positionals, keyword_count) else {
        return clap_args.to_vec();
    };
    rewrite_group_help_args(clap_args, root_name, bool_flags, value_flags, &parts)
}

/// Rewrites the `target`-th positional command token to `replacement`, preserving
/// flags. Token classification mirrors [`positional_command_tokens`].
fn replace_positional_command_token(
    args: &[String],
    root_name: &str,
    bool_flags: &BTreeSet<String>,
    value_flags: &BTreeSet<String>,
    target: usize,
    replacement: &str,
) -> Vec<String> {
    let mut out = args.to_vec();
    let mut index = 0;
    if out
        .first()
        .is_some_and(|arg| arg_matches_root_name(arg, root_name))
    {
        index = 1;
    }

    let mut positional = 0;
    while index < out.len() {
        let arg = &out[index];
        if arg == "--" {
            break;
        }
        if arg.contains('=') {
            index += 1;
            continue;
        }
        if bool_flags.contains(arg) {
            index += 1;
            continue;
        }
        if value_flags.contains(arg)
            || unknown_flag_consumes_value(arg, out.get(index + 1).as_ref())
        {
            index += 2;
            continue;
        }
        if arg.starts_with('-') {
            index += 1;
            continue;
        }
        if positional == target {
            out[index] = replacement.to_owned();
            break;
        }
        positional += 1;
        index += 1;
    }
    out
}

/// Finds the closest visible subcommand name or alias within edit-distance
/// `max(1, token_len / 3)`. Returns the canonical name; ties break alphabetically.
fn nearest_subcommand(command: &Command, token: &str) -> Option<String> {
    let token = token.to_ascii_lowercase();
    let max_distance = 1.max(token.chars().count() / 3);

    command
        .get_subcommands()
        .filter(|child| !child.is_hide_set())
        .filter_map(|child| {
            let best = std::iter::once(child.get_name())
                .chain(child.get_all_aliases())
                .map(|candidate| strsim::osa_distance(&token, &candidate.to_ascii_lowercase()))
                .min()?;
            (best <= max_distance).then(|| (best, child.get_name().to_owned()))
        })
        .min_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)))
        .map(|(_, name)| name)
}

/// Corrects every unknown group token to its nearest subcommand. Returns `None`
/// when any token has no near match, or when there is nothing to correct.
/// Stops at a leaf operand, curated `<group> help`, or an unfixable token.
fn full_command_correction(root: &Command, positionals: &[String]) -> Option<Vec<(usize, String)>> {
    let mut current = root;
    let mut corrections = Vec::new();
    for (index, token) in positionals.iter().enumerate() {
        if let Some(next) = current.find_subcommand(token) {
            current = next;
            continue;
        }
        if current.get_subcommands().next().is_none() {
            break;
        }
        if token == "help" && current.find_subcommand("help").is_none() {
            break;
        }
        let suggestion = nearest_subcommand(current, token)?;
        let next = current.find_subcommand(&suggestion)?;
        corrections.push((index, suggestion));
        current = next;
    }
    (!corrections.is_empty()).then_some(corrections)
}

/// Prompt/display text for a correction. Last-token-only fixes show the bare
/// token; anything else shows the full corrected command path.
fn correction_display(
    root_name: &str,
    positionals: &[String],
    corrections: &[(usize, String)],
) -> String {
    if let [(index, only)] = corrections
        && *index + 1 == positionals.len()
    {
        return only.clone();
    }
    let mut tokens = vec![root_name.to_owned()];
    for (index, token) in positionals.iter().enumerate() {
        let corrected = corrections
            .iter()
            .find(|(i, _)| *i == index)
            .map(|(_, replacement)| replacement.clone())
            .unwrap_or_else(|| token.clone());
        tokens.push(corrected);
    }
    tokens.join(" ")
}

#[cfg(test)]
mod unknown_command_suggestion_tests {
    use super::*;

    fn sample_group() -> Command {
        Command::new("gddy").subcommand(
            Command::new("domain")
                .alias("dns-domain")
                .subcommand(Command::new("list"))
                .subcommand(Command::new("available")),
        )
    }

    #[test]
    fn osa_distance_treats_adjacent_transposition_as_one_edit() {
        // Guard against swapping to `strsim::levenshtein`, which counts swaps as two edits.
        assert_eq!(strsim::osa_distance("domain", "domain"), 0);
        assert_eq!(strsim::osa_distance("domian", "domain"), 1);
        assert_eq!(strsim::osa_distance("lst", "list"), 1);
        assert_eq!(strsim::osa_distance("lsit", "list"), 1);
        assert_eq!(strsim::osa_distance("cat", "set"), 2);
    }

    #[test]
    fn nearest_subcommand_matches_close_typos() {
        let root = sample_group();
        let domain = root.find_subcommand("domain").expect("domain registered");
        assert_eq!(nearest_subcommand(domain, "lst").as_deref(), Some("list"));
        assert_eq!(nearest_subcommand(domain, "ilst").as_deref(), Some("list"));
        assert_eq!(
            nearest_subcommand(domain, "avaliable").as_deref(),
            Some("available")
        );
    }

    #[test]
    fn nearest_subcommand_rejects_unrelated_tokens() {
        let root = sample_group();
        let domain = root.find_subcommand("domain").expect("domain registered");
        assert_eq!(nearest_subcommand(domain, "missing"), None);
    }

    #[test]
    fn nearest_subcommand_returns_canonical_name_for_alias_typos() {
        let root = sample_group();
        assert_eq!(
            nearest_subcommand(&root, "dns-domian").as_deref(),
            Some("domain")
        );
    }

    #[test]
    fn nearest_subcommand_skips_hidden_commands() {
        let root = Command::new("gddy")
            .subcommand(Command::new("visible"))
            .subcommand(Command::new("hiddeen").hide(true));
        assert_eq!(nearest_subcommand(&root, "hidden"), None);
    }

    #[test]
    fn nearest_subcommand_rejects_short_unrelated_tokens() {
        let root = Command::new("gddy").subcommand(
            Command::new("config")
                .subcommand(Command::new("get"))
                .subcommand(Command::new("set"))
                .subcommand(Command::new("add")),
        );
        let config = root.find_subcommand("config").expect("config registered");
        assert_eq!(nearest_subcommand(config, "cat"), None);
        assert_eq!(nearest_subcommand(config, "x"), None);
        assert_eq!(nearest_subcommand(config, "st").as_deref(), Some("set"));
    }

    #[test]
    fn unknown_group_command_formats_did_you_mean_suffix() {
        let root = sample_group();
        let unknown = detect_unknown_group_command(&root, &["domian".to_owned()])
            .expect("domian is an unknown top-level command");
        assert_eq!(unknown.base, "unknown command \"domian\" for \"gddy\"");
        assert_eq!(
            format_did_you_mean(&unknown.base, "domain"),
            "unknown command \"domian\" for \"gddy\" — did you mean \"domain\"?"
        );
    }

    #[test]
    fn detect_unknown_group_command_reports_nested_typos() {
        let root = sample_group();
        let unknown = detect_unknown_group_command(&root, &["domain".to_owned(), "lst".to_owned()])
            .expect("lst is an unknown subcommand of domain");
        assert_eq!(unknown.base, "unknown command \"lst\" for \"gddy domain\"");
        assert_eq!(
            format_did_you_mean(&unknown.base, "list"),
            "unknown command \"lst\" for \"gddy domain\" — did you mean \"list\"?"
        );
    }

    #[test]
    fn detect_unknown_group_command_omits_hint_for_unrelated_tokens() {
        let root = sample_group();
        let unknown = detect_unknown_group_command(&root, &["missing".to_owned()])
            .expect("missing is an unknown top-level command");
        assert_eq!(unknown.base, "unknown command \"missing\" for \"gddy\"");
    }

    #[test]
    fn full_command_correction_fixes_a_single_group_typo() {
        let root = sample_group();
        let corrections = full_command_correction(&root, &["domian".to_owned()])
            .expect("domian is correctable to domain");
        assert_eq!(corrections, vec![(0, "domain".to_owned())]);
    }

    #[test]
    fn full_command_correction_fixes_every_typo_in_a_nested_path() {
        let root = sample_group();
        let corrections = full_command_correction(&root, &["domian".to_owned(), "lst".to_owned()])
            .expect("both tokens are correctable");
        assert_eq!(
            corrections,
            vec![(0, "domain".to_owned()), (1, "list".to_owned())]
        );
    }

    #[test]
    fn full_command_correction_bails_when_a_token_has_no_near_match() {
        let root = sample_group();
        assert_eq!(
            full_command_correction(&root, &["domain".to_owned(), "missing".to_owned()]),
            None
        );
    }

    #[test]
    fn full_command_correction_is_none_when_there_is_nothing_to_correct() {
        let root = sample_group();
        assert_eq!(full_command_correction(&root, &["domain".to_owned()]), None);
        assert_eq!(full_command_correction(&root, &[]), None);
    }

    #[test]
    fn full_command_correction_corrects_the_group_before_curated_help() {
        let root = sample_group();
        let corrections = full_command_correction(&root, &["domian".to_owned(), "help".to_owned()])
            .expect("domian is correctable even ahead of a help token");
        assert_eq!(corrections, vec![(0, "domain".to_owned())]);
    }

    #[test]
    fn full_command_correction_keeps_corrections_when_a_leaf_is_followed_by_an_operand() {
        let root = sample_group();
        let corrections = full_command_correction(
            &root,
            &[
                "domain".to_owned(),
                "avaliable".to_owned(),
                "example.com".to_owned(),
            ],
        )
        .expect("avaliable is correctable to available");
        assert_eq!(corrections, vec![(1, "available".to_owned())]);
    }

    #[test]
    fn correction_display_shows_the_bare_token_for_a_single_fix() {
        let corrections = vec![(1, "list".to_owned())];
        assert_eq!(
            correction_display(
                "gddy",
                &["domain".to_owned(), "lst".to_owned()],
                &corrections
            ),
            "list"
        );
    }

    #[test]
    fn correction_display_shows_the_full_command_when_a_single_fix_is_not_the_last_token() {
        let corrections = vec![(0, "domain".to_owned())];
        assert_eq!(
            correction_display(
                "gddy",
                &["domian".to_owned(), "list".to_owned()],
                &corrections
            ),
            "gddy domain list"
        );
    }

    #[test]
    fn correction_display_shows_the_full_command_for_multiple_fixes() {
        let corrections = vec![(0, "domain".to_owned()), (1, "list".to_owned())];
        assert_eq!(
            correction_display(
                "gddy",
                &["domian".to_owned(), "lst".to_owned()],
                &corrections
            ),
            "gddy domain list"
        );
    }

    #[test]
    fn replace_positional_command_token_rewrites_only_the_target() {
        let bool_flags: BTreeSet<String> = ["--verbose".to_owned()].into_iter().collect();
        let value_flags: BTreeSet<String> = ["--output".to_owned()].into_iter().collect();
        let args = vec![
            "gddy".to_owned(),
            "--output".to_owned(),
            "json".to_owned(),
            "domain".to_owned(),
            "lst".to_owned(),
        ];
        let corrected =
            replace_positional_command_token(&args, "gddy", &bool_flags, &value_flags, 1, "list");
        assert_eq!(
            corrected,
            vec!["gddy", "--output", "json", "domain", "list"]
        );
    }

    #[test]
    fn rewrite_group_help_if_needed_runs_after_typo_correction() {
        let root = sample_group();
        let bool_flags = derive_bool_flags(&root);
        let value_flags = derive_value_flags(&root);
        let args = vec!["gddy".to_owned(), "domian".to_owned(), "help".to_owned()];
        let corrected =
            replace_positional_command_token(&args, "gddy", &bool_flags, &value_flags, 0, "domain");
        assert_eq!(corrected, vec!["gddy", "domain", "help"]);
        let rewritten =
            rewrite_group_help_if_needed(&root, &corrected, "gddy", &bool_flags, &value_flags);
        assert_eq!(rewritten, vec!["gddy", "help", "domain"]);
    }
}

/// Detects the `<group> help [sub...]` form and returns the command path whose
/// help should be rendered.
///
/// The engine ships a curated root `help` command, so it disables clap's
/// auto-generated help subcommand on the root. That setting propagates to every
/// subcommand and cannot be re-enabled per child, so `<group> help` would
/// otherwise hit clap's "unrecognized subcommand" error even though the group's
/// help listing advertises a `help` entry. We recognize the form here so the
/// caller can route it through the curated help renderer, matching clap's
/// documented equivalence between `cmd group help sub` and `cmd help group sub`.
///
/// Only groups (commands that have subcommands) are matched: a group is pure
/// subcommand dispatch, so a `help` token in that position is unambiguously a
/// help request. Leaf commands may accept a literal `help` positional argument,
/// so they are left for clap to parse (`<leaf> --help` still works). A group
/// that registers its own real `help` subcommand is likewise deferred to clap,
/// which dispatches the user-defined command (only auto-generated help is
/// suppressed).
///
/// `command_keyword_count` is the number of leading positionals that are
/// genuine command keywords (those before any `--`). A `help` at or beyond that
/// index is a literal operand after `--`, not a help request, so it is ignored.
fn group_help_target_parts(
    root: &Command,
    positionals: &[String],
    command_keyword_count: usize,
) -> Option<Vec<String>> {
    let help_index = positionals.iter().position(|token| token == "help")?;
    // A leading `help` is the curated root help command; let it flow through.
    if help_index == 0 {
        return None;
    }
    // A `help` after a `--` separator is a literal operand; leave it for clap.
    if help_index >= command_keyword_count {
        return None;
    }
    let prefix = &positionals[..help_index];
    let mut current = root;
    for token in prefix {
        current = current.find_subcommand(token)?;
    }
    // The token before `help` must resolve to a group; leaves are left to clap.
    current.get_subcommands().next()?;
    // Defer to clap when the group defines a real `help` subcommand of its own.
    if current.find_subcommand("help").is_some() {
        return None;
    }
    // `<group> help <sub...>` shows help for `<group> <sub...>`.
    let suffix = &positionals[help_index + 1..];
    Some(prefix.iter().chain(suffix).cloned().collect())
}

/// Rewrites a `<group> help [sub...]` invocation into the canonical
/// `help <group> [sub...]` argument vector.
///
/// Only the positional command tokens are reordered (from `[group..., help,
/// sub...]` to `[help, group..., sub...]`); every flag — including `key=value`
/// forms, value-consuming flags, unknown flags that consume a value, and
/// anything after `--` — is preserved in its original place. Reordering keeps
/// the positional count unchanged, so the rewritten stream is filled slot for
/// slot. `parts` is the resolved command path (group + subcommand) from
/// [`group_help_target_parts`].
fn rewrite_group_help_args(
    clap_args: &[String],
    root_name: &str,
    bool_flags: &BTreeSet<String>,
    value_flags: &BTreeSet<String>,
    parts: &[String],
) -> Vec<String> {
    // New positional order: the curated `help` command, then the command path.
    let mut next_positional = std::iter::once("help".to_owned())
        .chain(parts.iter().cloned())
        .peekable();
    let mut out = Vec::with_capacity(clap_args.len());
    let mut iter = clap_args.iter().peekable();
    if iter
        .peek()
        .is_some_and(|arg| arg_matches_root_name(arg, root_name))
        && let Some(program) = iter.next()
    {
        out.push(program.clone());
    }

    let mut take_positional =
        |fallback: &String| next_positional.next().unwrap_or(fallback.clone());

    while let Some(arg) = iter.next() {
        if arg == "--" {
            out.push(arg.clone());
            // Everything after `--` is positional.
            for rest in iter.by_ref() {
                out.push(take_positional(rest));
            }
            break;
        }
        if arg.contains('=') || bool_flags.contains(arg) {
            out.push(arg.clone());
            continue;
        }
        if value_flags.contains(arg) || unknown_flag_consumes_value(arg, iter.peek()) {
            out.push(arg.clone());
            if let Some(value) = iter.next() {
                out.push(value.clone());
            }
            continue;
        }
        if arg.starts_with('-') {
            out.push(arg.clone());
            continue;
        }
        out.push(take_positional(arg));
    }
    // Defensive: emit any positionals not yet placed (counts normally match).
    out.extend(next_positional);
    out
}

fn positional_command_tokens(
    args: &[String],
    root_name: &str,
    bool_flags: &BTreeSet<String>,
    value_flags: &BTreeSet<String>,
) -> Vec<String> {
    let mut tokens = Vec::new();
    let mut iter = args.iter().peekable();
    if iter
        .peek()
        .is_some_and(|arg| arg_matches_root_name(arg, root_name))
    {
        iter.next();
    }

    while let Some(arg) = iter.next() {
        if arg == "--" {
            tokens.extend(iter.cloned());
            break;
        }
        if arg.contains('=') {
            continue;
        }
        if bool_flags.contains(arg) {
            continue;
        }
        if value_flags.contains(arg) || unknown_flag_consumes_value(arg, iter.peek()) {
            iter.next();
            continue;
        }
        if arg.starts_with('-') {
            continue;
        }
        tokens.push(arg.clone());
    }
    tokens
}

fn unknown_flag_consumes_value(arg: &str, next: Option<&&String>) -> bool {
    arg.starts_with('-') && next.is_some_and(|value| !value.starts_with('-'))
}

fn arg_matches_root_name(arg: &str, root_name: &str) -> bool {
    arg == root_name
        || Path::new(arg)
            .file_stem()
            .and_then(|n| n.to_str())
            .is_some_and(|n| n == root_name)
}

/// Outcome of [`Cli::resolve_argv0`]: either rewritten arguments to feed the
/// normal pipeline, or a fully rendered result to return immediately.
enum Argv0Outcome {
    /// Continue the normal run pipeline with these arguments.
    Proceed(Vec<String>),
    /// Return this already-rendered result without further processing.
    Handled(CliRunOutput),
}

/// Extracts the bare program name from an `argv[0]` value, dropping any directory
/// path and file extension (e.g. `/usr/bin/pl` or `pl.exe` both yield `pl`).
/// Falls back to the raw value when no file stem can be derived.
fn program_basename(arg: &str) -> String {
    Path::new(arg)
        .file_stem()
        .and_then(|stem| stem.to_str())
        .map_or_else(|| arg.to_owned(), ToOwned::to_owned)
}

/// Returns `true` when `name` is a valid alternative `argv[0]` route name: a
/// non-empty token of ASCII letters, digits, `-`, or `_`. This keeps the name
/// safe as a link/shim filename and as an `argv[0]` basename (which is matched
/// with its extension stripped, so an embedded dot would break matching).
fn is_valid_argv0_name(name: &str) -> bool {
    !name.is_empty()
        && name.chars().all(|character| {
            character.is_ascii_alphanumeric() || character == '-' || character == '_'
        })
}

/// Returns `true` when the entry at `link` already matches what [`Cli::create_link`]
/// would produce for `method`/`target`/`name`, so it can be left untouched. A
/// mismatch (wrong kind, stale symlink target, or differing contents) returns
/// `false` so the caller replaces it.
fn argv0_link_matches(
    link: &Path,
    target: &Path,
    name: &str,
    method: Argv0LinkMethod,
) -> std::io::Result<bool> {
    let metadata = std::fs::symlink_metadata(link)?;
    match method {
        Argv0LinkMethod::SoftLink => {
            Ok(metadata.file_type().is_symlink() && std::fs::read_link(link)? == target)
        }
        Argv0LinkMethod::HardLink => {
            if metadata.file_type().is_symlink() {
                return Ok(false);
            }
            // A correct hard link is indistinguishable from the target by content;
            // comparing bytes also accepts an identical copy, which is harmless.
            Ok(std::fs::read(link)? == std::fs::read(target)?)
        }
        Argv0LinkMethod::Script => {
            if metadata.file_type().is_symlink() {
                return Ok(false);
            }
            Ok(std::fs::read_to_string(link).ok() == Some(argv0_script_contents(target, name)))
        }
    }
}

/// File name for an alternative `argv[0]` link, per method and host platform.
fn argv0_link_file_name(name: &str, method: Argv0LinkMethod) -> String {
    let extension = match method {
        Argv0LinkMethod::Script if cfg!(windows) => ".cmd",
        // Unix scripts are extension-less executables; links carry `.exe` on Windows.
        Argv0LinkMethod::Script => "",
        _ if cfg!(windows) => ".exe",
        _ => "",
    };
    format!("{name}{extension}")
}

/// Contents of an alternative `argv[0]` shim script that forwards to `target`
/// via the explicit `argv0` command. A `.cmd` batch file on Windows, an
/// executable POSIX shell script elsewhere.
fn argv0_script_contents(target: &Path, name: &str) -> String {
    let target = target.display();
    if cfg!(windows) {
        format!("@\"{target}\" argv0 {name} %*\r\n")
    } else {
        format!("#!/bin/sh\nexec \"{target}\" argv0 {name} \"$@\"\n")
    }
}

#[cfg(unix)]
fn create_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
    std::os::unix::fs::symlink(target, link)
}

#[cfg(windows)]
fn create_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
    std::os::windows::fs::symlink_file(target, link)
}

#[cfg(not(any(unix, windows)))]
fn create_symlink(_target: &Path, _link: &Path) -> std::io::Result<()> {
    Err(std::io::Error::new(
        std::io::ErrorKind::Unsupported,
        "symlink creation is not supported on this platform",
    ))
}

/// Marks a freshly written shim script executable on Unix; a no-op elsewhere.
#[cfg(unix)]
fn make_executable(path: &Path) -> std::io::Result<()> {
    use std::os::unix::fs::PermissionsExt;
    let mut permissions = std::fs::metadata(path)?.permissions();
    permissions.set_mode(0o755);
    std::fs::set_permissions(path, permissions)
}

#[cfg(not(unix))]
fn make_executable(_path: &Path) -> std::io::Result<()> {
    Ok(())
}

/// Walks a runtime group tree, resolving each node's effective feature flag by
/// cascading from `inherited` — a node's own [`GroupSpec::feature_flag`] or
/// [`CommandSpec::feature_flag`] wins if set, otherwise it inherits the
/// nearest ancestor's effective flag, otherwise (nothing in the ancestor
/// chain declared a flag) it implicitly resolves to [`Stage::Ga`] with no key.
/// Every node that resolves to a *named* flag (own or inherited) is recorded
/// into `registry` under its colon-separated path, together with whether
/// `policy` judged it visible. Nodes that resolve to the implicit no-flag
/// default are not recorded (there is nothing to introspect) and are always
/// visible.
///
/// Returns `None` when this group itself should be dropped from the tree —
/// either because its effective flag is not visible under `policy`, or
/// because every one of its commands and subgroups was pruned away, leaving
/// an empty group with nothing to mount. An emptied-out group is dropped
/// unconditionally, even if its own flag was visible: a `clap` subcommand
/// group with zero children is useless either way, so this simplifies the
/// pruning logic rather than threading through a "was this group itself
/// visible but empty" distinction that no caller needs.
///
/// Note that an invisible ancestor short-circuits before its children are
/// even visited: a more permissive flag on a descendant cannot resurrect a
/// subtree whose enclosing group already failed the visibility check.
fn prune_feature_flag_tree(
    mut group: RuntimeGroupSpec,
    inherited: Option<&FeatureFlag>,
    policy: &FlagPolicy,
    prefix: &mut Vec<String>,
    registry: &mut FlagRegistry,
) -> Option<RuntimeGroupSpec> {
    prefix.push(group.group.name.clone());

    let effective = group
        .group
        .feature_flag
        .clone()
        .or_else(|| inherited.cloned());
    if !record_and_check_visibility(effective.as_ref(), policy, prefix, registry) {
        prefix.pop();
        return None;
    }

    let mut kept_groups = Vec::with_capacity(group.groups.len());
    for child in std::mem::take(&mut group.groups) {
        if let Some(pruned) =
            prune_feature_flag_tree(child, effective.as_ref(), policy, prefix, registry)
        {
            kept_groups.push(pruned);
        }
    }
    group.groups = kept_groups;

    let mut kept_commands = Vec::with_capacity(group.commands.len());
    for command in std::mem::take(&mut group.commands) {
        prefix.push(command.spec.name.clone());
        let command_effective = command
            .spec
            .feature_flag
            .clone()
            .or_else(|| effective.clone());
        let visible =
            record_and_check_visibility(command_effective.as_ref(), policy, prefix, registry);
        prefix.pop();
        if visible {
            kept_commands.push(command);
        }
    }
    group.commands = kept_commands;

    prefix.pop();

    if group.commands.is_empty() && group.groups.is_empty() {
        None
    } else {
        Some(group)
    }
}

/// Records `effective` at the current `prefix` path into `registry` (only
/// when it names a flag key — the implicit Ga default is not recorded) and
/// returns whether the node is visible under `policy`.
fn record_and_check_visibility(
    effective: Option<&FeatureFlag>,
    policy: &FlagPolicy,
    prefix: &[String],
    registry: &mut FlagRegistry,
) -> bool {
    let Some(flag) = effective else {
        return true;
    };
    let visible = policy.visible(Some(flag.key.as_str()), flag.stage);
    registry.record(FlagEntry {
        path: prefix.join(":"),
        key: flag.key.clone(),
        stage: flag.stage,
        visible,
    });
    visible
}

fn register_runtime_group_metadata(
    group: &RuntimeGroupSpec,
    prefix: &mut Vec<String>,
    schemas: &mut SchemaRegistry,
    views: &mut HumanViewRegistry,
) {
    prefix.push(group.group.name.clone());
    for child_group in &group.groups {
        register_runtime_group_metadata(child_group, prefix, schemas, views);
    }
    for child in &group.commands {
        prefix.push(child.spec.name.clone());
        let command_path = prefix.join(":");
        register_command_schema(&child.spec, &command_path, schemas);
        // An inline `with_view` is registered under the command's own path; the
        // dispatch references it by that path. A `with_view_id` takes precedence
        // (dispatch uses it instead), so skip the inline registration when one is
        // set — registering it would leave an unused entry. Shared views are
        // registered separately by the module/CLI.
        if child.spec.view_id.is_none() && !child.spec.view_columns.is_empty() {
            views.register(HumanViewDef::new(
                command_path,
                child.spec.view_columns.clone(),
            ));
        }
        prefix.pop();
    }
    prefix.pop();
}

fn register_command_schema(spec: &CommandSpec, command_path: &str, schemas: &mut SchemaRegistry) {
    if let Some(schema) = &spec.output_schema {
        schemas.register_info(command_path.to_owned(), schema.clone());
    }
}

fn runtime_group_clap_command_with_schema_help(
    group: &RuntimeGroupSpec,
    prefix: &mut Vec<String>,
    schemas: &SchemaRegistry,
) -> Command {
    let mut command = group_clap_command_without_children(&group.group);
    prefix.push(group.group.name.clone());
    for child_group in &group.groups {
        command = command.subcommand(runtime_group_clap_command_with_schema_help(
            child_group,
            prefix,
            schemas,
        ));
    }
    for child in &group.commands {
        prefix.push(child.spec.name.clone());
        let command_path = prefix.join(":");
        command = command.subcommand(command_clap_command_with_schema_help(
            &child.spec,
            &command_path,
            schemas,
        ));
        prefix.pop();
    }
    prefix.pop();
    command
}

fn group_clap_command_without_children(group: &GroupSpec) -> Command {
    let mut command = Command::new(group.name.clone())
        .about(group.short.clone())
        .help_template(GROUP_HELP_TEMPLATE);
    if let Some(long) = &group.long
        && !long.is_empty()
    {
        command = command.long_about(long.clone());
    }
    for alias in &group.aliases {
        command = command.alias(alias.clone());
    }
    if group.hidden {
        command = command.hide(true);
    }
    command
}

fn command_clap_command_with_schema_help(
    spec: &CommandSpec,
    command_path: &str,
    schemas: &SchemaRegistry,
) -> Command {
    debug_assert!(
        !(spec.raw_output && spec.pagination.is_some()),
        "command {:?} sets both raw_output and with_pagination; a single verbatim string \
         has no pages, so the two are mutually exclusive",
        spec.name
    );
    let mut command = spec.clap_command();
    command = apply_dry_run_visibility(command, spec);
    command = apply_pagination_args(command, spec);
    let schema = schemas.get_by_path(command_path);
    let default_fields = default_field_names(spec);
    command = apply_fields_arg(
        command,
        spec,
        schema.as_ref().map(|schema| schema.fields.as_slice()),
        &default_fields,
    );
    command = apply_output_format_visibility(command, spec);
    let filter_expr_fields = schema
        .as_ref()
        .map_or(&[][..], |schema| schema.fields.as_slice());
    apply_filter_and_expr_examples(command, spec, filter_expr_fields)
}

/// Hides this command's inherited `--output` flag when it opted into
/// [`CommandSpec::raw_output`].
fn apply_output_format_visibility(command: Command, spec: &CommandSpec) -> Command {
    if !spec.raw_output {
        return command;
    }
    use std::io::IsTerminal;
    command.arg(
        Arg::new("output")
            .long("output")
            .short('o')
            .value_name("FORMAT")
            .default_value(if std::io::stdout().is_terminal() {
                "human"
            } else {
                "json"
            })
            .conflicts_with_all(["json", "toon", "human"])
            .display_order(crate::flags::global_flag_order::OUTPUT)
            .hide(true)
            .help("Ignored — this command always prints raw text"),
    )
}

/// Hides this command's inherited `--dry-run` flag when the command isn't
/// mutating (per [`CommandSpec::metadata`]'s `dry_run_prompt` — mirrored
/// here rather than reused, since that method returns the broader
/// [`CommandMeta`], not this one bool). `--dry-run` only ever does anything
/// for a command that opted in via `.mutates(true)`/`.with_tier(...)` (see
/// `Middleware::render_envelope`'s `meta.dry_run_prompt` gate), so showing
/// it on every other command is noise. The override still parses `--dry-run`
/// identically (same value parser, same defaults) in case a caller passes
/// it anyway — hidden only changes what `--help` shows, never behavior.
fn apply_dry_run_visibility(command: Command, spec: &CommandSpec) -> Command {
    let mutates = spec.mutates || spec.tier.is_some_and(crate::Tier::is_mutating);
    if mutates {
        return command;
    }
    command.arg(
        Arg::new("dry-run")
            .long("dry-run")
            .num_args(0..=1)
            .require_equals(true)
            .default_missing_value("true")
            .default_value("false")
            .value_parser(crate::flags::compat_bool_value_parser())
            .display_order(crate::flags::global_flag_order::DRY_RUN)
            .hide(true)
            .help("Preview mutations without executing"),
    )
}

/// Registers `--limit`/`--offset` on this command's own `Command` when its
/// spec opted in via [`CommandSpec::with_pagination`], and leaves the command
/// untouched otherwise so a non-paginating command never sees those flags —
/// in `--help` or on its command line. See [`flags::apply_pagination_args`].
fn apply_pagination_args(command: Command, spec: &CommandSpec) -> Command {
    let Some(pagination) = spec.pagination else {
        return command;
    };
    crate::flags::apply_pagination_args(command, pagination.default_limit, pagination.max_limit)
}

/// Splits a command's raw `default_fields` string into individual field
/// names, dropping the `all`/`*` sentinels that mean "every field" rather
/// than naming a real field.
fn default_field_names(spec: &CommandSpec) -> Vec<&str> {
    spec.default_fields
        .as_deref()
        .map(|fields| {
            fields
                .split(',')
                .map(str::trim)
                .filter(|field| !field.is_empty() && *field != "all" && *field != "*")
                .collect()
        })
        .unwrap_or_default()
}

/// Overrides this command's `--fields` flag with everything specific to this
/// command: its own `default_fields` as a native clap default value (so
/// `--help` shows `[default: ...]` on the flag itself, the same way
/// `--dry-run` shows `[default: false]`), and, when a schema is registered,
/// the output-field summary table appended to the flag's own help text
/// instead of the command's description — a long field table there used to
/// push `Usage:` far down the page. Global args apply to every subcommand,
/// but a subcommand-local arg of the same name takes precedence, so this
/// only affects the one command being built here.
fn apply_fields_arg(
    command: Command,
    spec: &CommandSpec,
    schema_fields: Option<&[FieldInfo]>,
    default_fields: &[&str],
) -> Command {
    if spec.raw_output {
        return command.arg(
            Arg::new("fields")
                .long("fields")
                .value_name("FIELDS")
                .display_order(crate::flags::global_flag_order::FIELDS)
                .hide(true)
                .help("Ignored — this command always prints raw text"),
        );
    }
    let default_value = spec
        .default_fields
        .as_deref()
        .filter(|fields| !fields.is_empty());
    let table = schema_fields
        .filter(|fields| !fields.is_empty())
        .map(|fields| format_help_section(fields, default_fields));
    if default_value.is_none() && table.is_none() {
        return command;
    }

    let mut help = String::from(
        "Comma-separated fields to include in output (use 'all' or '*' for everything)",
    );
    if let Some(table) = &table {
        help.push_str("\n\n");
        help.push_str(table.trim_end());
    }

    let mut arg = Arg::new("fields")
        .long("fields")
        .value_name("FIELDS")
        // Must match `global_flag_order::FIELDS` — this re-registers the
        // same flag with contextual help, not a new one, and needs to keep
        // its place among the other global flags rather than falling back
        // to this subcommand's own low, command-specific counter value.
        .display_order(crate::flags::global_flag_order::FIELDS)
        .help(help);
    if let Some(default_value) = default_value {
        arg = arg.default_value(default_value.to_owned());
    }
    command.arg(arg)
}

/// Overrides this command's `--filter` and `--expr` flags with help text
/// carrying usage examples built from its own output fields, so `--help`
/// shows them right under the flag instead of in a separate "Filter
/// examples:"/"Expr examples:" section disconnected from the flags they
/// demonstrate. Mirrors [`apply_fields_arg`]: a subcommand-local arg of the
/// same name shadows the framework's global one, and must carry the same
/// `global_flag_order` value as that global one for the same reason.
fn apply_filter_and_expr_examples(
    mut command: Command,
    spec: &CommandSpec,
    fields: &[FieldInfo],
) -> Command {
    if spec.raw_output {
        return command
            .arg(
                Arg::new("filter")
                    .long("filter")
                    .value_name("EXPR")
                    .display_order(crate::flags::global_flag_order::FILTER)
                    .hide(true)
                    .help("Ignored — this command always prints raw text"),
            )
            .arg(
                Arg::new("expr")
                    .long("expr")
                    .value_name("EXPR")
                    .display_order(crate::flags::global_flag_order::EXPR)
                    .hide(true)
                    .help("Ignored — this command always prints raw text"),
            );
    }
    if fields.is_empty() {
        return command;
    }
    let first_string = fields
        .iter()
        .find(|field| field.field_type == "string")
        .map(|field| field.name.as_str());
    let first_bool = fields
        .iter()
        .find(|field| field.field_type == "bool")
        .map(|field| field.name.as_str());

    if first_string.is_some() || first_bool.is_some() {
        let mut help = String::from("Per-item JMESPath predicate for list data");
        if let Some(name) = first_string {
            help.push_str(&format!("\ne.g. --filter \"contains({name}, 'example')\""));
        }
        if let Some(name) = first_bool {
            help.push_str(&format!("\ne.g. --filter '{name}'"));
        }
        command = command.arg(
            Arg::new("filter")
                .long("filter")
                .value_name("EXPR")
                .display_order(crate::flags::global_flag_order::FILTER)
                .help(help),
        );
    }

    let mut expr_help = String::from("JMESPath query applied to the whole result");
    expr_help.push_str("\ne.g. --expr 'length(@)'");
    if let Some(name) = first_string {
        expr_help.push_str(&format!("\ne.g. --expr '[].{name}'"));
    }
    command.arg(
        Arg::new("expr")
            .long("expr")
            .value_name("EXPR")
            .display_order(crate::flags::global_flag_order::EXPR)
            .help(expr_help),
    )
}

fn process_exit_code(code: i32) -> ExitCode {
    if code == 0 {
        return ExitCode::SUCCESS;
    }
    match u8::try_from(code) {
        Ok(code) if code != 0 => ExitCode::from(code),
        Ok(_) | Err(_) => ExitCode::from(1),
    }
}

async fn run_streaming_command(
    middleware: &Middleware,
    request: MiddlewareRequest<'_>,
    raw_matches: Arc<ArgMatches>,
    streaming_handler: crate::command::StreamingCommandHandler,
) -> Result<CliRunOutput> {
    use tokio::{io::AsyncWriteExt, sync::mpsc};

    let args_for_handler = request.args.clone();
    let user_args_for_handler = request.user_args.clone();
    let handler_path = request.command_path.to_owned();
    let middleware_for_handler = middleware.clone();
    let raw_matches_for_handler = raw_matches;

    let (tx, mut rx) = mpsc::channel::<serde_json::Value>(64);
    let sender = StreamSender(tx);

    // Drain the channel concurrently so the handler's sends don't stall
    // while the writer flushes to stdout. If stdout is under backpressure
    // the bounded channel can still fill and the handler will await send.
    let writer = tokio::spawn(async move {
        let mut stdout = tokio::io::stdout();
        while let Some(event) = rx.recv().await {
            let Ok(line) = serde_json::to_string(&event) else {
                continue;
            };
            if stdout.write_all(line.as_bytes()).await.is_err()
                || stdout.write_all(b"\n").await.is_err()
                || stdout.flush().await.is_err()
            {
                break;
            }
        }
    });

    let output = middleware
        .run(request, async move |credential| {
            streaming_handler(
                CommandContext {
                    credential,
                    args: args_for_handler,
                    user_args: user_args_for_handler,
                    command_path: handler_path,
                    middleware: middleware_for_handler,
                    raw_matches: raw_matches_for_handler,
                },
                sender,
            )
            .await?;
            Ok(crate::CommandResult::new(serde_json::Value::Null))
        })
        .await;

    // Handler has completed; its sender is dropped, which closes the channel.
    // Wait for the writer task to flush all remaining events.
    let _write_result = writer.await;

    match output {
        Ok(out) if out.exit_code == 0 => Ok(CliRunOutput {
            exit_code: 0,
            rendered: String::new(),
        }),
        Ok(out) => Ok(out.into()),
        Err(err) => Ok(CliRunOutput {
            exit_code: exit_code_for_error(&err),
            rendered: render_cli_error(middleware, &err, middleware.app_id.as_str()).rendered,
        }),
    }
}

#[cfg(test)]
mod user_agent_tests {
    use super::*;

    #[test]
    fn user_agent_string_derives_name_and_version_by_default() {
        let config =
            CliConfig::new("gdx", "GoDaddy CLI", "gdx").with_build(BuildInfo::new("1.2.3"));
        assert_eq!(config.user_agent_string(), "gdx/1.2.3");
    }

    #[test]
    fn user_agent_string_prefers_explicit_override() {
        let config = CliConfig::new("gdx", "GoDaddy CLI", "gdx")
            .with_build(BuildInfo::new("1.2.3"))
            .with_user_agent("gdx-cli/9.9 (custom)");
        assert_eq!(config.user_agent_string(), "gdx-cli/9.9 (custom)");
    }

    #[test]
    fn user_agent_string_omits_version_when_absent() {
        let config = CliConfig::new("gdx", "GoDaddy CLI", "gdx");
        assert_eq!(config.user_agent_string(), "gdx");
    }

    #[test]
    fn install_default_user_agent_publishes_config_value() {
        let _guard = crate::transport::client::UA_TEST_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let _restore = crate::transport::client::RestoreDefaultUserAgent;
        crate::transport::set_default_user_agent("cli/dev");
        let cli = Cli::new(
            CliConfig::new("uatest", "UA test", "uatest").with_build(BuildInfo::new("4.5.6")),
        );
        cli.install_default_user_agent();
        assert_eq!(
            crate::transport::client::default_user_agent(),
            "uatest/4.5.6"
        );
    }

    #[test]
    fn install_debug_transport_logger_tracks_the_debug_pattern() {
        // Asserts on `debug_transport_logger_for`'s decision directly rather
        // than publishing to and reading back the process-wide default
        // logger, which `Cli::run` republishes on every call — including the
        // many unrelated tests that call `cli.run(...)` with no `--debug`
        // flag and would otherwise race with this assertion.

        // `transport` selected -> an active (enabled) logger is built.
        assert!(debug_transport_logger_for("transport", &[]).enabled());

        // Wildcard with transport excluded -> a disabled (noop) logger.
        assert!(!debug_transport_logger_for("*,-transport", &[]).enabled());

        // Empty pattern -> disabled (noop).
        assert!(!debug_transport_logger_for("", &[]).enabled());
    }
}

#[cfg(test)]
mod env_config_tests {
    use super::*;

    #[test]
    fn with_environments_stores_shared_arc_with_consumer_app_id() {
        // The consumer sets app_id on the Environments before sharing the Arc;
        // CliConfig stores it as-is, so the file path resolves only because the
        // consumer stamped the matching app_id (not because the engine did).
        let cfg = CliConfig::new("gddy", "GoDaddy CLI", "gddy").with_environments(Arc::new(
            crate::environments::Environments::new("prod")
                .with_app_id("gddy")
                .with_config_file(true),
        ));
        let envs = cfg.environments.as_ref().expect("environments set");
        assert!(envs.config_file_path().is_some());
    }

    #[tokio::test]
    async fn env_flag_overrides_default_and_reaches_middleware_env() {
        use crate::{CommandResult, CommandSpec, RuntimeCommandSpec};
        use serde_json::json;
        let mut cli = Cli::new(
            CliConfig::new("envtest", "Env test", "envtest")
                .with_environments(Arc::new(
                    crate::environments::Environments::new("prod")
                        .with_environment("prod", crate::environments::EnvTable::new())
                        .with_environment("ote", crate::environments::EnvTable::new()),
                ))
                .with_startup_args(Vec::<&str>::new()),
        );
        cli.add_command(RuntimeCommandSpec::new_with_context(
            CommandSpec::new("whichenv", "echo env").no_auth(true),
            async |ctx| {
                Ok(CommandResult::new(
                    json!({ "env": ctx.environment()?.name().to_owned() }),
                ))
            },
        ));
        let out = cli
            .run(["envtest", "whichenv", "--env", "ote", "--output", "json"])
            .await;
        assert_eq!(out.exit_code, 0, "rendered: {}", out.rendered);
        assert!(out.rendered.contains("\"env\""));
        assert!(out.rendered.contains("ote"));
    }

    #[tokio::test]
    async fn unknown_env_flag_produces_error_envelope() {
        let cli = Cli::new(
            CliConfig::new("envtest2", "Env test", "envtest2")
                .with_environments(Arc::new(
                    crate::environments::Environments::new("prod")
                        .with_environment("prod", crate::environments::EnvTable::new()),
                ))
                .with_startup_args(Vec::<&str>::new()),
        );
        let out = cli.run(["envtest2", "tree", "--env", "nope"]).await;
        assert_ne!(out.exit_code, 0);
        assert!(out.rendered.contains("nope"));
    }
}

#[cfg(test)]
mod prescan_env_flag_tests {
    use super::*;

    fn argv(args: &[&str]) -> impl Iterator<Item = String> {
        args.iter()
            .map(|s| s.to_string())
            .collect::<Vec<_>>()
            .into_iter()
    }

    #[test]
    fn finds_space_separated_value() {
        assert_eq!(
            prescan_env_flag(argv(&["--dry-run", "--env", "dev", "list"])),
            Some("dev".to_owned())
        );
    }

    #[test]
    fn finds_equals_separated_value() {
        assert_eq!(
            prescan_env_flag(argv(&["--env=dev", "list"])),
            Some("dev".to_owned())
        );
    }

    #[test]
    fn is_none_without_the_flag() {
        assert_eq!(prescan_env_flag(argv(&["env", "list"])), None);
    }

    #[test]
    fn trailing_env_flag_with_no_value_is_none() {
        assert_eq!(prescan_env_flag(argv(&["--env"])), None);
    }

    #[test]
    fn keeps_the_last_of_multiple_occurrences() {
        // A global `--env` and a command-local one sharing the same arg id
        // can both appear (e.g. `app --env bar sub --env foo ...`); clap
        // resolves the *last* one as effective, so this scan must too.
        assert_eq!(
            prescan_env_flag(argv(&["--env", "bar", "sub", "cmd", "--env", "foo", "arg"])),
            Some("foo".to_owned())
        );
    }

    #[test]
    fn ignores_an_empty_equals_value() {
        assert_eq!(prescan_env_flag(argv(&["--env="])), None);
    }

    #[test]
    fn empty_occurrence_does_not_clobber_an_earlier_real_value() {
        assert_eq!(
            prescan_env_flag(argv(&["--env", "dev", "--env="])),
            Some("dev".to_owned())
        );
    }

    #[test]
    fn space_separated_value_starting_with_dash_is_not_a_value() {
        // clap rejects `--env --dry-run` outright ("a value is required for
        // '--env <ENV>' but none was supplied") rather than treating
        // `--dry-run` as the value; this scan must agree.
        assert_eq!(prescan_env_flag(argv(&["--env", "--dry-run"])), None);
    }

    #[test]
    fn equals_form_accepts_a_value_starting_with_dash() {
        // `--env=-foo` is unambiguous (unlike the space-separated form) and
        // still accepted, matching clap's own disambiguation rule.
        assert_eq!(
            prescan_env_flag(argv(&["--env=-foo"])),
            Some("-foo".to_owned())
        );
    }

    #[test]
    fn stops_at_the_end_of_options_sentinel() {
        // Everything after a bare `--` is positional to clap, never a flag —
        // `app cmd -- --env dev` must not be read as a real `--env` override.
        assert_eq!(prescan_env_flag(argv(&["cmd", "--", "--env", "dev"])), None);
    }

    #[test]
    fn a_real_flag_before_the_sentinel_is_still_found() {
        assert_eq!(
            prescan_env_flag(argv(&["--env", "dev", "--", "positional"])),
            Some("dev".to_owned())
        );
    }
}

#[cfg(test)]
mod feature_flag_pruning_tests {
    use super::*;
    use crate::CommandResult;

    fn trivial_command(name: &str) -> RuntimeCommandSpec {
        RuntimeCommandSpec::new(
            CommandSpec::new(name, "short").no_auth(true),
            async |_, _| Ok(CommandResult::new(serde_json::Value::Null)),
        )
    }

    fn flagged_command(name: &str, key: &str, stage: Stage) -> RuntimeCommandSpec {
        let mut command = trivial_command(name);
        command.spec = command.spec.with_feature_flag(key, stage);
        command
    }

    fn empty_policy() -> FlagPolicy {
        FlagPolicy::default()
    }

    #[test]
    fn no_flags_anywhere_keeps_everything() {
        let group = RuntimeGroupSpec::new(GroupSpec::new("root", "short"))
            .with_command(trivial_command("a"))
            .with_command(trivial_command("b"))
            .with_group(
                RuntimeGroupSpec::new(GroupSpec::new("child", "short"))
                    .with_command(trivial_command("c")),
            );

        let mut prefix = Vec::new();
        let mut registry = FlagRegistry::new();
        let pruned =
            prune_feature_flag_tree(group, None, &empty_policy(), &mut prefix, &mut registry);

        let pruned = pruned.expect("unflagged tree should never be dropped");
        assert_eq!(pruned.commands.len(), 2);
        assert_eq!(pruned.groups.len(), 1);
        assert_eq!(pruned.groups[0].commands.len(), 1);
        assert!(registry.entries().is_empty());
    }

    #[test]
    fn experimental_command_is_pruned_sibling_is_not() {
        let group = RuntimeGroupSpec::new(GroupSpec::new("root", "short"))
            .with_command(flagged_command("gated", "gated-flag", Stage::Experimental))
            .with_command(trivial_command("sibling"));

        let mut prefix = Vec::new();
        let mut registry = FlagRegistry::new();
        let pruned =
            prune_feature_flag_tree(group, None, &empty_policy(), &mut prefix, &mut registry)
                .expect("group still has a visible command left");

        assert_eq!(pruned.commands.len(), 1);
        assert_eq!(pruned.commands[0].spec.name, "sibling");

        let entries = registry.entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].path, "root:gated");
        assert_eq!(entries[0].key, "gated-flag");
        assert!(!entries[0].visible);
    }

    #[test]
    fn beta_group_pruned_under_ga_min_stage_kept_under_beta_min_stage() {
        let build_tree = || {
            RuntimeGroupSpec::new(GroupSpec::new("root", "short"))
                .with_command(trivial_command("keep-me"))
                .with_group(
                    RuntimeGroupSpec::new(
                        GroupSpec::new("flagged-group", "short")
                            .with_feature_flag("group-flag", Stage::Beta),
                    )
                    .with_command(trivial_command("cmd-default"))
                    .with_command(flagged_command(
                        "cmd-ga",
                        "cmd-ga-flag",
                        Stage::Ga,
                    )),
                )
        };

        // Default policy (min_stage: Ga) drops the whole Beta subtree, including
        // both its undeclared and explicitly-Ga-declared children, because the
        // ancestor group itself already fails visibility before children are
        // even visited.
        let mut prefix = Vec::new();
        let mut registry = FlagRegistry::new();
        let pruned = prune_feature_flag_tree(
            build_tree(),
            None,
            &empty_policy(),
            &mut prefix,
            &mut registry,
        )
        .expect("root keeps its unflagged sibling command");
        assert!(pruned.groups.is_empty());
        assert_eq!(pruned.commands.len(), 1);
        assert_eq!(pruned.commands[0].spec.name, "keep-me");
        // Only the group itself was recorded; its children were never visited.
        assert_eq!(registry.entries().len(), 1);
        assert_eq!(registry.entries()[0].path, "root:flagged-group");
        assert!(!registry.entries()[0].visible);

        // A Beta-permissive policy keeps the group and both of its children.
        let policy = FlagPolicy::default().with_min_stage(Stage::Beta);
        let mut prefix = Vec::new();
        let mut registry = FlagRegistry::new();
        let pruned =
            prune_feature_flag_tree(build_tree(), None, &policy, &mut prefix, &mut registry)
                .expect("root is kept");
        assert_eq!(pruned.groups.len(), 1);
        assert_eq!(pruned.groups[0].commands.len(), 2);
        assert!(registry.entries().iter().all(|entry| entry.visible));
    }

    #[test]
    fn ancestor_invisibility_short_circuits_before_children_are_visited() {
        // The child declares its own, more permissive Ga flag under a distinct
        // key. Per the documented pruning semantics, an invisible ancestor drops
        // its whole subtree unconditionally: the child's own flag is never even
        // considered, because `prune_feature_flag_tree` returns `None` for the
        // ancestor as soon as its own effective flag fails visibility, before
        // recursing into commands or subgroups at all.
        let group = RuntimeGroupSpec::new(
            GroupSpec::new("ancestor", "short").with_feature_flag("ancestor-flag", Stage::Beta),
        )
        .with_command(flagged_command("child", "child-flag", Stage::Ga));

        let mut prefix = Vec::new();
        let mut registry = FlagRegistry::new();
        let pruned =
            prune_feature_flag_tree(group, None, &empty_policy(), &mut prefix, &mut registry);

        assert!(
            pruned.is_none(),
            "invisible ancestor drops its whole subtree"
        );
        // The child was never visited, so nothing about it was recorded.
        assert_eq!(registry.entries().len(), 1);
        assert_eq!(registry.entries()[0].path, "ancestor");
        assert!(registry.by_key("child-flag").is_empty());
    }

    #[test]
    fn cascading_inherited_flag_key_and_stage_reach_unflagged_descendants() {
        // Simulates a module-level flag with no per-group/per-command
        // declaration anywhere below it: `inherited` here stands in for
        // `Module::feature_flag`, exactly as `add_module_group_inner` passes it.
        let module_flag = FeatureFlag::new("module-flag", Stage::Beta);
        let group = RuntimeGroupSpec::new(GroupSpec::new("root", "short"))
            .with_command(trivial_command("unflagged-child"));

        let policy = FlagPolicy::default().with_min_stage(Stage::Beta);
        let mut prefix = Vec::new();
        let mut registry = FlagRegistry::new();
        let pruned = prune_feature_flag_tree(
            group,
            Some(&module_flag),
            &policy,
            &mut prefix,
            &mut registry,
        )
        .expect("Beta-permissive policy keeps a Beta-inherited tree");
        assert_eq!(pruned.commands.len(), 1);

        // Both the group and the descendant command recorded the *same*
        // inherited key/stage, proving real cascading rather than an implicit
        // Ga default at either level.
        let entries = registry.entries();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].path, "root");
        assert_eq!(entries[0].key, "module-flag");
        assert_eq!(entries[0].stage, Stage::Beta);
        assert_eq!(entries[1].path, "root:unflagged-child");
        assert_eq!(entries[1].key, "module-flag");
        assert_eq!(entries[1].stage, Stage::Beta);

        // Under the default (Ga) policy the same inherited Beta flag makes the
        // whole tree invisible together, since the group and its unflagged
        // child resolve to the identical effective flag.
        let mut prefix = Vec::new();
        let mut registry = FlagRegistry::new();
        let pruned = prune_feature_flag_tree(
            RuntimeGroupSpec::new(GroupSpec::new("root", "short"))
                .with_command(trivial_command("unflagged-child")),
            Some(&module_flag),
            &empty_policy(),
            &mut prefix,
            &mut registry,
        );
        assert!(pruned.is_none());
    }

    #[test]
    fn registry_records_only_named_flags_not_unflagged_nodes() {
        let group = RuntimeGroupSpec::new(GroupSpec::new("root", "short")).with_group(
            RuntimeGroupSpec::new(
                GroupSpec::new("g", "short").with_feature_flag("g-flag", Stage::Beta),
            )
            .with_command(trivial_command("c1"))
            .with_command(flagged_command("c2", "c2-flag", Stage::Ga)),
        );

        // Permissive enough that nothing is pruned, so every node is visited.
        let policy = FlagPolicy::default().with_min_stage(Stage::Experimental);
        let mut prefix = Vec::new();
        let mut registry = FlagRegistry::new();
        let pruned = prune_feature_flag_tree(group, None, &policy, &mut prefix, &mut registry)
            .expect("permissive policy keeps everything");
        assert_eq!(pruned.groups[0].commands.len(), 2);

        let entries = registry.entries();
        assert_eq!(entries.len(), 3, "root has no flag and is not recorded");
        assert_eq!(entries[0].path, "root:g");
        assert_eq!(entries[0].key, "g-flag");
        assert_eq!(entries[1].path, "root:g:c1");
        assert_eq!(entries[1].key, "g-flag");
        assert_eq!(entries[1].stage, Stage::Beta);
        assert_eq!(entries[2].path, "root:g:c2");
        assert_eq!(entries[2].key, "c2-flag");
        assert_eq!(entries[2].stage, Stage::Ga);
        assert!(entries.iter().all(|entry| entry.visible));
    }

    #[test]
    fn module_feature_flag_cascades_into_its_group_via_add_module() {
        // Regression test for the bug this task fixes: `add_module` used to
        // discard `module.feature_flag` entirely, so a module-level flag could
        // never reach its group/commands. `Module::new` returns a group with an
        // unflagged command; the module itself declares Experimental, and the
        // default (Ga) policy must prune the whole group away.
        let module = Module::new("Test Category", |_ctx| {
            RuntimeGroupSpec::new(GroupSpec::new("gated-mod", "short"))
                .with_command(trivial_command("list"))
        })
        .with_feature_flag("module-flag", Stage::Experimental);

        let mut cli = Cli::new(CliConfig::new("modtest", "Module test", "modtest"));
        cli.add_module(module);

        assert!(
            !cli.commands.contains_key("gated-mod:list"),
            "module-level Experimental flag should have pruned the whole group under the default Ga policy"
        );
        assert!(
            !has_subcommand(&cli.root, "gated-mod"),
            "the pruned group must not be mounted in the clap tree either"
        );
    }

    #[test]
    fn module_feature_flag_keeps_group_when_policy_allows_it() {
        let module = Module::new("Test Category", |_ctx| {
            RuntimeGroupSpec::new(GroupSpec::new("gated-mod-2", "short"))
                .with_command(trivial_command("list"))
        })
        .with_feature_flag("module-flag-2", Stage::Experimental);

        let mut cli = Cli::new(
            CliConfig::new("modtest2", "Module test", "modtest2")
                .with_min_stage(Stage::Experimental),
        );
        cli.add_module(module);

        assert!(cli.commands.contains_key("gated-mod-2:list"));
        assert!(has_subcommand(&cli.root, "gated-mod-2"));
    }

    #[test]
    fn active_environment_min_stage_loosens_consumer_level_policy() {
        // The CliConfig itself leaves min_stage at its Ga default, which would
        // normally prune this Experimental-flagged group. The active ("prod")
        // environment's compiled min_stage override should reach
        // `middleware.flag_policy` before pruning runs and keep it instead.
        let module = Module::new("Test Category", |_ctx| {
            RuntimeGroupSpec::new(GroupSpec::new("gated-mod-3", "short"))
                .with_command(trivial_command("list"))
        })
        .with_feature_flag("module-flag-3", Stage::Experimental);

        let mut cli = Cli::new(
            CliConfig::new("modtest3", "Module test", "modtest3")
                .with_environments(Arc::new(
                    crate::environments::Environments::new("prod").with_environment(
                        "prod",
                        crate::environments::EnvTable::new().with("min_stage", "experimental"),
                    ),
                ))
                .with_startup_args(Vec::<&str>::new()),
        );
        cli.add_module(module);

        assert!(cli.commands.contains_key("gated-mod-3:list"));
        assert!(has_subcommand(&cli.root, "gated-mod-3"));
    }

    /// The direct proof of the startup `--env` prescan (see `Cli::new`):
    /// unlike [`active_environment_min_stage_loosens_consumer_level_policy`]
    /// (which exercises the *default* active environment), here "prod" is
    /// the default and carries no override, while "dev" loosens `min_stage`.
    /// A `--env dev` supplied via `with_startup_args` — standing in for real
    /// process argv — must be consulted before `add_module` prunes the tree,
    /// in the *same* construction, not just update `middleware.env` for a
    /// later run.
    #[test]
    fn startup_env_flag_reveals_beta_and_experimental_modules_for_the_named_env() {
        fn gated_module() -> Module {
            Module::new("Test Category", |_ctx| {
                RuntimeGroupSpec::new(GroupSpec::new("gated-mod-4", "short"))
                    .with_command(trivial_command("list"))
            })
            .with_feature_flag("module-flag-4", Stage::Experimental)
        }
        fn environments() -> Arc<crate::environments::Environments> {
            Arc::new(
                crate::environments::Environments::new("prod")
                    .with_environment("prod", crate::environments::EnvTable::new())
                    .with_environment(
                        "dev",
                        crate::environments::EnvTable::new().with("min_stage", "experimental"),
                    ),
            )
        }

        let mut with_dev_flag = Cli::new(
            CliConfig::new("modtest4a", "Module test", "modtest4a")
                .with_environments(environments())
                .with_startup_args(["modtest4a", "--env", "dev"]),
        );
        with_dev_flag.add_module(gated_module());
        assert!(
            with_dev_flag.commands.contains_key("gated-mod-4:list"),
            "--env dev in startup_args should reveal the Experimental module"
        );
        assert!(has_subcommand(&with_dev_flag.root, "gated-mod-4"));

        // Negative counterpart: with no `--env` at all, the default ("prod",
        // no override) still governs — nothing changed for the common case.
        let mut without_flag = Cli::new(
            CliConfig::new("modtest4b", "Module test", "modtest4b")
                .with_environments(environments())
                .with_startup_args(Vec::<&str>::new()),
        );
        without_flag.add_module(gated_module());
        assert!(
            !without_flag.commands.contains_key("gated-mod-4:list"),
            "without --env, the default env's Ga policy should still prune the module"
        );
        assert!(!has_subcommand(&without_flag.root, "gated-mod-4"));
    }

    static GLOBAL_MIN_STAGE_ENV_LOCK: Mutex<()> = Mutex::new(());

    /// RAII guard that restores (or removes) an env var on drop, even if a
    /// test panics.
    struct GlobalMinStageEnvGuard {
        key: &'static str,
        prev: Option<std::ffi::OsString>,
    }
    impl GlobalMinStageEnvGuard {
        /// Sets `key` to `value`. Caller must hold [`GLOBAL_MIN_STAGE_ENV_LOCK`]
        /// for the guard's entire lifetime.
        #[allow(unsafe_code)]
        fn set(key: &'static str, value: &str) -> Self {
            let prev = std::env::var_os(key);
            // SAFETY: serialized by GLOBAL_MIN_STAGE_ENV_LOCK; guard
            // restores/removes on any exit incl. panic.
            unsafe { std::env::set_var(key, value) };
            Self { key, prev }
        }

        /// Removes `key` (if set). Caller must hold
        /// [`GLOBAL_MIN_STAGE_ENV_LOCK`] for the guard's entire lifetime.
        #[allow(unsafe_code)]
        fn unset(key: &'static str) -> Self {
            let prev = std::env::var_os(key);
            // SAFETY: serialized by GLOBAL_MIN_STAGE_ENV_LOCK; guard restores
            // on any exit incl. panic.
            unsafe { std::env::remove_var(key) };
            Self { key, prev }
        }
    }
    impl Drop for GlobalMinStageEnvGuard {
        #[allow(unsafe_code)]
        fn drop(&mut self) {
            // SAFETY: test holds GLOBAL_MIN_STAGE_ENV_LOCK; restore/clean up
            // on any exit including panic.
            unsafe {
                match &self.prev {
                    Some(v) => std::env::set_var(self.key, v),
                    None => std::env::remove_var(self.key),
                }
            }
        }
    }

    #[test]
    #[allow(unsafe_code)]
    fn global_min_stage_override_is_a_noop_when_unset() {
        let _g = GLOBAL_MIN_STAGE_ENV_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        const VAR: &str = "UNSET_MIN_STAGE_APP_MIN_STAGE";
        // Explicitly unset (and restored on drop) rather than assumed absent,
        // so the test is hermetic even if a developer/CI happens to have this
        // var set.
        let _guard = GlobalMinStageEnvGuard::unset(VAR);

        assert_eq!(global_min_stage_override("unset-min-stage-app"), None);
    }

    #[test]
    #[allow(unsafe_code)]
    fn global_min_stage_override_parses_a_valid_value() {
        let _g = GLOBAL_MIN_STAGE_ENV_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        const VAR: &str = "VALID_MIN_STAGE_APP_MIN_STAGE";
        let _guard = GlobalMinStageEnvGuard::set(VAR, "beta");

        assert_eq!(
            global_min_stage_override("valid-min-stage-app"),
            Some(Stage::Beta)
        );
    }

    #[test]
    #[allow(unsafe_code)]
    fn global_min_stage_override_ignores_a_malformed_value() {
        let _g = GLOBAL_MIN_STAGE_ENV_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        const VAR: &str = "BAD_MIN_STAGE_APP_MIN_STAGE";
        let _guard = GlobalMinStageEnvGuard::set(VAR, "nightly");

        assert_eq!(global_min_stage_override("bad-min-stage-app"), None);
    }
}

#[cfg(test)]
mod flags_command_tests {
    use super::*;
    use crate::CommandResult;

    /// Builds a module with one flagged group containing one flagged (via
    /// inheritance) `list` command, so `flag_registry` has something to
    /// introspect once the module is mounted.
    fn flagged_module(group_name: &'static str, key: &'static str, stage: Stage) -> Module {
        Module::new("Test Category", move |_ctx| {
            RuntimeGroupSpec::new(GroupSpec::new(group_name, "short")).with_command(
                RuntimeCommandSpec::new(
                    CommandSpec::new("list", "short").no_auth(true),
                    async |_, _| Ok(CommandResult::new(serde_json::Value::Null)),
                ),
            )
        })
        .with_feature_flag(key, stage)
    }

    #[tokio::test]
    async fn flags_list_reports_flagged_entries() {
        let mut cli = Cli::new(
            CliConfig::new("flagtest", "Flag test", "flagtest").with_min_stage(Stage::Beta),
        );
        cli.add_module(flagged_module("flagged-mod", "list-flag", Stage::Beta));

        let out = cli
            .run(["flagtest", "flags", "list", "--output", "json"])
            .await;
        assert_eq!(out.exit_code, 0, "rendered: {}", out.rendered);
        let rendered: serde_json::Value =
            serde_json::from_str(&out.rendered).expect("stdout should contain json");
        let entries = rendered["data"].as_array().expect("data should be array");
        let command_entry = entries
            .iter()
            .find(|entry| entry["path"] == "flagged-mod:list")
            .expect("flagged command entry should be present");
        assert_eq!(command_entry["key"], "list-flag");
        assert_eq!(command_entry["stage"], "beta");
        assert_eq!(command_entry["visible"], true);
    }

    #[tokio::test]
    async fn flags_info_returns_policy_and_entries_for_known_key() {
        let mut cli = Cli::new(
            CliConfig::new("flagtest2", "Flag test", "flagtest2").with_min_stage(Stage::Beta),
        );
        cli.add_module(flagged_module("flagged-mod-2", "info-flag", Stage::Beta));

        let out = cli
            .run([
                "flagtest2",
                "flags",
                "info",
                "info-flag",
                "--output",
                "json",
            ])
            .await;
        assert_eq!(out.exit_code, 0, "rendered: {}", out.rendered);
        let rendered: serde_json::Value =
            serde_json::from_str(&out.rendered).expect("stdout should contain json");
        let data = &rendered["data"];
        assert_eq!(data["key"], "info-flag");
        assert_eq!(data["policy"]["min_stage"], "beta");
        assert!(data["policy"]["override"].is_null());
        let entries = data["entries"].as_array().expect("entries should be array");
        assert!(!entries.is_empty());
        assert!(entries.iter().any(|entry| {
            entry["path"] == "flagged-mod-2:list" && entry["decided_by"] == "min_stage"
        }));
    }

    #[tokio::test]
    async fn flags_info_reports_override_decided_by() {
        // The module declares Experimental, which the default Ga policy would
        // normally hide; the override forces Ga instead, so the entries stay
        // visible even though `entry.stage` still reports the node's own
        // (Experimental) declaration, not the override.
        let mut cli = Cli::new(
            CliConfig::new("flagtest3", "Flag test", "flagtest3")
                .with_feature_override("override-flag", Stage::Ga),
        );
        cli.add_module(flagged_module(
            "flagged-mod-3",
            "override-flag",
            Stage::Experimental,
        ));

        let out = cli
            .run([
                "flagtest3",
                "flags",
                "info",
                "override-flag",
                "--output",
                "json",
            ])
            .await;
        assert_eq!(out.exit_code, 0, "rendered: {}", out.rendered);
        let rendered: serde_json::Value =
            serde_json::from_str(&out.rendered).expect("stdout should contain json");
        let data = &rendered["data"];
        assert_eq!(data["policy"]["min_stage"], "ga");
        assert_eq!(data["policy"]["override"], "ga");
        let entries = data["entries"].as_array().expect("entries should be array");
        assert!(!entries.is_empty());
        assert!(
            entries
                .iter()
                .all(|entry| entry["decided_by"] == "override")
        );
        assert!(entries.iter().all(|entry| entry["visible"] == true));
        assert!(entries.iter().all(|entry| entry["stage"] == "experimental"));
    }

    #[tokio::test]
    async fn flags_info_unknown_key_errors() {
        let cli = Cli::new(CliConfig::new("flagtest4", "Flag test", "flagtest4"));

        let out = cli
            .run(["flagtest4", "flags", "info", "no-such-flag"])
            .await;
        assert_ne!(out.exit_code, 0);
        assert!(out.rendered.contains("no such flag"));
    }
}