newt-agent 0.8.2

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
//! `newt doctor` — health-check local backends and provider plugins.

#[path = "doctor/durable_grants.rs"]
mod durable_grants;

use newt_core::dgx::{DgxConfig, EndpointKind};
use newt_core::ocap::SecurityReport;
use newt_core::Config;
use newt_inference::local::LocalOllamaBackend;
use newt_tui::{classify_readiness, readiness_label, McpReadiness};
use std::path::Path;

/// Render the achieved-security report as `doctor` posture lines. Pure over the
/// report so it is testable without a live host: one honest line per guarantee,
/// derived from the report (never independent prose), and headed with the
/// platform so an unsupported platform's lines read `unsupported on <plat>`.
fn security_posture_lines(report: &SecurityReport) -> Vec<String> {
    let mut lines = Vec::with_capacity(report.summary_lines().len() + 1);
    lines.push(format!("platform: {}", report.platform));
    lines.extend(report.summary_lines());
    lines
}

pub async fn run(config_path: Option<&Path>, fix: bool) -> anyhow::Result<()> {
    println!("newt doctor — checking backends\n");

    println!("Push tool paths:");
    for line in newt_core::git_staging::tool_diagnostics::diagnose_tool_paths().lines {
        println!("  {line}");
    }

    // #1951: a resolution failure is exactly what doctor exists to diagnose —
    // `?` here used to end the whole command with that same failure before a
    // single line of diagnosis printed, which is the defect an operator hit
    // live (a legacy backend drop-in newt could not attribute). Render it as
    // a finding and keep going with everything that does not need a resolved
    // config; only the sections built from `config` below are skipped.
    let config = match config_path {
        Some(p) => crate::migration_notices::read(|report| Config::load(p, report)),
        None => crate::migration_notices::read(|report| Config::resolve(report)),
    };
    let config = match config {
        Ok(c) => Some(c),
        Err(e) => {
            println!("FINDING: config did not resolve — {e}\n");
            None
        }
    };

    // File-level drop-in diagnostics run regardless: they are the ONLY
    // visibility left once resolution has failed, and per-file rather than
    // aggregate, so a second bad file is not hidden behind the first the way
    // `Config::resolve`'s merge (which stops at its first unattributable
    // file) would hide it.
    diagnose_backend_dropins(fix, config.is_some()).await;
    durable_grants::diagnose(config.as_ref(), fix);

    let Some(config) = config else {
        println!(
            "\n(backend/provider/DGX/MCP checks skipped — config did not resolve; \
             see the finding above)"
        );
        return Ok(());
    };

    println!("\nConfigured backends:");
    for backend in &config.backends {
        // #1212: probe by the backend's declared KIND via the BackendApi trait
        // — an openai/vLLM backend answers `/v1/models`, not Ollama's
        // `/api/tags`, and probing the wrong surface reported healthy
        // endpoints as `HTTP 404`. The kind knowledge lives in `api_for`,
        // not here (three-Cs).
        let status = probe_configured_backend(backend).await;
        println!(
            "  {} ({}, {}) — {status}",
            backend.name,
            backend.endpoint,
            backend.kind_label()
        );
        // Credential verdict (encrypted token store, unboxing bundle): where
        // the bearer comes from and whether it is usable right now.
        if let Some(line) = token_status_line(
            backend.api_key_env.as_deref(),
            backend.api_key_file.as_deref(),
        ) {
            println!("    token: {line}");
        }
    }

    println!("\nConfigured providers:");
    if config.providers.is_empty() {
        println!("  (none)");
    }
    for provider in &config.providers {
        let status = probe_provider(&provider.command);
        println!(
            "  {} (command: {}) — {status}",
            provider.name, provider.command
        );
    }

    // DGX nodes from [dgx] config section.
    println!("\nDGX nodes:");
    match &config.dgx {
        None => println!("  (none configured)"),
        Some(dgx) => probe_dgx(dgx).await,
    }

    // Also try endpoint discovery.
    println!("\nEndpoint discovery:");
    match LocalOllamaBackend::discover("default").await {
        Ok(backend) => println!("  Ollama: reachable at {}", backend.endpoint()),
        Err(e) => println!("  Ollama: {e}"),
    }

    // Discovered MCP servers — newt's own `[[mcp_servers]]` merged with the
    // servers already configured for Claude Code (~/.claude.json + ./.mcp.json),
    // so you can confirm newt sees the same set without re-configuring anything.
    // Shell engine + OCAP posture (#868 / #926): which engine parses run_command
    // (L2) and which kernel backend fences it (L3) — separate axes.
    println!("\nShell engine (OCAP):");
    let (backend, l3_active) = newt_core::ocap_l3_backend();
    let worker_available = newt_core::ShellEngine::Brush.validate_available().is_ok();
    match config.shell.as_ref().and_then(|s| s.engine) {
        Some(engine) => {
            println!("  configured engine (L2): {engine} (explicit [shell] engine)");
            if let Err(reason) = engine.validate_available() {
                println!("  startup refusal: {reason}");
            }
        }
        None => {
            // #1243 Leg 1: the confined default is L3-gated and resolved
            // per-dispatch — report what THIS host resolves to right now, not a
            // stale hardcoded default. Keyed off the RESOLVED engine (not the
            // raw fence bit) so the reason is consistent on platforms where the
            // brush flip is not enabled (e.g. Windows keeps safe-subset).
            let resolved = newt_core::resolved_confined_default();
            let why = if resolved == newt_core::ShellEngine::Brush {
                "native fence and authenticated worker transport available"
            } else if !worker_available {
                "authenticated worker transport unavailable — full shell grammar unavailable"
            } else {
                "no per-run kernel fence here — safe-subset refuses dynamic constructs"
            };
            println!(
                "  confined default (L2): {resolved} — L3-gated, resolved per run_command ({why})"
            );
        }
    }
    println!("    · safe-subset — refuses $(...)/dynamic constructs (portable default)");
    println!("    · host        — real /bin/sh (full grammar; restricted grants require native confinement)");
    println!("{}", brush_engine_description(worker_available));
    println!(
        "  full-access default: {}",
        newt_core::full_access_default_engine()
    );
    println!("  override per-run: --shell-engine <safe-subset|host|brush>");
    println!(
        "  L3 kernel jail (this platform): {backend} — {}",
        if l3_active {
            "available"
        } else {
            "NOT available → a restricted fs grant is refused when its kernel floor cannot be met"
        }
    );
    println!(
        "  agent-bridle attenuates your full ambient authority into structural OCAP grants; \
         --full-access temporarily lifts them."
    );

    // Achieved OCAP posture, per guarantee (#11 / #12). Every line is DERIVED
    // from the same `verify_*` invariants the capability gates enforce (via
    // `SecurityReport::current()`), never hand-written prose — so this diagnostic
    // cannot drift from what is actually enforced, and an unsupported platform
    // reports `unsupported` rather than a Linux-equivalent claim.
    println!("\nAchieved OCAP posture (per guarantee):");
    for line in security_posture_lines(&newt_core::ocap::SecurityReport::current()) {
        println!("  {line}");
    }

    println!("\nMCP servers (newt config + Claude Code config):");
    let home = std::env::var_os("HOME").map(std::path::PathBuf::from);
    let workspace = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
    let mcp_toml = newt_core::Config::user_config_dir().map(|d| d.join("mcp.toml"));
    let servers = newt_core::mcp::discover(
        &config.mcp_servers,
        mcp_toml.as_deref(),
        home.as_deref(),
        &workspace,
    );
    if servers.is_empty() {
        println!("  (none discovered)");
    }
    // The leash `doctor` spawns stdio servers under — the SAME confinement the
    // live session applies, derived from the operator's configured preset (else a
    // read-only default), NEVER `Caveats::top()` (#94: no top() in a dispatch
    // path). So the diagnostic shows each server under its real confinement.
    // Shared with `newt mcp probe` (#1292) via Config::mcp_probe_caveats.
    let mcp_caveats = config.mcp_probe_caveats(&workspace);
    // For stdio servers we actually CONNECT (spawn + initialize + tools/list)
    // so you can see whether each is reachable and which tools it offers.
    for s in &servers {
        match s.transport {
            newt_core::mcp::TransportKind::Stdio => {
                // step-1.1: admission gate — doctor does not spawn an untrusted
                // or disabled server; it reports the refusal instead.
                let admitted = match newt_core::mcp::admit(s) {
                    Ok(a) => a,
                    Err(denied) => {
                        println!("  · {} — not admitted: {denied}", s.name);
                        continue;
                    }
                };
                match newt_mcp_client::connect_stdio(&admitted, &mcp_caveats).await {
                    Ok(connected) => {
                        let names: Vec<&str> =
                            connected.tools.iter().map(|t| t.name.as_str()).collect();
                        let list = if names.is_empty() {
                            "(none)".to_string()
                        } else {
                            names.join(", ")
                        };
                        println!("  {} [stdio] — OK, {} tool(s): {list}", s.name, names.len());
                    }
                    Err(e) => println!("  {} [stdio] — ERROR: {e:#}", s.name),
                }
            }
            newt_core::mcp::TransportKind::Sse => {
                // Legacy SSE is rejected by the runtime (mcp_management.rs) —
                // never suggest `newt auth` for it; point at streamable-HTTP.
                println!(
                    "  {} [sse] — unsupported transport (legacy SSE); switch \
                     this server to a streamable-HTTP endpoint.",
                    s.name
                );
            }
            newt_core::mcp::TransportKind::Http => {
                let url = s.url.clone().unwrap_or_default();
                let readiness =
                    classify_readiness(s, &|v| std::env::var(v).ok(), &newt_tui::saved_oauth_valid);
                let auth_note = match readiness {
                    McpReadiness::NotAdmitted => {
                        format!(" ({} — cannot connect)", readiness_label(readiness))
                    }
                    McpReadiness::Configured => format!(
                        " ({} — grant net for `{url}`, then `newt auth {}`)",
                        readiness_label(readiness),
                        s.name
                    ),
                    McpReadiness::Authenticated => format!(
                        " ({} — credential present; connect via `/mcp` or `newt auth {}`)",
                        readiness_label(readiness),
                        s.name
                    ),
                };
                println!("  {} [http] — {url}{auth_note}", s.name);
            }
        }
    }

    Ok(())
}

/// The `backends/` directory [`Config::resolve`]'s merge reads: the
/// operator's only. A project's `.newt/backends/` is never merged, so doctor
/// must not parse or probe it either (it would authenticate to a
/// repo-chosen endpoint with the operator's credentials).
fn backend_dropin_dirs() -> Vec<std::path::PathBuf> {
    Config::user_config_dir()
        .map(|dir| dir.join("backends"))
        .into_iter()
        .collect()
}

/// `newt doctor`'s file-level backend drop-in diagnostics (#1951): parseable,
/// attributable (operator config vs probe residue), and shadowed — the three
/// questions [`Config::resolve`]'s merge answers only implicitly, by either
/// succeeding or aborting on the first file it cannot place. Doctor answers
/// them explicitly, per file, so one unattributable drop-in does not hide a
/// problem in a sibling the way the merge's early return would, and so this
/// still runs when resolution as a whole failed — which is exactly when it
/// is needed most (see the finding printed above this in [`run`]).
///
/// `config_resolved` gates the live endpoint probe: a resolved config already
/// probes every merged backend in "Configured backends:" below, so probing
/// again here would just repeat that output. When resolution failed, that
/// section never runs at all, and this is the only liveness check an
/// operator gets.
async fn diagnose_backend_dropins(fix: bool, config_resolved: bool) {
    println!("Backend drop-ins:");
    let mut seen_stems: std::collections::HashMap<String, std::path::PathBuf> =
        std::collections::HashMap::new();
    let mut any = false;
    for dir in backend_dropin_dirs() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        let mut paths: Vec<std::path::PathBuf> = entries
            .flatten()
            .map(|e| e.path())
            .filter(|p| p.extension().is_some_and(|x| x == "toml"))
            .collect();
        paths.sort();
        for path in paths {
            any = true;
            if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                if let Some(shadowed) = seen_stems.get(stem) {
                    println!(
                        "  {} — SHADOWED by {} (same name, lower precedence; never read)",
                        shadowed.display(),
                        path.display()
                    );
                } else {
                    seen_stems.insert(stem.to_string(), path.clone());
                }
            }

            let text = match std::fs::read_to_string(&path) {
                Ok(t) => t,
                Err(e) => {
                    println!("  {} — FINDING: cannot read ({e})", path.display());
                    continue;
                }
            };
            match newt_core::classify_backend_dropin(&text) {
                Ok(ownership) => {
                    let label = match ownership {
                        newt_core::DropinOwnership::Operator => "operator",
                        newt_core::DropinOwnership::Probe => "probe",
                        _ => "unknown ownership (newer variant than this build knows)",
                    };
                    println!("  {} — OK ({label})", path.display());
                    if !config_resolved {
                        if let Ok(backend) = toml::from_str::<newt_core::BackendConfig>(&text) {
                            if !backend.endpoint.is_empty()
                                && backend.kind != Some(newt_core::BackendKind::Embedded)
                            {
                                let status = probe_configured_backend(&backend).await;
                                println!("    live: {status}");
                            }
                        }
                    }
                }
                Err(reason) => {
                    println!("  {} — FINDING: {reason}", path.display());
                    if fix {
                        repair_ambiguous_dropin(&path, &text).await;
                    }
                }
            }
        }
    }
    if !any {
        println!("  (none)");
    }
}

/// Offer the interactive repair for a drop-in doctor could not attribute:
/// claim it as operator configuration, or discard it as probe residue —
/// mirroring `newt dgx adopt`'s three-way drift menu (the one existing
/// non-TUI consumer of [`newt_core::InteractionDefinition`]) rather than
/// inventing a second convention. Checks `is_tty` itself, before requesting
/// the terminal, the same way that menu does — a piped or headless run
/// refuses to guess (C0b) and reports only, exactly as without `--fix`.
async fn repair_ambiguous_dropin(path: &Path, text: &str) {
    use std::io::IsTerminal as _;
    if !std::io::stdin().is_terminal() {
        println!("    --fix needs a terminal to choose — refusing to guess, nothing changed");
        return;
    }
    let menu = newt_core::interaction_form::menu(
        format!("{}: operator record or probe residue?", path.display()),
        "carries the old newt-adopt probe marker plus operator-looking fields — \
         ambiguous, so nothing changes until you choose",
        &[
            (
                "o",
                "claim as operator config (tag record = \"operator_v1\", keep every field)",
            ),
            (
                "d",
                "discard as probe residue (delete the file; newt re-probes on next use)",
            ),
        ],
    );
    let window = newt_core::tty::Terminal::suspend_for_prompt(
        newt_core::tty::TerminalTaker::PlainCliConfirm,
    );
    let picked = newt_core::interaction_terminal::resolve_on_terminal(&window, &menu);
    match picked.as_ref().map(|id| id.as_str()) {
        Some("o") => match newt_core::claim_backend_dropin_as_operator(text) {
            Ok(claimed) => {
                match newt_core::atomic_fs::ResolvedPath::resolve(path)
                    .and_then(|dest| dest.atomic_write(claimed.as_bytes()))
                {
                    Ok(()) => println!("    fixed: claimed as operator configuration"),
                    Err(e) => println!("    fix failed: {e:#}"),
                }
            }
            Err(e) => println!("    fix failed: {e}"),
        },
        Some("d") => match std::fs::remove_file(path) {
            Ok(()) => println!("    fixed: deleted (probe residue) — newt re-probes on next use"),
            Err(e) => println!("    fix failed: {e}"),
        },
        _ => println!("    no repair chosen — file left as-is"),
    }
}

async fn probe_dgx(dgx: &DgxConfig) {
    let active_node_name = dgx.active_node.as_deref();
    let active_endpoint = dgx.active_endpoint;
    let active_model = dgx.active_model.as_deref().unwrap_or("(none)");

    if dgx.nodes.is_empty() {
        println!("  (no nodes — using env overrides only)");
    }

    for node in &dgx.nodes {
        let is_active_node = active_node_name.map_or(dgx.nodes.len() == 1, |n| n == node.name);
        let node_marker = if is_active_node { " [active node]" } else { "" };
        println!("  {}{node_marker}", node.name);

        for kind in EndpointKind::ALL {
            let Some(url) = node.endpoint(kind) else {
                continue;
            };
            let is_active_ep = is_active_node && kind == active_endpoint;
            let active_marker = if is_active_ep { " *" } else { "" };
            let status = if kind.is_openai_compatible() {
                probe_vllm(url).await
            } else {
                probe_backend(url).await
            };
            println!("    {kind} ({url}){active_marker} — {status}");
        }
    }

    // Resolve and show the active endpoint URL (may come from env vars too).
    match dgx.resolve_endpoint() {
        Ok(url) => println!("  Active: {active_model} @ {active_endpoint} → {url}"),
        Err(e) => println!("  Active endpoint: unresolved ({e})"),
    }
}

/// Probe a `[[backends]]` entry the way a session would reach it (#1212):
/// route by `kind` through [`newt_core::backend_probe::api_for`] — the same
/// list-models call session-start adoption makes, with the same auth. When
/// `kind` is unset, race protocols via [`newt_core::backend_probe::detect_endpoint`].
/// An `embedded` backend has no endpoint to probe; report it as in-process.
async fn probe_configured_backend(backend: &newt_core::config::BackendConfig) -> String {
    if backend.kind == Some(newt_core::config::BackendKind::Embedded) {
        return "in-process (embedded — no endpoint to probe)".to_string();
    }
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(2))
        .build()
        .unwrap();
    let api_key = backend.resolve_api_key();
    if backend.needs_kind_probe() {
        return match newt_core::backend_probe::detect_endpoint(
            &client,
            &backend.endpoint,
            api_key.as_deref(),
        )
        .await
        {
            Ok(probe) => format!(
                "OK (detected {}, {} model(s) served)",
                probe.kind.label(),
                probe.models.len()
            ),
            Err(e) if e.to_string().starts_with("HTTP ") => e.to_string(),
            Err(e) => format!("unreachable: {e}"),
        };
    }
    let kind = backend.kind.expect("needs_kind_probe was false");
    match newt_core::backend_probe::api_for(kind)
        .list_models(&client, &backend.endpoint, api_key.as_deref())
        .await
    {
        Ok(models) => format!("OK ({} model(s) served)", models.len()),
        // The fetchers bail with `HTTP <status>` for a reachable-but-erroring
        // endpoint — keep that distinct from a connection failure.
        Err(e) if e.to_string().starts_with("HTTP ") => e.to_string(),
        Err(e) => format!("unreachable: {e}"),
    }
}

/// One human line for a backend's credential state, `None` when no
/// credential is configured at all (most local backends — no noise).
fn token_status_line(api_key_env: Option<&str>, api_key_file: Option<&str>) -> Option<String> {
    use newt_core::secrets::TokenStatus;
    match newt_core::secrets::token_status(api_key_env, api_key_file) {
        TokenStatus::Unset => None,
        TokenStatus::FromEnv { var } => Some(format!("from env ${var}")),
        TokenStatus::PlaintextFile { path } => Some(format!(
            "plaintext file {} (re-run `newt setup` to store it encrypted)",
            path.display()
        )),
        TokenStatus::EncryptedUnlocked { path } => {
            Some(format!("encrypted (unlocked) — {}", path.display()))
        }
        TokenStatus::EncryptedLocked { path, reason } => Some(format!(
            "encrypted (LOCKED) — {} · {reason}",
            path.display()
        )),
        TokenStatus::MissingFile { path } => Some(format!("file missing — {}", path.display())),
    }
}

async fn probe_vllm(endpoint: &str) -> String {
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(2))
        .build()
        .unwrap();
    let url = format!("{}/v1/models", endpoint.trim_end_matches('/'));
    match client.get(&url).send().await {
        Ok(resp) if resp.status().is_success() => "OK".to_string(),
        Ok(resp) => format!("HTTP {}", resp.status()),
        Err(e) => format!("unreachable: {e}"),
    }
}

async fn probe_backend(endpoint: &str) -> String {
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(2))
        .build()
        .unwrap();
    let url = format!("{}/api/tags", endpoint.trim_end_matches('/'));
    match client.get(&url).send().await {
        Ok(resp) if resp.status().is_success() => "OK".to_string(),
        Ok(resp) => format!("HTTP {}", resp.status()),
        Err(e) => format!("unreachable: {e}"),
    }
}

fn probe_provider(command: &str) -> &'static str {
    let status = std::process::Command::new(command)
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();
    match status {
        Ok(s) if s.success() => "found on PATH",
        Ok(_) => "found but exited with error",
        Err(_) => "not found on PATH",
    }
}

/// `newt doctor --sign-ocap` (#1207): the blessing ceremony for
/// `~/.newt/ocap/approve.toml`. A PRESENT human running this command is
/// explicitly vouching for the file as it stands — every entry is re-signed
/// with the operator's root key (the same newt-identity root the session's
/// operating authority is minted from), which is the ONLY way hand-edited
/// entries become valid durable grants. High-danger targets (interpreters,
/// broad fs roots — the production danger table's judgment) are REFUSED a
/// signature, per the contract's mandatory `validate_approve` check, and are
/// reported so the operator can move them to `passkey.toml` or delete them.
///
/// Returns the process exit code: 0 = blessed (or nothing to sign); 2 = one
/// or more entries were refused (the file was still written — valid entries
/// are blessed, refused ones stay unsigned and will drop at load,
/// fail-closed). Errors bubble as `Err` (exit 1).
///
/// Re-serialising through [`newt_core::ocap_store::PolicyFile::to_toml`]
/// drops any TOML comments the operator hand-wrote into `approve.toml`.
pub fn sign_ocap() -> anyhow::Result<i32> {
    use newt_core::ocap_store::{self, PolicyFile, Verdict};

    let Some(config_path) = newt_core::Config::user_config_path() else {
        anyhow::bail!("cannot resolve the user config directory (~/.newt)");
    };
    // #2524 round 2 item 4: the SAME lock `persist_approve` (the interactive
    // "allow permanently" writer) takes — one route so an in-session grant
    // and a `--sign-ocap` run can never interleave a read-modify-write.
    let (destination, _lock) = ocap_store::lock_approve_file(&config_path)?;
    let approve_path = destination.as_path().to_path_buf();
    let text = match std::fs::read_to_string(&approve_path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            println!("nothing to sign: {} does not exist", approve_path.display());
            return Ok(0);
        }
        Err(e) => anyhow::bail!("cannot read {}: {e}", approve_path.display()),
    };
    let mut file = PolicyFile::parse(&text).map_err(|e| anyhow::anyhow!(e))?;

    let key_path = newt_identity::default_key_path()?;
    let user = newt_identity::load_or_generate(&key_path)?;

    let (signed, refused) = ocap_store::sign_approves(
        &mut file,
        newt_tui::ocap_high_danger_predicate(),
        |payload| user.sign(payload).to_bytes(),
    );
    destination
        .atomic_write(file.to_toml().map_err(|e| anyhow::anyhow!(e))?.as_bytes())
        .map_err(|e| anyhow::anyhow!("cannot write {}: {e}", approve_path.display()))?;

    println!(
        "blessed {}: {signed} entr{} signed with the root key ({})",
        approve_path.display(),
        if signed == 1 { "y" } else { "ies" },
        key_path.display()
    );
    for r in &refused {
        println!("  REFUSED: {r}");
    }

    // Prove the result the way the session will see it: reload through the
    // same verify-at-load path and report the live durable grants.
    let (set, warnings) = ocap_store::load_store(&config_path, Some(user.public().as_bytes()));
    for w in &warnings {
        println!("  load warning: {w}");
    }
    let live = set
        .files
        .get(&Verdict::Approve)
        .map(|f| f.exec.len() + f.fs.len() + f.net.len())
        .unwrap_or(0);
    println!("verified: {live} durable grant(s) live at load");

    Ok(if refused.is_empty() { 0 } else { 2 })
}

fn brush_engine_description(worker_available: bool) -> &'static str {
    if worker_available {
        "    · brush       — carried bash-in-Rust worker with static command/file policies; descendant confinement requires the native backend"
    } else {
        "    · brush       — unavailable: authenticated worker transport is not implemented on this platform; full shell grammar remains unavailable"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use newt_core::ocap::{Guarantee, RuntimeEvidence, LINUX_CEILING, MACOS_CEILING};

    /// #2929 review: `doctor` parsed a project's `.newt/backends/` drop-ins and
    /// probed them with the operator's credentials when config resolution
    /// failed. RED before the fix: the project dir was listed after the
    /// operator's. Real fs and serial: the walk reads cwd, HOME and
    /// NEWT_CONFIG_DIR, all saved and restored here.
    #[test]
    #[serial_test::serial(real_fs)]
    fn doctor_reads_only_the_operator_backend_dropins() {
        let root = tempfile::tempdir().unwrap();
        let operator = root.path().join("home/.newt");
        let repo = root.path().join("repo");
        std::fs::create_dir_all(operator.join("backends")).unwrap();
        std::fs::create_dir_all(repo.join(".newt/backends")).unwrap();
        std::fs::write(repo.join(".newt/config.toml"), "").unwrap();
        std::fs::write(
            repo.join(".newt/backends/gpu.toml"),
            "endpoint = \"http://attacker.invalid:9999\"\n",
        )
        .unwrap();
        let saved_dir = std::env::var_os(newt_core::config::NEWT_CONFIG_DIR_ENV);
        let saved_home = std::env::var_os("HOME");
        let prev = std::env::current_dir().unwrap();
        std::env::set_var(newt_core::config::NEWT_CONFIG_DIR_ENV, &operator);
        std::env::set_var("HOME", root.path().join("home"));
        std::env::set_current_dir(&repo).unwrap();
        let dirs = backend_dropin_dirs();
        std::env::set_current_dir(prev).unwrap();
        match saved_home {
            Some(v) => std::env::set_var("HOME", v),
            None => std::env::remove_var("HOME"),
        }
        match saved_dir {
            Some(v) => std::env::set_var(newt_core::config::NEWT_CONFIG_DIR_ENV, v),
            None => std::env::remove_var(newt_core::config::NEWT_CONFIG_DIR_ENV),
        }
        assert_eq!(dirs, vec![operator.join("backends")]);
    }

    #[test]
    fn brush_description_reports_transport_limit_without_parity_claims() {
        let unavailable = brush_engine_description(false);
        assert!(unavailable.contains("unavailable"));
        assert!(unavailable.contains("authenticated worker transport"));
        assert!(!unavailable.contains("Windows full-access default"));
        let available = brush_engine_description(true);
        assert!(available.contains("static command/file policies"));
        assert!(!available.contains("confines restricted exec too"));
    }

    #[test]
    fn posture_lines_are_derived_from_the_report_not_prose() {
        // #11: doctor renders exactly the report's guarantees, one line each,
        // plus a platform header — the diagnostic cannot drift from enforcement.
        let report = SecurityReport::from_parts(&LINUX_CEILING, &RuntimeEvidence::current());
        let lines = security_posture_lines(&report);
        assert_eq!(lines.len(), Guarantee::ALL.len() + 1);
        assert_eq!(lines[0], "platform: linux");
        // #1711: disclosure filtering is a per-THREAD probe, not a build-wide
        // constant. `doctor` runs with no session filter installed, so the
        // honest render is OPEN — and, like the b1 rows below, it names its
        // deviation rather than silently claiming the guarantee.
        assert!(lines
            .iter()
            .any(|l| l == "disclosure-filtering: OPEN (disclosure-gate-live-path)"));
        // …and the render still tracks the verifier: with the backstop actually
        // installed on this thread, the same code path says enforced. Without
        // this half the assertion above would pass against a render that had
        // simply hard-coded the row.
        {
            let mut filter = newt_core::ocap::DisclosureFilter::new();
            filter.register("sk-probe-9f3a2b7c1d4e6a8b");
            let _guard = newt_core::ocap::scoped_session_disclosure(filter);
            let live = SecurityReport::from_parts(&LINUX_CEILING, &RuntimeEvidence::current());
            assert!(security_posture_lines(&live)
                .iter()
                .any(|l| l == "disclosure-filtering: enforced"));
        }
        // b1-gated guarantees are honestly OPEN, not silently claimed.
        assert!(lines
            .iter()
            .any(|l| l.contains("network-confinement: OPEN (b1-os-isolation)")));
    }

    #[test]
    fn unsupported_platform_never_renders_a_linux_equivalent_claim() {
        // #12: even if every runtime verifier were Verified, a macOS render
        // reports kernel-backed guarantees as `unsupported on macos`.
        let all_verified = {
            let v = || newt_core::ocap::Verification::Verified {
                evidence: "synthetic".into(),
            };
            RuntimeEvidence {
                b1: v(),
                disclosure: v(),
                fs_object_bound: v(),
                constrained_executor: v(),
                fail_closed: v(),
            }
        };
        let report = SecurityReport::from_parts(&MACOS_CEILING, &all_verified);
        let lines = security_posture_lines(&report);
        assert_eq!(lines[0], "platform: macos");
        assert!(lines
            .iter()
            .any(|l| l == "fs-confinement: unsupported on macos"));
        assert!(lines
            .iter()
            .any(|l| l == "process-confinement: unsupported on macos"));
        // No line may claim a kernel guarantee is "enforced" on macOS.
        assert!(!lines.iter().any(|l| l == "fs-confinement: enforced"));
    }

    #[test]
    fn mcp_readiness_classifies_http_server_configured_authenticated_and_not_admitted() {
        use newt_core::mcp::{McpServerEntry, McpTrust, TransportKind};
        use newt_tui::{classify_readiness, McpReadiness};

        fn entry(transport: TransportKind, header: bool) -> McpServerEntry {
            McpServerEntry {
                name: "h".into(),
                enabled: true,
                transport,
                command: None,
                args: vec![],
                env: Default::default(),
                url: Some("https://example.test/mcp".into()),
                headers: if header {
                    [(
                        "Authorization".into(),
                        newt_core::mcp::SecretValue::literal("${TOKEN}"),
                    )]
                    .into_iter()
                    .collect()
                } else {
                    Default::default()
                },
                login_argv: Vec::new(),
                request_timeout_secs: None,
                trust: McpTrust::Trusted,
                origin: None,
            }
        }

        assert_eq!(
            classify_readiness(&entry(TransportKind::Http, false), &|_: &str| None, &|_| {
                false
            }),
            McpReadiness::Configured
        );
        // Step 2 (#2913): a `${...}` reference literal is unresolved at rest —
        // configured, but no usable credential. Only a `SecretValue::Ref`
        // (env/file/cmd secret reference) counts as authenticated — and only
        // when the referenced value actually resolves (an unset `${VAR}` is a
        // missing credential → Configured).
        let ref_entry = McpServerEntry {
            name: "h".into(),
            enabled: true,
            transport: TransportKind::Http,
            command: None,
            args: vec![],
            env: Default::default(),
            url: Some("https://example.test/mcp".into()),
            headers: [(
                "Authorization".into(),
                newt_core::mcp::SecretValue::Ref(newt_core::agent_identity::SecretRef {
                    env: Some("TOKEN".into()),
                    ..Default::default()
                }),
            )]
            .into_iter()
            .collect(),
            login_argv: Vec::new(),
            request_timeout_secs: None,
            trust: McpTrust::Trusted,
            origin: None,
        };
        // TOKEN is unset → missing credential → Configured, not Authenticated.
        assert_eq!(
            classify_readiness(&ref_entry, &|_: &str| None, &|_| false),
            McpReadiness::Configured
        );
        assert_eq!(
            classify_readiness(
                &ref_entry,
                &|v| if v == "TOKEN" {
                    Some("resolved-secret".into())
                } else {
                    None
                },
                &|_| false
            ),
            McpReadiness::Authenticated
        );
        assert_eq!(
            classify_readiness(&entry(TransportKind::Http, true), &|_: &str| None, &|_| {
                false
            }),
            McpReadiness::Configured
        );
        // Step 2 (#2913): a plaintext bearer header is rejected — it is not a
        // usable credential. A `${...}` reference header counts as configured,
        // but a literal bearer does not.
        fn plaintext_entry() -> McpServerEntry {
            McpServerEntry {
                name: "h".into(),
                enabled: true,
                transport: TransportKind::Http,
                command: None,
                args: vec![],
                env: Default::default(),
                url: Some("https://example.test/mcp".into()),
                headers: [(
                    "Authorization".into(),
                    newt_core::mcp::SecretValue::literal("Bearer deadbeef"),
                )]
                .into_iter()
                .collect(),
                login_argv: Vec::new(),
                request_timeout_secs: None,
                trust: McpTrust::Trusted,
                origin: None,
            }
        }
        assert_eq!(
            classify_readiness(&plaintext_entry(), &|_: &str| None, &|_| false),
            McpReadiness::Configured
        );
        let mut disabled = entry(TransportKind::Http, true);
        disabled.enabled = false;
        assert_eq!(
            classify_readiness(&disabled, &|_: &str| None, &|_| false),
            McpReadiness::NotAdmitted
        );
    }

    #[test]
    fn mcp_readiness_labels_are_stable_across_surfaces() {
        use newt_tui::{readiness_label, McpReadiness};
        assert_eq!(
            readiness_label(McpReadiness::Configured),
            "configured (no credential)"
        );
        assert_eq!(
            readiness_label(McpReadiness::Authenticated),
            "authenticated"
        );
        assert_eq!(readiness_label(McpReadiness::NotAdmitted), "not admitted");
    }

    // Step 1 (#2913): one classifier, shared. doctor and `newt auth` must
    // classify the same server identically — admission, header presence, and
    // reference-versus-plaintext all agree on a single fixture.
    #[test]
    fn mcp_readiness_agrees_between_doctor_and_auth() {
        use newt_core::mcp::{McpServerEntry, McpTrust, TransportKind};
        use newt_tui::{classify_readiness, McpReadiness};

        let header = |value| {
            [(
                "Authorization".into(),
                newt_core::mcp::SecretValue::literal(value),
            )]
            .into_iter()
            .collect()
        };
        let ref_header = || {
            [(
                "Authorization".into(),
                newt_core::mcp::SecretValue::Ref(newt_core::agent_identity::SecretRef {
                    env: Some("TOKEN".into()),
                    ..Default::default()
                }),
            )]
            .into_iter()
            .collect()
        };
        let entry = |headers| McpServerEntry {
            name: "h".into(),
            enabled: true,
            transport: TransportKind::Http,
            command: None,
            args: vec![],
            env: Default::default(),
            url: Some("https://example.test/mcp".into()),
            headers,
            login_argv: Vec::new(),
            request_timeout_secs: None,
            trust: McpTrust::Trusted,
            origin: None,
        };

        // Plaintext bearer: rejected by both doctor and auth.
        assert_eq!(
            classify_readiness(&entry(header("Bearer deadbeef")), &|_: &str| None, &|_| {
                false
            }),
            McpReadiness::Configured
        );
        // `${...}` reference literal: unresolved at rest, not authenticated.
        assert_eq!(
            classify_readiness(&entry(header("${TOKEN}")), &|_: &str| None, &|_| false),
            McpReadiness::Configured
        );
        // Structured secret reference: counts as configured credential only
        // when the referenced value actually resolves. TOKEN unset → missing
        // credential → Configured; TOKEN set → Authenticated.
        assert_eq!(
            classify_readiness(&entry(ref_header()), &|_: &str| None, &|_| false),
            McpReadiness::Configured
        );
        assert_eq!(
            classify_readiness(
                &entry(ref_header()),
                &|v| if v == "TOKEN" {
                    Some("resolved-secret".into())
                } else {
                    None
                },
                &|_| false
            ),
            McpReadiness::Authenticated
        );
        // No header at all: admitted but no credential.
        assert_eq!(
            classify_readiness(&entry(Default::default()), &|_: &str| None, &|_| false),
            McpReadiness::Configured
        );
    }

    // Step 3 (#2913): legacy SSE keeps its own unsupported-transport diagnosis
    // and never suggests `newt auth`. (Doctor itself never connects, so this is
    // a pure output check against the read-only SSE arm.)
    #[test]
    fn mcp_readiness_sse_never_suggests_auth() {
        use newt_core::mcp::{McpServerEntry, McpTrust, TransportKind};
        use newt_tui::{classify_readiness, readiness_label, McpReadiness};

        let entry = McpServerEntry {
            name: "sse-server".into(),
            enabled: true,
            transport: TransportKind::Sse,
            command: None,
            args: vec![],
            env: Default::default(),
            url: Some("https://example.test/mcp".into()),
            headers: Default::default(),
            login_argv: Vec::new(),
            request_timeout_secs: None,
            trust: McpTrust::Trusted,
            origin: None,
        };
        // SSE is admitted (trusted + enabled) but reports Configured — never
        // Authenticated, and never "callable". Doctor's SSE arm renders the
        // unsupported-transport line with no `newt auth` advice.
        assert_eq!(
            classify_readiness(&entry, &|_: &str| None, &|_| false),
            McpReadiness::Configured
        );
        assert_ne!(
            readiness_label(classify_readiness(&entry, &|_: &str| None, &|_| false)),
            "authenticated",
            "legacy SSE must never be presented as authenticated"
        );
    }

    // Step 3 (#2913): a valid saved OAuth login (resource- and issuer-bound,
    // unexpired, in the token store) counts as Authenticated even with no
    // Authorization header. The store status is injected — no real token
    // files, no HOME change.
    #[test]
    fn mcp_readiness_counts_valid_saved_oauth_login_as_authenticated() {
        use newt_core::mcp::{McpServerEntry, McpTrust, TransportKind};
        use newt_tui::{classify_readiness, McpReadiness};

        let resource = "https://mcp.example.test/mcp";

        let entry = McpServerEntry {
            name: "example-server".into(),
            enabled: true,
            transport: TransportKind::Http,
            command: None,
            args: vec![],
            env: Default::default(),
            url: Some(resource.to_string()),
            headers: Default::default(),
            login_argv: Vec::new(),
            request_timeout_secs: None,
            trust: McpTrust::Trusted,
            origin: None,
        };

        // No Authorization header, and the injected store reports a valid
        // saved OAuth login → Authenticated.
        assert_eq!(
            classify_readiness(&entry, &|_: &str| None, &|_| true),
            McpReadiness::Authenticated
        );

        // No Authorization header and the injected store reports no saved
        // login → Configured (nothing else supplies a credential).
        assert_eq!(
            classify_readiness(&entry, &|_: &str| None, &|_| false),
            McpReadiness::Configured
        );
    }

    // P1 (#2913): classify_readiness must NEVER resolve a secret or run a
    // command. The injected lookup seam counts resolution attempts — count must
    // stay 0 for env, file, and cmd references. If the old classifier resolved
    // the secret (or ran the command), the count would be non-zero.
    #[test]
    fn mcp_readiness_never_resolves_a_secret_or_runs_a_command() {
        use newt_core::mcp::{McpServerEntry, McpTrust, SecretValue, TransportKind};
        use newt_tui::{classify_readiness, McpReadiness};

        let executions: std::sync::Mutex<usize> = std::sync::Mutex::new(0);

        // Counting env lookup seam: every call increments the counter, but it
        // never RESOLVES a secret (no file read, no command run). Production
        // passes `std::env::var`; tests inject this seam so no process-global
        // env is touched. It returns None for every var, so the new classifier
        // (which uses the injected lookup) sees every reference as missing
        // → Configured. The old classifier bypasses this seam entirely and
        // reads real env via std::env::var — HOME is set in this environment,
        // so the old classifier resolves this secret → Authenticated — red.
        let counting_lookup = &|_var: &str| {
            *executions.lock().unwrap() += 1;
            None
        };

        // env reference — classifier must only LOOK UP, not resolve (no file
        // read, no command). The lookup returns None for HOME under the new
        // classifier → missing → Configured, with zero resolutions through the
        // seam. The old classifier ignores the seam and reads real env (HOME is
        // set) → Authenticated — red against old.
        let env_entry = McpServerEntry {
            name: "env-server".into(),
            enabled: true,
            transport: TransportKind::Http,
            command: None,
            args: vec![],
            env: Default::default(),
            url: Some("https://example.test/mcp".into()),
            headers: [(
                "Authorization".into(),
                SecretValue::Ref(newt_core::agent_identity::SecretRef {
                    env: Some("HOME".into()),
                    ..Default::default()
                }),
            )]
            .into_iter()
            .collect(),
            login_argv: Vec::new(),
            request_timeout_secs: None,
            trust: McpTrust::Trusted,
            origin: None,
        };

        // file reference — classifier must never read the file.
        let file_entry = McpServerEntry {
            name: "file-server".into(),
            enabled: true,
            transport: TransportKind::Http,
            command: None,
            args: vec![],
            env: Default::default(),
            url: Some("https://example.test/mcp".into()),
            headers: [(
                "Authorization".into(),
                SecretValue::Ref(newt_core::agent_identity::SecretRef {
                    file: Some("/nonexistent/secret.txt".into()),
                    ..Default::default()
                }),
            )]
            .into_iter()
            .collect(),
            login_argv: Vec::new(),
            request_timeout_secs: None,
            trust: McpTrust::Trusted,
            origin: None,
        };

        // cmd reference — classifier must never run the command.
        let cmd_entry = McpServerEntry {
            name: "cmd-server".into(),
            enabled: true,
            transport: TransportKind::Http,
            command: None,
            args: vec![],
            env: Default::default(),
            url: Some("https://example.test/mcp".into()),
            headers: [(
                "Authorization".into(),
                SecretValue::Ref(newt_core::agent_identity::SecretRef {
                    cmd: Some("echo token".into()),
                    ..Default::default()
                }),
            )]
            .into_iter()
            .collect(),
            login_argv: Vec::new(),
            request_timeout_secs: None,
            trust: McpTrust::Trusted,
            origin: None,
        };

        for (entry, expect_calls) in [
            (&env_entry, 1usize),  // env ref: one env lookup, no resolution
            (&file_entry, 0usize), // file ref: nothing touched
            (&cmd_entry, 0usize),  // cmd ref: nothing run
        ] {
            *executions.lock().unwrap() = 0;
            assert_eq!(
                classify_readiness(entry, counting_lookup, &|_| false),
                McpReadiness::Configured,
                "a `{:?}` reference must stay Configured — not resolved",
                entry
                    .headers
                    .iter()
                    .find(|(n, _)| n.eq_ignore_ascii_case("authorization"))
                    .map(|(_, v)| v)
            );
            assert_eq!(
                *executions.lock().unwrap(),
                expect_calls,
                "classification must not resolve env/file/cmd secrets — count stayed 0 for file/cmd, one lookup only for env"
            );
        }
    }

    // Step 1 (#2913): an env var set to whitespace-only is missing → Configured,
    // via the injected lookup only (no process-global env).
    #[test]
    fn mcp_readiness_whitespace_env_value_is_configured_not_authenticated() {
        use newt_core::mcp::{McpServerEntry, McpTrust, SecretValue, TransportKind};
        use newt_tui::{classify_readiness, McpReadiness};

        let entry = |headers| McpServerEntry {
            name: "h".into(),
            enabled: true,
            transport: TransportKind::Http,
            command: None,
            args: vec![],
            env: Default::default(),
            url: Some("https://example.test/mcp".into()),
            headers,
            login_argv: Vec::new(),
            request_timeout_secs: None,
            trust: McpTrust::Trusted,
            origin: None,
        };

        // WHITESPACE_VAR is set to spaces → missing → Configured.
        assert_eq!(
            classify_readiness(
                &entry(
                    [(
                        "Authorization".into(),
                        SecretValue::literal("Bearer ${WHITESPACE_VAR}".to_string())
                    )]
                    .into_iter()
                    .collect()
                ),
                &|v| if v == "WHITESPACE_VAR" {
                    Some("   ".into())
                } else {
                    None
                },
                &|_| false
            ),
            McpReadiness::Configured
        );
    }

    // Step 1 (#2913): a `Bearer ${env:VAR}` literal whose var is set → Authenticated.
    #[test]
    fn mcp_readiness_env_var_reference_authenticates_when_set() {
        use newt_core::mcp::{McpServerEntry, McpTrust, TransportKind};
        use newt_tui::{classify_readiness, McpReadiness};

        let entry = |headers| McpServerEntry {
            name: "h".into(),
            enabled: true,
            transport: TransportKind::Http,
            command: None,
            args: vec![],
            env: Default::default(),
            url: Some("https://example.test/mcp".into()),
            headers,
            login_argv: Vec::new(),
            request_timeout_secs: None,
            trust: McpTrust::Trusted,
            origin: None,
        };

        let bearer_env =
            |var: &str| newt_core::mcp::SecretValue::literal(format!("Bearer ${{env:{var}}}"));

        assert_eq!(
            classify_readiness(
                &entry(
                    [("Authorization".into(), bearer_env("ENV_VAR"))]
                        .into_iter()
                        .collect()
                ),
                &|v| if v == "ENV_VAR" {
                    Some("token".into())
                } else {
                    None
                },
                &|_| false
            ),
            McpReadiness::Authenticated
        );
    }

    // Step 1 (#2913): a bare `${VAR}` literal whose whole value is the
    // reference and whose var is set → Authenticated.
    #[test]
    fn mcp_readiness_bare_env_var_authenticates_when_set() {
        use newt_core::mcp::{McpServerEntry, McpTrust, TransportKind};
        use newt_tui::{classify_readiness, McpReadiness};

        let entry = |headers| McpServerEntry {
            name: "h".into(),
            enabled: true,
            transport: TransportKind::Http,
            command: None,
            args: vec![],
            env: Default::default(),
            url: Some("https://example.test/mcp".into()),
            headers,
            login_argv: Vec::new(),
            request_timeout_secs: None,
            trust: McpTrust::Trusted,
            origin: None,
        };

        let bearer_bare = |var: &str| newt_core::mcp::SecretValue::literal(format!("${{{var}}}"));

        assert_eq!(
            classify_readiness(
                &entry(
                    [("Authorization".into(), bearer_bare("BARE_VAR"))]
                        .into_iter()
                        .collect()
                ),
                &|v| if v == "BARE_VAR" {
                    Some("token".into())
                } else {
                    None
                },
                &|_| false
            ),
            McpReadiness::Authenticated
        );
    }

    // Step 2 (#2913): a literal "Bearer ${VAR}" header counts as Authenticated
    // when VAR is set and non-empty; otherwise it is Configured (unresolved).
    #[test]
    fn mcp_readiness_literal_bearer_env_var_authenticates_when_var_set() {
        use newt_core::mcp::{McpServerEntry, McpTrust, TransportKind};
        use newt_tui::{classify_readiness, McpReadiness};

        let entry = |headers| McpServerEntry {
            name: "h".into(),
            enabled: true,
            transport: TransportKind::Http,
            command: None,
            args: vec![],
            env: Default::default(),
            url: Some("https://example.test/mcp".into()),
            headers,
            login_argv: Vec::new(),
            request_timeout_secs: None,
            trust: McpTrust::Trusted,
            origin: None,
        };

        let bearer_ref =
            |var: &str| newt_core::mcp::SecretValue::literal(format!("Bearer ${{{var}}}"));

        // VAR unset → unresolved literal → Configured.
        assert_eq!(
            classify_readiness(
                &entry(
                    [("Authorization".into(), bearer_ref("BEARER_VAR_UNSET"),)]
                        .into_iter()
                        .collect()
                ),
                &|_: &str| None,
                &|_| false
            ),
            McpReadiness::Configured
        );

        // VAR set and non-empty → Authenticated.
        assert_eq!(
            classify_readiness(
                &entry(
                    [("Authorization".into(), bearer_ref("BEARER_VAR_SET"),)]
                        .into_iter()
                        .collect()
                ),
                &|v| if v == "BEARER_VAR_SET" {
                    Some("token-value".into())
                } else {
                    None
                },
                &|_| false
            ),
            McpReadiness::Authenticated
        );
    }

    // Step 2 (#2913): an explicit Authorization header decides; a valid saved
    // OAuth login applies only when there is no explicit header — they are not
    // OR'd together. The store status is injected — no real token files, no
    // HOME change.
    #[test]
    fn mcp_readiness_explicit_header_ignores_saved_oauth() {
        use newt_core::mcp::{McpServerEntry, McpTrust, TransportKind};
        use newt_tui::{classify_readiness, McpReadiness};

        let resource = "https://mcp.example.test/mcp";

        let entry = |headers| McpServerEntry {
            name: "example-server".into(),
            enabled: true,
            transport: TransportKind::Http,
            command: None,
            args: vec![],
            env: Default::default(),
            url: Some(resource.to_string()),
            headers,
            login_argv: Vec::new(),
            request_timeout_secs: None,
            trust: McpTrust::Trusted,
            origin: None,
        };

        // No Authorization header → valid saved OAuth counts as Authenticated.
        assert_eq!(
            classify_readiness(&entry(Default::default()), &|_: &str| None, &|_| true),
            McpReadiness::Authenticated
        );

        // An explicit Authorization header is present → saved OAuth is ignored,
        // not OR'd → Configured.
        assert_eq!(
            classify_readiness(
                &entry(
                    [(
                        "Authorization".into(),
                        newt_core::mcp::SecretValue::literal("Bearer deadbeef"),
                    )]
                    .into_iter()
                    .collect()
                ),
                &|_: &str| None,
                &|_| true
            ),
            McpReadiness::Configured
        );
    }
}