newt-agent 0.8.0

Newt-Agent — free, friendly, local agentic coder (vi to Hermes's emacs)
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
//! Newt CLI dispatch surface.
//!
//! Subcommands: `code`, `pilot`, `worker`, `mcp`, `doctor`, `config`,
//! `identity`, `dgx`, `tunings`.
//!
//! The mesh subcommands (`announce`, `ask`) live in a sibling binary,
//! `newt-mesh-cli`, inside the out-of-workspace `newt-mesh/` crate.
//! See `docs/decisions/mesh_integration.md` for why that crate is
//! kept out of the default workspace.

mod auth_cmd;
mod compaction_cmd;
mod config_cmd;
pub mod crew;
pub mod crew_runner;
mod dgx;
mod dgx_card;
mod dgx_pull;
pub mod dgx_registry;
pub mod dgx_status;
pub mod dgx_vllm;
mod dock_cmd;
mod doctor;
mod frame_cmd;
mod headless;
pub mod help_suite;
mod identity_cmd;
mod mcp_cmd;
mod mcp_probe_cmd;
mod migration_notices;
mod models_cmd;
mod new_project;
mod ocap_cmd;
mod providers_cmd;
mod providers_import;
mod skills;
// W0 (#1511): the pure emitter-side declaration of the observability
// contract (`contract_version: "1"`) `newt headless` appends to `--events`.
mod headless_contract;
pub mod stack;
pub mod stdio_guard;
mod summarizer_cmd;
mod timer_cmd;
mod tuning_cmd;
mod web_cmd;

use clap::{Parser, Subcommand};
use std::io::IsTerminal;
use std::path::PathBuf;

/// clap value parser for `--shell-engine`. Delegates to [`newt_core::ShellEngine`]'s
/// `FromStr` (canonical names plus aliases like `landlock`→`host`); a bad value
/// is rejected at parse time, as is an unavailable worker transport.
fn parse_shell_engine(
    s: &str,
) -> Result<newt_core::ShellEngine, Box<dyn std::error::Error + Send + Sync + 'static>> {
    let engine = s.parse::<newt_core::ShellEngine>()?;
    engine.validate_available()?;
    Ok(engine)
}

// Model: GPT-5 | Harness: Codex | Operator: Shawn Hartsock | Time: 13:18 EDT | Date: 2026-08-12

/// Build a parser command graph with the shared `help` formatting applied to
/// this command and all subcommands.
pub fn help_command() -> clap::Command {
    help_suite::help_command()
}

/// Parse CLI args with the shared help format wiring.
pub fn parse_with_help() -> anyhow::Result<Cli> {
    help_suite::parse_with_help()
}

#[derive(Parser, Debug)]
#[command(
    name = "newt",
    version = newt_core::build_info::VERSION_WITH_COMMIT,
    about = "Free, friendly, local agentic coder"
)]
// `newt help [command]` renders newt's INTERACTIVE `/help` command catalog
// startup-free (no session, no backend) via the `Help` subcommand below —
// deliberately taking over the name from clap's auto-generated `help`
// subcommand, whose CLI-tree text remains available as `newt --help`.
#[command(disable_help_subcommand = true)]
pub struct Cli {
    /// Path to config file (overrides default search order).
    #[arg(short, long, global = true)]
    pub config: Option<PathBuf>,

    /// Use a different user config root instead of ~/.newt.
    /// Reads config.toml and sibling state files from this directory. An
    /// explicit --config file still wins for the main config document.
    #[arg(long, global = true, value_name = "DIR")]
    pub config_dir: Option<PathBuf>,

    /// Skip the full-screen splash: print a compact inline header instead.
    /// Applies to the `code` subcommand (the default). Also configurable
    /// via `[tui] no_splash = true` in newt.toml. Overrides `--splash`.
    #[arg(
        long,
        global = true,
        default_value_t = false,
        overrides_with = "splash"
    )]
    pub no_splash: bool,

    /// Force the full-screen splash even when `[tui] no_splash = true` is set
    /// in the config. Overrides `--no-splash`.
    #[arg(
        long,
        global = true,
        default_value_t = false,
        overrides_with = "no_splash"
    )]
    pub splash: bool,

    /// Lean / flight / wyvern mode (issue #527): drop the rich footer and use the
    /// dead-simple LeanTUI text box, where each prompt renders as a timestamped
    /// server-log line (`[ts] ❯ <prompt>`). Equivalent to `NEWT_FOOTER=off` /
    /// `[tui] footer = "off"`. By default the rich footer shows on a TTY and
    /// auto-degrades to this lean morphology off one (pipes, `newt worker`).
    /// `-n` / `--neat` / `--lite` (vi's "no-swap" spirit) are the same switch.
    #[arg(
        short = 'n',
        long,
        visible_aliases = ["neat", "lite", "lean", "flight", "no-footer"],
        global = true,
        default_value_t = false
    )]
    pub plain: bool,

    /// Color / theme (issue #527): always|never|auto|minimal|inverted|dark|
    /// light|mono. Controls whether — and how — ANSI color is emitted.
    /// Precedence: this flag > NO_COLOR / TERM=dumb > `[tui] color` > auto. An
    /// explicit `--color` also overrides NO_COLOR. Equivalent to `NEWT_COLOR`.
    #[arg(long, global = true, value_name = "MODE", value_parser = parse_color_mode)]
    pub color: Option<newt_core::ColorMode>,

    /// Force monochrome output (no color). Sugar for `--color=mono`; wins over
    /// `--color` when both are given.
    #[arg(long, global = true, default_value_t = false)]
    pub mono: bool,

    /// Enable per-round agent-loop diagnostics: prints each round's content
    /// excerpt, tool-call count, and token usage. Also enables fallback
    /// messages when the model returns an empty reply. Equivalent to setting
    /// `NEWT_DEBUG=1` in the environment or `[tui] debug = true` in newt.toml.
    #[arg(long, global = true, default_value_t = false)]
    pub debug: bool,

    /// Enable deep inference diagnostics for backend compatibility failures.
    /// Implies `--debug` and emits structural response details intended for
    /// GitHub issues and backend debugging. Also set via `NEWT_TRACE=1`.
    #[arg(long, global = true, default_value_t = false)]
    pub trace: bool,

    /// Start the TUI coder with a named persona from ~/.newt/personas/<name>.md.
    /// Defaults are created lazily the first time persona mode is used.
    #[arg(long, global = true, value_name = "NAME")]
    pub persona: Option<String>,

    /// Operating altitude (FR-5, #999): `doer` acts (make the change), `coach`
    /// (alias `advise`) advises without mutating — it REPLACES the base identity
    /// with the coach soul. Overrides a `--persona`'s own altitude; with no
    /// `--persona` it runs a coach with no other role overlay.
    #[arg(long, global = true, value_name = "LEVEL", value_parser = ["doer", "coach", "advise"])]
    pub altitude: Option<String>,

    /// Tenacity (#psyche): how long the agent pursues the task — `normal` |
    /// `relentless`. Default `normal`. In interactive code sessions and
    /// `headless`, `relentless` makes the initial tool-round allowance effectively
    /// unlimited; an explicit initial allowance wins. Fresh progress can renew
    /// either allowance; set `workflow_grace_rounds = 0` for a hard cap. The pre-split levels
    /// (`relaxed` / `standard` / `insistent`) are refused with their
    /// `--initiative` replacement.
    #[arg(long, global = true, value_name = "LEVEL", value_parser = parse_tenacity)]
    pub tenacity: Option<newt_core::Tenacity>,

    /// Initiative (#psyche): how much the agent looks before acting —
    /// `patient` | `measured` | `decisive` | `eager`. Higher nudges the model to
    /// edit after fewer read-only rounds (12/3/2/1 by default, from
    /// `[initiative.rounds]`), and `decisive`/`eager` make plan-mode exit hand
    /// off to a mandatory edit. Unset ⇒ the persona's, else the model family's
    /// `[initiative.families]` default, else `[initiative] default`, else
    /// `measured`.
    #[arg(long, global = true, value_name = "LEVEL", value_parser = parse_initiative)]
    pub initiative: Option<newt_core::Initiative>,

    /// Cognition (#psyche): how much reasoning to spend per call —
    /// `zen` | `rational` | `thoughtful` | `meticulous`, mapping to the
    /// OpenAI `reasoning.effort` wire field (minimal … high) on the Responses API.
    /// A session-wide override that beats a persona's `cognition:`; applies to the
    /// interactive TUI AND the `headless` / worker path. Unset ⇒ no
    /// `reasoning.effort` is sent (unless a persona sets one).
    #[arg(long, global = true, value_name = "LEVEL", value_parser = parse_cognition)]
    pub cognition: Option<newt_core::role_profile::Cognition>,

    /// Obsessive (#psyche): the max-effort posture — newt's "ultra". A named
    /// launch act that moves three orthogonal dials at once: cognition to
    /// `meticulous` (deepest reasoning.effort), tenacity to `relentless`, and
    /// the crew ON (as if `NEWT_TEAM` were set). For interactive code sessions
    /// and `headless`, Relentless makes the default round budget effectively
    /// unlimited. Initiative is left alone (`--initiative` is independent). An
    /// explicit `--tenacity` alongside still wins. In-session, `/psyche
    /// obsessive` engages the two live dials; crew needs a launch with this
    /// flag. Alias `--obsessive-relentless` names the tenacity axis explicitly.
    #[arg(
        long,
        visible_alias = "obsessive-relentless",
        global = true,
        default_value_t = false
    )]
    pub obsessive: bool,

    /// Run with NO conversation persistence: nothing is auto-resumed, no
    /// conversation row is created, and no turn is saved. Equivalent to
    /// setting `NEWT_EPHEMERAL=1`. Takes precedence over
    /// `NEWT_CONVERSATION_ID` and `[conversations] resume` (Step 17.7).
    #[arg(long, global = true, default_value_t = false)]
    pub ephemeral: bool,

    /// #1671: resume a saved conversation by NAME (the title `/rename` set —
    /// case-insensitive; a unique substring also works) or by id/prefix, in
    /// this workspace. Equivalent to `NEWT_RESUME=<name>`; an explicit
    /// `NEWT_CONVERSATION_ID` still wins, and a name that matches nothing or
    /// several conversations is a hard error (never a silent fresh start).
    /// In-session, bare `/resume` browses and `/rename <title>` names.
    #[arg(long, global = true, value_name = "NAME", conflicts_with = "ephemeral")]
    pub resume: Option<String>,

    /// Admit only the explicitly resumed conversation into Smart Harness as
    /// historical context, without reconstructing past execution evidence.
    /// Requires [smart_harness] enabled = true. Interactive TUI only.
    #[arg(long, global = true, requires = "resume", conflicts_with = "ephemeral")]
    pub adopt_frame: bool,

    /// When a tool call is denied by the session's permission caveats, ask
    /// interactively — allow once / allow for this session / deny — instead
    /// of failing the call outright (issue #263). Decisions are recorded to
    /// `~/.newt/permission-log.jsonl` for later review (`/permissions` lists
    /// them). Equivalent to `[tui.permissions] prompt = true`. Interactive
    /// TUI only: headless runs (worker / eval) always keep the plain denial.
    /// As of #721 this is now the DEFAULT for interactive sessions, so the
    /// flag is usually redundant; use `--no-prompt-for-permissions` to opt out.
    #[arg(long, global = true, default_value_t = false)]
    pub prompt_for_permissions: bool,

    /// Opt OUT of interactive permission prompting (#721). By default an
    /// interactive session now asks the operator on a capability denial; pass
    /// this to keep the plain, fail-closed denial instead (the model still gets
    /// the recoverable `request_permissions` guidance). Wins over
    /// `--prompt-for-permissions` / `[tui.permissions] prompt`. Equivalent to
    /// `NEWT_NO_PROMPT_FOR_PERMISSIONS=1`. Headless runs are unaffected (they
    /// never prompt regardless).
    #[arg(long, global = true, default_value_t = false)]
    pub no_prompt_for_permissions: bool,

    /// INTERIM (#297): disable the ocap confined shell for THIS invocation —
    /// run_command executes unconfined on the plain host shell (same venv/PATH
    /// handling, same output shape). fs tools keep the workspace fence and
    /// web_fetch keeps its leash: this is unconfined exec, not authority-off.
    /// Equivalent to NEWT_DISABLE_OCAP=1; deliberately NO config-file key, so
    /// the bypass must be asserted per invocation. Static Brush filters are
    /// integrated; native confinement and authenticated worker transport still
    /// need platform parity before this interim switch can be retired.
    #[arg(long, visible_alias = "yolo", global = true, default_value_t = false)]
    pub disable_ocap: bool,

    /// Use cmd.exe /C instead of Brush for Windows ambient commands.
    /// Overrides [shell] windows_cmd; does not disable confinement.
    #[arg(long, global = true, default_value_t = false)]
    pub windows_cmd: bool,

    /// Override the configured `[tui.permissions]` preset with `full_access`
    /// for THIS invocation — session authority becomes unrestricted (fs fence,
    /// net leash, and exec allowlist all lifted; `write_file` behaves exactly
    /// as it does under the `full_access` preset). A DISTINCT switch from
    /// `--disable-ocap`/`--yolo`: this widens *authority*, while `--yolo`
    /// changes the exec *mechanism* (host shell vs confined shell) and still
    /// honors the active exec floor. Combine them (`--yolo --full-access`)
    /// for a fully unrestricted host shell. Equivalent to `NEWT_FULL_ACCESS=1`;
    /// deliberately NO config-file key beyond the existing preset, so the
    /// per-run override can never silently persist.
    #[arg(long, global = true, default_value_t = false)]
    pub full_access: bool,

    /// Full access inside the workspace for this interactive session: run
    /// commands and create, change, rename, or delete files below `code <DIR>`.
    /// Native filesystem confinement remains active; network access follows
    /// the independently configured permissions. This startup choice overrides
    /// the configured preset and inherited global-access/host-bypass switches.
    #[arg(long, global = true, default_value_t = false, conflicts_with_all = ["full_access", "disable_ocap"])]
    pub workspace_access: bool,

    /// Select the shell **engine** `run_command` uses for THIS invocation (the
    /// ADR 0005 D2 seam): `safe-subset` (portable default — refuses
    /// `$(...)`/dynamic constructs), `host` (real `/bin/sh -c` inside the L3
    /// kernel jail — full grammar on hosts with /bin/sh), or `brush` (carried
    /// bash-in-Rust in an authenticated worker, currently Linux/macOS only).
    /// Unsupported Brush choices fail at startup. Full access defaults to host
    /// on Linux/macOS and safe-subset elsewhere. Overrides the
    /// `[shell] engine` config key. The L3 backend (Landlock/Seatbelt) is a
    /// separate, auto-selected axis.
    #[arg(long, global = true, value_parser = parse_shell_engine)]
    pub shell_engine: Option<newt_core::ShellEngine>,

    /// facade P4 (#780): turn OFF the convenience tool-call ROUTING for THIS
    /// invocation. By default supported `run_command` calls such as `cat X`,
    /// `ls`, and `find` use the governed built-in; `--no-route` runs the
    /// original command on the normal exec path instead. Git commands always
    /// use native exec, with or without this switch. This is the L2
    /// convenience-OFF switch and is DELIBERATELY DISTINCT from `--disable-ocap`
    /// /`--yolo`: it NEVER disables the L3 boundary — the confined shell still
    /// gates exec and the fs fence still governs reads. Equivalent to
    /// `NEWT_NO_ROUTE=1`; env-only, no config key, so it cannot silently persist.
    #[arg(long, global = true, default_value_t = false)]
    pub no_route: bool,

    /// Cap the Ollama context window (KV-cache) to this many tokens.
    /// Prevents VRAM exhaustion on large models by limiting how much memory
    /// Ollama allocates for the attention cache. Equivalent to setting
    /// `NEWT_NUM_CTX=<N>` or `[tui] num_ctx = <N>` in newt.toml.
    /// Recommended starting point: 8192. Omit to use the model default.
    #[arg(long, global = true, value_name = "TOKENS")]
    pub num_ctx: Option<u32>,

    /// Apply a named profile (`[profiles.<name>]` in newt.toml) — a composition
    /// of harness techniques + their knob settings tuned for a model family /
    /// context. Equivalent to `NEWT_PROFILE=<name>`. An unknown profile, or one
    /// naming an unknown technique, is a hard error. Omit for default behavior.
    #[arg(long, global = true, value_name = "NAME")]
    pub profile: Option<String>,

    /// Load a named bundle (`[bundles.<name>]`) — the loadable unit of the model
    /// support kit. The bundle resolves to a profile for the active model (its
    /// `families` map, else `default_profile`). `--profile` overrides it; with
    /// neither, a bundle whose `applies_to` matches the model is auto-inferred.
    /// Equivalent to `NEWT_BUNDLE=<name>`. An unknown bundle is a hard error.
    #[arg(long, global = true, value_name = "NAME")]
    pub bundle: Option<String>,

    /// Load a named loadout (`[loadouts.<name>]`) — the full composition of
    /// provider → model → kit → role → settings. Each axis is fed to its existing
    /// selector; an explicit `--profile`/`--bundle`/`--num-ctx`/`--persona`
    /// overrides the corresponding loadout field. Equivalent to `NEWT_LOADOUT=<name>`.
    /// An unknown loadout or a dangling reference inside it is a hard error.
    #[arg(long, global = true, value_name = "NAME")]
    pub loadout: Option<String>,

    /// Directory to search for AGENTS.md/CLAUDE.md, or a specific instructions
    /// file. Default: the workspace (`./`). Also `[agents] path`.
    #[arg(long, global = true, value_name = "PATH")]
    pub agents_file: Option<String>,

    /// Don't load AGENTS.md/CLAUDE.md into the system prompt (overrides
    /// `[agents] enabled`).
    #[arg(long, global = true, default_value_t = false)]
    pub no_agents_file: bool,

    /// Activate a Python virtual environment for all agent-run commands.
    /// Injects `VIRTUAL_ENV` and prepends the venv's `bin/` to `PATH` inside
    /// the confined shell, and grants exec permission for every executable in
    /// the venv's `bin/` — a fast alternative to listing them one-by-one in
    /// `[tui.permissions] extra_exec`. If omitted and `$VIRTUAL_ENV` is already
    /// set (shell-activated venv), that environment is used automatically.
    #[arg(long, global = true, value_name = "PATH")]
    pub venv: Option<PathBuf>,

    /// Grant the agent exec permission for all executables in `<DIR>` and
    /// prepend `<DIR>` to `PATH` in the confined shell. May be repeated.
    /// Example: `newt --exec-path ~/bin --exec-path ~/workspaces/bin`.
    #[arg(long = "exec-path", global = true, value_name = "DIR")]
    pub exec_paths: Vec<PathBuf>,

    /// Grant the agent READ access to a file or directory OUTSIDE the workspace.
    /// A directory grants everything under it; a file grants just that file. May
    /// be repeated. Reference the path by its absolute path in tools.
    /// Example: `newt --read ~/.newt --read ~/.hotseat/config.yml`.
    #[arg(long = "read", global = true, value_name = "PATH")]
    pub read_paths: Vec<PathBuf>,

    /// Grant the agent READ+WRITE access to a file or directory OUTSIDE the
    /// workspace (implies `--read` for the same path). May be repeated.
    /// Example: `newt --write ~/scratch`.
    #[arg(long = "write", global = true, value_name = "PATH")]
    pub write_paths: Vec<PathBuf>,

    /// Backend override flags (`--backend-*`): pin the model backend from the
    /// command line, bypassing discovery and probe drop-ins.
    #[command(flatten)]
    pub backend: BackendArgs,

    /// Subcommand to run. Defaults to `code` (TUI coder) when omitted.
    #[command(subcommand)]
    pub command: Option<Command>,
}

/// `--backend-*` flags — set any backend field from the command line. Each
/// mirrors an operator-settable [`newt_core::config::BackendConfig`] field. When
/// an endpoint (or `--backend-model-path`) is given the flags define the sole,
/// exclusive backend for the invocation, so no discovery or probe drop-in can
/// reroute the session; otherwise the set fields override the selected backend
/// in place (e.g. just `--backend-model`). Built into a
/// [`newt_core::config::BackendOverride`] by [`Cli::backend_override`].
#[derive(clap::Args, Debug, Default, Clone)]
// Every arg carries an EXPLICIT namespaced clap id (`backend_*`): clap
// identifies args by id, not by long flag, and these are `global = true`,
// so a bare derive id like `name` collides with any subcommand's own
// `--name` — global-value propagation then silently hands the
// subcommand's value to the backend override (`mcp probe --name X`
// became `--backend-name X`, latent until the named-miss hard error).
pub struct BackendArgs {
    /// Backend endpoint URL. Setting this makes the CLI backend EXCLUSIVE:
    /// discovery and probe drop-ins are bypassed for the session.
    #[arg(
        id = "backend_endpoint",
        long = "backend-endpoint",
        global = true,
        value_name = "URL"
    )]
    pub endpoint: Option<String>,

    /// Model this backend serves (e.g. `qwen3-coder_30b`).
    #[arg(
        id = "backend_model",
        long = "backend-model",
        global = true,
        value_name = "MODEL"
    )]
    pub model: Option<String>,

    /// For `--backend-kind embedded`: local GGUF model file path.
    #[arg(
        id = "backend_model_path",
        long = "backend-model-path",
        global = true,
        value_name = "PATH"
    )]
    pub model_path: Option<String>,

    /// Tiers this backend serves, comma-separated: FAST,STANDARD,COMPLEX,REVIEW
    /// (case-insensitive). Default when creating an exclusive backend: all four.
    #[arg(
        id = "backend_tiers",
        long = "backend-tiers",
        global = true,
        value_name = "TIERS",
        value_delimiter = ',',
        value_parser = parse_tier
    )]
    pub tiers: Vec<newt_core::Tier>,

    /// Wire protocol: `ollama`, `openai` (alias `vllm`), `anthropic` (alias
    /// `claude`), or `embedded`.
    #[arg(id = "backend_kind", long = "backend-kind", global = true, value_name = "KIND", value_parser = parse_backend_kind)]
    pub kind: Option<newt_core::config::BackendKind>,

    /// Detected inference engine metadata: `ollama`, `llama.cpp`, or `vllm`.
    #[arg(id = "backend_engine", long = "backend-engine", global = true, value_name = "ENGINE", value_parser = parse_engine)]
    pub engine: Option<newt_core::config::Engine>,

    /// OpenAI HTTP surface: `chat_completions` or `responses`.
    #[arg(id = "backend_api", long = "backend-api", global = true, value_name = "API", value_parser = parse_openai_api)]
    pub api: Option<newt_core::config::OpenAiApi>,

    /// Env var holding the bearer token (takes precedence over the file).
    #[arg(
        id = "backend_api_key_env",
        long = "backend-api-key-env",
        global = true,
        value_name = "VAR"
    )]
    pub api_key_env: Option<String>,

    /// File whose first non-empty line is the bearer token.
    #[arg(
        id = "backend_api_key_file",
        long = "backend-api-key-file",
        global = true,
        value_name = "PATH"
    )]
    pub api_key_file: Option<String>,

    /// Serving axis: `multiplexer` or `instance`.
    #[arg(id = "backend_serving", long = "backend-serving", global = true, value_name = "AXIS", value_parser = parse_serving)]
    pub serving: Option<newt_core::config::Serving>,

    /// Physical host of the endpoint, for same-host reasoning.
    #[arg(
        id = "backend_host",
        long = "backend-host",
        global = true,
        value_name = "HOST"
    )]
    pub host: Option<String>,

    /// Assert this host can run this backend alongside others (suppress the
    /// same-host starvation rule).
    #[arg(
        id = "backend_coexist",
        long = "backend-coexist",
        global = true,
        value_name = "BOOL"
    )]
    pub coexist: Option<bool>,

    /// Host memory available for serving (GiB), for the crew fit-gate.
    #[arg(
        id = "backend_ram_gib",
        long = "backend-ram-gib",
        global = true,
        value_name = "GIB"
    )]
    pub ram_gib: Option<f64>,

    /// Model-card pointer for this backend.
    #[arg(
        id = "backend_card",
        long = "backend-card",
        global = true,
        value_name = "CARD"
    )]
    pub card: Option<String>,

    /// Backend name (default `cli`). Names the exclusive backend, or selects
    /// which existing backend a field-only override targets.
    #[arg(
        id = "backend_name",
        long = "backend-name",
        global = true,
        value_name = "NAME"
    )]
    pub name: Option<String>,
}

impl BackendArgs {
    /// Build the [`newt_core::config::BackendOverride`] these flags describe.
    /// Unset flags stay `None`; an empty `--backend-tiers` stays `None` (not an
    /// empty tier list), so a field-only override never accidentally clears
    /// tiers.
    pub fn to_override(&self) -> newt_core::config::BackendOverride {
        newt_core::config::BackendOverride {
            name: self.name.clone(),
            endpoint: self.endpoint.clone(),
            model: self.model.clone(),
            model_path: self.model_path.clone(),
            tiers: (!self.tiers.is_empty()).then(|| self.tiers.clone()),
            kind: self.kind,
            api: self.api,
            api_key_env: self.api_key_env.clone(),
            api_key_file: self.api_key_file.clone(),
            serving: self.serving,
            engine: self.engine,
            host: self.host.clone(),
            coexist: self.coexist,
            ram_gib: self.ram_gib,
            card: self.card.clone(),
        }
    }
}

/// Which posture axes the `--backend-*` flag group owns for THIS invocation.
///
/// #1668 review-2 finding 4. Axis ownership asks what the operator NAMED on
/// this command line — not whether they also supplied a destination. Recording
/// used to live inside the "has a destination" arm, with two consequences:
/// `--backend-name X --resume A` let A's stored pin reroute the session away
/// from X, and `--backend-model M` was never recorded on ANY path, so a pin
/// naming a model beat the flag the operator had just typed. Both are the
/// precedence inversion #1668 exists to prevent, and neither could even be
/// REPORTED by the "your flag beats the pin" notice, because that notice is
/// driven by the same axes.
///
/// A bare destination (`--backend-endpoint`, `--backend-model-path`) with no
/// `--backend-name` still owns the backend axis: it pins where this run talks
/// to just as firmly as a name does.
fn backend_flag_axes(over: &newt_core::config::BackendOverride) -> newt_core::PreferenceAxes {
    newt_core::PreferenceAxes {
        backend: over.name.is_some() || over.endpoint.is_some() || over.model_path.is_some(),
        model: over.model.is_some(),
        ..Default::default()
    }
}

fn parse_tier(s: &str) -> Result<newt_core::Tier, String> {
    use newt_core::Tier;
    match s.trim().to_ascii_uppercase().as_str() {
        "FAST" => Ok(Tier::Fast),
        "STANDARD" => Ok(Tier::Standard),
        "COMPLEX" => Ok(Tier::Complex),
        "REVIEW" => Ok(Tier::Review),
        _ => Err(format!("unknown tier '{s}' (FAST|STANDARD|COMPLEX|REVIEW)")),
    }
}

fn parse_tenacity(s: &str) -> Result<newt_core::Tenacity, String> {
    s.parse()
}

fn parse_initiative(s: &str) -> Result<newt_core::Initiative, String> {
    s.parse()
}

fn parse_cognition(s: &str) -> Result<newt_core::role_profile::Cognition, String> {
    s.parse()
}

fn parse_backend_kind(s: &str) -> Result<newt_core::config::BackendKind, String> {
    use newt_core::config::BackendKind;
    match s.trim().to_ascii_lowercase().as_str() {
        "ollama" => Ok(BackendKind::Ollama),
        "openai" | "vllm" | "openai-compatible" => Ok(BackendKind::Openai),
        "embedded" => Ok(BackendKind::Embedded),
        "anthropic" | "claude" => Ok(BackendKind::Anthropic),
        _ => Err(format!(
            "unknown backend kind '{s}' (ollama|openai|anthropic|embedded)"
        )),
    }
}

fn parse_engine(s: &str) -> Result<newt_core::config::Engine, String> {
    use newt_core::config::Engine;
    match s.trim().to_ascii_lowercase().as_str() {
        "ollama" => Ok(Engine::Ollama),
        "llamacpp" | "llama.cpp" | "llama-cpp" => Ok(Engine::LlamaCpp),
        "vllm" => Ok(Engine::Vllm),
        _ => Err(format!("unknown engine '{s}' (ollama|llama.cpp|vllm)")),
    }
}

fn parse_openai_api(s: &str) -> Result<newt_core::config::OpenAiApi, String> {
    use newt_core::config::OpenAiApi;
    match s.trim().to_ascii_lowercase().as_str() {
        "chat_completions" | "chat-completions" | "chat" => Ok(OpenAiApi::ChatCompletions),
        "responses" => Ok(OpenAiApi::Responses),
        _ => Err(format!("unknown api '{s}' (chat_completions|responses)")),
    }
}

fn parse_serving(s: &str) -> Result<newt_core::config::Serving, String> {
    use newt_core::config::Serving;
    match s.trim().to_ascii_lowercase().as_str() {
        "multiplexer" | "mux" => Ok(Serving::Multiplexer),
        "instance" => Ok(Serving::Instance),
        _ => Err(format!("unknown serving '{s}' (multiplexer|instance)")),
    }
}

#[derive(Subcommand, Debug)]
pub enum Command {
    /// Standalone TUI coder.
    Code {
        /// Optional working path.
        path: Option<PathBuf>,
    },
    /// Print newt's interactive command catalog without starting a session.
    ///
    /// `newt help` lists every `/command`; `newt help <command>` shows one
    /// command's detail page (the same text as the in-session `/help` and
    /// `/<command> --help`). Renders with no backend connect, so it works
    /// offline and in CI. For the CLI subcommand tree instead, use `newt
    /// --help`.
    Help {
        /// Optional `/command` name to show the detail page for (omit for the
        /// full list). A leading slash is accepted and ignored.
        command: Option<String>,
    },
    /// Self-scheduled wake-up timers. `schedule` records a deferred prompt the
    /// agent re-enters with later; `fire --run` (from a cron/launchd job) drains
    /// due timers and drives each prompt through the `newt headless` entry point;
    /// bare `fire` prints `PROM\t…` lines for a host that pipes them onward;
    /// `list` / `dismiss` manage the queue. The host owns the clock.
    Timer {
        #[command(subcommand)]
        cmd: timer_cmd::TimerCmd,
    },
    /// Drake-swarm pilot dashboard.
    Pilot {
        /// Flight id to attach to.
        flight_id: String,
    },
    /// ACP worker (stdio JSON-RPC, no TUI).
    Worker {
        /// Activate the newt-coder plugin (whole-file emit +
        /// server-side diff normalization). Equivalent to setting
        /// `NEWT_CODER=1` in the environment. Closes failure mode
        /// T0b — see the knowledge card
        /// `~/workspaces/knowledge/board/drake/2026-05-29_newt-coder-failure-mode-taxonomy.md`.
        #[arg(long, env = "NEWT_CODER", default_value_t = false)]
        coder: bool,

        /// Per-user operator key path the headless worker derives its
        /// signed, attenuated dispatch [`newt_core::Caveats`] from.
        /// Default: `~/.newt/identity.pem` (resolved via
        /// `newt_identity::default_key_path`). Generated on first run
        /// with mode `0600` if the file doesn't yet exist.
        ///
        /// CLI > env > default file resolution. The env override is
        /// `NEWT_OPERATOR_KEY`. Issue #94.
        #[arg(long, env = "NEWT_OPERATOR_KEY")]
        operator_key_path: Option<PathBuf>,

        /// Debug-only escape hatch: skip the operator-key load and
        /// dispatch under `Caveats::top()` (pre-#94 behavior). Never
        /// the default. Use this when iterating locally without
        /// provisioning a key — never in production.
        #[arg(long, default_value_t = false)]
        allow_no_key: bool,
    },
    /// Manage MCP servers, or run newt as one. Subcommands manage the
    /// `[[mcp_servers]]` registrations (`add` / `remove` / `list` /
    /// `install` / `probe`); `serve` runs newt as an MCP server over stdio.
    ///
    /// Bare `newt mcp` is TTY-aware: with piped stdin (an MCP client) it
    /// serves over stdio as before; at an interactive terminal it prints
    /// this subcommand menu instead of blocking as a server. Use `newt mcp
    /// serve` to serve unconditionally.
    Mcp {
        #[command(subcommand)]
        cmd: Option<mcp_cmd::McpCmd>,
    },
    /// Run a multi-LLM crew on a task (navigate → plan → verify → triage), in an
    /// isolated git worktree. Exit 0 = passed, 2 = needs human review, 1 = error.
    Crew {
        /// The task for the crew (a coding-task description). In `--edit` mode
        /// this slot is instead the crew NAME to edit (or use `--crew`).
        task: Option<String>,
        /// Edit a crew's settings interactively (planner/navigator/triage
        /// loadouts, control loop, test command, budgets) and write
        /// `~/.newt/crews/<name>.toml`. No task is run.
        #[arg(long, default_value_t = false)]
        edit: bool,
        /// Crew name from `[crews.<name>]`. Omit when exactly one crew is defined.
        #[arg(long)]
        crew: Option<String>,
        /// Target repo dir (default: current dir). Must be a git repo.
        #[arg(long)]
        dir: Option<PathBuf>,
        /// Verification command override (default: the crew's `test`, else inferred).
        #[arg(long)]
        test: Option<String>,
        /// Cap on planning rounds (default: the crew's budget, else 3).
        #[arg(long)]
        max_attempts: Option<u32>,
        /// Resolve + show placements and exit, without editing or testing.
        #[arg(long, default_value_t = false)]
        dry_run: bool,
    },
    /// AUTHOR a plan from a goal (`--goal`), or PREVIEW / `--execute` an existing
    /// plan TOML file leaf-by-leaf via a crew. Authoring asks a strong model to
    /// decompose the goal into a `plan::Plan` (default-deny caveats) for you to
    /// review/edit — it never executes. Execution is preview-by-default; `--execute`
    /// runs an autonomous DAG of crews with no per-leaf review (bounded by
    /// `--max-leaves`), writing a sibling `<file>.run.toml` (source untouched).
    Plan {
        /// The plan TOML file to preview/execute: a `[[subtask]]` list, optionally
        /// a tree (`parent`) + a DAG (`deps`). Omit when authoring with `--goal`.
        file: Option<PathBuf>,
        /// Author a plan FROM this goal (a strong model decomposes it) instead of
        /// reading a file; writes to `--output` (or stdout). Never executes.
        #[arg(long, conflicts_with = "file")]
        goal: Option<String>,
        /// Where to write the authored plan (with `--goal`). Default: stdout.
        #[arg(long, short = 'o', value_name = "FILE")]
        output: Option<PathBuf>,
        /// Target repo dir (default: current dir). Must be a git repo.
        #[arg(long)]
        dir: Option<PathBuf>,
        /// Actually dispatch the crews. Without this, `newt plan` only PREVIEWS —
        /// autonomous multi-crew execution needs this explicit second affirmation.
        #[arg(long, default_value_t = false)]
        execute: bool,
        /// One-shot: AUTHOR (with `--goal`) **and** execute the plan autonomously
        /// in a single gesture, or one-shot an existing plan FILE end-to-end. Like
        /// `--execute`, the flag IS the approval — the plan runs with no per-leaf
        /// review (bounded by `--max-leaves`). The headless autonomous drive (e.g.
        /// the #548 evaluator): `newt plan --goal "…" --one-shot`.
        #[arg(long = "one-shot", default_value_t = false)]
        one_shot: bool,
        /// Cap on leaves to execute (and subtasks to author) without an explicit
        /// raise — each leaf is an autonomous crew with no per-leaf review.
        #[arg(long, default_value_t = 8)]
        max_leaves: usize,
        /// LOCKED behavioral gate (structurally-enforced TDD): an
        /// operator-supplied verify command that OVERRIDES every leaf's gate.
        /// Unlike a model-authored `verify`, it is trusted like the repo-inferred
        /// command (it comes from this human flag, not the model), so a crew
        /// cannot pass by deleting or weakening its own test. Typically a
        /// "restore the immutable spec, then run it" command. Only meaningful
        /// with `--one-shot`.
        #[arg(long = "locked-verify")]
        locked_verify: Option<String>,
    },
    /// Health-check local backends + provider plugins.
    Doctor {
        /// #1207: bless ~/.newt/ocap/approve.toml — sign every entry with your
        /// root key so it loads as a valid durable grant (unsigned entries drop
        /// fail-closed at session start). Running this IS the authorization:
        /// you are vouching for the file as it stands. High-danger targets are
        /// refused and reported (exit 2).
        #[arg(long = "sign-ocap")]
        sign_ocap: bool,
        /// Offer per-entry repair for stale durable grants and ambiguous backend
        /// drop-ins. Requires a terminal and explicit confirmation; piped runs
        /// report only. Grant pruning saves a dated backup and keeps signatures.
        /// Durable-grant repair is report-only on Windows until private backups
        /// are supported.
        #[arg(long)]
        fix: bool,
    },
    /// Manage the `~/.newt/ocap/` durable-policy store. `propose` folds the
    /// flight-recorder capture of a `--full-access` session into reviewable,
    /// unsigned `approve.toml` candidates (bless them with
    /// `newt doctor --sign-ocap`).
    Ocap {
        #[command(subcommand)]
        cmd: ocap_cmd::OcapCmd,
    },
    /// Manage approved docks for newt-web mesh docking (requirement 5). Approve
    /// a peer agent (SAS-confirmed, root-key-signed) so a hub cockpit will
    /// surface its sessions, list them, or revoke — the operator's standing,
    /// revocable intent behind every remote dock.
    Dock {
        #[command(subcommand)]
        cmd: dock_cmd::DockCmd,
    },
    /// Drive one task through the agentic loop with no interactive prompts,
    /// and exit. The same non-interactive entry Terminal-Bench uses (#1419),
    /// but not specific to it — any caller wanting a single headless turn
    /// (a cron-fired timer, a script, a bench harness) uses this. Drives the
    /// same agentic loop the TUI runs — no second loop. Reads the task from
    /// `--instruction-file`, runs in `--cwd`, and appends a JSONL trace to
    /// `--events`. Execution is confined by default; non-interactive
    /// operation does not grant host access.
    Headless {
        /// Workspace directory the agent runs against (default: current dir).
        #[arg(long, value_name = "DIR")]
        cwd: Option<PathBuf>,
        /// File whose contents are the task instruction.
        #[arg(long, value_name = "FILE")]
        instruction_file: PathBuf,
        /// Run headless with no interactive prompts (default true). P3: this
        /// controls INTERACTION only — it does NOT disable OCAP or grant host
        /// access. A plain `newt headless` is confined; unconfined execution needs
        /// the explicit `--unsafe-host-exec` below.
        #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
        non_interactive: bool,
        /// EXPLICIT opt-in to OCAP-off ambient host execution (full access, no
        /// prompt gate). The ONLY route to the unconfined lane — never a side
        /// effect of `--non-interactive`. Env twin: `NEWT_UNSAFE_HOST_EXEC`.
        /// `--confined` wins (confinement is never silently dropped).
        #[arg(long, default_value_t = false)]
        unsafe_host_exec: bool,
        /// OCAP-ON confined lane: keep OCAP enabled and fence writes to the
        /// workspace + the container's mutable roots (reads/exec/net stay open).
        /// Also enabled by `NEWT_BENCH_OCAP=on`. This is the lane the OCAP-parity
        /// gate measures, and (as of P3) the safe default when no lane flag is set.
        #[arg(long, default_value_t = false)]
        confined: bool,
        /// Append a JSONL trace record here.
        #[arg(long, value_name = "FILE")]
        events: Option<PathBuf>,
        /// Enable accounted context navigation and an independent CPU adjudicator.
        #[arg(long)]
        smart_harness: bool,
        /// Private frame directory (default: user config/frame/<workspace CID>).
        #[arg(long, value_name = "DIR")]
        frame_dir: Option<PathBuf>,
        /// Initial tool-call round allowance for this headless run. Concrete
        /// progress may renew it; `[tui] workflow_grace_rounds = 0` makes it a
        /// hard cap. Inference budgets and cancellation remain binding.
        #[arg(long, value_name = "N")]
        max_rounds: Option<usize>,
        /// The served model's FULL context window (e.g. llama.cpp `--ctx-size`,
        /// 32768). Newt gates input at the tighter of the configured percentage
        /// ceiling and the room left by the request's maximum output, so a long
        /// turn compacts instead of overrunning the shared window.
        #[arg(long, value_name = "N")]
        context_window: Option<u32>,
        /// Operator-supplied sha256 of the weights actually served (GGUF file
        /// hash / HF revision SHA) for the contract record's `model_digest`
        /// (W0 #1511). Env twin: `NEWT_MODEL_DIGEST`. Omitted from the record
        /// when absent — never fabricated.
        #[arg(long, value_name = "SHA256")]
        model_digest: Option<String>,
        /// Opt into the scratchpad with this explicit starting state: a JSON
        /// object of string values (`{}` starts it empty). The file is the only
        /// state source; nothing is inherited from earlier runs (#2314).
        #[arg(long, value_name = "FILE")]
        scratchpad_state: Option<PathBuf>,
        /// Refuse to start unless this feature can be supplied for the run
        /// (repeatable). Checked before any model request (#2314).
        #[arg(long, value_name = "FEATURE")]
        require_feature: Vec<headless_contract::Feature>,
        /// Output-token allowance for this headless; overrides
        /// `[[model_tuning]] output_allowance` for the model (#2312).
        #[arg(long, value_name = "TOKENS")]
        output_allowance: Option<u32>,
        /// Run-level call-count allowance for this headless; overrides
        /// `[[model_tuning]] run_allowance` for the model (#2313). Further
        /// primary inference dispatch is refused once this many calls have
        /// been made.
        #[arg(long, value_name = "CALLS")]
        run_allowance: Option<u32>,
        /// Start without inherited frame or ambient memory inputs. Smart mode
        /// otherwise starts a resumable frame; legacy headless keeps its default.
        /// This bounds admitted inputs, not model nondeterminism or provider-side
        /// transformations, and does not claim bit-for-bit inference replay.
        ///
        /// Mutually exclusive with `--resume` / `--resume-from`. Unlike the
        /// `--confined` / `--unsafe-host-exec` pair — where confinement wins
        /// because one side is safe and the other is not — neither of these is
        /// safer than the other. They are incompatible, so supplying both is
        /// refused rather than resolved by precedence.
        #[arg(long, conflicts_with_all = ["resume", "resume_from"])]
        hermetic: bool,
        /// Continue from a prior frame, named by its content id. Starts a
        /// resumable chain, at the cost of the reproducibility `--hermetic`
        /// gives. The bare "resumable, but no named parent" case is the
        /// EXISTING global `--resume <NAME>` (#1671): there is one `--resume`
        /// in this binary and it means non-hermetic continuity, whether the
        /// thing continued is a named conversation or a named frame.
        #[arg(long, value_name = "CID", conflicts_with = "hermetic")]
        resume_from: Option<String>,
    },
    /// Print resolved config.
    Config,
    /// Diagnose + tune mid-loop context compaction (the summarizer): the
    /// effective trim trigger, count-vs-token firing, the summarizer backend,
    /// and warnings for over-aggressive firing / the no-abort hang (#979).
    Compaction,
    /// Show or set the agent commit identity (`.newt/agent-identity.toml`).
    ///
    /// Bare `newt identity` prints name, email, source layer, trailer,
    /// signing-key path + fingerprint, GitHub App coordinates, and token
    /// NAMES (never secret values). `newt identity set --name … --email …`
    /// writes an override file — the same path a future setup dialog will use.
    /// Default (no file): GitHub User https://github.com/newt-agent.
    Identity {
        #[command(subcommand)]
        cmd: Option<identity_cmd::IdentityCmd>,
    },
    /// Run (or re-run) the setup wizard: probe Ollama + write ~/.newt/config.toml.
    /// Edit that file directly for everything else — newt has no settings UI.
    Init,
    /// Configure an inference backend from a target, or run the interactive
    /// first-run wizard when no target is supplied.
    Setup {
        /// Backend hostname or URL to probe. Bare hosts expand through the
        /// configured discovery ports; URLs and host:port targets are singular.
        target: Option<String>,

        /// Environment variable containing the backend bearer token. Requires
        /// an explicit HTTPS URL (HTTP is allowed only for loopback).
        #[arg(
            long,
            visible_alias = "api-key-env",
            conflicts_with = "token_file",
            requires = "target"
        )]
        token_env: Option<String>,

        /// File containing the backend bearer token. Requires an explicit HTTPS
        /// URL (HTTP only for loopback); relative paths become absolute.
        #[arg(
            long,
            visible_alias = "api-key-file",
            conflicts_with = "token_env",
            requires = "target"
        )]
        token_file: Option<PathBuf>,

        /// Model to verify and configure for the target endpoint. Required for
        /// deterministic non-interactive selection from large public catalogs.
        #[arg(long, requires = "target")]
        model: Option<String>,

        /// Write the detected backend configuration without confirmation.
        #[arg(long, short = 'y', requires = "target")]
        yes: bool,
    },
    /// Launch the newt-web HTMX cockpit (a SEPARATELY built binary — decision
    /// D1 keeps its web dependency tree out of the agent workspace). Looks for
    /// `$NEWT_WEB_BIN`, then `newt-web` beside this binary (`just install-web`
    /// puts it there), then `PATH`. Extra args pass through to newt-web.
    Web {
        /// Arguments passed through to the newt-web binary.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Provider presets (the wizard's hosted-provider roster) — DISTINCT from
    /// `[[providers]]` subprocess plugins. Includes a Hermes Agent importer.
    Providers {
        #[command(subcommand)]
        cmd: providers_cmd::ProvidersCmd,
    },
    /// Scaffold a NEW project for an ecosystem, already wired for its lifecycle
    /// phases. `newt new pyo3 mypkg` lays down a minimal, buildable Rust+PyO3
    /// (maturin) project; `python` and `rust` too. Templates are DATA (built-in
    /// or `~/.newt/templates/<name>.toml` drop-ins). With no ecosystem, lists the
    /// available templates.
    New {
        /// Ecosystem template: `pyo3` | `python` | `rust` (or a drop-in name).
        /// Omit to list available templates.
        ecosystem: Option<String>,
        /// Project name (default: the target directory's final component).
        name: Option<String>,
        /// Target directory (default: `./<name>`).
        #[arg(long)]
        dir: Option<PathBuf>,
        /// Write into a non-empty target directory (overwriting colliding files).
        #[arg(long, default_value_t = false)]
        force: bool,
    },
    /// Manage skills across a configurable search path (newt + Claude Code +
    /// Codex + …). `list` / `install <path>` / `share`.
    Skills {
        #[command(subcommand)]
        cmd: skills::SkillsCmd,
    },
    /// NVIDIA DGX endpoint management (route a task to a formation; more
    /// subcommands land in later Phase 14 steps).
    Dgx {
        #[command(subcommand)]
        cmd: dgx::DgxCmd,
    },
    /// Authenticate an HTTP MCP server via the OAuth 2.1 PKCE browser flow.
    ///
    /// Without arguments: lists all discovered HTTP MCP servers and their token
    /// status (valid / expired / needs-login / unregistered).
    ///
    /// With a server name: opens the browser for the OAuth login flow, waits
    /// for the redirect, exchanges the code for tokens, and saves a Newt-owned
    /// private credential generation. Newt may adopt a complete, strictly
    /// resource/issuer-bound legacy Hermes credential as read-only input; Newt
    /// auth and refresh never overwrite Hermes' flat token files.
    Auth {
        /// Name of the MCP server to authenticate (e.g. `newt auth my-server`).
        /// Omit to list all servers and their current auth status.
        server: Option<String>,
    },
    /// Inspect, export, import, and reset per-model context-window tuning data.
    ///
    /// Tuning data is maintained automatically by the harness in
    /// `~/.newt/model-capabilities.json`. Human-readable overrides live in
    /// `~/.newt/config.toml` under `[[model_tuning]]`. Community profiles can be
    /// shared as plain TOML files and merged with `newt tunings import`.
    Tunings {
        #[command(subcommand)]
        cmd: tuning_cmd::TuningsCmd,
    },
    /// Manage the on-host mini-model palette for the embedded CPU summarizer
    /// (#661): `pull` a GGUF to ~/.newt/models, `list` the palette, `path`.
    Models {
        #[command(subcommand)]
        cmd: models_cmd::ModelsCmd,
    },
    /// Inspect and configure the mid-loop summarizer backend.
    Summarizer {
        #[command(subcommand)]
        cmd: Option<summarizer_cmd::SummarizerCmd>,
    },
    /// Forensics over the derivation frame: establish which source material a
    /// unit represents and how it was derived.
    ///
    /// `verify` recomputes a unit's claims from the source bytes and compares,
    /// exiting non-zero on mismatch. `explain` reports the derivation.
    /// `trace` walks a packet's parents to genesis.
    ///
    /// Every subcommand takes `--json` and emits a structured report a second
    /// program can consume; the human rendering is a projection of that same
    /// report, never a separate set of facts.
    Frame {
        #[command(subcommand)]
        cmd: frame_cmd::FrameCmd,
    },
}

/// clap `value_parser` for `--color`: parse a keyword into a
/// [`newt_core::ColorMode`] (keeps newt-core clap-free — no `ValueEnum` derive).
fn parse_color_mode(s: &str) -> Result<newt_core::ColorMode, String> {
    newt_core::ColorMode::from_keyword(s).ok_or_else(|| {
        format!(
            "invalid color mode '{s}' (expected one of: \
             always, never, auto, minimal, inverted, dark, light, mono)"
        )
    })
}

/// Resolve the user's home directory cross-platform: `$HOME` (set on Unix and
/// many Windows shells) first, then `%USERPROFILE%` (the Windows default). Empty
/// values are treated as unset.
fn home_dir() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .filter(|h| !h.is_empty())
        .or_else(|| std::env::var_os("USERPROFILE").filter(|h| !h.is_empty()))
        .map(PathBuf::from)
}

/// Absolutise a single `--read`/`--write` grant: expand a leading `~` (via
/// [`home_dir`]), then make it absolute relative to the current dir. Does NOT
/// require the path to exist (a `--write` target may be created later) and does
/// not canonicalise (which would resolve symlinks and need existence) — the goal
/// is a stable absolute path the fs tools' `workspace.join(path)` results can be
/// contained under.
fn abs_grant_path(p: &std::path::Path) -> PathBuf {
    let expanded: PathBuf = match p.strip_prefix("~") {
        Ok(rest) => match home_dir() {
            Some(home) => home.join(rest),
            None => p.to_path_buf(),
        },
        Err(_) => p.to_path_buf(),
    };
    if expanded.is_absolute() {
        expanded
    } else {
        std::env::current_dir()
            .map(|d| d.join(&expanded))
            .unwrap_or(expanded)
    }
}

/// Join absolutised grant paths into a single `NEWT_READ_PATHS` /
/// `NEWT_WRITE_PATHS` value using the platform path-list separator (`;` on
/// Windows, `:` elsewhere) via [`std::env::join_paths`], so a Windows
/// drive-letter path (`C:\…`) is not shattered on a literal `:`. Returns `Err`
/// (fail-closed) if a grant path itself contains the separator.
fn abs_grant_paths(paths: &[PathBuf]) -> Result<std::ffi::OsString, std::env::JoinPathsError> {
    std::env::join_paths(paths.iter().map(|p| abs_grant_path(p)))
}

fn validate_launch_options(cli: &Cli) -> anyhow::Result<()> {
    anyhow::ensure!(
        !cli.workspace_access || matches!(cli.command.as_ref(), None | Some(Command::Code { .. })),
        "--workspace-access is available for the interactive TUI: newt --workspace-access code <directory>"
    );
    anyhow::ensure!(
        !cli.adopt_frame || matches!(cli.command.as_ref(), None | Some(Command::Code { .. })),
        "--adopt-frame is available only for the interactive TUI with --resume"
    );
    Ok(())
}

pub async fn dispatch(cli: Cli) -> anyhow::Result<()> {
    validate_launch_options(&cli)?;
    if cli.windows_cmd {
        // Same startup-only publication seam as the other shell switches.
        unsafe { std::env::set_var("NEWT_WINDOWS_CMD", "1") };
    }
    // #1303 clause B: install the one-time mouse-capture panic-release hook at
    // binary entry, before any turn can enable capture. It emits
    // `DisableMouseCapture` ONLY when capture is currently active, so the
    // `worker`/`mcp`/piped paths (which never enable it) stay byte-for-byte
    // clean (clause E). Compiled out of the wyvern/lean build.
    #[cfg(all(unix, any(feature = "rich-tui", feature = "live-spill")))]
    newt_tui::install_panic_release_hook();

    if let Some(dir) = cli.config_dir.as_deref() {
        let dir = abs_grant_path(dir);
        // SAFETY: single-threaded before any async work or config resolution.
        unsafe { std::env::set_var(newt_core::config::NEWT_CONFIG_DIR_ENV, dir) };
    }
    // #1320: `--config <file>` is otherwise only forwarded to the path-taking
    // subcommands (headless/config/mcp/doctor/…) via `Config::load`; it never reaches
    // the arg-free `Config::resolve()` that chat/plan/worker use, so `newt --config
    // X` silently kept resolving `~/.newt` for the interactive session. Promote it
    // to the process-global `$NEWT_CONFIG` pin (`candidate_paths[0]`) — the same
    // normalization `--config-dir` gets above — so every entry point resolves the
    // operator's file identically. `$NEWT_CONFIG` is already the operator-explicit
    // "Trusted" base in `resolve()`.
    if let Some(file) = cli.config.as_deref() {
        let file = abs_grant_path(file);
        // SAFETY: single-threaded before any async work or config resolution.
        unsafe { std::env::set_var("NEWT_CONFIG", file) };
    }

    // Resolve the venv: --venv flag wins, then fall back to an already-activated $VIRTUAL_ENV.
    // Set NEWT_VENV so the TUI can inject it into the agent-bridle confined shell (which does
    // not inherit the host environment, so a process-level PATH change has no effect there).
    let venv_path = cli
        .venv
        .as_ref()
        .map(|p| p.display().to_string())
        .or_else(|| std::env::var("VIRTUAL_ENV").ok());
    // SAFETY: all set_var calls below are single-threaded before the TUI starts any async work.
    if let Some(ref venv) = venv_path {
        unsafe { std::env::set_var("NEWT_VENV", venv) };
        // Also prepend to the process PATH for non-bridle code paths.
        let venv_bin =
            std::path::Path::new(venv).join(if cfg!(windows) { "Scripts" } else { "bin" });
        let mut paths = std::env::var_os("PATH")
            .map(|path| std::env::split_paths(&path).collect::<Vec<_>>())
            .unwrap_or_default();
        if !paths.contains(&venv_bin) {
            paths.insert(0, venv_bin);
        }
        unsafe { std::env::set_var("PATH", std::env::join_paths(paths)?) };
    }

    // --exec-path: store as colon-separated NEWT_EXEC_PATHS so the TUI can
    // scan those directories and grant exec permission for their binaries.
    if !cli.exec_paths.is_empty() {
        let joined = cli
            .exec_paths
            .iter()
            .map(|p| p.display().to_string())
            .collect::<Vec<_>>()
            .join(":");
        unsafe { std::env::set_var("NEWT_EXEC_PATHS", &joined) };
    }

    // --read / --write: store absolutised paths (joined with the platform
    // path-list separator) so the TUI can widen the agent's fs_read / fs_write
    // scope to these out-of-workspace locations (a dir grants everything under
    // it; a file grants just itself). --write implies --read for the same path.
    if !cli.read_paths.is_empty() {
        match abs_grant_paths(&cli.read_paths) {
            Ok(joined) => unsafe { std::env::set_var("NEWT_READ_PATHS", &joined) },
            Err(e) => {
                eprintln!(
                    "warning: ignoring --read grants (path contains the path separator): {e}"
                );
            }
        }
    }
    if !cli.write_paths.is_empty() {
        match abs_grant_paths(&cli.write_paths) {
            Ok(joined) => unsafe { std::env::set_var("NEWT_WRITE_PATHS", &joined) },
            Err(e) => eprintln!(
                "warning: ignoring --write grants (path contains the path separator): {e}"
            ),
        }
    }

    // --color / --mono (issue #527): thread the color mode to every surface via
    // NEWT_COLOR (global flags, so set before the command match). --mono wins
    // over --color. Resolution (flag > NO_COLOR/TERM=dumb > [tui] color > auto)
    // happens in the TUI color layer.
    let color_kw = if cli.mono {
        Some("mono")
    } else {
        cli.color.map(|c| c.keyword())
    };
    if let Some(kw) = color_kw {
        // SAFETY: single-threaded before the TUI starts any async work.
        unsafe { std::env::set_var("NEWT_COLOR", kw) };
    }

    // Denial repair journal: arm every agent surface, including headless
    // workers/crews, before command dispatch. The journal is evidence only and
    // is never read back into authority. An explicit `off`/`0` opts out.
    if std::env::var_os(newt_core::denial_journal::DENIAL_JOURNAL_PATH_ENV).is_none() {
        if let Some(cfg_path) = newt_core::Config::user_config_path() {
            let journal = cfg_path.with_file_name("denial-journal.jsonl");
            unsafe {
                std::env::set_var(newt_core::denial_journal::DENIAL_JOURNAL_PATH_ENV, journal);
            }
        }
    }
    if let Ok(v) = std::env::var(newt_core::denial_journal::DENIAL_JOURNAL_PATH_ENV) {
        if v.eq_ignore_ascii_case("off") || v == "0" {
            unsafe {
                std::env::remove_var(newt_core::denial_journal::DENIAL_JOURNAL_PATH_ENV);
            }
        }
    }

    // CLI `--backend-*` flags: install the process-global override so every
    // Config::resolve honors it, and set NEWT_PROVIDER to the backend the
    // flags name so the tier→backend selector picks exactly it —
    // `--backend-name` is BOTH the edit target and this invocation's
    // selection, and a pinned destination selects its (possibly synthetic
    // `cli`) backend. This is the explicit escape hatch against
    // discovery/probe drop-ins silently rerouting the session (the
    // local-ollama-fallback incident).
    //
    // #1668: an axis THIS invocation set explicitly is recorded, so a resumed
    // conversation's stored preference pin never overwrites the flag the
    // operator just typed (the same precedence the `--backend-*` doc above
    // states). An ambient `NEWT_PROVIDER`/`NEWT_DGX_MODEL` exported by the
    // operator counts too — config.rs already documents it as always-wins —
    // but the #545 sticky settings restore below deliberately does NOT: that
    // is last run's choice, and this conversation's pin outranks it.
    newt_core::runtime::record_cli_preference_axes(newt_core::PreferenceAxes {
        backend: std::env::var_os("NEWT_PROVIDER").is_some(),
        model: std::env::var_os("NEWT_DGX_MODEL").is_some(),
        ..Default::default()
    });
    {
        let over = cli.backend.to_override();
        if !over.is_empty() {
            let has_destination = over.endpoint.is_some() || over.model_path.is_some();
            let named = over.name.as_deref().is_some_and(|n| !n.is_empty());
            newt_core::runtime::record_cli_preference_axes(backend_flag_axes(&over));
            let provider = over.name.clone().unwrap_or_else(|| "cli".to_string());
            newt_core::config::set_cli_backend_override(over);
            if named || has_destination {
                // SAFETY: single-threaded before the TUI starts any async work.
                unsafe { std::env::set_var("NEWT_PROVIDER", provider) };
            }
        }
    }

    // #psyche `--obsessive`: the max-everything launch posture (newt's "ultra").
    // Applied BEFORE the explicit `--tenacity` below so a simultaneous
    // `--tenacity <level>` still wins. Engages the two LIVE dials via the single
    // posture owner and leaves initiative alone (`--initiative` is independent);
    // crew is a startup gate, so we also set `NEWT_TEAM` here — the same var the
    // crew-runner build below reads — for full effect.
    if cli.obsessive {
        let (cog, ten) = newt_core::psyche::engage_obsessive_dials();
        // #1668: both dials were set explicitly this run — a stored pin must
        // not quietly undo them.
        newt_core::runtime::record_cli_preference_axes(newt_core::PreferenceAxes {
            cognition: true,
            tenacity: true,
            ..Default::default()
        });
        // SAFETY: single-threaded before the TUI starts any async work.
        unsafe { std::env::set_var("NEWT_TEAM", "1") };
        eprintln!(
            "obsessive engaged — cognition={}, tenacity={}, crew=on",
            cog.label(),
            ten.label()
        );
    }

    // CLI `--tenacity`: the explicit pursuit level (tenacity's only input);
    // explicit `relentless` lifts the default tool-round budget.
    if let Some(level) = cli.tenacity {
        newt_core::tenacity::set_cli_tenacity(level);
        // #1668: explicit this run — beats a resumed conversation's pin.
        newt_core::runtime::record_cli_preference_axes(newt_core::PreferenceAxes {
            tenacity: true,
            ..Default::default()
        });
    }

    // CLI `--initiative`: install the process-global read-before-acting level
    // the agentic loop reads when it builds each turn's WorkflowRuntimeState.
    if let Some(level) = cli.initiative {
        newt_core::initiative::set_cli_initiative(level);
        // #1668: explicit this run — beats a resumed conversation's pin.
        newt_core::runtime::record_cli_preference_axes(newt_core::PreferenceAxes {
            initiative: true,
            ..Default::default()
        });
    }

    // CLI `--cognition`: install the session cognition override (→ the
    // `reasoning.effort` wire field), read by both the TUI's `resolve_cognition`
    // and the headless driver. Applied AFTER `--obsessive` so an explicit
    // `--cognition` supersedes the macro's meticulous.
    if let Some(level) = cli.cognition {
        newt_core::cognition::set_cli_cognition(newt_core::cognition::CognitionOverride::Set(
            level,
        ));
        // #1668: explicit this run — beats a resumed conversation's pin.
        newt_core::runtime::record_cli_preference_axes(newt_core::PreferenceAxes {
            cognition: true,
            ..Default::default()
        });
    }

    match cli.command.unwrap_or(Command::Code { path: None }) {
        Command::Code { path } => {
            let selected_workspace = newt_tui::resolve_code_workspace(path.as_deref())?;
            anyhow::ensure!(
                !selected_workspace.has_profile || (!cli.full_access && !cli.disable_ocap),
                "saved workspace settings require a confined launch; remove --full-access/--yolo or use another workspace"
            );
            let path = selected_workspace.path;
            // --debug / --trace / --num-ctx set env vars so the TUI picks them up
            // without requiring a run_code signature change.
            if cli.debug || cli.trace {
                // SAFETY: single-threaded before the TUI starts any async work.
                unsafe { std::env::set_var("NEWT_DEBUG", "1") };
            }
            if cli.trace {
                unsafe { std::env::set_var("NEWT_TRACE", "1") };
            }
            if let Some(n) = cli.num_ctx {
                unsafe { std::env::set_var("NEWT_NUM_CTX", n.to_string()) };
            }
            if let Some(p) = cli.profile.as_deref().filter(|p| !p.is_empty()) {
                // --profile threads to the TUI the same way; run_chat resolves +
                // validates it against [profiles.<name>] once per session.
                unsafe { std::env::set_var("NEWT_PROFILE", p) };
            }
            if let Some(b) = cli.bundle.as_deref().filter(|b| !b.is_empty()) {
                // --bundle threads the same way; run_chat resolves it → a profile
                // for the active model, with --profile taking precedence.
                unsafe { std::env::set_var("NEWT_BUNDLE", b) };
            }
            // --loadout (NEWT_LOADOUT): resolve the named composition and feed each
            // axis's EXISTING selector — explicit --profile/--bundle/--num-ctx/
            // --persona override it (a loadout is a default you can poke). This is
            // the dispatcher-not-merger design: run_chat resolves each axis as usual.
            let loadout_role: Option<String> = {
                let name = cli
                    .loadout
                    .clone()
                    .or_else(|| std::env::var("NEWT_LOADOUT").ok())
                    .filter(|s| !s.is_empty());
                if let Some(name) = name {
                    let cfg = crate::migration_notices::read(|report| {
                        newt_core::Config::resolve(report)
                    })?;
                    let loadout = cfg.loadouts.get(&name).ok_or_else(|| {
                        let known = if cfg.loadouts.is_empty() {
                            "none defined".to_string()
                        } else {
                            cfg.loadouts.keys().cloned().collect::<Vec<_>>().join(", ")
                        };
                        anyhow::anyhow!("no such loadout '{name}' (known: {known})")
                    })?;
                    loadout
                        .validate(&cfg)
                        .map_err(|e| anyhow::anyhow!("loadout '{name}': {e}"))?;
                    // SAFETY: single-threaded before the TUI starts async work.
                    unsafe {
                        if cli.profile.is_none() {
                            if let Some(p) = &loadout.profile {
                                std::env::set_var("NEWT_PROFILE", p);
                            }
                        }
                        if cli.bundle.is_none() {
                            if let Some(k) = &loadout.kit {
                                std::env::set_var("NEWT_BUNDLE", k);
                            }
                        }
                        if cli.num_ctx.is_none() {
                            if let Some(n) = loadout.settings.as_ref().and_then(|s| s.num_ctx) {
                                std::env::set_var("NEWT_NUM_CTX", n.to_string());
                            }
                        }
                        // Provider axis (Slice 2): the loadout's `provider` names a
                        // [backends] entry; resolve_backend_choice honors NEWT_PROVIDER
                        // to select it (endpoint/kind/auth). Validated above.
                        if std::env::var_os("NEWT_PROVIDER").is_none() {
                            if let Some(p) = &loadout.provider {
                                std::env::set_var("NEWT_PROVIDER", p);
                                // #1668: a --loadout axis is explicit this run.
                                newt_core::runtime::record_cli_preference_axes(
                                    newt_core::PreferenceAxes {
                                        backend: true,
                                        ..Default::default()
                                    },
                                );
                            }
                        }
                        // Model selection: the catalog resolves `@variant` (catalog
                        // epic); here the bare model id feeds the existing selector and
                        // overrides the chosen backend's default model.
                        if std::env::var_os("NEWT_DGX_MODEL").is_none() {
                            if let Some(m) = &loadout.model {
                                let bare = m.split('@').next().unwrap_or(m);
                                std::env::set_var("NEWT_DGX_MODEL", bare);
                                // #1668: a --loadout axis is explicit this run.
                                newt_core::runtime::record_cli_preference_axes(
                                    newt_core::PreferenceAxes {
                                        model: true,
                                        ..Default::default()
                                    },
                                );
                            }
                        }
                    }
                    // role → persona, unless --persona was given explicitly.
                    cli.persona
                        .as_ref()
                        .map_or_else(|| loadout.role.clone(), |_| None)
                } else {
                    None
                }
            };
            // Sticky last-active selections (#545): the provider/model the user
            // last chose via `/backends`/`/model` are restored from
            // ~/.newt/settings.toml so the next start picks up where they left
            // off. LOWEST precedence — an explicit NEWT_PROVIDER/NEWT_DGX_MODEL
            // (env) or a --loadout axis (set just above) always wins, and a
            // provider naming a since-removed [[backends]] entry is ignored.
            {
                // Key on the session workspace, not the launch directory.
                if let Some(dir) = &path {
                    newt_core::settings::set_workspace(dir);
                }
                let session = newt_core::settings::load();
                if !session.is_empty() {
                    let cfg =
                        crate::migration_notices::read(|report| newt_core::Config::resolve(report))
                            .ok();
                    let current_provider = std::env::var("NEWT_PROVIDER")
                        .ok()
                        .filter(|s| !s.is_empty());
                    let restore = session.restore(
                        current_provider.as_deref(),
                        std::env::var_os("NEWT_DGX_MODEL").is_some(),
                        |name| {
                            cfg.as_ref()
                                .is_some_and(|c| c.backends.iter().any(|b| b.name == name))
                        },
                    );
                    // SAFETY: single-threaded before the TUI starts async work.
                    unsafe {
                        if let Some(provider) = restore.provider {
                            std::env::set_var("NEWT_PROVIDER", provider);
                        }
                        if let Some(model) = restore.model {
                            std::env::set_var("NEWT_DGX_MODEL", model);
                        }
                    }
                }
            }
            // --ephemeral threads to the TUI the same way (Step 17.7): the
            // session start resolution reads NEWT_EPHEMERAL once.
            if cli.ephemeral {
                unsafe { std::env::set_var("NEWT_EPHEMERAL", "1") };
            }
            // #1671: --resume <name> threads the same way; the TUI resolves
            // the name against the workspace store (title or id/prefix) and
            // fails hard on a miss. clap already refuses --resume + --ephemeral.
            if let Some(name) = cli.resume.as_deref() {
                unsafe { std::env::set_var("NEWT_RESUME", name) };
            }
            // A launch-scoped selected name, never a persisted blanket opt-in.
            // Clear inherited consent when this invocation did not request it.
            unsafe {
                if cli.adopt_frame {
                    std::env::set_var(
                        "NEWT_ADOPT_FRAME",
                        cli.resume.as_deref().expect("clap requires resume"),
                    );
                } else {
                    std::env::remove_var("NEWT_ADOPT_FRAME");
                }
            }
            // --prompt-for-permissions threads the same way (issue #263);
            // only the interactive TUI reads it — worker/eval never prompt.
            if cli.prompt_for_permissions {
                unsafe { std::env::set_var("NEWT_PROMPT_FOR_PERMISSIONS", "1") };
            }
            // #721: --no-prompt-for-permissions opts back out of the new
            // interactive default; it wins over --prompt-for-permissions/config.
            if cli.no_prompt_for_permissions {
                unsafe { std::env::set_var("NEWT_NO_PROMPT_FOR_PERMISSIONS", "1") };
            }
            // --plain (alias --no-footer) forces the footer off; the TUI reads
            // NEWT_FOOTER once. CLI > env > [tui] footer > default (auto).
            if cli.plain {
                unsafe { std::env::set_var("NEWT_FOOTER", "off") };
            }
            // INTERIM (#297): --disable-ocap / --yolo threads the same way.
            // The run_command dispatch in newt-core reads NEWT_DISABLE_OCAP
            // per call; the TUI reads it once at session start for the loud
            // banner + the permission-log session record. Env-only on
            // purpose — no config key, no silent persistence.
            if cli.disable_ocap {
                unsafe { std::env::set_var("NEWT_DISABLE_OCAP", "1") };
            }
            // --full-access threads the same way: the TUI's policy_for reads
            // NEWT_FULL_ACCESS when building the session capability, and the
            // session banner surfaces it loudly. Env-only on purpose — the
            // per-run override never persists to config.
            if cli.full_access {
                unsafe { std::env::set_var("NEWT_FULL_ACCESS", "1") };
            }
            // Freeze the launch authority now that the flags have set their env
            // twins. Deep libraries read this frozen value (never the live env),
            // so a `NEWT_DISABLE_OCAP` / `NEWT_FULL_ACCESS` that appears LATER
            // cannot widen authority mid-process (noninteractive-launch-policy).
            newt_core::launch_authority::freeze(if cli.workspace_access {
                newt_core::launch_authority::LaunchAuthority::WORKSPACE_ACCESS
            } else if selected_workspace.has_profile {
                // A verified operator profile selects confinement, including
                // when a parent shell carried legacy global/bypass switches.
                newt_core::launch_authority::LaunchAuthority::CONFINED
            } else {
                newt_core::launch_authority::LaunchAuthority::from_env()
            });
            // #1176: arm the shadow-OCAP flight recorder whenever the session
            // runs UNCONFINED (--full-access or --yolo/--disable-ocap). Every
            // unconfined command then records the authority a leash would have
            // gated on, building a policy-gap catalog + bridle repro fixtures.
            // Respects an explicit NEWT_FLIGHT_RECORDER (a chosen path, or
            // `off`/`0` to opt out); default is ~/.newt/flight-recorder/
            // unconfined.jsonl (append-only across runs).
            if (cli.full_access || cli.disable_ocap)
                && std::env::var_os(newt_core::flight_recorder::CAPTURE_PATH_ENV).is_none()
            {
                if let Some(cfg_path) = newt_core::Config::user_config_path() {
                    let capture = cfg_path
                        .with_file_name("flight-recorder")
                        .join("unconfined.jsonl");
                    unsafe {
                        std::env::set_var(newt_core::flight_recorder::CAPTURE_PATH_ENV, &capture);
                    }
                }
            }
            // Explicit opt-out (`off`/`0`) clears the recorder for this run.
            if let Ok(v) = std::env::var(newt_core::flight_recorder::CAPTURE_PATH_ENV) {
                if v.eq_ignore_ascii_case("off") || v == "0" {
                    unsafe { std::env::remove_var(newt_core::flight_recorder::CAPTURE_PATH_ENV) };
                }
            }
            // #1951: resolved ONCE for this arm's four startup checks below
            // (shell engine, splash preference, team runner, DGX drift
            // notice) — each used to call `Config::resolve()` independently,
            // so a config that fails to resolve (e.g. an unattributable
            // legacy backend drop-in) logged the same warning repeatedly on
            // a single command, paying the disk read + drop-in merge again
            // for an answer already in hand.
            let session_cfg =
                crate::migration_notices::read(|report| newt_core::Config::resolve(report)).ok();
            // --shell-engine selects which agent-bridle engine run_command uses
            // (ADR 0005 D2 seam). Precedence: `--shell-engine` > `[shell] engine`
            // > `--full-access` platform default > `safe-subset` — published via
            // NEWT_SHELL_ENGINE for newt-core's dispatch to read (same env
            // pattern as NEWT_FULL_ACCESS).
            {
                let shell_cfg = session_cfg.as_ref().and_then(|c| c.shell.clone());
                // #1243 Leg 1: publish NEWT_SHELL_ENGINE only for a FIXED choice
                // (explicit flag/config or the --full-access auto-upgrade). The
                // confined default is intentionally left UNPUBLISHED so the deep
                // dispatch resolves it per-command against the live L3 fence
                // (confined_default_engine) — never caching the startup fence
                // state (the agent-bridle #239 TOCTOU obligation).
                let selected = newt_core::resolve_shell_engine_choice(
                    cli.shell_engine,
                    shell_cfg.as_ref().and_then(|s| s.engine),
                    cli.full_access,
                );
                let effective = selected.or_else(|| {
                    std::env::var("NEWT_SHELL_ENGINE")
                        .ok()
                        .and_then(|value| value.parse().ok())
                });
                if let Some(engine) = effective {
                    engine.validate_available().map_err(anyhow::Error::msg)?;
                }
                if let Some(engine) = selected {
                    unsafe { std::env::set_var("NEWT_SHELL_ENGINE", engine.as_str()) };
                }
                // Confined-shell env passthrough (so `~` expands — brush needs
                // HOME): `[shell] env_passthrough` (default HOME+USER), published
                // colon-separated for newt-core's confined dispatch to seed.
                let passthrough = shell_cfg
                    .and_then(|s| s.env_passthrough)
                    .unwrap_or_else(newt_core::shell_env_passthrough_default);
                unsafe {
                    std::env::set_var("NEWT_SHELL_ENV_PASSTHROUGH", passthrough.join(":"));
                }
            }
            // facade P4 (#780): --no-route turns OFF the convenience tool-call
            // routing (run_command reads the var per call). A DISTINCT switch
            // from --disable-ocap (§7-F5): L2-convenience-off, L3-boundary
            // untouched — the two env vars never alias. Env-only, no config key.
            if cli.no_route {
                unsafe { std::env::set_var("NEWT_NO_ROUTE", "1") };
            }
            // --no-agents-file / --agents-file thread to the TUI via env vars.
            if cli.no_agents_file {
                unsafe { std::env::set_var("NEWT_NO_AGENTS_FILE", "1") };
            }
            if let Some(p) = &cli.agents_file {
                unsafe { std::env::set_var("NEWT_AGENTS_FILE", p) };
            }
            // Resolve splash preference: CLI flags override config, and
            // --splash overrides --no-splash (enforced by overrides_with).
            let config_no_splash = session_cfg
                .as_ref()
                .and_then(|c| c.tui.clone())
                .map(|t| t.no_splash)
                .unwrap_or(false);
            let no_splash = (cli.no_splash || config_no_splash) && !cli.splash;
            // The loadout's `role` is the persona when `--persona` was not given.
            let persona = cli.persona.as_deref().or(loadout_role.as_deref());
            // #479 part 2 — the crew/team runner: BUILT HERE (newt-cli owns
            // newt-scheduler + the worktree) and injected DOWN into the
            // scheduler-free TUI loop. Enabled by NEWT_TEAM (the operator's /team
            // toggle); off by default, so nothing changes unless asked. Crews run
            // under attenuated caveats (the runner fails closed on a read-only
            // session) in an isolated worktree.
            let team_runner = if std::env::var("NEWT_TEAM").is_ok() {
                let dir = path
                    .as_deref()
                    .map(|p| p.to_path_buf())
                    .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
                // The NEWT_TEAM enable IS the human gesture today — a soft
                // affirmation, modelled as `Presence::Prompt` (23.2). It's the
                // dev-escape stand-in for the real attest ceremony, which arrives
                // with BOOT (#472); a `Passkey`-required crew op holds until then.
                session_cfg.clone().map(|cfg| {
                    crate::crew_runner::LocalCrewRunner::new(
                        cfg,
                        dir,
                        newt_core::agentic::Presence::Prompt,
                    )
                })
            } else {
                None
            };
            // Best-effort: if the DGX node has drifted from [dgx] config, print a
            // one-line notice (→ `newt dgx adopt`) before the session. Never
            // blocks startup; silent when dgx is unconfigured or unreachable.
            dgx::startup_drift_notice(session_cfg.as_ref()).await;
            // First-run provisioning is COVERED by the splash (#985): build a
            // background setup handle (interactive + embedded + unprovisioned) and
            // hand it to run_code, which shows a spinner over the download instead
            // of dumping raw output before the TUI (which let a stray key dismiss
            // the splash). Non-interactive / lean / already-present → None.
            let setup = models_cmd::spawn_setup();
            // FR-5 (#999): map the validated `--altitude` string to the enum.
            // `value_parser` already fenced the input to doer/coach/advise, so a
            // non-"coach"/"advise" value can only be "doer".
            let altitude = cli.altitude.as_deref().map(|level| match level {
                "coach" | "advise" => newt_core::Altitude::Coach,
                _ => newt_core::Altitude::Doer,
            });
            newt_tui::run_code(
                path.as_deref(),
                no_splash,
                persona,
                altitude,
                team_runner
                    .as_ref()
                    .map(|r| r as &dyn newt_core::agentic::CrewRunner),
                setup,
            )
        }
        Command::Pilot { flight_id } => newt_tui::run_pilot(&flight_id),
        Command::Worker {
            coder,
            operator_key_path,
            allow_no_key,
        } => run_worker(coder, operator_key_path, allow_no_key).await,
        // #1021 PR 5.3: `--persona` is already a global flag (parsed for
        // every subcommand); it was just silently dropped here before now.
        //
        // Bare `newt mcp` (no subcommand) is TTY-aware: piped stdin (an MCP
        // client, or the stdout-purity tests) serves over stdio exactly as
        // before; an interactive terminal prints the subcommand menu instead
        // of blocking as a server on a human's stdin. `newt mcp serve` always
        // serves regardless of TTY. See `mcp_cmd::bare_mcp_action`.
        Command::Mcp { cmd: None } => {
            match mcp_cmd::bare_mcp_action(std::io::stdin().is_terminal()) {
                mcp_cmd::BareMcpAction::Serve => run_mcp(cli.persona.as_deref()).await,
                mcp_cmd::BareMcpAction::Help => print_mcp_help(),
            }
        }
        Command::Mcp {
            cmd: Some(mcp_cmd::McpCmd::Serve),
        } => run_mcp(cli.persona.as_deref()).await,
        Command::Mcp { cmd: Some(cmd) } => mcp_cmd::run(cmd, cli.config.as_deref()).await,
        Command::Crew {
            task,
            edit,
            crew,
            dir,
            test,
            max_attempts,
            dry_run,
        } => {
            if edit {
                // Edit-settings mode: the name comes from --crew, else the
                // positional slot. No task is run.
                let name = crew.or(task);
                return newt_tui::run_crew_edit(name.as_deref(), newt_tui::color_supported());
            }
            let task = task.ok_or_else(|| {
                anyhow::anyhow!("a task is required (or pass --edit to edit crew settings)")
            })?;
            let code = crew::run_cli(crew::CrewArgs {
                task,
                crew,
                dir,
                test,
                max_attempts,
                dry_run,
            })
            .await?;
            if code != 0 {
                std::process::exit(code);
            }
            Ok(())
        }
        Command::Plan {
            file,
            goal,
            output,
            dir,
            execute,
            one_shot,
            max_leaves,
            locked_verify,
        } => {
            let code = if let Some(goal) = goal {
                if one_shot {
                    // One gesture: author the plan AND execute it autonomously.
                    crew::one_shot_goal_cli(&goal, dir, max_leaves, locked_verify).await?
                } else {
                    // Author a plan from the goal (a strong model decomposes it),
                    // grounded in the target repo (`--dir`, else cwd).
                    crew::author_plan_cli(goal, output, max_leaves, dir).await?
                }
            } else if let Some(file) = file {
                // `--one-shot` on a FILE is the approval to run it end-to-end
                // (equivalent to `--execute`).
                crew::run_plan_cli(crew::PlanArgs {
                    file,
                    dir,
                    execute: execute || one_shot,
                    one_shot,
                    max_leaves,
                })
                .await?
            } else {
                anyhow::bail!(
                    "pass a plan FILE to preview/execute, or --goal \"<text>\" to author one"
                );
            };
            if code != 0 {
                std::process::exit(code);
            }
            Ok(())
        }
        Command::Doctor { sign_ocap, fix } => {
            if sign_ocap {
                let code = doctor::sign_ocap()?;
                if code != 0 {
                    std::process::exit(code);
                }
                Ok(())
            } else {
                doctor::run(cli.config.as_deref(), fix).await
            }
        }
        Command::Ocap { cmd } => {
            let code = ocap_cmd::run(cmd, cli.config.as_deref())?;
            if code != 0 {
                std::process::exit(code);
            }
            Ok(())
        }
        Command::Dock { cmd } => {
            let code = dock_cmd::run(cmd, cli.config.as_deref())?;
            if code != 0 {
                std::process::exit(code);
            }
            Ok(())
        }
        Command::Timer { cmd } => {
            let code = timer_cmd::run(cmd, cli.config.as_deref()).await?;
            if code != 0 {
                std::process::exit(code);
            }
            Ok(())
        }
        Command::Web { args } => {
            let code = web_cmd::run(&args)?;
            if code != 0 {
                std::process::exit(code);
            }
            Ok(())
        }
        Command::Providers { cmd } => providers_cmd::run(cmd),
        Command::Headless {
            cwd,
            instruction_file,
            non_interactive,
            unsafe_host_exec,
            confined,
            events,
            smart_harness,
            frame_dir,
            max_rounds,
            context_window,
            model_digest,
            scratchpad_state,
            require_feature,
            output_allowance,
            run_allowance,
            hermetic,
            resume_from,
        } => {
            // Refuse an illegal combination BEFORE any work starts. `clap`'s
            // `conflicts_with` above already catches it at the terminal with a
            // better message; this is the same rule where a non-CLI caller can
            // reach it, so the two consumers cannot disagree about what is legal.
            let launch =
                newt_launch::LaunchConfig::from_flags(hermetic, cli.resume.is_some(), resume_from)
                    .map_err(|e| anyhow::anyhow!("{e}"))?;
            let code = headless::run(headless::HeadlessArgs {
                cwd: cwd.unwrap_or_else(|| PathBuf::from(".")),
                instruction_file,
                // The pinned benchmark profile is the global `--config <FILE>`.
                profile: cli.config.clone(),
                non_interactive,
                unsafe_host_exec,
                confined,
                events,
                smart_harness,
                frame_dir,
                hermetic_explicit: hermetic,
                max_rounds,
                context_window,
                model_digest,
                scratchpad_state,
                require_feature,
                output_allowance,
                run_allowance,
                launch,
            })
            .await?;
            if code != 0 {
                std::process::exit(code);
            }
            Ok(())
        }
        Command::Config => config_cmd::run(cli.config.as_deref()),
        Command::Compaction => compaction_cmd::run(cli.config.as_deref()),
        Command::Frame { cmd } => {
            let code = frame_cmd::run(&cmd)?;
            std::process::exit(code);
        }
        Command::Identity { cmd } => identity_cmd::run(cli.config.as_deref(), cmd),
        Command::Init => newt_tui::run_init(newt_tui::color_supported()),
        Command::Setup {
            target,
            token_env,
            token_file,
            model,
            yes,
        } => match target {
            Some(target) => {
                newt_tui::run_setup_target_with_model(
                    &target,
                    token_env.as_deref(),
                    token_file.as_deref(),
                    model.as_deref(),
                    yes,
                    cli.config.as_deref(),
                )
                .await
            }
            None => newt_tui::run_setup(newt_tui::color_supported()),
        },
        Command::Auth { server } => auth_cmd::run(server),
        Command::New {
            ecosystem,
            name,
            dir,
            force,
        } => new_project::run(ecosystem, name, dir, force),
        Command::Skills { cmd } => skills::run(cmd, cli.config.as_deref()),
        Command::Dgx { cmd } => dgx::run(cmd, cli.config.as_deref()).await,
        Command::Tunings { cmd } => tuning_cmd::run(cmd, cli.config.as_deref()),
        Command::Models { cmd } => models_cmd::run(cmd).await,
        Command::Summarizer { cmd } => summarizer_cmd::run(cmd).await,
        // Startup-free help: no session, no backend connect. Uses the same
        // command corpus as interactive `/help`, in its stable plain format,
        // so `newt help` is a hosted-CI-safe way to inspect the catalog. A
        // leading `/` on the topic is tolerated so `newt help /dgx` and
        // `newt help dgx` behave alike.
        Command::Help { command } => {
            let topic = command.as_deref().map(|c| c.trim_start_matches('/'));
            print!(
                "{}",
                newt_tui::render_help(topic, newt_tui::color_supported(), false)
            );
            Ok(())
        }
    }
}

/// Spawn the ACP worker with stdio safety.
///
/// On Unix we redirect fd 1 to fd 2 (stderr) and hand the saved real
/// stdout to the server. Any rogue `println!()` from a dependency
/// will land on stderr instead of corrupting the JSON-RPC wire. On
/// non-Unix targets we fall back to plain stdout — a deliberate
/// out-of-scope corner documented in the PR.
///
/// `coder` activates the newt-coder plugin (whole-file emit +
/// server-side diff normalization). The flag is plumbed through to
/// the server via `NEWT_CODER=1`, which `handle_new_session` reads;
/// this is the same env the ACP server already honors, so a user
/// invoking the daemon under systemd can either pass `--coder` or
/// set `NEWT_CODER=1` in the unit file — both work.
///
/// `operator_key_path` and `allow_no_key` plumb the worker's signed
/// operator identity (#94). The headless worker derives an attenuated,
/// signed [`newt_core::Caveats`] from that identity per dispatch instead
/// of dispatching under `Caveats::top()`. CLI > env > default-file
/// resolution. On any unresolved-key failure without `--allow-no-key`,
/// the worker refuses to start.
async fn run_worker(
    coder: bool,
    operator_key_path: Option<PathBuf>,
    allow_no_key: bool,
) -> anyhow::Result<()> {
    // fd 1 is the ACP JSON-RPC wire from here on. Declare it BEFORE any other
    // work so no ephemeral writer can ever paint a frame into a protocol
    // stream. Deliberately unconditional on platform: the `dup2` guard below is
    // `#[cfg(unix)]` and its non-unix arm returns `ErrorKind::Unsupported`, so
    // on Windows this flag is the ONLY thing protecting the wire.
    newt_core::tty::enter_protocol_mode();

    if coder {
        // SAFETY: single-threaded section before tokio takes over —
        // set_var is safe here because no other thread reads/writes
        // env yet. handle_new_session reads this for every session.
        unsafe {
            std::env::set_var("NEWT_CODER", "1");
        }
        tracing::info!("newt-coder plugin activated (whole-file emit)");
    }

    // Resolve the operator identity once, BEFORE any tokio work, so a
    // missing-key refusal fails fast and never tries to drain stdin.
    // step-1.3: the `--allow-no-key` debug fallback is compiled out of
    // production builds (the `allow-no-key` feature is dev-only, off by
    // default). Keep the hint honest about whether the flag can actually help.
    #[cfg(feature = "allow-no-key")]
    const ALLOW_NO_KEY_HINT: &str = "or use --allow-no-key (debug only) to fall back to top()";
    #[cfg(not(feature = "allow-no-key"))]
    const ALLOW_NO_KEY_HINT: &str =
        "the --allow-no-key debug fallback is compiled out of this build \
         (dev-only `allow-no-key` feature) and is inert";
    let identity =
        newt_acp_worker::WorkerIdentity::resolve(operator_key_path.as_deref(), allow_no_key)
            .map_err(|e| {
                anyhow::anyhow!(
                    "headless worker refused to start: {e}\n\
                     hint: pass --operator-key-path <PEM>, set NEWT_OPERATOR_KEY; {ALLOW_NO_KEY_HINT}"
                )
            })?;

    if !identity.is_operator() {
        tracing::warn!(
            "headless worker started with --allow-no-key: dispatching under \
             unbounded debug authority (debug-only fallback, never the default)"
        );
    } else {
        tracing::info!("headless worker started with operator-rooted identity");
    }

    // Start the Prometheus /metrics endpoint if NEWT_METRICS_PORT is set.
    // The registry lives for the lifetime of the worker process.
    let metrics = maybe_start_metrics_server();

    #[cfg(unix)]
    {
        match stdio_guard::redirect_stdout_to_stderr() {
            Ok(private_stdout) => {
                let tokio_stdout = tokio::fs::File::from_std(private_stdout);
                newt_acp_worker::run_with_io_metrics_and_identity(
                    tokio::io::stdin(),
                    tokio_stdout,
                    metrics,
                    identity,
                )
                .await
            }
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "stdio_guard fd redirect failed; falling back to raw stdout"
                );
                newt_acp_worker::run_with_io_metrics_and_identity(
                    tokio::io::stdin(),
                    tokio::io::stdout(),
                    metrics,
                    identity,
                )
                .await
            }
        }
    }
    #[cfg(not(unix))]
    {
        newt_acp_worker::run_with_io_metrics_and_identity(
            tokio::io::stdin(),
            tokio::io::stdout(),
            metrics,
            identity,
        )
        .await
    }
}

/// Check `NEWT_METRICS_PORT`; if set, create a metrics registry and spawn the
/// HTTP scrape server as a background task.
///
/// Returns the registry for injection into the ACP server, or `None` if the
/// env var is absent or invalid.
fn maybe_start_metrics_server() -> Option<std::sync::Arc<newt_acp_worker::NewtMetrics>> {
    let port: u16 = std::env::var("NEWT_METRICS_PORT")
        .ok()
        .and_then(|s| s.parse().ok())
        .filter(|&p| p > 0)?;

    let registry = match newt_acp_worker::NewtMetrics::new() {
        Ok(r) => std::sync::Arc::new(r),
        Err(e) => {
            tracing::warn!(error = %e, "failed to create Prometheus registry — metrics disabled");
            return None;
        }
    };

    let reg = registry.clone();
    tokio::spawn(async move {
        newt_acp_worker::prom::serve(port, reg).await;
    });

    tracing::info!(port, "Prometheus metrics server started");
    Some(registry)
}

/// Spawn the MCP server with the same stdio safety dance as
/// [`run_worker`].
///
/// `persona` (#1021 PR 5.3) is the already-global `--persona` flag, wired
/// into this subcommand for the first time: when set, the server loads that
/// role profile, connects its declared MCP servers (e.g. `modulex`), and
/// restricts the advertised `tools/list` to the persona's `tools:`
/// allow-list — the same enforcement the TUI applies, reused via
/// `newt_core::agentic::filter_advertised_tools`.
/// Print the `mcp` subcommand menu for an interactive human who typed bare
/// `newt mcp` at a terminal — instead of blocking as a stdio server on their
/// keyboard. The verb list is rendered from clap's own help for the `mcp`
/// subcommand so it can never drift from the parser, followed by a one-line
/// pointer to the two ways to actually serve. Returns `Ok` (exit 0).
fn print_mcp_help() -> anyhow::Result<()> {
    let mut cmd = help_command();
    if let Some(mcp) = cmd.find_subcommand_mut("mcp") {
        // `render_long_help` lists each verb with its description — the menu.
        print!("{}", mcp.render_long_help());
    }
    println!(
        "\nTo run newt as an MCP server for a client, invoke it with piped \
         stdio (e.g. `claude mcp add newt -- newt mcp`) or run `newt mcp serve`."
    );
    Ok(())
}

async fn run_mcp(persona: Option<&str>) -> anyhow::Result<()> {
    // fd 1 is the MCP JSON-RPC wire from here on — see the note in
    // `run_worker`. Unconditional on platform, and irreversible.
    newt_core::tty::enter_protocol_mode();

    #[cfg(unix)]
    {
        match stdio_guard::redirect_stdout_to_stderr() {
            Ok(private_stdout) => {
                let tokio_stdout = tokio::fs::File::from_std(private_stdout);
                newt_mcp_server::run_with_io(tokio::io::stdin(), tokio_stdout, persona).await
            }
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "stdio_guard fd redirect failed; falling back to raw stdout"
                );
                newt_mcp_server::run_stdio(persona).await
            }
        }
    }
    #[cfg(not(unix))]
    {
        newt_mcp_server::run_stdio(persona).await
    }
}

#[cfg(test)]
mod backend_flag_axis_tests {
    use super::backend_flag_axes;
    use newt_core::config::BackendOverride;

    fn over() -> BackendOverride {
        BackendOverride::default()
    }

    /// #1668 review-2 finding 4: `--backend-name X` owns the backend axis with
    /// no destination given. Before the fix this returned `backend: false`, so
    /// `newt --backend-name sol --resume A` let A's pin reroute the session off
    /// the backend the operator had just named on the command line.
    #[test]
    fn a_named_backend_owns_the_backend_axis_without_a_destination() {
        let axes = backend_flag_axes(&BackendOverride {
            name: Some("sol".into()),
            ..over()
        });
        assert!(axes.backend, "--backend-name owns the backend axis");
        assert!(!axes.model, "and says nothing about the model axis");
    }

    /// #1668 review-2 finding 4: `--backend-model M` owns the MODEL axis. This
    /// was recorded on no path at all, so a stored pin naming a model silently
    /// beat the flag — the precedence inversion, inverted.
    #[test]
    fn an_explicit_backend_model_owns_the_model_axis() {
        let axes = backend_flag_axes(&BackendOverride {
            model: Some("qwen3-coder_30b".into()),
            ..over()
        });
        assert!(axes.model, "--backend-model owns the model axis");
        assert!(
            !axes.backend,
            "naming only a model does not claim the backend axis"
        );
    }

    /// A bare destination still owns the backend axis — it pins where this run
    /// talks to as firmly as a name does. (The pre-fix behavior, preserved.)
    #[test]
    fn a_bare_destination_still_owns_the_backend_axis() {
        assert!(
            backend_flag_axes(&BackendOverride {
                endpoint: Some("http://dgx1.test:8080".into()),
                ..over()
            })
            .backend
        );
        assert!(
            backend_flag_axes(&BackendOverride {
                model_path: Some("/models/x.gguf".into()),
                ..over()
            })
            .backend
        );
    }

    /// The negative: unrelated `--backend-*` knobs claim NO posture axis. An
    /// over-broad rule would suppress a pin the operator never overrode, which
    /// fails in the quiet direction — the conversation's stored posture simply
    /// stops applying and nothing says why.
    #[test]
    fn unrelated_backend_knobs_own_no_posture_axis() {
        let axes = backend_flag_axes(&BackendOverride {
            api_key_env: Some("OPENAI_API_KEY".into()),
            ram_gib: Some(24.0),
            ..over()
        });
        assert!(!axes.backend);
        assert!(!axes.model);
    }
}

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

    #[test]
    fn shell_engine_flag_preserves_host_and_validates_brush_transport() {
        let host = Cli::try_parse_from(["newt", "--shell-engine", "host"]).unwrap();
        assert_eq!(host.shell_engine, Some(newt_core::ShellEngine::Host));
        let brush = Cli::try_parse_from(["newt", "--shell-engine", "brush"]);
        if newt_core::ShellEngine::Brush.validate_available().is_ok() {
            assert_eq!(
                brush.unwrap().shell_engine,
                Some(newt_core::ShellEngine::Brush)
            );
        } else {
            assert!(brush
                .unwrap_err()
                .to_string()
                .contains("authenticated worker transport"));
        }
    }

    #[test]
    fn backend_flags_parse_and_build_an_exclusive_override() {
        let cli = Cli::try_parse_from([
            "newt",
            "--backend-endpoint",
            "http://router:8080",
            "--backend-model",
            "qwen3-coder_30b",
            "--backend-kind",
            "openai",
            "--backend-api",
            "chat_completions",
            "--backend-tiers",
            "FAST,STANDARD,COMPLEX,REVIEW",
            "--backend-api-key-file",
            "/vault/token",
        ])
        .unwrap();
        let over = cli.backend.to_override();
        assert!(!over.is_empty());
        assert_eq!(over.endpoint.as_deref(), Some("http://router:8080"));
        assert_eq!(over.model.as_deref(), Some("qwen3-coder_30b"));
        assert_eq!(over.kind, Some(newt_core::config::BackendKind::Openai));
        assert_eq!(
            over.api,
            Some(newt_core::config::OpenAiApi::ChatCompletions)
        );
        assert_eq!(over.api_key_file.as_deref(), Some("/vault/token"));
        assert_eq!(
            over.tiers,
            Some(vec![
                newt_core::Tier::Fast,
                newt_core::Tier::Standard,
                newt_core::Tier::Complex,
                newt_core::Tier::Review,
            ])
        );

        // The override is exclusive and replaces discovered backends.
        let mut cfg = newt_core::Config {
            backends: vec![newt_core::config::BackendConfig {
                name: "discovered".into(),
                endpoint: "http://localhost:11434".into(),
                ..Default::default()
            }],
            ..Default::default()
        };
        over.apply(&mut cfg);
        assert_eq!(cfg.backends.len(), 1);
        assert_eq!(cfg.backends[0].name, "cli");
        assert_eq!(cfg.backends[0].endpoint, "http://router:8080");
    }

    #[test]
    fn no_backend_flags_yields_an_empty_override() {
        let cli = Cli::try_parse_from(["newt"]).unwrap();
        assert!(cli.backend.to_override().is_empty());
    }

    #[test]
    fn backend_kind_rejects_garbage() {
        assert!(Cli::try_parse_from(["newt", "--backend-kind", "banana"]).is_err());
    }

    /// Slice 1a rename: `--cognition` takes the new labels, and an old label
    /// is a parse error that names its replacement.
    #[test]
    fn cognition_flag_rejects_an_old_label_with_the_rename() {
        let cli = Cli::try_parse_from(["newt", "--cognition", "meticulous"]).unwrap();
        assert_eq!(
            cli.cognition,
            Some(newt_core::role_profile::Cognition::Meticulous)
        );
        let err = Cli::try_parse_from(["newt", "--cognition", "contemplating"])
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("cognition 'contemplating' was renamed to 'meticulous'"),
            "{err}"
        );
    }

    /// Regression (slice 1b): `--tenacity insistent` used to parse. The
    /// pre-split levels are now refused with the `--initiative` flag that
    /// replaces them, and `--initiative` takes the new levels.
    #[test]
    fn tenacity_flag_refuses_a_pre_split_level_with_its_initiative_replacement() {
        for (old, new) in [
            ("relaxed", "patient"),
            ("standard", "measured"),
            ("insistent", "decisive"),
        ] {
            let err = Cli::try_parse_from(["newt", "--tenacity", old])
                .unwrap_err()
                .to_string();
            assert!(err.contains(&format!("--initiative {new}")), "{err}");
        }
        let cli =
            Cli::try_parse_from(["newt", "--tenacity", "relentless", "--initiative", "eager"])
                .unwrap();
        assert_eq!(cli.tenacity, Some(newt_core::Tenacity::Relentless));
        assert_eq!(cli.initiative, Some(newt_core::Initiative::Eager));
        assert!(Cli::try_parse_from(["newt", "--initiative", "insistent"]).is_err());
    }

    #[test]
    fn parses_global_persona_for_default_code_command() {
        let cli = Cli::try_parse_from(["newt", "--persona", "coder"]).unwrap();

        assert_eq!(cli.persona.as_deref(), Some("coder"));
        assert!(cli.command.is_none());
    }

    #[test]
    fn parses_global_persona_for_explicit_code_command() {
        let cli = Cli::try_parse_from(["newt", "code", "--persona", "reviewer"]).unwrap();

        assert_eq!(cli.persona.as_deref(), Some("reviewer"));
        assert!(matches!(cli.command, Some(Command::Code { .. })));
    }

    #[test]
    fn parses_debug_and_num_ctx_globals() {
        let cli = Cli::try_parse_from(["newt", "--debug", "--num-ctx", "8192"]).unwrap();

        assert!(cli.debug);
        assert_eq!(cli.num_ctx, Some(8192));
    }

    #[test]
    fn headless_context_window_rejects_values_that_cannot_enter_the_contract() {
        assert!(Cli::try_parse_from([
            "newt",
            "headless",
            "--instruction-file",
            "task.md",
            "--context-window",
            "4294967296",
        ])
        .is_err());
    }

    #[test]
    fn parses_trace_global() {
        let cli = Cli::try_parse_from(["newt", "--trace"]).unwrap();

        assert!(cli.trace);
    }

    // ── color / theme flags (issue #527) ────────────────────────────────

    #[test]
    fn parses_color_mode_global() {
        // Works bare (default `code`) and after the subcommand; off by default.
        let cli = Cli::try_parse_from(["newt", "--color", "always"]).unwrap();
        assert_eq!(cli.color, Some(newt_core::ColorMode::Always));
        let cli = Cli::try_parse_from(["newt", "code", "--color", "dark"]).unwrap();
        assert_eq!(cli.color, Some(newt_core::ColorMode::Dark));
        let cli = Cli::try_parse_from(["newt"]).unwrap();
        assert_eq!(cli.color, None);
    }

    #[test]
    fn rejects_unknown_color_mode() {
        // The value_parser surfaces a clap error for an unknown keyword.
        assert!(Cli::try_parse_from(["newt", "--color", "rainbow"]).is_err());
    }

    #[test]
    fn parses_mono_global() {
        let cli = Cli::try_parse_from(["newt", "--mono"]).unwrap();
        assert!(cli.mono);
        let cli = Cli::try_parse_from(["newt"]).unwrap();
        assert!(!cli.mono);
    }

    #[test]
    fn mono_and_color_can_coexist_mono_wins_in_dispatch() {
        // Both parse; dispatch resolves --mono ahead of --color (mono wins).
        let cli = Cli::try_parse_from(["newt", "--mono", "--color", "always"]).unwrap();
        assert!(cli.mono);
        assert_eq!(cli.color, Some(newt_core::ColorMode::Always));
        let color_kw = if cli.mono {
            Some("mono")
        } else {
            cli.color.map(|c| c.keyword())
        };
        assert_eq!(color_kw, Some("mono"));
    }

    #[test]
    fn help_suite_applies_next_line_help_to_root_and_subcommands() {
        let mut command = help_command();
        let mut root_help = Vec::new();
        command.write_long_help(&mut root_help).unwrap();
        let root_help = String::from_utf8(root_help).unwrap();

        let mut sub_help = Vec::new();
        let dgx = command.find_subcommand_mut("dgx").unwrap();
        dgx.write_long_help(&mut sub_help).unwrap();
        let dgx_help = String::from_utf8(sub_help).unwrap();

        assert!(root_help.contains("  -h, --help\n          Print help"));
        assert!(dgx_help.contains("  -h, --help\n          Print help"));
    }

    #[test]
    fn parse_color_mode_accepts_aliases_and_rejects_garbage() {
        assert_eq!(parse_color_mode("on"), Ok(newt_core::ColorMode::Always));
        assert_eq!(parse_color_mode("OFF"), Ok(newt_core::ColorMode::Never));
        assert!(parse_color_mode("chartreuse").is_err());
    }

    // ── lean / flight flag (issue #527) ─────────────────────────────────

    #[test]
    fn parses_lean_flag_and_all_aliases() {
        // -n / --neat / --lite / --lean / --flight / --plain / --no-footer all
        // set the same `plain` switch (lean morphology), bare or after `code`.
        for argv in [
            vec!["newt", "-n"],
            vec!["newt", "--neat"],
            vec!["newt", "--lite"],
            vec!["newt", "--lean"],
            vec!["newt", "--flight"],
            vec!["newt", "--plain"],
            vec!["newt", "--no-footer"],
            vec!["newt", "code", "-n"],
        ] {
            let cli = Cli::try_parse_from(argv.clone()).unwrap();
            assert!(cli.plain, "{argv:?} should set the lean/plain switch");
        }
        // Off by default.
        assert!(!Cli::try_parse_from(["newt"]).unwrap().plain);
    }

    #[test]
    fn parses_ephemeral_global() {
        // 17.7: works bare (default `code` command) and explicit; off by default.
        let cli = Cli::try_parse_from(["newt", "--ephemeral"]).unwrap();
        assert!(cli.ephemeral);
        let cli = Cli::try_parse_from(["newt", "code", "--ephemeral"]).unwrap();
        assert!(cli.ephemeral);
        let cli = Cli::try_parse_from(["newt"]).unwrap();
        assert!(!cli.ephemeral);
    }

    /// #1671: `--resume <name>` parses bare and under `code`, defaults off,
    /// and contradicting `--ephemeral` is unrepresentable at the parser.
    #[test]
    fn parses_resume_by_name_global() {
        let cli = Cli::try_parse_from(["newt", "--resume", "mesh docking"]).unwrap();
        assert_eq!(cli.resume.as_deref(), Some("mesh docking"));
        let cli = Cli::try_parse_from(["newt", "code", "--resume", "taxes"]).unwrap();
        assert_eq!(cli.resume.as_deref(), Some("taxes"));
        assert!(Cli::try_parse_from(["newt"]).unwrap().resume.is_none());
        // Resume-a-conversation and never-persist cannot both be meant.
        assert!(Cli::try_parse_from(["newt", "--resume", "x", "--ephemeral"]).is_err());
    }

    #[test]
    fn frame_adoption_requires_explicit_selected_resume() {
        assert!(Cli::try_parse_from(["newt", "--adopt-frame"]).is_err());
        assert!(
            Cli::try_parse_from(["newt", "--resume", "saved", "--adopt-frame", "--ephemeral"])
                .is_err()
        );
        assert!(!Cli::try_parse_from(["newt"]).unwrap().adopt_frame);
        for args in [
            vec!["newt", "--resume", "saved", "--adopt-frame"],
            vec!["newt", "code", "--resume", "saved", "--adopt-frame"],
        ] {
            let cli = Cli::try_parse_from(args).unwrap();
            assert!(cli.adopt_frame);
            assert_eq!(cli.resume.as_deref(), Some("saved"));
            assert!(validate_launch_options(&cli).is_ok());
        }
    }

    #[test]
    fn frame_adoption_rejects_noninteractive_commands_before_dispatch() {
        let cli =
            Cli::try_parse_from(["newt", "--resume", "saved", "--adopt-frame", "doctor"]).unwrap();
        assert!(validate_launch_options(&cli).is_err());
    }

    /// The continuity flags share the ONE global `--resume`; `headless` must not
    /// redeclare that id. A second definition under a different type does not
    /// fail to compile — it panics at parse time with "Mismatch between
    /// definition and access of `resume`", so a plain `newt headless` dies before
    /// doing any work. This pins that `headless` still parses bare, which is the
    /// shape the panic broke.
    #[test]
    fn headless_continuity_flags_share_the_one_global_resume() {
        assert!(Cli::try_parse_from([
            "newt",
            "headless",
            "--instruction-file",
            "x.md",
            "--max-rounds",
            "1"
        ])
        .is_ok());
        assert!(Cli::try_parse_from([
            "newt",
            "headless",
            "--instruction-file",
            "x.md",
            "--hermetic"
        ])
        .is_ok());
        assert!(Cli::try_parse_from([
            "newt",
            "headless",
            "--instruction-file",
            "x.md",
            "--resume",
            "a name"
        ])
        .is_ok());
        assert!(Cli::try_parse_from([
            "newt",
            "headless",
            "--instruction-file",
            "x.md",
            "--resume-from",
            "bafy"
        ])
        .is_ok());
        // Hermetic refuses either shape of continuity, not one of them.
        assert!(Cli::try_parse_from([
            "newt",
            "headless",
            "--instruction-file",
            "x.md",
            "--hermetic",
            "--resume",
            "n"
        ])
        .is_err());
        assert!(Cli::try_parse_from([
            "newt",
            "headless",
            "--instruction-file",
            "x.md",
            "--hermetic",
            "--resume-from",
            "b"
        ])
        .is_err());
    }

    // ── plan --one-shot (#646) ──────────────────────────────────────────
    #[test]
    fn parses_plan_one_shot_flag() {
        // `--goal … --one-shot`: author AND execute in one gesture. Distinct from
        // `--execute` (the flag carries its own approval).
        let cli = Cli::try_parse_from(["newt", "plan", "--goal", "do X", "--one-shot"]).unwrap();
        match cli.command {
            Some(Command::Plan {
                one_shot,
                goal,
                execute,
                ..
            }) => {
                assert!(one_shot, "--one-shot should set one_shot");
                assert_eq!(goal.as_deref(), Some("do X"));
                assert!(!execute, "--one-shot is its own flag, not --execute");
            }
            other => panic!("expected Command::Plan, got {other:?}"),
        }
        // `--one-shot` on a FILE one-shots the existing plan end-to-end.
        let cli = Cli::try_parse_from(["newt", "plan", "plan.toml", "--one-shot"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Plan { one_shot: true, .. })
        ));
        // Off by default.
        let cli = Cli::try_parse_from(["newt", "plan", "plan.toml"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Plan {
                one_shot: false,
                ..
            })
        ));
    }

    #[test]
    fn smart_harness_flags_preserve_hermetic_resume_exclusion() {
        let cli = Cli::try_parse_from([
            "newt",
            "headless",
            "--instruction-file",
            "task.md",
            "--smart-harness",
            "--frame-dir",
            "frame",
        ])
        .unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Headless {
                smart_harness: true,
                frame_dir: Some(_),
                ..
            })
        ));
        assert!(Cli::try_parse_from([
            "newt",
            "headless",
            "--instruction-file",
            "task.md",
            "--smart-harness",
            "--hermetic",
            "--resume-from",
            "bafy"
        ])
        .is_err());
    }

    #[test]
    fn parses_plan_locked_verify_flag() {
        // `--locked-verify` carries the operator's fixed gate command (the locked
        // behavioral gate). Defaults to None.
        let cli = Cli::try_parse_from([
            "newt",
            "plan",
            "--goal",
            "do X",
            "--one-shot",
            "--locked-verify",
            "cargo test --test grade_spec",
        ])
        .unwrap();
        match cli.command {
            Some(Command::Plan {
                locked_verify,
                one_shot,
                ..
            }) => {
                assert!(one_shot);
                assert_eq!(
                    locked_verify.as_deref(),
                    Some("cargo test --test grade_spec")
                );
            }
            other => panic!("expected Command::Plan, got {other:?}"),
        }
        // Absent by default.
        let cli = Cli::try_parse_from(["newt", "plan", "--goal", "y", "--one-shot"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Plan {
                locked_verify: None,
                ..
            })
        ));
    }

    #[test]
    fn parses_prompt_for_permissions_global() {
        // #263: works bare (default `code` command) and explicit; OFF by
        // default — no flag means denial behavior is unchanged.
        let cli = Cli::try_parse_from(["newt", "--prompt-for-permissions"]).unwrap();
        assert!(cli.prompt_for_permissions);
        let cli = Cli::try_parse_from(["newt", "code", "--prompt-for-permissions"]).unwrap();
        assert!(cli.prompt_for_permissions);
        let cli = Cli::try_parse_from(["newt"]).unwrap();
        assert!(!cli.prompt_for_permissions);
    }

    #[test]
    fn parses_no_prompt_for_permissions_global() {
        // #721: the opt-out flag — off by default, parses bare and under `code`.
        let cli = Cli::try_parse_from(["newt"]).unwrap();
        assert!(!cli.no_prompt_for_permissions);
        let cli = Cli::try_parse_from(["newt", "--no-prompt-for-permissions"]).unwrap();
        assert!(cli.no_prompt_for_permissions);
        let cli = Cli::try_parse_from(["newt", "code", "--no-prompt-for-permissions"]).unwrap();
        assert!(cli.no_prompt_for_permissions);
    }

    #[test]
    fn parses_disable_ocap_and_yolo_alias() {
        // #297: works bare (default `code` command) and explicit, and the
        // --yolo alias maps to the same field; OFF by default — no flag
        // means the confined dispatch is unchanged.
        let cli = Cli::try_parse_from(["newt", "--disable-ocap"]).unwrap();
        assert!(cli.disable_ocap);
        let cli = Cli::try_parse_from(["newt", "--yolo"]).unwrap();
        assert!(cli.disable_ocap);
        let cli = Cli::try_parse_from(["newt", "code", "--yolo"]).unwrap();
        assert!(cli.disable_ocap);
        assert!(matches!(cli.command, Some(Command::Code { .. })));
        let cli = Cli::try_parse_from(["newt"]).unwrap();
        assert!(!cli.disable_ocap);
    }

    /// facade P4 (#780): `--no-route` parses bare and under `code`, is OFF by
    /// default, and is a DISTINCT flag from `--disable-ocap`/`--yolo` (§7-F5) —
    /// the two never alias, so the routing escape can never imply an unconfine.
    #[test]
    fn parses_no_route_distinct_from_disable_ocap() {
        let cli = Cli::try_parse_from(["newt"]).unwrap();
        assert!(!cli.no_route);
        let cli = Cli::try_parse_from(["newt", "--no-route"]).unwrap();
        assert!(cli.no_route);
        let cli = Cli::try_parse_from(["newt", "code", "--no-route"]).unwrap();
        assert!(cli.no_route);
        // --no-route does NOT set the L3-off bypass, and --yolo does NOT set
        // the routing flag: distinct mechanisms, never aliased.
        let cli = Cli::try_parse_from(["newt", "--no-route"]).unwrap();
        assert!(cli.no_route && !cli.disable_ocap);
        let cli = Cli::try_parse_from(["newt", "--yolo"]).unwrap();
        assert!(cli.disable_ocap && !cli.no_route);
    }

    /// `--full-access` parses bare and under `code`, is OFF by default, and is
    /// a DISTINCT flag from `--disable-ocap`/`--yolo`: authority-widening and
    /// the exec-mechanism bypass never alias — asking for one never implies
    /// the other.
    #[test]
    fn parses_full_access_distinct_from_disable_ocap() {
        let cli = Cli::try_parse_from(["newt"]).unwrap();
        assert!(!cli.full_access);
        let cli = Cli::try_parse_from(["newt", "--full-access"]).unwrap();
        assert!(cli.full_access && !cli.disable_ocap);
        let cli = Cli::try_parse_from(["newt", "code", "--full-access"]).unwrap();
        assert!(cli.full_access);
        assert!(matches!(cli.command, Some(Command::Code { .. })));
        let cli = Cli::try_parse_from(["newt", "--yolo"]).unwrap();
        assert!(cli.disable_ocap && !cli.full_access);
        let cli = Cli::try_parse_from(["newt", "--yolo", "--full-access"]).unwrap();
        assert!(cli.disable_ocap && cli.full_access);
    }

    #[test]
    fn workspace_access_is_a_confined_startup_choice() {
        let cli = Cli::try_parse_from(["newt", "--workspace-access", "code", "project"]).unwrap();
        assert!(cli.workspace_access && !cli.full_access && !cli.disable_ocap);
        assert!(
            matches!(cli.command, Some(Command::Code { path: Some(path) }) if path == std::path::Path::new("project"))
        );
        for incompatible in ["--full-access", "--yolo", "--disable-ocap"] {
            assert!(Cli::try_parse_from(["newt", "--workspace-access", incompatible]).is_err());
        }
    }

    #[test]
    fn parses_repeated_read_and_write_grants() {
        let cli = Cli::try_parse_from([
            "newt",
            "--read",
            "/a/.newt",
            "--read",
            "/a/x.yml",
            "--write",
            "/a/scratch",
        ])
        .unwrap();
        assert_eq!(
            cli.read_paths,
            vec![PathBuf::from("/a/.newt"), PathBuf::from("/a/x.yml")]
        );
        assert_eq!(cli.write_paths, vec![PathBuf::from("/a/scratch")]);
    }

    #[test]
    fn abs_grant_path_expands_tilde_and_absolutises() {
        use std::path::Path;
        let original_home = std::env::var_os("HOME");
        // Exercise the process's real home without mutating HOME: other
        // parallel tests launch subprocesses and resolve configuration from it.
        // join also handles a relative home or the no-home tilde fallback.
        let expected_home = std::env::current_dir()
            .unwrap()
            .join(home_dir().unwrap_or_else(|| PathBuf::from("~")));
        assert_eq!(
            abs_grant_path(Path::new("~/.newt")),
            expected_home.join(".newt")
        );
        // An already-absolute path is unchanged.
        let abs = if cfg!(windows) {
            r"C:\etc\hosts"
        } else {
            "/etc/hosts"
        };
        assert_eq!(abs_grant_path(Path::new(abs)), PathBuf::from(abs));
        // A relative path is joined onto the current dir.
        let rel = abs_grant_path(Path::new("sub/file"));
        assert!(rel.is_absolute(), "relative grant absolutised: {rel:?}");
        assert!(rel.ends_with("sub/file"));
        assert_eq!(
            std::env::var_os("HOME"),
            original_home,
            "grant-path fixtures must not change the environment seen by parallel tests"
        );
    }

    #[test]
    fn parses_agents_file_global() {
        let cli = Cli::try_parse_from(["newt", "--agents-file", "docs/AGENTS.md"]).unwrap();
        assert_eq!(cli.agents_file.as_deref(), Some("docs/AGENTS.md"));
        assert!(!cli.no_agents_file);
    }

    #[test]
    fn parses_no_agents_file_global() {
        let cli = Cli::try_parse_from(["newt", "code", "--no-agents-file"]).unwrap();
        assert!(cli.no_agents_file);
        assert_eq!(cli.agents_file, None);
        assert!(matches!(cli.command, Some(Command::Code { .. })));
    }

    #[test]
    fn parses_venv_and_repeated_exec_paths() {
        let cli = Cli::try_parse_from([
            "newt",
            "--venv",
            "/opt/venv",
            "--exec-path",
            "/home/u/bin",
            "--exec-path",
            "/usr/local/bin",
        ])
        .unwrap();

        assert_eq!(cli.venv.as_deref(), Some(std::path::Path::new("/opt/venv")));
        assert_eq!(
            cli.exec_paths,
            vec![
                PathBuf::from("/home/u/bin"),
                PathBuf::from("/usr/local/bin")
            ]
        );
    }

    #[test]
    fn splash_flag_overrides_no_splash() {
        let cli = Cli::try_parse_from(["newt", "--no-splash", "--splash"]).unwrap();
        assert!(cli.splash);
        assert!(!cli.no_splash);

        // …and the override works in both orders.
        let cli = Cli::try_parse_from(["newt", "--splash", "--no-splash"]).unwrap();
        assert!(cli.no_splash);
        assert!(!cli.splash);
    }

    #[test]
    fn parses_setup_target_token_env_and_yes() {
        let cli = Cli::try_parse_from([
            "newt",
            "setup",
            "https://dgx1.home.arpa:8000",
            "--token-env",
            "DGX_TOKEN",
            "--yes",
        ])
        .unwrap();

        match cli.command {
            Some(Command::Setup {
                target,
                token_env,
                token_file,
                model,
                yes,
            }) => {
                assert_eq!(target.as_deref(), Some("https://dgx1.home.arpa:8000"));
                assert_eq!(token_env.as_deref(), Some("DGX_TOKEN"));
                assert_eq!(token_file, None);
                assert_eq!(model, None);
                assert!(yes);
            }
            other => panic!("expected setup command, got {other:?}"),
        }
    }

    #[test]
    fn parses_setup_token_reference_aliases() {
        let env_cli = Cli::try_parse_from([
            "newt",
            "setup",
            "https://dgx1.home.arpa:8000",
            "--api-key-env",
            "DGX_TOKEN",
        ])
        .unwrap();
        assert!(matches!(
            env_cli.command,
            Some(Command::Setup {
                token_env: Some(ref value),
                ..
            }) if value == "DGX_TOKEN"
        ));

        let file_cli = Cli::try_parse_from([
            "newt",
            "setup",
            "https://dgx1.home.arpa:8080",
            "--api-key-file",
            "/tmp/dgx-token",
        ])
        .unwrap();
        assert!(matches!(
            file_cli.command,
            Some(Command::Setup {
                token_file: Some(ref value),
                ..
            }) if value == std::path::Path::new("/tmp/dgx-token")
        ));
    }

    #[test]
    fn setup_token_references_conflict() {
        let err = Cli::try_parse_from([
            "newt",
            "setup",
            "dgx1.home.arpa",
            "--token-env",
            "DGX_TOKEN",
            "--token-file",
            "/tmp/dgx-token",
        ])
        .unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
    }

    #[test]
    fn parses_setup_without_target_for_interactive_wizard() {
        let cli = Cli::try_parse_from(["newt", "setup"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Setup {
                target: None,
                token_env: None,
                token_file: None,
                model: None,
                yes: false,
            })
        ));
    }

    #[test]
    fn setup_target_only_flags_require_a_target() {
        for args in [
            vec!["newt", "setup", "--yes"],
            vec!["newt", "setup", "--token-env", "DGX_TOKEN"],
            vec!["newt", "setup", "--token-file", "/tmp/dgx-token"],
            vec!["newt", "setup", "--model", "served-model"],
        ] {
            let err = Cli::try_parse_from(args).unwrap_err();
            assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
        }
    }

    #[test]
    fn parses_worker_identity_flags() {
        let cli = Cli::try_parse_from([
            "newt",
            "worker",
            "--coder",
            "--operator-key-path",
            "/tmp/id.pem",
            "--allow-no-key",
        ])
        .unwrap();

        match cli.command {
            Some(Command::Worker {
                coder,
                operator_key_path,
                allow_no_key,
            }) => {
                assert!(coder);
                assert_eq!(operator_key_path, Some(PathBuf::from("/tmp/id.pem")));
                assert!(allow_no_key);
            }
            other => panic!("expected worker command, got {other:?}"),
        }
    }

    #[test]
    fn worker_flags_default_to_safe_values() {
        let cli = Cli::try_parse_from(["newt", "worker"]).unwrap();

        match cli.command {
            Some(Command::Worker {
                coder,
                operator_key_path,
                allow_no_key,
            }) => {
                assert!(!coder, "coder plugin must be opt-in");
                assert_eq!(operator_key_path, None);
                assert!(!allow_no_key, "allow-no-key must never be the default");
            }
            other => panic!("expected worker command, got {other:?}"),
        }
    }
}

#[cfg(test)]
mod windows_cmd_flag_tests {
    use super::*;
    #[test]
    fn windows_2776_cmd_flag_is_explicit_and_does_not_grant_authority() {
        let cli = Cli::try_parse_from(["newt", "--windows-cmd"]).unwrap();
        assert!(cli.windows_cmd);
        assert!(!cli.disable_ocap);
        assert!(!Cli::try_parse_from(["newt"]).unwrap().windows_cmd);
    }
}