newt-agent 0.7.1

Newt-Agent — small, fast, local-first 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
//! 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 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 doctor;
mod identity_cmd;
mod new_project;
mod skills;
pub mod stack;
pub mod stdio_guard;
mod tuning_cmd;

use clap::{Parser, Subcommand};
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 with the list of accepted engines.
fn parse_shell_engine(
    s: &str,
) -> Result<newt_core::ShellEngine, Box<dyn std::error::Error + Send + Sync + 'static>> {
    Ok(s.parse::<newt_core::ShellEngine>()?)
}

#[derive(Parser, Debug)]
#[command(
    name = "newt",
    version,
    about = "Small, fast, local-first agentic coder"
)]
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>,

    /// 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,

    /// 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. Removed (or demoted to a
    /// debug flag) once brush upstreams CommandInterceptor and agent-bridle's
    /// real confined shell works everywhere (agent-bridle#20).
    #[arg(long, visible_alias = "yolo", global = true, default_value_t = false)]
    pub disable_ocap: 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,

    /// 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; what `--full-access` auto-selects), or
    /// `brush` (the carried bash-in-Rust engine + L2 interceptor; falls back to
    /// `host` until the brush build ships, agent-bridle#20). 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 a model's `run_command("cat X")` / `ls` / `find` /
    /// read-only `git` is silently rewritten to the governed built-in
    /// (`read_file`/`list_dir`/`find`/the git read path); `--no-route` runs the
    /// command on the normal exec path as-is instead. 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>,

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

#[derive(Subcommand, Debug)]
pub enum Command {
    /// Standalone TUI coder.
    Code {
        /// Optional working path.
        path: Option<PathBuf>,
    },
    /// 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,
    },
    /// MCP server (stdio JSON-RPC, no TUI).
    Mcp,
    /// 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,
    /// Print resolved config.
    Config,
    /// Print the resolved agent commit identity (`.newt/agent-identity.toml`):
    /// name, email, the layer it resolved from, the signing-key path +
    /// fingerprint (if it loads), the GitHub App's public coordinates, and the
    /// configured token NAMES. Never prints a secret value.
    Identity,
    /// 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,
    /// Interactive first-run setup: choose Ollama or DGX, pick a model from the
    /// endpoint, preview, and write ~/.newt/config.toml. Unlike `init` (which
    /// silently auto-probes Ollama), this prompts the human through each choice.
    Setup,
    /// 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 them to
    /// `~/.hermes/mcp-tokens/`. Both newt and hermes-agent share the same token
    /// store, so this authenticates both.
    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,
    },
}

/// 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)))
}

pub async fn dispatch(cli: Cli) -> anyhow::Result<()> {
    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) };
    }

    // 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 = format!("{venv}/bin");
        let mut path = std::env::var("PATH").unwrap_or_default();
        if !path.split(':').any(|p| p == venv_bin) {
            path = format!("{venv_bin}:{path}");
        }
        unsafe { std::env::set_var("PATH", path) };
    }

    // --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) };
    }

    match cli.command.unwrap_or(Command::Code { path: None }) {
        Command::Code { 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 = newt_core::Config::resolve()?;
                    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);
                            }
                        }
                        // 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);
                            }
                        }
                    }
                    // 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.
            {
                let session = newt_core::settings::load();
                if !session.is_empty() {
                    let cfg = newt_core::Config::resolve().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") };
            }
            // --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") };
            }
            // --shell-engine selects which agent-bridle engine run_command uses
            // (ADR 0005 D2 seam). Resolved ONCE here — precedence
            // `--shell-engine` > `[shell] engine` > `--full-access`→`host` >
            // `safe-subset` — and published via NEWT_SHELL_ENGINE for newt-core's
            // dispatch to read (same env pattern as NEWT_FULL_ACCESS).
            {
                let configured = newt_core::Config::resolve()
                    .ok()
                    .and_then(|c| c.shell.and_then(|s| s.engine));
                let engine =
                    newt_core::resolve_shell_engine(cli.shell_engine, configured, cli.full_access);
                unsafe { std::env::set_var("NEWT_SHELL_ENGINE", engine.as_str()) };
            }
            // 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 = newt_core::Config::resolve()
                .ok()
                .and_then(|c| c.tui)
                .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.
                newt_core::Config::resolve().ok().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(cli.config.as_deref()).await;
            newt_tui::run_code(
                path.as_deref(),
                no_splash,
                persona,
                team_runner
                    .as_ref()
                    .map(|r| r as &dyn newt_core::agentic::CrewRunner),
            )
        }
        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,
        Command::Mcp => run_mcp().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 => doctor::run(cli.config.as_deref()).await,
        Command::Config => config_cmd::run(cli.config.as_deref()),
        Command::Identity => identity_cmd::run(cli.config.as_deref()),
        Command::Init => newt_tui::run_init(newt_tui::color_supported()),
        Command::Setup => 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()),
    }
}

/// 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<()> {
    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.
    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, \
                     or use --allow-no-key (debug only) to fall back to top()"
                )
            })?;

    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`].
async fn run_mcp() -> anyhow::Result<()> {
    #[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).await
            }
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "stdio_guard fd redirect failed; falling back to raw stdout"
                );
                newt_mcp_server::run_stdio().await
            }
        }
    }
    #[cfg(not(unix))]
    {
        newt_mcp_server::run_stdio().await
    }
}

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

    #[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 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 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);
    }

    // ── 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 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 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;
        // A leading ~ expands to the home dir. Use a platform-absolute HOME so
        // the expansion is itself absolute on both Unix and Windows (a bare
        // `/home/u` is NOT absolute on Windows, where it would be re-based).
        let home = if cfg!(windows) {
            r"C:\home\u"
        } else {
            "/home/u"
        };
        std::env::set_var("HOME", home);
        assert_eq!(
            abs_grant_path(Path::new("~/.newt")),
            PathBuf::from(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"));
    }

    #[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_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:?}"),
        }
    }
}