secretenv 0.19.0

SecretEnv CLI — resolves aliases to secrets and runs commands with them injected
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
// Copyright (C) 2026 Mandeep Patel
// SPDX-License-Identifier: AGPL-3.0-only

//! `secretenv doctor` — health checks for every configured backend.
//!
//! - **Default (Level 1+2):** is the native CLI installed and is the
//!   backend authenticated? Renders a human tree; `--json` emits a
//!   machine-readable shape for CI pre-flight gating.
//! - **`--fix`:** when a backend reports `NotAuthenticated`, run the
//!   canonical remediation CLI interactively (`aws sso login`, `op
//!   signin`, `gcloud auth login`, `az login`, `vault login`), then
//!   re-run the health check and render the post-remediation report.
//! - **`--extensive` (Level 3):** for each backend that's `Ok`, read
//!   every registry source it serves and count the aliases found,
//!   surfacing permission scope ("can read" vs "denied").
//!
//! Runs all backend `check()` calls concurrently via
//! `futures::future::join_all`. Depth probes also run concurrently per
//! backend instance.
//!
//! Exit semantics: if any backend reports a non-`Ok` status (after
//! remediation, when `--fix` is set), the command returns `Err` so the
//! process exits non-zero. Depth-probe failures are reported but do
//! not change the exit code on their own — a non-`Ok` Level 2 status
//! always dominates.
#![allow(clippy::module_name_repetitions)]

use std::collections::HashMap;
use std::fmt::Write as _;
use std::process::Stdio;

use anyhow::{anyhow, Result};
use futures::future::join_all;
use secretenv_core::{
    with_timeout, Backend, BackendRegistry, BackendStatus, BackendUri, Config,
    DEFAULT_CHECK_TIMEOUT,
};
use serde::Serialize;

/// Knobs for [`run_doctor`]. Kept as a struct so future flag additions
/// don't grow the function signature.
///
/// Four orthogonal bools; see the matching `DoctorArgs` clap struct
/// in `cli.rs` for the rationale on not collapsing into an enum.
#[derive(Debug, Clone, Copy, Default)]
#[allow(clippy::struct_excessive_bools)]
pub struct DoctorOpts {
    pub json: bool,
    pub fix: bool,
    pub extensive: bool,
    /// v0.17 Phase 6.2 — install a local in-memory `TracerProvider`,
    /// capture every span the doctor pass emits, and render them as
    /// a chronologically-sorted table after the normal report. No
    /// OTLP collector required.
    pub trace: bool,
}

/// Machine-readable shape for `--json`.
///
/// Wraps [`secretenv_core::BackendStatus`] to keep `serde` out of
/// core's public API. Kept internal to the CLI.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "status", rename_all = "snake_case")]
enum DoctorStatus {
    Ok { cli_version: String, identity: String },
    NotAuthenticated { hint: String },
    CliMissing { cli_name: String, install_hint: String },
    Error { message: String },
}

impl From<BackendStatus> for DoctorStatus {
    fn from(s: BackendStatus) -> Self {
        match s {
            BackendStatus::Ok { cli_version, identity } => Self::Ok { cli_version, identity },
            BackendStatus::NotAuthenticated { hint } => Self::NotAuthenticated { hint },
            BackendStatus::CliMissing { cli_name, install_hint } => {
                Self::CliMissing { cli_name, install_hint }
            }
            BackendStatus::Error { message } => Self::Error { message },
        }
    }
}

impl DoctorStatus {
    const fn variant_key(&self) -> &'static str {
        match self {
            Self::Ok { .. } => "ok",
            Self::NotAuthenticated { .. } => "not_authenticated",
            Self::CliMissing { .. } => "cli_missing",
            Self::Error { .. } => "error",
        }
    }
}

/// One Level 3 depth-probe result for a single registry source URI
/// served by a backend instance. Populated only when `--extensive` is set.
#[derive(Debug, Clone, Serialize)]
struct DepthProbe {
    uri: String,
    #[serde(flatten)]
    outcome: DepthOutcome,
}

#[derive(Debug, Clone, Serialize)]
#[serde(tag = "depth_status", rename_all = "snake_case")]
enum DepthOutcome {
    /// `list()` succeeded; backend returned this many entries.
    Read { entry_count: usize },
    /// `list()` failed — typically a permissions issue or missing
    /// resource. Original error message preserved.
    Failed { error: String },
}

#[derive(Debug, Clone, Serialize)]
struct DoctorEntry {
    instance_name: String,
    backend_type: String,
    #[serde(flatten)]
    status: DoctorStatus,
    /// Empty unless `--extensive` ran AND this backend was `Ok`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    depth: Vec<DepthProbe>,
}

#[derive(Debug, Clone, Serialize)]
struct DoctorSummary {
    total: usize,
    ok: usize,
    not_authenticated: usize,
    cli_missing: usize,
    error: usize,
}

impl DoctorSummary {
    fn from_entries(entries: &[DoctorEntry]) -> Self {
        let mut s =
            Self { total: entries.len(), ok: 0, not_authenticated: 0, cli_missing: 0, error: 0 };
        for entry in entries {
            match entry.status.variant_key() {
                "ok" => s.ok += 1,
                "not_authenticated" => s.not_authenticated += 1,
                "cli_missing" => s.cli_missing += 1,
                "error" => s.error += 1,
                _ => {}
            }
        }
        s
    }

    const fn all_ok(&self) -> bool {
        self.ok == self.total
    }
}

/// Per-registry-source reachability report for the `Registries` section.
///
/// "Reachable" means the backend instance referenced by the source's
/// scheme has a passing Level 2 check — not that the URI itself was
/// fetched. The heavier per-URI probe lives in `--extensive` (Level 3,
/// rendered alongside the backend it targets).
#[derive(Debug, Clone, Serialize)]
struct RegistrySourceReport {
    uri: String,
    /// Parse failure or unregistered scheme produces a source-local
    /// `Error` variant so the cascade always renders a line per source.
    #[serde(flatten)]
    status: DoctorStatus,
}

#[derive(Debug, Clone, Serialize)]
struct RegistryReport {
    name: String,
    sources: Vec<RegistrySourceReport>,
}

#[derive(Debug, Clone, Serialize)]
struct DoctorReport {
    backends: Vec<DoctorEntry>,
    /// Per-registry cascade reachability. Empty when no `[registries.*]`
    /// blocks are configured (e.g. a `--registry <uri>`-only setup).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    registries: Vec<RegistryReport>,
    summary: DoctorSummary,
    /// Set when `--fix` ran. Records each remediation attempt — the
    /// canonical CLI argv invoked and whether the child process
    /// reported success. The post-remediation re-check populates the
    /// `backends` array; this field is the audit trail.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    fix_actions: Vec<FixAction>,
    /// OpenTelemetry exporter status. Populated only when
    /// `--extensive` is set (v0.17 Phase 6.3). `None` for the default
    /// L1+L2 doctor pass — the `OTel` section is opt-in via the same
    /// flag that gates registry-read depth probes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    otel: Option<OtelStatus>,
    /// Captured trace spans rendered as the `--trace` section
    /// (v0.17 Phase 6.2). Populated only when `--trace` is set. JSON
    /// shape is a flat array sorted by start time; the human render
    /// shows one line per span with name + duration + selected
    /// attributes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    trace: Option<Vec<TraceSpanRow>>,
}

/// One captured span as rendered in the `--trace` section. Mirrors
/// [`secretenv_telemetry::LocalTraceSpan`] without the `start_unix_ms`
/// field (already sorted; the absolute timestamp is not operator-useful).
#[derive(Debug, Clone, Serialize)]
struct TraceSpanRow {
    name: String,
    duration_ms: u64,
    /// Attribute key/values lifted from the span; the render path
    /// surfaces a subset (`backend.type`, `backend.instance_name`)
    /// but JSON callers see every key/value pair.
    attributes: Vec<(String, String)>,
}

/// OpenTelemetry exporter status as surfaced by `doctor --extensive`.
/// Carries the env-driven configuration snapshot + a reachability
/// probe result for the configured endpoint.
#[derive(Debug, Clone, Serialize)]
struct OtelStatus {
    /// `true` when any `OTEL_*` env var is set that would cause
    /// `secretenv_telemetry::init` to install an exporter (i.e.
    /// `OTEL_EXPORTER_OTLP_ENDPOINT` or `OTEL_TRACES_EXPORTER=otlp`).
    configured: bool,
    /// The configured OTLP endpoint, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    endpoint: Option<String>,
    /// `service.name` resource attribute that spans/metrics will
    /// carry. Defaults to `secretenv`; overridden by
    /// `OTEL_SERVICE_NAME`.
    service_name: String,
    /// Sampler identifier. v0.17 always installs
    /// `parentbased_always_on` under the mutation-non-droppable
    /// wrapper; this string is the doc-facing render.
    sampler: String,
    /// Reachability probe result. `None` when `configured == false`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    reachability: Option<OtelReachability>,
}

/// TCP-connect reachability probe outcome for the OTLP endpoint.
/// `doctor --extensive` deliberately does NOT send a test span —
/// just confirms the port answers a TCP handshake within 1 second.
#[derive(Debug, Clone, Serialize)]
struct OtelReachability {
    ok: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    rtt_ms: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    error: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
struct FixAction {
    instance_name: String,
    backend_type: String,
    command: Vec<String>,
    success: bool,
    /// Populated only when the spawn itself failed (the binary was
    /// missing, etc.) — distinct from a child-exit-non-zero failure.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    spawn_error: Option<String>,
}

/// Run `check()` on every registered backend concurrently, build a
/// per-registry cascade reachability report, and print the combined
/// output.
///
/// Behavior depends on `opts`:
/// - `opts.fix`: each `NotAuthenticated` backend triggers an
///   interactive remediation child process; the report rendered is
///   the post-remediation state.
/// - `opts.extensive`: each `Ok` backend gets per-source depth probes
///   rendered alongside its tree node and serialized into the
///   `backends[*].depth` JSON array.
///
/// Exit semantics: the non-zero exit is driven by the post-`--fix`
/// `Backends` summary only. Depth-probe failures and registry-source
/// errors are informational. Backend-level failures already propagate
/// into every registry source that uses them, so duplicating the
/// signal would double-count.
///
/// # Errors
/// Returns `Err` — and thus a non-zero exit code — if any backend
/// reports a non-`Ok` status (after remediation, when `--fix` is on),
/// even though the human report is still printed normally. This makes
/// `secretenv doctor` usable as a CI pre-flight gate.
// v0.18 Phase 4: the doctor.registry span scope pushed this function
// past the soft 100-line cap. Splitting would not aid readability —
// the function is a sequence of distinct passes (auth check, backend
// per-instance status, registry cascade reachability, optional
// extensive probes, optional OTel reachability, trace drain, report
// emit). The line-count is a smell, not a defect.
#[allow(clippy::too_many_lines)]
pub async fn run_doctor(
    config: &Config,
    backends: &BackendRegistry,
    opts: DoctorOpts,
) -> Result<()> {
    let list: Vec<&dyn Backend> = backends.all().collect();

    // ---- v0.17 Phase 6.2: install a local in-memory tracer if
    // ---- --trace is set, so the doctor probe spans get captured
    // ---- locally and we can render the trace section after the
    // ---- normal report. doctor --trace is a one-shot, so the
    // ---- global-provider swap has no downstream consequence.
    //
    // v0.18 Sec-M-2: install() returns Result. `doctor --trace` is
    // a one-shot command at the top of the process; an already-
    // installed capture here means a programming error (no other
    // call site exists in the workspace). Map Err -> anyhow and
    // bubble; the operator sees a clear diagnostic instead of a
    // silently-swapped global provider.
    let trace_capture = if opts.trace {
        Some(
            secretenv_telemetry::LocalTraceCapture::install()
                .map_err(|e| anyhow::anyhow!("doctor --trace: {e}"))?,
        )
    } else {
        None
    };

    // ---- Pass 1: initial Level 1+2 check across all backends ----
    let mut statuses = check_all_backends(&list).await;

    // ---- Optional --fix pass ----
    let mut fix_actions: Vec<FixAction> = Vec::new();
    if opts.fix {
        let needs_remediation: Vec<usize> = statuses
            .iter()
            .enumerate()
            .filter_map(|(i, s)| matches!(s, BackendStatus::NotAuthenticated { .. }).then_some(i))
            .collect();
        for i in needs_remediation {
            let backend = list[i];
            if let Some(action) = remediate(backend).await {
                fix_actions.push(action);
            }
        }
        // Re-check only if we actually attempted at least one remediation
        // — otherwise the second pass is just network for nothing.
        if !fix_actions.is_empty() {
            statuses = check_all_backends(&list).await;
        }
    }

    // ---- Build entries (post-fix view) ----
    // Dedupe-by-scheme lookup so a registry source referencing an
    // already-checked backend instance reuses its status instead of
    // re-running `check()`. Keyed by `instance_name` (the scheme).
    let mut statuses_by_instance: HashMap<String, DoctorStatus> = HashMap::new();
    let mut entries: Vec<DoctorEntry> = Vec::with_capacity(list.len());
    // v0.18 Phase 4: capture aggregate counts BEFORE the zip consumes
    // `statuses` so the doctor.registry span can emit them.
    // v0.18 Phase 7b Code-L-6: was `as u64` residue from Phase 4;
    // saturating per Phase 6 convention.
    let backend_count = u64::try_from(statuses.len()).unwrap_or(u64::MAX);
    let failure_count =
        u64::try_from(statuses.iter().filter(|s| !matches!(s, BackendStatus::Ok { .. })).count())
            .unwrap_or(u64::MAX);
    for (b, s) in list.iter().zip(statuses) {
        let doctor_status: DoctorStatus = s.into();
        statuses_by_instance.insert(b.instance_name().to_owned(), doctor_status.clone());
        entries.push(DoctorEntry {
            instance_name: b.instance_name().to_owned(),
            backend_type: b.backend_type().to_owned(),
            status: doctor_status,
            depth: Vec::new(),
        });
    }
    entries.sort_by(|a, b| a.instance_name.cmp(&b.instance_name));

    // ---- Per-registry cascade reachability ----
    // v0.18 Phase 4 — `secretenv.doctor.registry` schema-reserved span
    // (Arch-M6 subset). Wraps the per-registry cascade-reachability
    // pass with aggregate doctor-level attributes. Sibling of the
    // existing per-backend `secretenv.doctor.backend` spans rather
    // than parent (Arch-M1 deferred to v0.20).
    let registries = {
        let (mut registry_span, _registry_guard) =
            secretenv_telemetry::SecretEnvSpan::start("secretenv.doctor.registry");
        let check_level = if opts.extensive {
            secretenv_telemetry::DoctorCheckLevel::Extensive
        } else if opts.fix {
            secretenv_telemetry::DoctorCheckLevel::Standard
        } else {
            secretenv_telemetry::DoctorCheckLevel::Quick
        };
        registry_span
            .record_doctor_check_level(check_level)
            .record_doctor_backend_count(backend_count)
            .record_doctor_failure_count(failure_count);

        let mut registry_names: Vec<&String> = config.registries.keys().collect();
        registry_names.sort();
        let mut registries: Vec<RegistryReport> = Vec::with_capacity(registry_names.len());
        for name in registry_names {
            let cfg = &config.registries[name];
            let mut sources: Vec<RegistrySourceReport> = Vec::with_capacity(cfg.sources.len());
            for raw in &cfg.sources {
                let status = source_status(raw, &statuses_by_instance);
                sources.push(RegistrySourceReport { uri: raw.clone(), status });
            }
            registries.push(RegistryReport { name: name.clone(), sources });
        }
        registries
    };

    // ---- Optional --extensive depth probes ----
    if opts.extensive {
        run_depth_probes(&list, &mut entries, &registries).await;
    }

    // ---- v0.17 Phase 6.3: --extensive OTel reachability section ----
    let otel = if opts.extensive { Some(probe_otel_status().await) } else { None };

    // ---- v0.17 Phase 6.2: drain captured spans for --trace section.
    // Done after every probe site so the table includes every span
    // the doctor pass emitted, including the per-backend ones from
    // `check_all_backends`.
    let trace = trace_capture.map(|c| {
        c.drain()
            .into_iter()
            .map(|s| TraceSpanRow {
                name: s.name,
                duration_ms: s.duration_ms,
                attributes: s.attributes,
            })
            .collect()
    });

    let summary = DoctorSummary::from_entries(&entries);
    let report = DoctorReport { backends: entries, registries, summary, fix_actions, otel, trace };

    if opts.json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        print!("{}", render_human(&report));
    }

    if report.summary.all_ok() {
        Ok(())
    } else {
        Err(anyhow!(
            "{} of {} backend(s) are not ready — see the report above",
            report.summary.total - report.summary.ok,
            report.summary.total
        ))
    }
}

/// Run `check()` against every backend concurrently. Each call is
/// wrapped in its own timeout so one wedged backend cannot hang the
/// whole doctor run; a timeout surfaces as a synthesized
/// `BackendStatus::Error` so the JSON shape stays uniform.
///
/// Each per-backend probe is also wrapped in a `secretenv.doctor.backend`
/// `SecretEnvSpan`, recording `backend.type`, `backend.instance_name`,
/// and the elapsed `duration_ms`. These spans are no-ops when no
/// `TracerProvider` is installed; the v0.17 `doctor --trace` path
/// captures them through `LocalTraceCapture` so the operator can see
/// per-backend latency without standing up an OTLP collector.
async fn check_all_backends(list: &[&dyn Backend]) -> Vec<BackendStatus> {
    join_all(list.iter().map(|b| async {
        let started = std::time::Instant::now();
        let (mut span, _guard) =
            secretenv_telemetry::SecretEnvSpan::start("secretenv.doctor.backend");
        span.record_backend_type(secretenv_telemetry::BackendType::from_runtime_str(
            b.backend_type(),
        ))
        .record_backend_instance(b.instance_name());
        let label = format!("{}::check", b.instance_name());
        let status = match with_timeout(DEFAULT_CHECK_TIMEOUT, &label, async {
            Ok(b.check().await)
        })
        .await
        {
            Ok(status) => status,
            Err(err) => BackendStatus::Error { message: err.to_string() },
        };
        let elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
        span.record_duration_ms(elapsed_ms);
        status
    }))
    .await
}

/// The canonical interactive remediation argv for a backend type. The
/// remediation IS always the native CLI's auth command — no
/// abstraction; just a lookup. `local` (no auth) and any unknown
/// backend type return `None`.
fn remediation_argv(backend_type: &str) -> Option<&'static [&'static str]> {
    match backend_type {
        "aws-ssm" | "aws-secrets" => Some(&["aws", "sso", "login"]),
        "1password" => Some(&["op", "signin"]),
        "gcp" => Some(&["gcloud", "auth", "login"]),
        "azure" => Some(&["az", "login"]),
        "vault" => Some(&["vault", "login"]),
        _ => None,
    }
}

/// Spawn the remediation CLI with inherited stdio so the user can
/// complete an interactive auth flow (SSO browser handoff, MFA prompt,
/// password entry). Returns `Some(FixAction)` describing the attempt;
/// `None` only when no remediation is known for this backend type.
async fn remediate(backend: &dyn Backend) -> Option<FixAction> {
    let argv = remediation_argv(backend.backend_type())?;
    let command: Vec<String> = argv.iter().map(|s| (*s).to_owned()).collect();
    eprintln!(
        "→ remediating '{}' [{}]: {}",
        backend.instance_name(),
        backend.backend_type(),
        command.join(" ")
    );
    let mut cmd = tokio::process::Command::new(argv[0]);
    cmd.args(&argv[1..]);
    cmd.stdin(Stdio::inherit());
    cmd.stdout(Stdio::inherit());
    cmd.stderr(Stdio::inherit());
    match cmd.status().await {
        Ok(status) => Some(FixAction {
            instance_name: backend.instance_name().to_owned(),
            backend_type: backend.backend_type().to_owned(),
            command,
            success: status.success(),
            spawn_error: None,
        }),
        Err(err) => {
            // Most likely cause: the remediation CLI itself is missing
            // from PATH (the same problem `CliMissing` flags for the
            // primary check). Surface it the same way.
            let msg = format!("failed to spawn '{}': {err}", argv[0]);
            eprintln!("{msg}");
            Some(FixAction {
                instance_name: backend.instance_name().to_owned(),
                backend_type: backend.backend_type().to_owned(),
                command,
                success: false,
                spawn_error: Some(msg),
            })
        }
    }
}

/// Per-`Ok`-backend Level 3 probes. For each backend that's `Ok`, find
/// every registry source URI in any `[registries.*]` block whose scheme
/// matches the backend's `instance_name`, then run `check_extensive`
/// against each one. Probes for one backend run sequentially against
/// that backend (most have only one source); the outer loop across
/// backends runs sequentially too — `check_extensive` is itself a CLI
/// shell-out per source, so the headline parallelism that matters
/// (multiple backends checking concurrently) was already captured by
/// `check_all_backends` above.
async fn run_depth_probes(
    list: &[&dyn Backend],
    entries: &mut [DoctorEntry],
    registries: &[RegistryReport],
) {
    for backend in list {
        let Some(entry_idx) =
            entries.iter().position(|e| e.instance_name == backend.instance_name())
        else {
            continue;
        };
        if !matches!(entries[entry_idx].status, DoctorStatus::Ok { .. }) {
            continue;
        }
        // Collect every source URI across every registry that targets
        // this backend instance. Dedupe — a config that lists the same
        // URI in two cascades would otherwise probe it twice.
        let mut seen: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
        for reg in registries {
            for src in &reg.sources {
                if let Ok(parsed) = BackendUri::parse(&src.uri) {
                    if parsed.scheme == backend.instance_name() && seen.insert(src.uri.clone()) {
                        let outcome = match backend.check_extensive(&parsed).await {
                            Ok(count) => DepthOutcome::Read { entry_count: count },
                            Err(err) => DepthOutcome::Failed { error: format!("{err:#}") },
                        };
                        entries[entry_idx].depth.push(DepthProbe { uri: src.uri.clone(), outcome });
                    }
                }
            }
        }
    }
}

/// Map a raw `sources = [...]` entry to its reachability status:
///
/// - Parse error → source-local `Error`.
/// - Scheme with no registered backend → source-local `Error` naming
///   the instance and pointing at config.toml.
/// - Everything else → reuse the already-computed backend status.
fn source_status(raw: &str, statuses_by_instance: &HashMap<String, DoctorStatus>) -> DoctorStatus {
    match BackendUri::parse(raw) {
        Ok(uri) => {
            statuses_by_instance.get(&uri.scheme).cloned().unwrap_or_else(|| DoctorStatus::Error {
                message: format!(
                    "backend instance '{}' is not configured in config.toml",
                    uri.scheme
                ),
            })
        }
        Err(e) => DoctorStatus::Error { message: format!("source '{raw}' failed to parse: {e}") },
    }
}

// `writeln!`/`write!` into a `String` is infallible — `String`'s `fmt::Write`
// impl never returns `Err`. The `.unwrap()` calls below can never panic at
// runtime, so the workspace `clippy::unwrap_used` warning is suppressed on
// these functions specifically.
#[allow(clippy::unwrap_used)]
fn render_human(report: &DoctorReport) -> String {
    let mut out = String::new();
    writeln!(out, "secretenv doctor").unwrap();
    writeln!(out, "================\n").unwrap();

    if !report.fix_actions.is_empty() {
        writeln!(out, "Remediation actions ({})", report.fix_actions.len()).unwrap();
        for action in &report.fix_actions {
            let tick = if action.success { "" } else { "" };
            writeln!(
                out,
                "  {tick} {} [{}] — {}",
                action.instance_name,
                action.backend_type,
                action.command.join(" ")
            )
            .unwrap();
            if let Some(err) = &action.spawn_error {
                writeln!(out, "{err}").unwrap();
            }
        }
        writeln!(out).unwrap();
    }

    if report.backends.is_empty() {
        writeln!(out, "No backends configured in config.toml.").unwrap();
        return out;
    }

    writeln!(out, "Backends ({} configured)", report.summary.total).unwrap();

    let last = report.backends.len() - 1;
    for (i, entry) in report.backends.iter().enumerate() {
        let branch = if i == last { "└──" } else { "├──" };
        let indent = if i == last { "    " } else { "" };
        writeln!(out, "{branch} {} [{}]", entry.instance_name, entry.backend_type).unwrap();
        render_status_block(&mut out, indent, &entry.status);
        if !entry.depth.is_empty() {
            render_depth_block(&mut out, indent, &entry.depth);
        }
    }

    if !report.registries.is_empty() {
        writeln!(out).unwrap();
        render_registries(&mut out, &report.registries);
    }

    if let Some(otel) = &report.otel {
        writeln!(out).unwrap();
        render_otel(&mut out, otel);
    }

    if let Some(trace) = &report.trace {
        writeln!(out).unwrap();
        render_trace(&mut out, trace);
    }

    writeln!(out).unwrap();
    write!(out, "Summary: {}/{} OK", report.summary.ok, report.summary.total).unwrap();
    if report.summary.not_authenticated > 0 {
        write!(out, ", {} not authenticated", report.summary.not_authenticated).unwrap();
    }
    if report.summary.cli_missing > 0 {
        write!(out, ", {} missing CLI", report.summary.cli_missing).unwrap();
    }
    if report.summary.error > 0 {
        write!(out, ", {} error", report.summary.error).unwrap();
    }
    writeln!(out).unwrap();

    out
}

/// v0.17 Phase 6.3 — render the `OTel` exporter status section.
///
/// Output shape (configured):
///
/// ```text
/// -- OpenTelemetry --------------------------------------------------
///   Exporter endpoint: http://localhost:4317
///   Connection check:  ok (TCP 12ms)
///   Service name:      secretenv
///   Sampler:           parentbased_always_on (mutation-non-droppable)
/// ```
///
/// When not configured, prints a one-line "not configured" message
/// with a pointer to the reference doc.
#[allow(clippy::unwrap_used)]
fn render_otel(out: &mut String, otel: &OtelStatus) {
    writeln!(out, "-- OpenTelemetry --------------------------------------------------").unwrap();
    if !otel.configured {
        writeln!(out, "  No exporter configured. Set OTEL_EXPORTER_OTLP_ENDPOINT to enable.")
            .unwrap();
        writeln!(out, "  Docs: docs/reference/opentelemetry.md").unwrap();
        return;
    }
    if let Some(endpoint) = &otel.endpoint {
        writeln!(out, "  Exporter endpoint: {endpoint}").unwrap();
    }
    if let Some(reach) = &otel.reachability {
        let summary = if reach.ok {
            reach.rtt_ms.map_or_else(|| "ok".to_owned(), |ms| format!("ok (TCP {ms}ms)"))
        } else {
            reach.error.clone().unwrap_or_else(|| "unreachable".to_owned())
        };
        writeln!(out, "  Connection check:  {summary}").unwrap();
    }
    writeln!(out, "  Service name:      {}", otel.service_name).unwrap();
    writeln!(out, "  Sampler:           {}", otel.sampler).unwrap();
}

/// v0.17 Phase 6.2 — render the captured-spans table.
///
/// Output shape:
///
/// ```text
/// -- Trace (local capture) ------------------------------------------
///   secretenv.doctor.backend   aws-ssm/payments        124ms
///   secretenv.doctor.backend   1password/work          341ms
///   ...
///   P95 latency (this run): 341ms   Slowest: 1password/work
/// ```
///
/// When the operator's probe pass emitted no spans (no instrumented
/// site fired, e.g. an empty backend list), prints an empty-section
/// notice instead.
#[allow(clippy::unwrap_used)]
fn render_trace(out: &mut String, spans: &[TraceSpanRow]) {
    writeln!(out, "-- Trace (local capture) ------------------------------------------").unwrap();
    if spans.is_empty() {
        writeln!(out, "  No spans captured during this doctor pass.").unwrap();
        return;
    }
    for s in spans {
        let label = backend_label_from_attrs(&s.attributes);
        writeln!(out, "  {:<28} {:<24} {:>5}ms", s.name, label, s.duration_ms).unwrap();
    }
    // P95 + slowest summary line for operator at-a-glance triage.
    let mut durations: Vec<u64> = spans.iter().map(|s| s.duration_ms).collect();
    durations.sort_unstable();
    let p95 = percentile(&durations, 95);
    if let Some(slowest) = spans.iter().max_by_key(|s| s.duration_ms) {
        writeln!(
            out,
            "  P95 latency (this run): {p95}ms   Slowest: {}",
            backend_label_from_attrs(&slowest.attributes),
        )
        .unwrap();
    }
}

/// Build the `backend.type/instance_name` label used as the second
/// column of the trace table. Falls back to `-` when neither
/// attribute is present (e.g. a future non-backend span).
fn backend_label_from_attrs(attrs: &[(String, String)]) -> String {
    let bt = attrs.iter().find(|(k, _)| k == "secretenv.backend.type").map(|(_, v)| v.as_str());
    let bi =
        attrs.iter().find(|(k, _)| k == "secretenv.backend.instance_name").map(|(_, v)| v.as_str());
    match (bt, bi) {
        (Some(t), Some(i)) => format!("{t}/{i}"),
        (Some(t), None) => t.to_owned(),
        (None, Some(i)) => i.to_owned(),
        (None, None) => "-".to_owned(),
    }
}

/// Nearest-rank percentile over a sorted slice; returns 0 on empty
/// input. Phase 6.2 uses this for the P95 line in the trace table.
fn percentile(sorted: &[u64], pct: usize) -> u64 {
    if sorted.is_empty() {
        return 0;
    }
    let rank = (pct * sorted.len()).div_ceil(100).saturating_sub(1);
    sorted[rank.min(sorted.len() - 1)]
}

/// Probe the operator's `OTel` env to populate [`OtelStatus`]. When an
/// endpoint is configured, perform a 1-second TCP-connect probe to
/// confirm the port answers — deliberately not a span export to keep
/// `doctor --extensive` side-effect-free on the collector side.
async fn probe_otel_status() -> OtelStatus {
    let endpoint_env = std::env::var("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT")
        .ok()
        .or_else(|| std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT").ok());
    let exporter_explicit = std::env::var("OTEL_TRACES_EXPORTER")
        .ok()
        .or_else(|| std::env::var("OTEL_METRICS_EXPORTER").ok())
        .filter(|v| matches!(v.as_str(), "otlp" | "console"));
    let configured = endpoint_env.is_some() || exporter_explicit.is_some();
    let service_name =
        std::env::var("OTEL_SERVICE_NAME").unwrap_or_else(|_| "secretenv".to_owned());
    let sampler = "parentbased_always_on (mutation-non-droppable)".to_owned();

    let reachability = if let Some(ep) = endpoint_env.as_deref() {
        Some(probe_otel_reachability(ep).await)
    } else {
        None
    };

    OtelStatus { configured, endpoint: endpoint_env, service_name, sampler, reachability }
}

/// 1-second TCP-connect probe against the configured endpoint.
/// Parses host:port from URLs of the shape `http://host:port`,
/// `https://host:port`, or `grpc://host:port`. Falls back to assuming
/// the input is already a `host:port` pair otherwise.
///
/// v0.18 Code-N5 / Phase 7 M-2: respects `OTEL_EXPORTER_OTLP_PROTOCOL`
/// when no explicit port is set on the endpoint. `http/protobuf` and
/// `http/json` default to port 4318 (OTLP/HTTP); `grpc` (and unset)
/// keep the prior 4317 default. Operators running an HTTP/protobuf
/// exporter no longer see a false "unreachable" diagnostic.
async fn probe_otel_reachability(endpoint: &str) -> OtelReachability {
    let protocol_default_port =
        match std::env::var("OTEL_EXPORTER_OTLP_PROTOCOL").as_deref().unwrap_or("") {
            "http/protobuf" | "http/json" => 4318,
            // grpc (default) and any unknown value fall back to the
            // OTLP/gRPC standard port.
            _ => 4317,
        };
    let host_port = parse_endpoint_host_port(endpoint, protocol_default_port);
    let started = std::time::Instant::now();
    let connect_fut = tokio::net::TcpStream::connect(&host_port);
    match tokio::time::timeout(std::time::Duration::from_secs(1), connect_fut).await {
        Ok(Ok(_stream)) => OtelReachability {
            ok: true,
            rtt_ms: Some(u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)),
            error: None,
        },
        Ok(Err(e)) => OtelReachability {
            ok: false,
            rtt_ms: None,
            error: Some(format!("TCP connect failed: {e}")),
        },
        Err(_) => OtelReachability {
            ok: false,
            rtt_ms: None,
            error: Some("TCP connect timed out after 1s".to_owned()),
        },
    }
}

/// Strip the scheme + path from an OTLP endpoint URL and return
/// `host:port`. Defaults to `default_port` when the URL omits an
/// explicit port. v0.18 Code-N5 / Phase 7 M-2: callers pass
/// 4317 (gRPC) or 4318 (HTTP) based on
/// `OTEL_EXPORTER_OTLP_PROTOCOL`.
fn parse_endpoint_host_port(endpoint: &str, default_port: u16) -> String {
    let after_scheme = endpoint.split_once("://").map_or(endpoint, |(_, rest)| rest);
    let host_port = after_scheme.split('/').next().unwrap_or(after_scheme);
    if host_port.contains(':') {
        host_port.to_owned()
    } else {
        format!("{host_port}:{default_port}")
    }
}

#[allow(clippy::unwrap_used)]
fn render_registries(out: &mut String, registries: &[RegistryReport]) {
    writeln!(out, "Registries ({} configured)", registries.len()).unwrap();
    for reg in registries {
        writeln!(out, "  {}", reg.name).unwrap();
        for source in &reg.sources {
            let tick = if matches!(source.status, DoctorStatus::Ok { .. }) { "" } else { "" };
            let suffix = source_status_suffix(&source.status);
            writeln!(out, "    {tick} {}   {suffix}", source.uri).unwrap();
            // For non-OK statuses, render a second indented line with
            // the remediation hint if one is available. Keeps the
            // one-line-per-source scan readable for a healthy cascade.
            if let Some(hint) = source_status_hint(&source.status) {
                writeln!(out, "{hint}").unwrap();
            }
        }
    }
}

#[allow(clippy::unwrap_used)]
fn render_depth_block(out: &mut String, indent: &str, depth: &[DepthProbe]) {
    writeln!(
        out,
        "{indent}  depth probe ({} {})",
        depth.len(),
        pluralize("source", "sources", depth.len())
    )
    .unwrap();
    for probe in depth {
        match &probe.outcome {
            DepthOutcome::Read { entry_count } => {
                writeln!(
                    out,
                    "{indent}{}   {} {} readable",
                    probe.uri,
                    entry_count,
                    pluralize("alias", "aliases", *entry_count)
                )
                .unwrap();
            }
            DepthOutcome::Failed { error } => {
                writeln!(out, "{indent}{}   read failed", probe.uri).unwrap();
                writeln!(out, "{indent}{error}").unwrap();
            }
        }
    }
}

const fn pluralize(singular: &'static str, plural: &'static str, n: usize) -> &'static str {
    if n == 1 {
        singular
    } else {
        plural
    }
}

/// One-line suffix describing the source's status — appended to the
/// `<tick> <uri>   ` line. For `Ok` status, this is "reachable" (the
/// per-source depth probe in `--extensive` reports counts separately).
/// For failure states, it's a short classification like "not authenticated".
fn source_status_suffix(status: &DoctorStatus) -> String {
    match status {
        DoctorStatus::Ok { .. } => "reachable".to_owned(),
        DoctorStatus::NotAuthenticated { .. } => "backend not authenticated".to_owned(),
        DoctorStatus::CliMissing { cli_name, .. } => format!("backend CLI '{cli_name}' missing"),
        DoctorStatus::Error { .. } => "backend error".to_owned(),
    }
}

/// The actionable fix-it hint for non-OK source statuses. `None` for
/// `Ok` (no remediation needed).
fn source_status_hint(status: &DoctorStatus) -> Option<&str> {
    match status {
        DoctorStatus::Ok { .. } => None,
        DoctorStatus::NotAuthenticated { hint } => Some(hint),
        DoctorStatus::CliMissing { install_hint, .. } => Some(install_hint),
        DoctorStatus::Error { message } => Some(message),
    }
}

#[allow(clippy::unwrap_used)]
fn render_status_block(out: &mut String, indent: &str, status: &DoctorStatus) {
    match status {
        DoctorStatus::Ok { cli_version, identity } => {
            writeln!(out, "{indent}✓ ready").unwrap();
            writeln!(out, "{indent}  cli:      {cli_version}").unwrap();
            writeln!(out, "{indent}  identity: {identity}").unwrap();
        }
        DoctorStatus::NotAuthenticated { hint } => {
            writeln!(out, "{indent}✗ not authenticated").unwrap();
            writeln!(out, "{indent}  {hint}").unwrap();
        }
        DoctorStatus::CliMissing { cli_name, install_hint } => {
            writeln!(out, "{indent}✗ CLI '{cli_name}' not found on PATH").unwrap();
            writeln!(out, "{indent}  install: {install_hint}").unwrap();
        }
        DoctorStatus::Error { message } => {
            writeln!(out, "{indent}✗ error").unwrap();
            writeln!(out, "{indent}  {message}").unwrap();
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    fn entry(instance: &str, ty: &str, status: DoctorStatus) -> DoctorEntry {
        DoctorEntry {
            instance_name: instance.to_owned(),
            backend_type: ty.to_owned(),
            status,
            depth: Vec::new(),
        }
    }

    fn entry_with_depth(
        instance: &str,
        ty: &str,
        status: DoctorStatus,
        depth: Vec<DepthProbe>,
    ) -> DoctorEntry {
        DoctorEntry {
            instance_name: instance.to_owned(),
            backend_type: ty.to_owned(),
            status,
            depth,
        }
    }

    fn report(entries: Vec<DoctorEntry>) -> DoctorReport {
        let summary = DoctorSummary::from_entries(&entries);
        DoctorReport {
            backends: entries,
            registries: Vec::new(),
            summary,
            fix_actions: Vec::new(),
            otel: None,
            trace: None,
        }
    }

    fn report_with_registries(
        entries: Vec<DoctorEntry>,
        registries: Vec<RegistryReport>,
    ) -> DoctorReport {
        let summary = DoctorSummary::from_entries(&entries);
        DoctorReport {
            backends: entries,
            registries,
            summary,
            fix_actions: Vec::new(),
            otel: None,
            trace: None,
        }
    }

    fn report_with_fix(entries: Vec<DoctorEntry>, fix_actions: Vec<FixAction>) -> DoctorReport {
        let summary = DoctorSummary::from_entries(&entries);
        DoctorReport {
            backends: entries,
            registries: Vec::new(),
            summary,
            fix_actions,
            otel: None,
            trace: None,
        }
    }

    // ---- From<BackendStatus> ----

    #[test]
    fn status_from_backend_status_ok() {
        let s: DoctorStatus =
            BackendStatus::Ok { cli_version: "aws-cli/2".into(), identity: "x".into() }.into();
        assert_eq!(s.variant_key(), "ok");
    }

    #[test]
    fn status_from_backend_status_not_authenticated() {
        let s: DoctorStatus = BackendStatus::NotAuthenticated { hint: "op signin".into() }.into();
        assert_eq!(s.variant_key(), "not_authenticated");
    }

    #[test]
    fn status_from_backend_status_cli_missing() {
        let s: DoctorStatus = BackendStatus::CliMissing {
            cli_name: "aws".into(),
            install_hint: "brew install awscli".into(),
        }
        .into();
        assert_eq!(s.variant_key(), "cli_missing");
    }

    #[test]
    fn status_from_backend_status_error() {
        let s: DoctorStatus = BackendStatus::Error { message: "boom".into() }.into();
        assert_eq!(s.variant_key(), "error");
    }

    // ---- Summary counting ----

    #[test]
    fn summary_counts_each_variant() {
        let entries = vec![
            entry("a", "local", DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() }),
            entry("b", "aws-ssm", DoctorStatus::NotAuthenticated { hint: "h".into() }),
            entry(
                "c",
                "op",
                DoctorStatus::CliMissing { cli_name: "op".into(), install_hint: "hint".into() },
            ),
            entry("d", "local", DoctorStatus::Error { message: "m".into() }),
            entry("e", "local", DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() }),
        ];
        let s = DoctorSummary::from_entries(&entries);
        assert_eq!(s.total, 5);
        assert_eq!(s.ok, 2);
        assert_eq!(s.not_authenticated, 1);
        assert_eq!(s.cli_missing, 1);
        assert_eq!(s.error, 1);
        assert!(!s.all_ok());
    }

    #[test]
    fn summary_all_ok_when_every_backend_ok() {
        let entries = vec![
            entry("a", "local", DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() }),
            entry("b", "local", DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() }),
        ];
        let s = DoctorSummary::from_entries(&entries);
        assert!(s.all_ok());
    }

    // ---- Human renderer ----

    #[test]
    fn render_human_includes_tree_and_ticks() {
        let r = report(vec![
            entry(
                "local",
                "local",
                DoctorStatus::Ok { cli_version: "local".into(), identity: "filesystem".into() },
            ),
            entry(
                "aws-ssm-prod",
                "aws-ssm",
                DoctorStatus::NotAuthenticated { hint: "aws sso login".into() },
            ),
        ]);
        let out = render_human(&r);
        assert!(out.contains("Backends (2 configured)"));
        assert!(out.contains("├──"));
        assert!(out.contains("└──"));
        assert!(out.contains("✓ ready"));
        assert!(out.contains("✗ not authenticated"));
        assert!(out.contains("aws sso login"));
        assert!(out.contains("Summary: 1/2 OK, 1 not authenticated"));
    }

    #[test]
    fn render_human_reports_no_backends() {
        let r = report(vec![]);
        let out = render_human(&r);
        assert!(out.contains("No backends configured"));
    }

    #[test]
    fn render_human_cli_missing_shows_install_hint() {
        let r = report(vec![entry(
            "aws-ssm",
            "aws-ssm",
            DoctorStatus::CliMissing {
                cli_name: "aws".into(),
                install_hint: "brew install awscli".into(),
            },
        )]);
        let out = render_human(&r);
        assert!(out.contains("CLI 'aws' not found"));
        assert!(out.contains("brew install awscli"));
    }

    // ---- JSON serialization ----

    #[test]
    fn json_output_has_stable_shape() {
        let r = report(vec![
            entry(
                "local",
                "local",
                DoctorStatus::Ok { cli_version: "local".into(), identity: "filesystem".into() },
            ),
            entry(
                "aws-ssm-prod",
                "aws-ssm",
                DoctorStatus::NotAuthenticated { hint: "aws sso login".into() },
            ),
        ]);
        let json = serde_json::to_value(&r).unwrap();
        // Top-level keys
        assert!(json.get("backends").is_some());
        assert!(json.get("summary").is_some());
        // Summary keys
        let summary = &json["summary"];
        assert_eq!(summary["total"], 2);
        assert_eq!(summary["ok"], 1);
        assert_eq!(summary["not_authenticated"], 1);
        // Per-backend shape: status tag + variant fields flattened.
        let ok = &json["backends"][0];
        assert_eq!(ok["instance_name"], "local");
        assert_eq!(ok["backend_type"], "local");
        assert_eq!(ok["status"], "ok");
        assert_eq!(ok["cli_version"], "local");
        assert_eq!(ok["identity"], "filesystem");
        let na = &json["backends"][1];
        assert_eq!(na["status"], "not_authenticated");
        assert_eq!(na["hint"], "aws sso login");
        // No --fix run → no fix_actions key.
        assert!(json.get("fix_actions").is_none());
        // No --extensive → no depth array on entries.
        assert!(ok.get("depth").is_none());
    }

    // ---- Registry section ----

    fn src(uri: &str, status: DoctorStatus) -> RegistrySourceReport {
        RegistrySourceReport { uri: uri.to_owned(), status }
    }

    #[test]
    fn human_output_omits_registries_section_when_empty() {
        let r = report(vec![entry(
            "local",
            "local",
            DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() },
        )]);
        let out = render_human(&r);
        assert!(!out.contains("Registries"));
    }

    #[test]
    fn human_output_renders_single_source_registry() {
        let r = report_with_registries(
            vec![entry(
                "local",
                "local",
                DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() },
            )],
            vec![RegistryReport {
                name: "default".into(),
                sources: vec![src(
                    "local:///tmp/r.toml",
                    DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() },
                )],
            }],
        );
        let out = render_human(&r);
        assert!(out.contains("Registries (1 configured)"));
        assert!(out.contains("  default"));
        assert!(out.contains("✓ local:///tmp/r.toml"));
        assert!(out.contains("reachable"));
    }

    #[test]
    fn human_output_renders_cascade_with_mixed_source_status() {
        let r = report_with_registries(
            vec![
                entry(
                    "aws-ssm-dev",
                    "aws-ssm",
                    DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() },
                ),
                entry(
                    "aws-ssm-platform",
                    "aws-ssm",
                    DoctorStatus::NotAuthenticated {
                        hint: "aws sso login --profile platform".into(),
                    },
                ),
            ],
            vec![RegistryReport {
                name: "dev".into(),
                sources: vec![
                    src(
                        "aws-ssm-dev:///secretenv/dev-registry",
                        DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() },
                    ),
                    src(
                        "aws-ssm-platform:///secretenv/org-registry",
                        DoctorStatus::NotAuthenticated {
                            hint: "aws sso login --profile platform".into(),
                        },
                    ),
                ],
            }],
        );
        let out = render_human(&r);
        assert!(
            out.contains("✓ aws-ssm-dev:///secretenv/dev-registry"),
            "expected tick on reachable source:\n{out}"
        );
        assert!(
            out.contains("✗ aws-ssm-platform:///secretenv/org-registry"),
            "expected cross on unreachable source:\n{out}"
        );
        assert!(out.contains("backend not authenticated"), "suffix: {out}");
        assert!(out.contains("→ aws sso login --profile platform"), "hint rendered:\n{out}");
    }

    #[test]
    fn human_output_handles_unparseable_source_gracefully() {
        let r = report_with_registries(
            vec![entry(
                "local",
                "local",
                DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() },
            )],
            vec![RegistryReport {
                name: "broken".into(),
                sources: vec![src(
                    "not-a-uri",
                    DoctorStatus::Error {
                        message: "source 'not-a-uri' failed to parse: malformed input".into(),
                    },
                )],
            }],
        );
        let out = render_human(&r);
        assert!(out.contains("✗ not-a-uri"));
        assert!(out.contains("backend error"));
        assert!(out.contains("failed to parse"));
    }

    #[test]
    fn json_output_includes_registries_section_when_present() {
        let r = report_with_registries(
            vec![entry(
                "aws-ssm-prod",
                "aws-ssm",
                DoctorStatus::NotAuthenticated { hint: "aws sso login".into() },
            )],
            vec![RegistryReport {
                name: "prod".into(),
                sources: vec![src(
                    "aws-ssm-prod:///secretenv/prod-reg",
                    DoctorStatus::NotAuthenticated { hint: "aws sso login".into() },
                )],
            }],
        );
        let json = serde_json::to_value(&r).unwrap();
        let registries = &json["registries"];
        assert!(registries.is_array());
        assert_eq!(registries[0]["name"], "prod");
        let first_source = &registries[0]["sources"][0];
        assert_eq!(first_source["uri"], "aws-ssm-prod:///secretenv/prod-reg");
        assert_eq!(first_source["status"], "not_authenticated");
        assert_eq!(first_source["hint"], "aws sso login");
    }

    #[test]
    fn json_output_omits_registries_key_when_empty() {
        let r = report(vec![entry(
            "local",
            "local",
            DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() },
        )]);
        let json = serde_json::to_value(&r).unwrap();
        assert!(json.get("registries").is_none(), "registries key should be omitted: {json}");
    }

    // ---- source_status helper ----

    #[test]
    fn source_status_uses_cached_backend_status_on_parse_ok() {
        let mut m = HashMap::new();
        m.insert(
            "aws-ssm-prod".to_owned(),
            DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() },
        );
        let got = source_status("aws-ssm-prod:///some/path", &m);
        assert_eq!(got.variant_key(), "ok");
    }

    #[test]
    fn source_status_errors_when_scheme_not_registered() {
        let m: HashMap<String, DoctorStatus> = HashMap::new();
        let got = source_status("aws-ssm-prod:///path", &m);
        match got {
            DoctorStatus::Error { message } => {
                assert!(
                    message.contains("aws-ssm-prod") && message.contains("not configured"),
                    "message: {message}"
                );
            }
            other => panic!("expected Error, got {other:?}"),
        }
    }

    #[test]
    fn source_status_errors_on_unparseable_uri() {
        let m: HashMap<String, DoctorStatus> = HashMap::new();
        let got = source_status("not-a-uri-at-all", &m);
        match got {
            DoctorStatus::Error { message } => {
                assert!(message.contains("not-a-uri-at-all"), "message: {message}");
                assert!(message.contains("failed to parse"), "message: {message}");
            }
            other => panic!("expected Error, got {other:?}"),
        }
    }

    // ---- remediation_argv ----

    #[test]
    fn remediation_argv_known_backends() {
        // Lock the canonical remediation command per backend type.
        // Each entry is the contract a future backend addition must
        // either match (by reusing a known type) or extend (by adding
        // its own arm).
        assert_eq!(remediation_argv("aws-ssm"), Some(&["aws", "sso", "login"][..]));
        assert_eq!(remediation_argv("aws-secrets"), Some(&["aws", "sso", "login"][..]));
        assert_eq!(remediation_argv("1password"), Some(&["op", "signin"][..]));
        assert_eq!(remediation_argv("gcp"), Some(&["gcloud", "auth", "login"][..]));
        assert_eq!(remediation_argv("azure"), Some(&["az", "login"][..]));
        assert_eq!(remediation_argv("vault"), Some(&["vault", "login"][..]));
    }

    #[test]
    fn remediation_argv_local_is_none() {
        // `local` has no auth surface — `--fix` must not try to
        // remediate it. None means the report renders as-is.
        assert_eq!(remediation_argv("local"), None);
    }

    #[test]
    fn remediation_argv_unknown_backend_is_none() {
        // Defensive — a typo or future-unrecognized backend type
        // returns None instead of panicking. The user sees
        // NotAuthenticated stay NotAuthenticated post-fix; safe
        // default.
        assert_eq!(remediation_argv("definitely-not-real"), None);
    }

    // ---- --fix render path ----

    #[test]
    fn render_human_includes_fix_actions_section() {
        let entries = vec![entry(
            "1password-personal",
            "1password",
            DoctorStatus::Ok { cli_version: "2".into(), identity: "me".into() },
        )];
        let actions = vec![FixAction {
            instance_name: "1password-personal".into(),
            backend_type: "1password".into(),
            command: vec!["op".into(), "signin".into()],
            success: true,
            spawn_error: None,
        }];
        let r = report_with_fix(entries, actions);
        let out = render_human(&r);
        assert!(out.contains("Remediation actions (1)"), "section header: {out}");
        assert!(out.contains("✓ 1password-personal [1password] — op signin"), "row: {out}");
    }

    #[test]
    fn render_human_fix_action_failure_includes_spawn_error() {
        let entries = vec![entry(
            "vault-prod",
            "vault",
            DoctorStatus::NotAuthenticated { hint: "vault login".into() },
        )];
        let actions = vec![FixAction {
            instance_name: "vault-prod".into(),
            backend_type: "vault".into(),
            command: vec!["vault".into(), "login".into()],
            success: false,
            spawn_error: Some("failed to spawn 'vault': No such file or directory".into()),
        }];
        let r = report_with_fix(entries, actions);
        let out = render_human(&r);
        assert!(out.contains("✗ vault-prod"));
        assert!(out.contains("→ failed to spawn 'vault'"), "spawn-error indented: {out}");
    }

    #[test]
    fn json_output_includes_fix_actions_when_set() {
        let entries = vec![entry(
            "azure-prod",
            "azure",
            DoctorStatus::Ok { cli_version: "2".into(), identity: "me".into() },
        )];
        let actions = vec![FixAction {
            instance_name: "azure-prod".into(),
            backend_type: "azure".into(),
            command: vec!["az".into(), "login".into()],
            success: true,
            spawn_error: None,
        }];
        let r = report_with_fix(entries, actions);
        let json = serde_json::to_value(&r).unwrap();
        let fix = json["fix_actions"].as_array().expect("fix_actions array");
        assert_eq!(fix.len(), 1);
        assert_eq!(fix[0]["instance_name"], "azure-prod");
        assert_eq!(fix[0]["backend_type"], "azure");
        assert_eq!(fix[0]["command"], serde_json::json!(["az", "login"]));
        assert_eq!(fix[0]["success"], true);
        assert!(fix[0].get("spawn_error").is_none());
    }

    // ---- --extensive render path ----

    #[test]
    fn render_human_includes_depth_block_with_alias_count() {
        let depth = vec![DepthProbe {
            uri: "aws-ssm-prod:///secretenv/prod-registry".into(),
            outcome: DepthOutcome::Read { entry_count: 12 },
        }];
        let r = report(vec![entry_with_depth(
            "aws-ssm-prod",
            "aws-ssm",
            DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() },
            depth,
        )]);
        let out = render_human(&r);
        assert!(out.contains("depth probe (1 source)"), "header: {out}");
        assert!(out.contains("✓ aws-ssm-prod:///secretenv/prod-registry"), "uri line: {out}");
        assert!(out.contains("12 aliases readable"), "count + readable: {out}");
    }

    #[test]
    fn render_human_depth_failure_includes_error() {
        let depth = vec![DepthProbe {
            uri: "vault-prod:///kv/registry".into(),
            outcome: DepthOutcome::Failed {
                error: "permission denied: user lacks 'read' on secret/kv/registry".into(),
            },
        }];
        let r = report(vec![entry_with_depth(
            "vault-prod",
            "vault",
            DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() },
            depth,
        )]);
        let out = render_human(&r);
        assert!(out.contains("✗ vault-prod:///kv/registry"));
        assert!(out.contains("→ permission denied"), "error line: {out}");
    }

    #[test]
    fn render_human_depth_block_pluralizes_correctly() {
        let depth = vec![
            DepthProbe { uri: "x:///a".into(), outcome: DepthOutcome::Read { entry_count: 1 } },
            DepthProbe { uri: "x:///b".into(), outcome: DepthOutcome::Read { entry_count: 0 } },
        ];
        let r = report(vec![entry_with_depth(
            "x",
            "local",
            DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() },
            depth,
        )]);
        let out = render_human(&r);
        // "1 source" — wait, plural() returns "" for n == 1 and "es" for n != 1.
        // Source count is 2 (so "sources"); alias counts are 1 ("alias")
        // and 0 ("aliases"). Lock both forms.
        assert!(out.contains("depth probe (2 sources)"), "plural sources: {out}");
        assert!(out.contains("1 alias readable"), "singular alias: {out}");
        assert!(out.contains("0 aliases readable"), "zero is plural: {out}");
    }

    #[test]
    fn json_output_includes_depth_array_when_populated() {
        let depth = vec![
            DepthProbe {
                uri: "gcp-prod:///registry".into(),
                outcome: DepthOutcome::Read { entry_count: 7 },
            },
            DepthProbe {
                uri: "gcp-prod:///broken".into(),
                outcome: DepthOutcome::Failed { error: "denied".into() },
            },
        ];
        let r = report(vec![entry_with_depth(
            "gcp-prod",
            "gcp",
            DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() },
            depth,
        )]);
        let json = serde_json::to_value(&r).unwrap();
        let probes = json["backends"][0]["depth"].as_array().expect("depth array");
        assert_eq!(probes.len(), 2);
        assert_eq!(probes[0]["uri"], "gcp-prod:///registry");
        assert_eq!(probes[0]["depth_status"], "read");
        assert_eq!(probes[0]["entry_count"], 7);
        assert_eq!(probes[1]["depth_status"], "failed");
        assert_eq!(probes[1]["error"], "denied");
    }

    #[test]
    fn json_omits_depth_key_when_empty() {
        // No --extensive ran → depth is empty → JSON shape stays the
        // same as the v0.3 default contract for non-extensive consumers.
        let r = report(vec![entry(
            "local",
            "local",
            DoctorStatus::Ok { cli_version: "v".into(), identity: "i".into() },
        )]);
        let json = serde_json::to_value(&r).unwrap();
        assert!(json["backends"][0].get("depth").is_none(), "depth omitted: {json}");
    }
}