secretenv 0.17.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
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
// Copyright (C) 2026 Mandeep Patel
// SPDX-License-Identifier: AGPL-3.0-only

//! `secretenv` CLI — clap definitions and the per-subcommand dispatch.
//!
//! Keep each handler short and focused: the heavy lifting lives in
//! `secretenv-core` (resolver, runner, backends). This module is pure
//! wiring.
#![allow(clippy::module_name_repetitions)]

use std::io::{self, Write};
use std::path::PathBuf;
use std::str::FromStr;

use anyhow::{anyhow, bail, Context, Result};
use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum};
use secretenv_core::{
    resolve_manifest, resolve_registry, Backend, BackendRegistry, BackendUri, Config, HistoryEntry,
    Manifest, RegistryCache, RegistrySelection,
};

/// Command-line arguments for `secretenv`.
#[derive(Debug, Parser)]
#[command(
    name = "secretenv",
    version,
    about = "Run commands with secrets injected from any backend"
)]
pub struct Cli {
    /// Path to `config.toml`. Default lookup precedence (first
    /// existing file wins):
    ///   1. `$XDG_CONFIG_HOME/secretenv/config.toml` (any platform,
    ///      explicit env var)
    ///   2. `~/.config/secretenv/config.toml` (cross-platform XDG
    ///      convention; honored on macOS since v0.16 Phase 7d for
    ///      stow / chezmoi / yadm dotfile users)
    ///   3. Platform-native: `~/Library/Application Support/secretenv/`
    ///      on macOS, `%APPDATA%\secretenv\` on Windows.
    ///
    /// On Linux #1/#2/#3 collapse to the same `~/.config/` path.
    #[arg(long, global = true)]
    pub config: Option<PathBuf>,

    #[command(subcommand)]
    pub command: Command,
}

/// Top-level subcommands.
#[derive(Debug, Subcommand)]
pub enum Command {
    /// Run a command with secrets injected as env vars.
    ///
    /// Pipe-based stdout/stderr redaction (Mode A) is on by default.
    /// Limits: a child process can still write directly to `/dev/tty`
    /// (escapes the pipe), or via `syslog(3)` / `journald` / `mmap`,
    /// or by re-fetching values via the SDK. See `docs/security.md`
    /// for the full Limits matrix.
    #[command(long_about = "\
Run a command with secrets injected as env vars.

Pipe-based stdout/stderr redaction (Mode A) is on by default. Redaction \
catches secrets that the child writes to its own stdout/stderr; it does \
NOT catch:

  - writes to /dev/tty (escapes the pipe)
  - syslog(3) / journald / kernel-level logging
  - mmap'd output
  - core dumps + post-mortem analysis
  - children that re-fetch values via an SDK directly

See `docs/security.md` for the full Limits matrix.
")]
    Run(RunArgs),
    /// Registry document operations.
    #[command(subcommand)]
    Registry(RegistryCommand),
    /// Distribution profile operations — install, list, update, and
    /// uninstall shared config fragments (v0.4).
    #[command(subcommand)]
    Profile(ProfileCommand),
    /// Print the backend URI an alias resolves to (no fetch) plus
    /// the cascade source and backend auth status.
    Resolve(ResolveArgs),
    /// Fetch a secret value by alias. Prompts for confirmation
    /// before printing to stdout.
    Get(GetArgs),
    /// Diagnose backend installation and auth state (Phase 10).
    #[command(long_about = "\
Diagnose backend installation and auth state across every configured \
registry and backend.

Runs three probe levels: L1 = CLI installed, L2 = backend authenticated, \
L3 = registry readable (--extensive).

OpenTelemetry: SecretEnv emits OTel traces, metrics, and logs when \
OTEL_EXPORTER_OTLP_ENDPOINT is set. See docs/reference/opentelemetry.md for \
the full attribute schema, span topology, and the audit-facing ALLOW/DENY \
classification of every emitted attribute. With no endpoint configured \
SecretEnv installs no exporter (zero startup overhead).\
")]
    Doctor(DoctorArgs),
    /// Initialize `config.toml` for a registry URI (Phase 11).
    Setup(SetupArgs),
    /// Generate shell completion scripts.
    Completions(CompletionsArgs),
    /// Post-hoc redaction: scrub secret values out of an existing
    /// file or stream. Reads every alias's resolved value into the
    /// tainted set and rewrites the file with `[redacted:<alias>]`
    /// substitutions (or `--redact-token <fixed>`).
    Redact(RedactArgs),
    /// `MCP` (Model Context Protocol) server operations — start the
    /// stdio-only server, or toggle the disable sentinel that gates
    /// it. See [[build-plan-v0.16-mcp]] for the full design.
    #[command(subcommand)]
    Mcp(McpCommand),
}

/// Clap-friendly mirror of `secretenv_mcp::AllowMutations`. Kept here
/// rather than `clap::ValueEnum`-deriving the upstream enum so that
/// the MCP crate's public surface doesn't gain a clap dependency.
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
#[clap(rename_all = "lowercase")]
pub enum AllowMutationsCli {
    Never,
    Confirm,
    Always,
}

impl AllowMutationsCli {
    const fn to_mcp(self) -> secretenv_mcp::AllowMutations {
        match self {
            Self::Never => secretenv_mcp::AllowMutations::Never,
            Self::Confirm => secretenv_mcp::AllowMutations::Confirm,
            Self::Always => secretenv_mcp::AllowMutations::Always,
        }
    }
}

/// Clap-friendly mirror of `secretenv_mcp::ConfirmVia`.
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
#[clap(rename_all = "lowercase")]
pub enum ConfirmViaCli {
    Auto,
    Elicitation,
    Tty,
    Notification,
    None,
}

impl ConfirmViaCli {
    const fn to_mcp(self) -> secretenv_mcp::ConfirmVia {
        match self {
            Self::Auto => secretenv_mcp::ConfirmVia::Auto,
            Self::Elicitation => secretenv_mcp::ConfirmVia::Elicitation,
            Self::Tty => secretenv_mcp::ConfirmVia::Tty,
            Self::Notification => secretenv_mcp::ConfirmVia::Notification,
            Self::None => secretenv_mcp::ConfirmVia::None,
        }
    }
}

/// `secretenv mcp <subcommand>` — `MCP` server operations.
///
/// The disable sentinel lives at `$XDG_CONFIG_HOME/secretenv/mcp-disabled`
/// and is the single source of truth for "is the server allowed to start
/// right now". `disable` writes it (optionally with an auto-expiry);
/// `enable` removes it; `serve` checks it on every start.
#[derive(Debug, Subcommand)]
pub enum McpCommand {
    /// Run the `MCP` server over stdio until the transport closes.
    /// Honors the disable sentinel — if present and unexpired, exits
    /// with a clear stderr message before binding.
    Serve {
        /// Per-launch override for `[mcp].allow_mutations`. Takes
        /// precedence over the value in `config.toml`. v0.16 Phase 7f
        /// addition for per-IDE config scoping: IDEs that don't
        /// advertise MCP elicitation (e.g. Gemini CLI 0.43.0) can
        /// register secretenv with `args: ["mcp", "serve",
        /// "--allow-mutations", "always"]` to bypass the gate
        /// (mutations still audit-logged) without globally weakening
        /// `[mcp].allow_mutations` in the user's config.
        #[arg(long, value_name = "MODE")]
        allow_mutations: Option<AllowMutationsCli>,
        /// Per-launch override for `[mcp].confirm_via`. Same precedence
        /// + scoping rationale as `--allow-mutations`.
        #[arg(long, value_name = "SURFACE")]
        confirm_via: Option<ConfirmViaCli>,
    },
    /// Disable the `MCP` server by writing the sentinel file.
    /// Subsequent `mcp serve` invocations exit immediately until
    /// either the sentinel is removed (`mcp enable`) or, when
    /// `--duration` was given, the embedded expiry has passed.
    Disable {
        /// Optional auto-expiry — e.g. `30m`, `2h`, `1d`. Without
        /// this flag the disable is indefinite (requires explicit
        /// `mcp enable` to clear).
        #[arg(long, value_name = "DURATION")]
        duration: Option<String>,
    },
    /// Re-enable the `MCP` server by removing the disable sentinel.
    /// No-op if the sentinel is already absent.
    Enable,
    /// Emit a paste-ready MCP-client config block for one of the
    /// supported IDEs (Claude Code, Cursor, Codex, VS Code Copilot,
    /// Continue, Cline, Gemini Code Assist, `OpenCode`).
    ///
    /// Default behavior: print the rendered config + the target
    /// config-file path to stdout. The operator decides whether to
    /// paste, merge, or pipe to a file. With `--write`, the helper
    /// writes the file directly — refusing if the target already
    /// exists unless `--force` is set.
    Setup {
        /// Which IDE to render for. Use `--list-ides` to see options.
        /// Required unless `--list-ides` is given.
        #[arg(long, value_name = "IDE", conflicts_with = "list_ides")]
        ide: Option<String>,
        /// Print the supported IDE keys + their config-file paths
        /// and exit. Useful when you don't remember the exact key.
        #[arg(long, conflicts_with = "ide")]
        list_ides: bool,
        /// Absolute path to the `secretenv` binary the IDE will spawn.
        /// Defaults to `secretenv` (relies on the IDE's `$PATH`).
        /// Set this to the output of `which secretenv` for portable
        /// per-IDE setup that works regardless of the IDE's shell
        /// initialization.
        #[arg(long, value_name = "PATH", default_value = "secretenv")]
        binary: String,
        /// Write the rendered config to the target file. Default is
        /// stdout. Refuses if the target file already exists unless
        /// `--force` or `--merge` is set.
        #[arg(long)]
        write: bool,
        /// With `--write`, overwrite the target file even if it
        /// already exists. Without this flag, an existing file is
        /// treated as an error and the helper exits non-zero.
        /// Mutually exclusive with `--merge`.
        #[arg(long, requires = "write", conflicts_with = "merge")]
        force: bool,
        /// With `--write`, splice the SecretEnv MCP entry into the
        /// existing file in place rather than overwriting it.
        /// Preserves sibling keys (other MCP servers, unrelated IDE
        /// settings). Supported for JSON shapes — `--ide
        /// {gemini,cursor,cline,vscode-copilot,continue}`. For
        /// `OpenCode` (JSONC) / Codex (TOML), use `--force` or paste
        /// manually. Mutually exclusive with `--force`.
        #[arg(long, requires = "write")]
        merge: bool,
    },
    /// Inspect the MCP mutation audit log.
    ///
    /// Subcommands query the log written by `mcp serve` (one JSON
    /// line per mutation tool call). Use `audit tail` for a
    /// chronological view of recent activity.
    Audit {
        #[command(subcommand)]
        cmd: AuditCommand,
    },
}

/// `secretenv mcp audit <subcommand>` — operator-facing read-only
/// view onto the mutation audit log. v0.16.2 D.3.
#[derive(Debug, Subcommand)]
pub enum AuditCommand {
    /// Print the last N audit-log entries in chronological order.
    ///
    /// Reads the active log only (rotated files like
    /// `mcp-mutations.log.1` are not consulted — merge them
    /// externally if you need full history). Output is one JSON
    /// object per line, suitable for piping into `jq`.
    Tail {
        /// How many entries to print (default 50).
        #[arg(long, value_name = "N", default_value_t = 50)]
        lines: usize,
        /// Path to the audit-log file. Default is the same XDG
        /// state-dir location `mcp serve` writes to.
        #[arg(long, value_name = "PATH")]
        path: Option<std::path::PathBuf>,
    },
}

/// `secretenv redact <path> [...]` — Mode B post-hoc file scrubber.
#[derive(Debug, Args)]
pub struct RedactArgs {
    /// Path to the file to scrub. Stdin (`-`) is reserved for a
    /// future cycle; v0.14 requires a regular-file path.
    pub path: String,
    /// Registry selection — name or direct URI. Same semantics as
    /// `secretenv run --registry`. Determines which aliases'
    /// resolved values populate the tainted set.
    #[arg(long)]
    pub registry: Option<String>,
    /// Restrict the tainted set to these alias names. Repeatable;
    /// comma-separated values also accepted. Default: every alias
    /// resolvable from the active manifest + registry cascade.
    #[arg(long, value_delimiter = ',')]
    pub alias: Vec<String>,
    /// Rewrite the file in place (atomic rename). Without this flag,
    /// the scrubbed output is written to stdout and the original
    /// file is untouched.
    #[arg(long, conflicts_with = "dry_run")]
    pub in_place: bool,
    /// When `--in-place` is set, also keep a backup of the original
    /// content at `<path><suffix>` (e.g. `--backup=.bak`).
    #[arg(long, requires = "in_place")]
    pub backup: Option<String>,
    /// Count matches without writing any output. Implies neither
    /// `--in-place` nor stdout emission.
    #[arg(long)]
    pub dry_run: bool,
    /// Bypass the foreign-owner refusal that fires when the target
    /// file's UID differs from the caller's effective UID. By
    /// default, mode B refuses such files (defense against a
    /// maliciously-planted log file in a shared directory). Pass
    /// this flag only when scrubbing a file you intend to read but
    /// do not own — e.g. a root-owned `/var/log/*` log as a
    /// non-root user with read-only intent.
    #[arg(long)]
    pub allow_foreign_owner: bool,
    /// Override the substitution token. Default is
    /// `[redacted:<alias-name>]`; pass e.g. `--redact-token '***'`
    /// for the paranoid fixed-string form.
    #[arg(long)]
    pub redact_token: Option<String>,
}

/// `secretenv profile <subcommand>` — distribution-profile operations.
#[derive(Debug, Subcommand)]
pub enum ProfileCommand {
    /// Download a profile from the canonical host (or an explicit URL)
    /// and install it into the profiles directory. Auto-merges on the
    /// next config load — no manual editing of `config.toml` needed.
    Install {
        /// Profile name. Determines both the URL (when --url is absent)
        /// and the on-disk filename under `profiles/`.
        name: String,
        /// Override the fetch URL. Useful for private / staged /
        /// filesystem-hosted (file://) profiles.
        #[arg(long)]
        url: Option<String>,
    },
    /// List installed profiles with their source URLs + install times.
    List {
        /// Emit machine-readable JSON instead of the human table.
        #[arg(long)]
        json: bool,
    },
    /// Re-fetch a profile (or all profiles when no name is given) from
    /// their stored source URL. Uses `ETag` for conditional re-fetch.
    Update {
        /// Profile name. Omit to update every installed profile.
        name: Option<String>,
    },
    /// Remove an installed profile (both the .toml and .meta.json).
    Uninstall { name: String },
}

/// `secretenv run [...] -- <command>`
///
/// `clippy::struct_excessive_bools`: this is a clap-derived
/// arg struct; refactoring booleans into a state-enum loses the
/// flag/argument-name automation. The mutex constraints between
/// `--redact` / `--no-redact` / `--i-know` are enforced by clap's
/// `conflicts_with` + `requires` attrs above.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Args)]
pub struct RunArgs {
    /// Registry selection — name (from `[registries.<name>]`) or a
    /// direct backend URI. Overrides `SECRETENV_REGISTRY` and the
    /// `default` registry.
    #[arg(long)]
    pub registry: Option<String>,

    /// Print what would be fetched without fetching or executing.
    #[arg(long)]
    pub dry_run: bool,

    /// Emit fetch progress to stderr.
    #[arg(long)]
    pub verbose: bool,

    /// Force pipe-based stdout/stderr redaction even when stdin is
    /// a TTY. PTY-bound programs (`psql`, `vim`, `ssh`) may
    /// misbehave under pipe-based stdio; use only when you've
    /// confirmed your child works without a controlling terminal.
    #[arg(long, conflicts_with = "no_redact")]
    pub redact: bool,

    /// Disable runtime stdout/stderr redaction. Falls back to the
    /// pre-v0.14 `exec()` path. Requires `--i-know` on non-TTY
    /// parents so CI logs don't accidentally print secret values
    /// when a developer typos away the default protection.
    #[arg(long, conflicts_with = "redact", requires = "i_know")]
    pub no_redact: bool,

    /// Acknowledge the audit consequences of `--no-redact` on a
    /// non-TTY parent. Required by `--no-redact` per the v0.14
    /// security invariants (SEC-INV-07). On a TTY parent, an
    /// additional interactive "type yes" prompt fires regardless of
    /// this flag.
    #[arg(long)]
    pub i_know: bool,

    /// Override the substitution token. Default is
    /// `[redacted:<alias-name>]`. Same syntax as `redact
    /// --redact-token`.
    #[arg(long)]
    pub redact_token: Option<String>,

    /// Program + arguments to execute. Use `--` to separate
    /// secretenv flags from the command.
    #[arg(trailing_var_arg = true, required = true)]
    pub command: Vec<String>,
}

/// `secretenv registry <subcommand>`
#[derive(Debug, Subcommand)]
pub enum RegistryCommand {
    /// List all aliases in the registry.
    List {
        #[arg(long)]
        registry: Option<String>,
    },
    /// Print the backend URI for a single alias.
    Get {
        /// Alias name (the left-hand side of a registry entry).
        alias: String,
        #[arg(long)]
        registry: Option<String>,
    },
    /// Set an alias to point at a backend URI.
    Set {
        alias: String,
        /// The target backend URI (e.g. `aws-ssm-prod:///prod/stripe-key`).
        uri: String,
        #[arg(long)]
        registry: Option<String>,
    },
    /// Remove an alias from the registry.
    Unset {
        alias: String,
        #[arg(long)]
        registry: Option<String>,
    },
    /// Show version history for the secret an alias resolves to.
    /// Output is most-recent-first; backends with no native history
    /// API report "unsupported".
    History {
        /// Alias name. Resolved through the cascade just like `get`.
        alias: String,
        #[arg(long)]
        registry: Option<String>,
        /// Emit machine-readable JSON instead of the human table.
        #[arg(long)]
        json: bool,
    },
    /// Migrate an alias's value from its current backend to a new one.
    ///
    /// Reads the current value via the registry pointer, writes it to
    /// the destination, then atomically flips the registry pointer to
    /// the destination URI. The source value is NOT deleted by
    /// default — pass `--delete-source` to opt into cleanup (subject
    /// to an additional post-commit confirmation that fires even
    /// under `--yes`).
    Migrate {
        /// Alias to migrate.
        alias: String,
        /// Destination backend URI (e.g. `vault-prod:///secret/payments/stripe`).
        dest_uri: String,
        /// Plan-only mode. Runs source/destination probes, prints the
        /// migration plan, exits without mutation. Required for safe
        /// rollouts.
        #[arg(long)]
        dry_run: bool,
        /// Skip the top-level confirmation prompt. The
        /// `--delete-source` extra confirmation still fires even
        /// under this flag (SEC-INV-08).
        #[arg(long, short)]
        yes: bool,
        /// Override the inferred source URI. Used for recovery flows
        /// where the registry already points at the destination but
        /// the value is still in the old backend.
        #[arg(long)]
        from: Option<String>,
        /// Opt-in: after a successful migrate, delete the source
        /// value via the source backend's `delete_secret`. Subject
        /// to a separate confirmation gate even under `--yes`.
        #[arg(long)]
        delete_source: bool,
        /// Emit machine-readable JSON to stdout instead of the
        /// human-formatted progress + summary.
        #[arg(long)]
        json: bool,
        /// Registry selection — name or direct URI. Same semantics
        /// as the other `registry` subcommands.
        #[arg(long)]
        registry: Option<String>,
    },
    /// Emit a copy-pasteable config.toml snippet + IAM/RBAC grant
    /// command for onboarding a new collaborator to the named registry.
    Invite {
        /// Registry name. Defaults to the `default` registry / value
        /// of `$SECRETENV_REGISTRY`.
        #[arg(long)]
        registry: Option<String>,
        /// Identifier (IAM username, email, etc.) the inviter wants
        /// in the grant command. Defaults to a `<INVITEE>` placeholder.
        #[arg(long)]
        invitee: Option<String>,
        /// Emit machine-readable JSON instead of the human sections.
        #[arg(long)]
        json: bool,
    },
}

/// `secretenv resolve <alias>` — print the alias → URI mapping plus
/// cascade source, env-var binding, and backend auth status. Pure
/// metadata — never fetches the secret value.
#[derive(Debug, Args)]
pub struct ResolveArgs {
    pub alias: String,
    #[arg(long)]
    pub registry: Option<String>,
    /// Emit machine-readable JSON instead of human tabular output.
    #[arg(long)]
    pub json: bool,
}

/// `secretenv get <alias>` — prompts for confirmation by default.
#[derive(Debug, Args)]
pub struct GetArgs {
    pub alias: String,
    #[arg(long)]
    pub registry: Option<String>,
    /// Skip the interactive confirmation prompt.
    #[arg(long, short)]
    pub yes: bool,
}

/// `secretenv doctor [--json] [--fix] [--extensive] [--trace]`.
///
/// Four independent operator knobs deliberately modelled as bools
/// rather than a single enum: each flag composes orthogonally
/// (`--fix --extensive --trace --json` is a meaningful combo); an
/// enum would either force the operator to remember a Cartesian
/// product of variants or split into multiple subcommands.
#[derive(Debug, Args)]
#[allow(clippy::struct_excessive_bools)]
pub struct DoctorArgs {
    /// Emit machine-readable JSON instead of human output.
    #[arg(long)]
    pub json: bool,
    /// For each `NotAuthenticated` backend, run the canonical
    /// remediation CLI (`aws sso login`, `op signin`, `gcloud auth
    /// login`, `az login`, `vault login`) interactively, then re-run
    /// the health check and render the post-remediation report.
    #[arg(long)]
    pub fix: bool,
    /// Level 3 depth probe — for each `Ok` backend, read each
    /// registry source it serves and count the aliases found, surfacing
    /// permission scope ("can read" vs "denied").
    #[arg(long)]
    pub extensive: bool,
    /// Capture spans emitted during the doctor pass into a local
    /// in-memory exporter and render them as a chronologically-sorted
    /// table. No OTLP collector required — useful for operator
    /// observability without standing up infrastructure.
    #[arg(long)]
    pub trace: bool,
}

/// `secretenv setup <registry-uri>` — bootstrap a fresh config.toml.
#[derive(Debug, Args)]
pub struct SetupArgs {
    /// Backend URI the new `config.toml` should target as
    /// `[registries.default]`. The scheme becomes the backend
    /// instance name.
    pub registry_uri: String,

    /// AWS region — required for aws-ssm backends.
    #[arg(long)]
    pub region: Option<String>,

    /// AWS profile — optional, aws-ssm only.
    #[arg(long)]
    pub profile: Option<String>,

    /// 1Password account shorthand or URL — optional, 1password only.
    #[arg(long)]
    pub account: Option<String>,

    /// Vault instance URL — required for vault backends.
    #[arg(long)]
    pub vault_address: Option<String>,

    /// Vault Enterprise namespace — optional, vault only.
    #[arg(long)]
    pub vault_namespace: Option<String>,

    /// GCP project ID — required for gcp backends.
    #[arg(long)]
    pub gcp_project: Option<String>,

    /// GCP service-account email to impersonate — optional, gcp only.
    #[arg(long)]
    pub gcp_impersonate_service_account: Option<String>,

    /// Azure Key Vault HTTPS URL — required for azure backends.
    #[arg(long)]
    pub azure_vault_url: Option<String>,

    /// Azure tenant ID or domain — optional, azure only.
    #[arg(long)]
    pub azure_tenant: Option<String>,

    /// Azure subscription ID — optional, azure only.
    #[arg(long)]
    pub azure_subscription: Option<String>,

    /// Overwrite an existing config.toml.
    #[arg(long)]
    pub force: bool,

    /// Skip the post-write health check.
    #[arg(long)]
    pub skip_doctor: bool,
}

/// `secretenv completions <shell>` — emit a shell-completion script.
#[derive(Debug, Args)]
pub struct CompletionsArgs {
    /// Target shell. One of `bash`, `zsh`, `fish`.
    pub shell: Shell,

    /// Write the script here (chmod 0o644) instead of stdout.
    #[arg(long)]
    pub output: Option<PathBuf>,
}

/// Shells we emit completion scripts for. A deliberately small set —
/// the Big Three POSIX shells. PowerShell/Elvish can be added later
/// when a user asks; there's no reason to carry the surface preemptively.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum Shell {
    Bash,
    Zsh,
    Fish,
}

impl Cli {
    /// Dispatch to the per-subcommand handler.
    ///
    /// `backends` is already populated with factories + loaded
    /// instances from `config`.
    ///
    /// # Errors
    /// Forwarded from the individual subcommand handlers.
    pub async fn run(&self, config: &Config, backends: &BackendRegistry) -> Result<()> {
        // Each branch awaits a handler that returns a typed report
        // (per Phase 6 of [[build-plan-v0.14-redact]]). v0.14 discards
        // the reports via `let _ = ...`; v0.17 wires the OTel span
        // emission to the report's `Drop` (see [[v0.14-plus-synthesis]]
        // §6) and the discard remains a no-op.
        match &self.command {
            Command::Run(args) => {
                let _: crate::reports::RunReport = cmd_run(args, config, backends).await?;
                Ok(())
            }
            Command::Registry(rc) => {
                let _: crate::reports::RegistryReport = cmd_registry(rc, config, backends).await?;
                Ok(())
            }
            Command::Resolve(args) => {
                let _: crate::reports::ResolveReport = cmd_resolve(args, config, backends).await?;
                Ok(())
            }
            Command::Get(args) => {
                let _: crate::reports::GetReport = cmd_get(args, config, backends).await?;
                Ok(())
            }
            Command::Doctor(args) => {
                crate::doctor::run_doctor(
                    config,
                    backends,
                    crate::doctor::DoctorOpts {
                        json: args.json,
                        fix: args.fix,
                        extensive: args.extensive,
                        trace: args.trace,
                    },
                )
                .await
            }
            Command::Profile(pc) => {
                let _: crate::reports::ProfileReport =
                    cmd_profile(pc, self.config.as_deref()).await?;
                Ok(())
            }
            Command::Setup(args) => {
                let _: crate::reports::SetupReport =
                    cmd_setup(args, self.config.as_deref()).await?;
                Ok(())
            }
            Command::Completions(args) => {
                let _: crate::reports::CompletionsReport = cmd_completions(args)?;
                Ok(())
            }
            Command::Redact(args) => {
                let _: crate::reports::RedactReport = cmd_redact(args, config, backends).await?;
                Ok(())
            }
            Command::Mcp(mc) => cmd_mcp(mc, self.config.clone()).await,
        }
    }
}

/// Parse a duration string of the form `<n>(s|m|h|d)` into a [`Duration`].
/// Used by `secretenv mcp disable --duration`.
fn parse_duration(s: &str) -> Result<std::time::Duration> {
    let s = s.trim();
    let (n_str, unit) = s.split_at(
        s.find(|c: char| !c.is_ascii_digit())
            .ok_or_else(|| anyhow::anyhow!("duration `{s}` missing unit suffix (s|m|h|d)"))?,
    );
    let n: u64 = n_str
        .parse()
        .with_context(|| format!("duration `{s}` has invalid numeric portion `{n_str}`"))?;
    let secs = match unit {
        "s" => n,
        "m" => n * 60,
        "h" => n * 60 * 60,
        "d" => n * 60 * 60 * 24,
        other => {
            anyhow::bail!("duration `{s}` has unknown unit `{other}` (use s|m|h|d)")
        }
    };
    Ok(std::time::Duration::from_secs(secs))
}

/// Dispatch for `secretenv mcp <subcommand>`. `config_path` is the
/// global `--config <path>` flag (resolved to `None` for the XDG
/// default); `secretenv_mcp::serve` loads the [`Config`] itself so it
/// can `Arc`-wrap and own it. `mcp disable` / `mcp enable` are pure
/// sentinel-file operations and ignore `config_path`.
async fn cmd_mcp(mc: &McpCommand, config_path: Option<PathBuf>) -> Result<()> {
    match mc {
        McpCommand::Serve { allow_mutations, confirm_via } => {
            let overrides = secretenv_mcp::PolicyOverrides {
                allow_mutations: allow_mutations.map(AllowMutationsCli::to_mcp),
                confirm_via: confirm_via.map(ConfirmViaCli::to_mcp),
            };
            secretenv_mcp::serve_with_overrides(config_path, overrides).await
        }
        McpCommand::Disable { duration } => {
            let d = duration.as_deref().map(parse_duration).transpose()?;
            let path = secretenv_mcp::disable(d)?;
            match d {
                None => eprintln!(
                    "SecretEnv MCP server disabled (indefinite). Sentinel: {}",
                    path.display()
                ),
                Some(dur) => eprintln!(
                    "SecretEnv MCP server disabled for {} seconds. Sentinel: {}",
                    dur.as_secs(),
                    path.display()
                ),
            }
            Ok(())
        }
        McpCommand::Enable => {
            secretenv_mcp::enable()?;
            eprintln!("SecretEnv MCP server enabled (disable sentinel cleared).");
            Ok(())
        }
        McpCommand::Setup { ide, list_ides, binary, write, force, merge } => {
            cmd_mcp_setup(ide.as_deref(), *list_ides, binary, *write, *force, *merge)
        }
        McpCommand::Audit { cmd } => cmd_mcp_audit(cmd),
    }
}

/// `secretenv mcp audit <subcommand>` dispatch. v0.16.2 D.3.
fn cmd_mcp_audit(cmd: &AuditCommand) -> Result<()> {
    match cmd {
        AuditCommand::Tail { lines, path } => {
            let log_path = match path {
                Some(p) => p.clone(),
                None => secretenv_mcp::audit_log::default_audit_log_path()
                    .context("resolving default audit-log path")?,
            };
            let entries = secretenv_mcp::audit_log::tail_entries(&log_path, *lines)
                .with_context(|| format!("reading audit log at `{}`", log_path.display()))?;
            for entry in &entries {
                let line = serde_json::to_string(entry)
                    .context("serializing audit-log entry for output")?;
                println!("{line}");
            }
            Ok(())
        }
    }
}

/// `secretenv mcp setup` dispatch — print or write per-IDE config.
#[allow(clippy::too_many_lines, clippy::fn_params_excessive_bools)] // list/write/force/merge are 4 mutually-modal flags
fn cmd_mcp_setup(
    ide: Option<&str>,
    list_ides: bool,
    binary: &str,
    write: bool,
    force: bool,
    merge: bool,
) -> Result<()> {
    use secretenv_mcp::setup::{
        expand_home, find_profile, merge_config_into_file, render_config, MergeOutcome,
        IDE_PROFILES,
    };

    if list_ides {
        println!("Supported IDEs for `secretenv mcp setup`:\n");
        let widest = IDE_PROFILES.iter().map(|p| p.key.len()).max().unwrap_or(0);
        for p in IDE_PROFILES {
            println!(
                "  {key:<width$}  {name}\n    config: {path}\n    note:   {note}\n",
                key = p.key,
                width = widest,
                name = p.display_name,
                path = p.config_path,
                note = p.note,
            );
        }
        return Ok(());
    }

    let ide_key = ide.ok_or_else(|| {
        anyhow::anyhow!(
            "missing --ide <name>. Run `secretenv mcp setup --list-ides` to see options."
        )
    })?;
    let profile = find_profile(ide_key).ok_or_else(|| {
        anyhow::anyhow!(
            "unknown IDE `{ide_key}`. Run `secretenv mcp setup --list-ides` to see options.",
        )
    })?;
    let body = render_config(profile, binary);

    if !write {
        println!("# MCP config block for {} ({}):", profile.display_name, profile.key);
        println!("# Target file: {}", profile.config_path);
        println!("# Note: {}", profile.note);
        println!("# ---");
        print!("{body}");
        return Ok(());
    }

    // The `generic` and `claude-code` profiles are print-only:
    // - `generic` doesn't target a specific config file
    // - `claude-code` emits a `claude mcp add` shell command (the
    //   official safe mechanism; `~/.claude.json` is a 1000+ line
    //   shared config that must not be overwritten)
    if profile.key == "generic" {
        anyhow::bail!(
            "`--ide generic` is print-only — it doesn't target a specific config file. \
             Re-run without `--write`, then paste the block into the IDE's MCP config \
             (compatible with Claude Code, Cursor, Cline, Gemini CLI / Code Assist).",
        );
    }
    if profile.key == "claude-code" {
        anyhow::bail!(
            "`--ide claude-code` is print-only — it emits the official `claude mcp add` \
             shell command rather than overwriting `~/.claude.json` (which carries \
             unrelated Claude Code state). Re-run without `--write` and run the \
             printed command in your shell.",
        );
    }

    let target = expand_home(profile.config_path)
        .with_context(|| format!("expanding home directory for `{}`", profile.config_path))?;

    if merge {
        let outcome = merge_config_into_file(profile, binary, &target)?;
        match outcome {
            MergeOutcome::Created => eprintln!(
                "Wrote new MCP config for {} ({}).",
                profile.display_name,
                target.display()
            ),
            MergeOutcome::Added => eprintln!(
                "Merged SecretEnv entry into existing {} config ({}).",
                profile.display_name,
                target.display()
            ),
            MergeOutcome::AlreadyPresent => eprintln!(
                "SecretEnv entry already present in {} config ({}); no changes.",
                profile.display_name,
                target.display()
            ),
            MergeOutcome::Conflict => anyhow::bail!(
                "existing {} config at `{}` already has a `secretenv` MCP entry with a \
                 different shape. Re-run with `--write --force` to overwrite, or edit \
                 the file manually.",
                profile.display_name,
                target.display()
            ),
        }
        return Ok(());
    }

    if target.exists() && !force {
        anyhow::bail!(
            "target file `{}` already exists. Re-run with `--force` to overwrite, \
             with `--merge` to splice the SecretEnv entry into the existing file, \
             or paste the block from `secretenv mcp setup --ide {}` into the \
             existing file manually.",
            target.display(),
            profile.key,
        );
    }
    if let Some(parent) = target.parent() {
        std::fs::create_dir_all(parent).with_context(|| {
            format!("creating parent directory `{}` for IDE config", parent.display())
        })?;
    }
    std::fs::write(&target, &body)
        .with_context(|| format!("writing MCP config to `{}`", target.display()))?;
    eprintln!(
        "Wrote {} MCP config for {} ({}).",
        body.len(),
        profile.display_name,
        target.display()
    );
    Ok(())
}

// ---- Registry selection resolution --------------------------------------

/// Resolve the active registry selection per [[resolution-flow]]:
///   1. `explicit` (from `--registry <name-or-uri>` CLI flag).
///   2. `env_registry` (usually `std::env::var("SECRETENV_REGISTRY")`).
///   3. `[registries.default]` in config.
///   4. Hard error.
///
/// Taking `env_registry` as a parameter keeps the function pure —
/// tests pass `None` without having to touch process env (which is
/// `unsafe` in Rust 2024 and unsafe-forbidden in this crate).
///
/// # Errors
/// Returns an error if every fallback is exhausted, or if `explicit`
/// or `env_registry` fails to parse as a [`RegistrySelection`].
pub fn resolve_selection(
    explicit: Option<&str>,
    env_registry: Option<&str>,
    config: &Config,
) -> Result<RegistrySelection> {
    if let Some(s) = explicit {
        return s.parse().context("parsing --registry value");
    }
    if let Some(env) = env_registry {
        if !env.is_empty() {
            return env.parse().context("parsing $SECRETENV_REGISTRY");
        }
    }
    if config.registries.contains_key("default") {
        return Ok(RegistrySelection::Name("default".to_owned()));
    }
    Err(anyhow!(
        "no registry selected — pass --registry <name-or-uri>, set \
         $SECRETENV_REGISTRY, or add a [registries.default] block to config.toml"
    ))
}

/// Production call-site: read `SECRETENV_REGISTRY` from the process
/// env and delegate to [`resolve_selection`].
fn resolve_selection_from_env(
    explicit: Option<&str>,
    config: &Config,
) -> Result<RegistrySelection> {
    let env = std::env::var("SECRETENV_REGISTRY").ok();
    resolve_selection(explicit, env.as_deref(), config)
}

// ---- run ---------------------------------------------------------------

async fn cmd_run(
    args: &RunArgs,
    config: &Config,
    backends: &BackendRegistry,
) -> Result<crate::reports::RunReport> {
    use secretenv_core::{run_with_options, RedactMode, RunOptions};

    let starting_dir = std::env::current_dir().context("determining current directory")?;
    let manifest = Manifest::load(&starting_dir)
        .context("loading secretenv.toml (walked upward from $CWD)")?;
    let selection = resolve_selection_from_env(args.registry.as_deref(), config)?;
    let mut cache = RegistryCache::new();
    let aliases = resolve_registry(config, &selection, backends, &mut cache).await?;
    let resolved = resolve_manifest(&manifest, &aliases)?;

    let alias_count = resolved.len() as u64;

    // SEC-INV-07 (Phase 7 security audit H1): `--no-redact` on a TTY
    // requires an interactive "type yes" confirmation in addition to
    // the clap-enforced `--i-know` flag. On a non-TTY parent the
    // `--i-know` requirement alone provides friction; on a TTY the
    // operator is explicitly walking themselves into the unsafe path
    // and must type the word out. CI environments (non-TTY) skip the
    // prompt by definition; developer workstations (TTY) hit it.
    if args.no_redact {
        use std::io::IsTerminal as _;
        if io::stderr().is_terminal() {
            eprintln!(
                "WARNING: --no-redact disables runtime secret filtering. Resolved \
                 values will appear verbatim in the child's stdout/stderr."
            );
            eprint!("Type \"yes\" to continue: ");
            io::stderr().flush().ok();
            let mut input = String::new();
            io::stdin()
                .read_line(&mut input)
                .context("reading --no-redact confirmation from stdin")?;
            if input.trim() != "yes" {
                bail!("--no-redact aborted by user (did not type \"yes\")");
            }
        }
    }

    let redact = if args.no_redact {
        RedactMode::ForceExec
    } else if args.redact {
        RedactMode::ForcePipe
    } else {
        RedactMode::Auto
    };
    // RunOptions is `#[non_exhaustive]` (Phase 9b Code-H3 / Arch-L1)
    // so external constructions go through Default + field mutation
    // rather than a struct expression. Within-crate callers (e.g.
    // future builder methods) can still construct directly.
    let mut options = RunOptions::default();
    options.dry_run = args.dry_run;
    options.verbose = args.verbose;
    options.redact = redact;
    options.redact_token = args.redact_token.clone();
    options.registry_name = selection.registry_label().map(str::to_owned);

    // Capture the dispatch up front so the report reflects what we
    // actually did, not what we requested. `Auto` may degrade to
    // `Exec` inside the runner when stdin is a TTY; for the v0.14
    // report we record the requested intent (the runner emits the
    // operator-facing one-line advisory when the auto fallback fires).
    let dispatch = if args.dry_run {
        crate::reports::RunDispatch::DryRun
    } else if matches!(redact, RedactMode::ForceExec) {
        crate::reports::RunDispatch::Exec
    } else {
        crate::reports::RunDispatch::PipeRedact
    };

    run_with_options(&resolved, backends, &args.command, &options).await?;
    Ok(crate::reports::RunReport {
        alias_count,
        dispatch,
        outcome: crate::reports::CommandOutcome::Ok,
    })
}

// ---- resolve -----------------------------------------------------------

async fn cmd_resolve(
    args: &ResolveArgs,
    config: &Config,
    backends: &BackendRegistry,
) -> Result<crate::reports::ResolveReport> {
    use secretenv_core::{Manifest, DEFAULT_CHECK_TIMEOUT};

    let selection = resolve_selection_from_env(args.registry.as_deref(), config)?;
    let mut cache = RegistryCache::new();
    let aliases = resolve_registry(config, &selection, backends, &mut cache).await?;

    let (target, source) = aliases.get(&args.alias).ok_or_else(|| {
        anyhow!(
            "alias '{}' not found in registry cascade [{}]",
            args.alias,
            format_sources(&aliases)
        )
    })?;
    let target = target.clone();
    let source = source.clone();

    // Cascade layer index — position in `aliases.sources()` whose URI
    // matches the source we just resolved.
    let layer_index = aliases.sources().position(|u| u.raw == source.raw).unwrap_or(0);

    // Reverse-lookup env var from the manifest. Best-effort: if no
    // manifest exists (user is in a repo without `secretenv.toml`),
    // the env-var row shows `(none)` / null instead of erroring —
    // `resolve` is a debugging tool that should work anywhere.
    let env_var = std::env::current_dir()
        .ok()
        .and_then(|cwd| Manifest::load(&cwd).ok())
        .and_then(|m| manifest_env_var_for_alias(&m, &args.alias));

    // Backend auth status. Timed out per the Phase 0.5 check-timeout
    // wrapper. Resolve still succeeds even if check fails — operators
    // debug broken auth by seeing the status line, not by being
    // denied the alias→URI mapping.
    // Backend::check returns a bare BackendStatus (no Result), so wrap
    // it in Ok(..) inside an async block so with_timeout's
    // Future<Output = Result<T>> bound is satisfied. Same idiom as
    // doctor::run_doctor.
    let backend_check = match backends.get(&target.scheme) {
        Some(b) => {
            let op_label = format!("{}::check", b.backend_type());
            let check_future = async { Ok(b.check().await) };
            match secretenv_core::with_timeout(DEFAULT_CHECK_TIMEOUT, &op_label, check_future).await
            {
                Ok(status) => ResolveBackendCheck::Checked {
                    backend_type: b.backend_type().to_owned(),
                    status,
                },
                Err(err) => ResolveBackendCheck::CheckFailed {
                    backend_type: b.backend_type().to_owned(),
                    message: format!("{err:#}"),
                },
            }
        }
        None => ResolveBackendCheck::UnregisteredScheme,
    };

    let report = ResolveOutput {
        alias: args.alias.clone(),
        env_var,
        resolved: target.raw.clone(),
        source_uri: source.raw.clone(),
        layer_index,
        backend_scheme: target.scheme.clone(),
        check: backend_check,
    };

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

    Ok(crate::reports::ResolveReport {
        cascade_layer_index: u32::try_from(report.layer_index).unwrap_or(u32::MAX),
        backend_type: report.backend_scheme,
        outcome: crate::reports::CommandOutcome::Ok,
    })
}

/// Scan the manifest's `[secrets]` entries for the first key whose
/// `from = "secretenv://<alias>"` (or `"secretenv:///<alias>"`)
/// references the given alias. Returns `None` if nothing references
/// the alias.
fn manifest_env_var_for_alias(manifest: &secretenv_core::Manifest, alias: &str) -> Option<String> {
    for (env_var, decl) in &manifest.secrets {
        if let secretenv_core::SecretDecl::Alias { from } = decl {
            let Ok(parsed) = secretenv_core::BackendUri::parse(from) else {
                continue;
            };
            if parsed.is_alias() {
                let found = parsed.path.trim_start_matches('/');
                if found == alias {
                    return Some(env_var.clone());
                }
            }
        }
    }
    None
}

/// Backend-check outcome for a resolved alias. Kept separate from
/// `doctor::DoctorStatus` so the resolve handler doesn't depend on
/// doctor's internal shape.
enum ResolveBackendCheck {
    Checked { backend_type: String, status: secretenv_core::BackendStatus },
    CheckFailed { backend_type: String, message: String },
    UnregisteredScheme,
}

struct ResolveOutput {
    alias: String,
    env_var: Option<String>,
    resolved: String,
    source_uri: String,
    layer_index: usize,
    backend_scheme: String,
    check: ResolveBackendCheck,
}

impl ResolveOutput {
    fn render_human(&self) -> String {
        use std::fmt::Write as _;
        let mut out = String::new();
        writeln!(out, "alias:      {}", self.alias).ok();
        writeln!(out, "env var:    {}", self.env_var.as_deref().unwrap_or("(none)")).ok();
        writeln!(out, "resolved:   {}", self.resolved).ok();
        writeln!(out, "source:     {}  (cascade layer {})", self.source_uri, self.layer_index).ok();
        writeln!(out, "backend:    {}", self.render_backend_line()).ok();
        out
    }

    fn render_backend_line(&self) -> String {
        use secretenv_core::BackendStatus;
        match &self.check {
            ResolveBackendCheck::Checked { backend_type, status } => {
                let (state, detail) = match status {
                    BackendStatus::Ok { cli_version: _, identity } => {
                        ("authenticated".to_owned(), format!("({identity})"))
                    }
                    BackendStatus::NotAuthenticated { hint } => {
                        ("NOT authenticated".to_owned(), format!("(hint: {hint})"))
                    }
                    BackendStatus::CliMissing { cli_name, install_hint } => {
                        (format!("CLI '{cli_name}' missing"), format!("(install: {install_hint})"))
                    }
                    BackendStatus::Error { message } => {
                        ("error".to_owned(), format!("({message})"))
                    }
                };
                format!("{backend_type} instance '{}' — {state} {detail}", self.backend_scheme)
            }
            ResolveBackendCheck::CheckFailed { backend_type, message } => {
                format!(
                    "{backend_type} instance '{}' — check failed ({message})",
                    self.backend_scheme
                )
            }
            ResolveBackendCheck::UnregisteredScheme => {
                format!(
                    "instance '{}' is not registered in config.toml (resolve succeeded; fetch would fail)",
                    self.backend_scheme
                )
            }
        }
    }

    fn to_json(&self) -> serde_json::Value {
        use secretenv_core::BackendStatus;
        let check = match &self.check {
            ResolveBackendCheck::Checked { backend_type, status } => {
                let (status_key, detail) = match status {
                    BackendStatus::Ok { cli_version, identity } => (
                        "ok",
                        serde_json::json!({
                            "cli_version": cli_version,
                            "identity": identity,
                        }),
                    ),
                    BackendStatus::NotAuthenticated { hint } => {
                        ("not_authenticated", serde_json::json!({ "hint": hint }))
                    }
                    BackendStatus::CliMissing { cli_name, install_hint } => (
                        "cli_missing",
                        serde_json::json!({
                            "cli_name": cli_name,
                            "install_hint": install_hint,
                        }),
                    ),
                    BackendStatus::Error { message } => {
                        ("error", serde_json::json!({ "message": message }))
                    }
                };
                serde_json::json!({
                    "backend_type": backend_type,
                    "instance": self.backend_scheme,
                    "status": status_key,
                    "detail": detail,
                })
            }
            ResolveBackendCheck::CheckFailed { backend_type, message } => serde_json::json!({
                "backend_type": backend_type,
                "instance": self.backend_scheme,
                "status": "check_failed",
                "detail": { "message": message },
            }),
            ResolveBackendCheck::UnregisteredScheme => serde_json::json!({
                "instance": self.backend_scheme,
                "status": "unregistered_scheme",
                "detail": {},
            }),
        };
        serde_json::json!({
            "alias": self.alias,
            "env_var": self.env_var,
            "resolved": self.resolved,
            "source": {
                "uri": self.source_uri,
                "layer": self.layer_index,
            },
            "backend": check,
        })
    }
}

// ---- get (with confirmation) -------------------------------------------

async fn cmd_get(
    args: &GetArgs,
    config: &Config,
    backends: &BackendRegistry,
) -> Result<crate::reports::GetReport> {
    let selection = resolve_selection_from_env(args.registry.as_deref(), config)?;
    let mut cache = RegistryCache::new();
    let aliases = resolve_registry(config, &selection, backends, &mut cache).await?;
    let target = aliases
        .get(&args.alias)
        .ok_or_else(|| {
            anyhow!(
                "alias '{}' not found in registry cascade [{}]",
                args.alias,
                format_sources(&aliases)
            )
        })?
        .0
        .clone();

    let confirmed = args.yes || confirm_print_secret(&args.alias)?;
    if !confirmed {
        bail!("aborted by user");
    }

    let backend = backends
        .get(&target.scheme)
        .ok_or_else(|| anyhow!("no backend instance '{}' is configured", target.scheme))?;
    let backend_type = backend.backend_type().to_owned();
    let value = backend.get(&target).await?;
    println!("{}", value.expose_secret());
    Ok(crate::reports::GetReport {
        backend_type,
        confirmed,
        outcome: crate::reports::CommandOutcome::Ok,
    })
}

// ---- redact (Mode B post-hoc) -----------------------------------------

#[allow(clippy::too_many_lines)] // dispatch + three exits + typed report
async fn cmd_redact(
    args: &RedactArgs,
    config: &Config,
    backends: &BackendRegistry,
) -> Result<crate::reports::RedactReport> {
    use secretenv_core::redact::{
        scrub_file_in_place, Scrubber, SubstitutionToken, TaintedSet, TaintedValue,
    };

    let selection = resolve_selection_from_env(args.registry.as_deref(), config)?;
    let mut cache = RegistryCache::new();
    let aliases = resolve_registry(config, &selection, backends, &mut cache).await?;

    // Build the alias filter: either explicit `--alias <names>` or
    // every alias in the resolved cascade.
    let alias_names: Vec<String> = if args.alias.is_empty() {
        aliases.iter().map(|(name, _target, _source)| name.clone()).collect()
    } else {
        args.alias.clone()
    };

    if alias_names.is_empty() {
        bail!(
            "secretenv redact: no aliases to redact — registry cascade is empty \
             ({}). Add aliases via `secretenv registry set` first.",
            format_sources(&aliases),
        );
    }

    // Fetch each alias's value, build the tainted set.
    let mut tainted = TaintedSet::new();
    for name in &alias_names {
        let Some((target, _src)) = aliases.get(name) else {
            bail!("alias '{name}' not found in registry cascade [{}]", format_sources(&aliases));
        };
        let backend = backends
            .get(&target.scheme)
            .ok_or_else(|| anyhow!("no backend instance '{}' is configured", target.scheme))?;
        let value = backend.get(target).await.with_context(|| {
            format!("fetching value for alias '{name}' (target='{}')", target.raw)
        })?;
        tainted.insert(TaintedValue::from_alias(name.clone(), value.expose_secret()));
    }

    let token = args
        .redact_token
        .as_ref()
        .map_or(SubstitutionToken::AliasAware, |s| SubstitutionToken::Fixed(s.clone()));
    let Some(scrubber) = Scrubber::new(&tainted, token)? else {
        eprintln!(
            "secretenv redact: tainted set is empty after the {}-byte minimum filter; \
             nothing to redact.",
            secretenv_core::redact::MIN_TAINTED_LEN,
        );
        return Ok(crate::reports::RedactReport {
            mode: crate::reports::RedactMode::Stdout,
            match_count: 0,
            byte_count: 0,
            outcome: crate::reports::CommandOutcome::Ok,
        });
    };

    let path = std::path::Path::new(&args.path);

    // Per Phase 7 code-review H4: every dispatch arm now goes
    // through the same special-path + foreign-owner gate. The
    // `--dry-run` path previously skipped both — defense-in-depth
    // should not have an opt-out for "just count, don't write."
    // `scrub_file_in_place` re-applies the same guards internally,
    // so the in-place arm sees them at both layers.
    secretenv_core::redact::refuse_special_paths(path)?;
    secretenv_core::redact::refuse_foreign_owner(path, args.allow_foreign_owner)?;

    if args.dry_run {
        let mut sink = std::io::sink();
        let mut reader = secretenv_core::redact::open_no_follow(path).with_context(|| {
            format!("redact: opening '{}' with O_NOFOLLOW for dry-run", path.display())
        })?;
        let rep = scrubber.scrub_reader(&mut reader, &mut sink)?;
        eprintln!(
            "secretenv redact: would redact {} match(es) totaling {} byte(s) in '{}'",
            rep.match_count,
            rep.byte_count,
            path.display(),
        );
        return Ok(crate::reports::RedactReport {
            mode: crate::reports::RedactMode::DryRun,
            match_count: rep.match_count,
            byte_count: rep.byte_count,
            outcome: crate::reports::CommandOutcome::DryRun,
        });
    }

    if args.in_place {
        let rep =
            scrub_file_in_place(path, &scrubber, args.backup.as_deref(), args.allow_foreign_owner)?;
        eprintln!(
            "secretenv redact: rewrote '{}' — {} match(es), {} byte(s) replaced{}",
            path.display(),
            rep.match_count,
            rep.byte_count,
            args.backup
                .as_deref()
                .map_or(String::new(), |s| format!("; backup at '{}{s}'", path.display())),
        );
        return Ok(crate::reports::RedactReport {
            mode: crate::reports::RedactMode::InPlace,
            match_count: rep.match_count,
            byte_count: rep.byte_count,
            outcome: crate::reports::CommandOutcome::Ok,
        });
    }

    // Default: stream to stdout.
    let mut reader = secretenv_core::redact::open_no_follow(path)
        .with_context(|| format!("redact: opening '{}' with O_NOFOLLOW", path.display()))?;
    let mut stdout = io::stdout().lock();
    let rep = scrubber.scrub_reader(&mut reader, &mut stdout)?;
    drop(stdout);
    eprintln!(
        "secretenv redact: {} match(es), {} byte(s) replaced in '{}'",
        rep.match_count,
        rep.byte_count,
        path.display(),
    );
    // v0.17 Phase 8c — `secretenv redact <file>` is the post-hoc
    // path; emit one span summarising the scrub. Suppressed when no
    // matches occurred (matches the runtime-mode contract).
    if rep.match_count > 0 {
        let (mut span, _guard) =
            secretenv_telemetry::SecretEnvSpan::start("secretenv.redact.filter_event");
        span.record_redact_mode(secretenv_telemetry::RedactMode::PostHoc)
            .record_redact_stream(secretenv_telemetry::RedactionStream::Stdout)
            .record_redact_match_count(rep.match_count)
            .record_redact_byte_count(rep.byte_count);
    }
    Ok(crate::reports::RedactReport {
        mode: crate::reports::RedactMode::Stdout,
        match_count: rep.match_count,
        byte_count: rep.byte_count,
        outcome: crate::reports::CommandOutcome::Ok,
    })
}

fn confirm_print_secret(alias: &str) -> Result<bool> {
    eprint!("about to print the secret value for '{alias}' to stdout. continue? [y/N] ");
    io::stderr().flush().ok();
    let mut input = String::new();
    io::stdin().read_line(&mut input).context("reading confirmation from stdin")?;
    Ok(matches!(input.trim().to_lowercase().as_str(), "y" | "yes"))
}

// ---- registry subcommands -----------------------------------------------

async fn cmd_registry(
    rc: &RegistryCommand,
    config: &Config,
    backends: &BackendRegistry,
) -> Result<crate::reports::RegistryReport> {
    let (subcommand, aliases_touched) = match rc {
        RegistryCommand::List { registry } => {
            registry_list(registry.as_deref(), config, backends).await?;
            ("list", 0)
        }
        RegistryCommand::Get { alias, registry } => {
            registry_get(alias, registry.as_deref(), config, backends).await?;
            ("get", 1)
        }
        RegistryCommand::Set { alias, uri, registry } => {
            registry_set(alias, uri, registry.as_deref(), config, backends).await?;
            ("set", 1)
        }
        RegistryCommand::Unset { alias, registry } => {
            registry_unset(alias, registry.as_deref(), config, backends).await?;
            ("unset", 1)
        }
        RegistryCommand::History { alias, registry, json } => {
            registry_history(alias, registry.as_deref(), *json, config, backends).await?;
            ("history", 1)
        }
        RegistryCommand::Invite { registry, invitee, json } => {
            registry_invite(registry.as_deref(), invitee.as_deref(), *json, config)?;
            ("invite", 0)
        }
        RegistryCommand::Migrate {
            alias,
            dest_uri,
            dry_run,
            yes,
            from,
            delete_source,
            json,
            registry,
        } => {
            registry_migrate(
                alias,
                dest_uri,
                *dry_run,
                *yes,
                from.as_deref(),
                *delete_source,
                *json,
                registry.as_deref(),
                config,
                backends,
            )
            .await?;
            ("migrate", 1)
        }
    };
    Ok(crate::reports::RegistryReport {
        subcommand,
        aliases_touched,
        outcome: crate::reports::CommandOutcome::Ok,
    })
}

fn registry_invite(
    registry: Option<&str>,
    invitee: Option<&str>,
    json: bool,
    config: &Config,
) -> Result<()> {
    let selection = resolve_selection_from_env(registry, config)?;
    let invitation = crate::invite::build_invitation(config, &selection, invitee)?;
    if json {
        println!("{}", crate::invite::render_json(&invitation)?);
    } else {
        print!("{}", crate::invite::render_human(&invitation));
    }
    Ok(())
}

async fn registry_list(
    registry: Option<&str>,
    config: &Config,
    backends: &BackendRegistry,
) -> Result<()> {
    let selection = resolve_selection_from_env(registry, config)?;
    let mut cache = RegistryCache::new();
    let aliases = resolve_registry(config, &selection, backends, &mut cache).await?;
    // Effective cascade view — shadowed entries are filtered out by
    // AliasMap::iter. Sort alphabetically for deterministic output.
    let mut entries: Vec<_> =
        aliases.iter().map(|(a, target, _source)| (a.clone(), target.raw.clone())).collect();
    entries.sort_by(|a, b| a.0.cmp(&b.0));
    for (alias, uri) in entries {
        println!("{alias} = {uri}");
    }
    Ok(())
}

async fn registry_get(
    alias: &str,
    registry: Option<&str>,
    config: &Config,
    backends: &BackendRegistry,
) -> Result<()> {
    let selection = resolve_selection_from_env(registry, config)?;
    let mut cache = RegistryCache::new();
    let aliases = resolve_registry(config, &selection, backends, &mut cache).await?;
    let (target, _source) = aliases.get(alias).ok_or_else(|| {
        anyhow!("alias '{alias}' not found in registry cascade [{}]", format_sources(&aliases))
    })?;
    println!("{}", target.raw);
    Ok(())
}

async fn registry_set(
    alias: &str,
    target_uri: &str,
    registry: Option<&str>,
    config: &Config,
    backends: &BackendRegistry,
) -> Result<()> {
    secretenv_registry_mutate::validate_target_uri(target_uri, backends)?;
    let (source_uri, backend) = pick_registry_source(registry, config, backends)?;
    let registry_label = registry.unwrap_or("default").to_owned();
    secretenv_registry_mutate::apply_change(
        backend,
        &source_uri,
        &registry_label,
        secretenv_registry_mutate::AliasChange::Insert {
            alias: alias.to_owned(),
            target_uri: target_uri.to_owned(),
        },
    )
    .await?;
    eprintln!("set {alias}{target_uri} in registry at '{}'", source_uri.raw);
    Ok(())
}

/// `secretenv registry migrate <alias> <dest-uri>` — builds the
/// `MigrationPlan` once and drives [`secretenv_migrate::migrate_with_plan`]
/// with all the user-prompt + report-rendering machinery the library
/// entry leaves to the CLI.
#[allow(clippy::too_many_arguments, clippy::fn_params_excessive_bools)]
async fn registry_migrate(
    alias: &str,
    dest_uri: &str,
    dry_run: bool,
    yes: bool,
    from: Option<&str>,
    delete_source: bool,
    json: bool,
    registry: Option<&str>,
    config: &Config,
    backends: &BackendRegistry,
) -> Result<()> {
    let args = secretenv_migrate::MigrateArgs {
        alias: alias.to_owned(),
        dest_uri: dest_uri.to_owned(),
        source_uri: from.map(str::to_owned),
        registry: registry.map(str::to_owned),
        dry_run,
        delete_source,
    };

    // Phase 7 audit fix (code-rev B1): build the plan ONCE here in
    // the CLI handler. Use the same plan instance for both the
    // confirmation-prompt render and the actual migration via
    // `migrate_with_plan` — the `transaction_id` the operator sees
    // in the prompt is the same one that lands in the report. The
    // prior shape called `build_migration_plan` once for the
    // preview and once inside `migrate`, producing different
    // `transaction_id`s and opening a TOCTOU window on the registry
    // doc between confirmation and execution.
    let plan = secretenv_migrate::build_migration_plan(&args, config, backends).await?;

    // Top-level confirmation prompt: skipped under --dry-run (no
    // mutation) and under --yes (operator opted out globally).
    if !dry_run && !yes {
        eprintln!("About to migrate {}:", plan.alias);
        eprintln!("  from: {}", plan.source_uri.raw);
        eprintln!("  to:   {}", plan.dest_uri.raw);
        eprintln!();
        eprintln!(
            "This will read the current value from the source and write it to the destination."
        );
        eprintln!("The registry pointer will be updated on success.");
        if delete_source {
            eprintln!("The source value WILL be deleted after a separate confirmation.");
        } else {
            eprintln!("The source value will NOT be deleted.");
        }
        if !prompt_yes_no("\nContinue? [y/N] ")? {
            eprintln!("aborted; no changes made.");
            return Ok(());
        }
    }

    // The delete-source extra confirmation fires inside
    // `migrate_with_plan` AFTER the pointer flip commits, per
    // SEC-INV-08. It must run even under --yes; the closure handles
    // that by always reading stdin when --delete-source was passed.
    let post_commit_consent = |plan: &secretenv_migrate::MigrationPlan| -> bool {
        // No-op in dry-run (delete leg never runs).
        if dry_run {
            return false;
        }
        eprintln!();
        eprintln!("  4/4  About to permanently delete {}.", plan.source_uri.raw);
        eprintln!("       This cannot be undone.");
        // I/O error reading stdin treated as 'no' — the migration
        // is committed; the operator can clean up manually with the
        // printed `delete_hint`.
        prompt_yes_no("       Continue? [y/N] ").unwrap_or_default()
    };

    let result =
        secretenv_migrate::migrate_with_plan(plan, &args, backends, post_commit_consent).await;
    let report = match result {
        Ok(r) => r,
        Err(e) => {
            // Phase 7 audit fix (security M2): downcast the
            // pointer-flip partial-failure to render the manual
            // recovery block to stderr (terminal-only per
            // SEC-INV-22) without embedding URI bodies in the
            // bubbled error message.
            if let Some(flip) = e.downcast_ref::<secretenv_migrate::PointerFlipFailed>() {
                eprintln!("Error: migration partially failed.");
                eprintln!();
                eprintln!("  Step 1/3  Read from source:           OK");
                eprintln!("  Step 2/3  Write to destination:        OK");
                eprintln!("  Step 3/3  Registry pointer update:     FAILED");
                eprintln!();
                eprintln!(
                    "IMPORTANT: The value has been written to {dest}.",
                    dest = flip.dest_uri_raw
                );
                eprintln!("           The registry still points at the original source.");
                eprintln!("           The value now exists in TWO backends.");
                eprintln!();
                eprintln!("To complete the migration:");
                eprintln!(
                    "  secretenv registry set {alias} {dest}",
                    alias = flip.alias,
                    dest = flip.dest_uri_raw
                );
                eprintln!();
                eprintln!("To roll back (delete from destination):");
                eprintln!("  {}", flip.dest_delete_hint);
            }
            return Err(e);
        }
    };

    if json {
        println!("{}", render_migrate_json(&report)?);
    } else {
        print_migrate_human(&report);
    }
    Ok(())
}

/// Read one stdin line and return `true` iff it starts with `y` or `Y`.
/// Defaults to `false` on EOF (no input) and on any I/O error other
/// than EOF — the latter is rare enough that surfacing it would
/// confuse more than it would help in the interactive flow.
fn prompt_yes_no(prompt: &str) -> Result<bool> {
    use std::io::{BufRead, Write};
    eprint!("{prompt}");
    std::io::stderr().flush().ok();
    let stdin = std::io::stdin();
    let mut line = String::new();
    let n = stdin.lock().read_line(&mut line).context("reading stdin for confirmation")?;
    if n == 0 {
        // EOF before any input: treat as 'no'.
        return Ok(false);
    }
    Ok(line.trim().starts_with(['y', 'Y']))
}

fn print_migrate_human(report: &secretenv_migrate::MigrateReport) {
    use secretenv_migrate::MigrateReportOutcome;
    match report.outcome {
        MigrateReportOutcome::DryRun => {
            eprintln!("secretenv migrate (dry-run):");
            eprintln!("  alias:        {}", report.alias);
            eprintln!("  source type:  {}", report.source_backend_type);
            eprintln!("  dest type:    {}", report.dest_backend_type);
            eprintln!("\nProbes:");
            for (instance, result) in &report.probe_results {
                eprintln!("  {instance:20} {result}");
            }
            eprintln!("\nDry-run complete. No changes made. Remove --dry-run to execute.");
        }
        MigrateReportOutcome::Success => {
            eprintln!("Migration complete.");
            eprintln!("  alias:           {}", report.alias);
            eprintln!(
                "  probe / read / write / flip ms: {} / {} / {} / {}",
                report.phase_durations.probe_ms,
                report.phase_durations.read_ms,
                report.phase_durations.write_ms,
                report.phase_durations.pointer_flip_ms,
            );
            if let Some(ms) = report.phase_durations.source_delete_ms {
                eprintln!("  source-delete ms: {ms}");
                eprintln!("  source value deleted.");
            } else if let Some(hint) = &report.delete_hint {
                eprintln!("  source value still present. To remove it:");
                eprintln!("    {hint}");
            }
        }
        MigrateReportOutcome::SourceDeleteFailedPostCommit => {
            eprintln!("Migration committed but source-delete failed.");
            eprintln!("  alias:           {}", report.alias);
            if let Some(hint) = &report.delete_hint {
                eprintln!("  Cleanup the source manually:");
                eprintln!("    {hint}");
            }
        }
        MigrateReportOutcome::PartialFailurePointerFlip => {
            // This path is only reachable when migrate() returned Ok
            // with the PartialFailure outcome (it doesn't today;
            // pointer-flip failure is propagated as Err). Kept for
            // forward compatibility if migrate() ever returns
            // structured partial-failure reports instead of Err.
            eprintln!("Migration partially failed.");
        }
        // `MigrateReportOutcome` is `#[non_exhaustive]` (Phase 7h
        // R-4); future variants render as a generic "unknown
        // outcome" message rather than breaking the CLI at build
        // time. Operator upgrades secretenv-cli to get the new
        // variant rendered precisely.
        _ => eprintln!("Migration completed with an unknown outcome variant — upgrade secretenv to render details."),
    }
}

fn render_migrate_json(report: &secretenv_migrate::MigrateReport) -> Result<String> {
    use secretenv_migrate::MigrateReportOutcome;
    let outcome = match report.outcome {
        MigrateReportOutcome::Success => "success",
        MigrateReportOutcome::DryRun => "dry-run",
        MigrateReportOutcome::SourceDeleteFailedPostCommit => "source-delete-failed-post-commit",
        MigrateReportOutcome::PartialFailurePointerFlip => "partial-failure-pointer-flip",
        // `MigrateReportOutcome` is `#[non_exhaustive]` (Phase 7h R-4).
        _ => "unknown",
    };
    let mut durations = serde_json::json!({
        "probe_ms": report.phase_durations.probe_ms,
        "read_ms": report.phase_durations.read_ms,
        "write_ms": report.phase_durations.write_ms,
        "pointer_flip_ms": report.phase_durations.pointer_flip_ms,
    });
    if let Some(ms) = report.phase_durations.source_delete_ms {
        durations["source_delete_ms"] = serde_json::json!(ms);
    }
    // Phase 7 audit (code-rev B3): include `probe_results` in JSON so
    // `--dry-run --json` is consumable by CI. Each entry is an
    // object rather than a positional array — `{"instance": ...,
    // "status": ...}` — so future schema additions don't break
    // existing consumers.
    let probe_results: Vec<serde_json::Value> = report
        .probe_results
        .iter()
        .map(|(instance, status)| {
            serde_json::json!({
                "instance": instance,
                "status": status,
            })
        })
        .collect();
    // Phase 7 audit (security M1): do NOT emit `delete_hint` in JSON.
    // The hint string contains URI path components (Tier-1 redaction
    // per SEC-INV-20 / SEC-INV-22) and operators piping `--json` to a
    // log aggregator would leak backend topology. The hint is
    // terminal-only via `print_migrate_human`.
    let value = serde_json::json!({
        "alias": report.alias,
        "source_backend_type": report.source_backend_type,
        "dest_backend_type": report.dest_backend_type,
        "outcome": outcome,
        "phase_durations_ms": durations,
        "delete_source": report.delete_source,
        "probe_results": probe_results,
        "transaction_id": report.transaction_id,
    });
    Ok(serde_json::to_string_pretty(&value)?)
}

async fn registry_history(
    alias: &str,
    registry: Option<&str>,
    json: bool,
    config: &Config,
    backends: &BackendRegistry,
) -> Result<()> {
    let selection = resolve_selection_from_env(registry, config)?;
    let mut cache = RegistryCache::new();
    let aliases = resolve_registry(config, &selection, backends, &mut cache).await?;
    let (target, _source) = aliases.get(alias).ok_or_else(|| {
        anyhow!("alias '{alias}' not found in registry cascade [{}]", format_sources(&aliases))
    })?;
    let target = target.clone();
    let backend = backends
        .get(&target.scheme)
        .ok_or_else(|| anyhow!("no backend instance '{}' is configured", target.scheme))?;
    let entries = backend.history(&target).await?;
    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&render_history_json(alias, &target.raw, &entries))?
        );
    } else {
        print!("{}", render_history_human(alias, &target.raw, &entries));
    }
    Ok(())
}

/// Tabular human format: alias header + per-version rows. Width-aware
/// so a long actor or description doesn't push the table to one
/// column-per-row. Empty `entries` renders an explanatory line — the
/// backend reported zero versions (locally-untracked file, fresh
/// secret, etc.) without erroring.
#[allow(clippy::write_literal)] // Header literals + width-aligned format read more clearly as positional args.
fn render_history_human(alias: &str, uri: &str, entries: &[HistoryEntry]) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();
    let _ = writeln!(out, "alias:    {alias}");
    let _ = writeln!(out, "resolved: {uri}");
    let _ = writeln!(out);
    if entries.is_empty() {
        let _ = writeln!(out, "(no versions reported by the backend)");
        return out;
    }
    // Column widths derived from the longest cell in each.
    let v_w = entries.iter().map(|e| e.version.len()).max().unwrap_or(7).max(7);
    let t_w = entries.iter().map(|e| e.timestamp.len()).max().unwrap_or(20).max(20);
    let a_w =
        entries.iter().map(|e| e.actor.as_deref().unwrap_or("-").len()).max().unwrap_or(6).max(6);
    let _ = writeln!(
        out,
        "{:<v_w$}  {:<t_w$}  {:<a_w$}  {}",
        "VERSION",
        "TIMESTAMP",
        "ACTOR",
        "DESCRIPTION",
        v_w = v_w,
        t_w = t_w,
        a_w = a_w
    );
    for e in entries {
        let _ = writeln!(
            out,
            "{:<v_w$}  {:<t_w$}  {:<a_w$}  {}",
            e.version,
            e.timestamp,
            e.actor.as_deref().unwrap_or("-"),
            e.description.as_deref().unwrap_or(""),
            v_w = v_w,
            t_w = t_w,
            a_w = a_w
        );
    }
    out
}

fn render_history_json(alias: &str, uri: &str, entries: &[HistoryEntry]) -> serde_json::Value {
    serde_json::json!({
        "alias": alias,
        "resolved": uri,
        "versions": entries
            .iter()
            .map(|e| serde_json::json!({
                "version": e.version,
                "timestamp": e.timestamp,
                "actor": e.actor,
                "description": e.description,
            }))
            .collect::<Vec<_>>(),
    })
}

async fn registry_unset(
    alias: &str,
    registry: Option<&str>,
    config: &Config,
    backends: &BackendRegistry,
) -> Result<()> {
    let (source_uri, backend) = pick_registry_source(registry, config, backends)?;
    let registry_label = registry.unwrap_or("default").to_owned();
    secretenv_registry_mutate::apply_change(
        backend,
        &source_uri,
        &registry_label,
        secretenv_registry_mutate::AliasChange::Remove { alias: alias.to_owned(), required: true },
    )
    .await?;
    eprintln!("unset {alias} in registry at '{}'", source_uri.raw);
    Ok(())
}

fn pick_registry_source<'a>(
    registry: Option<&str>,
    config: &Config,
    backends: &'a BackendRegistry,
) -> Result<(BackendUri, &'a dyn Backend)> {
    let selection = resolve_selection_from_env(registry, config)?;
    let source_uri: BackendUri = match selection {
        RegistrySelection::Uri(u) => u,
        RegistrySelection::Name(name) => {
            let reg = config
                .registries
                .get(&name)
                .ok_or_else(|| anyhow!("no registry named '{name}' in config.toml"))?;
            let first =
                reg.sources.first().ok_or_else(|| anyhow!("registry '{name}' has no sources"))?;
            BackendUri::parse(first).with_context(|| {
                format!("registry '{name}' sources[0] = '{first}' is not a valid URI")
            })?
        }
    };
    let backend = backends.get(&source_uri.scheme).ok_or_else(|| {
        anyhow!(
            "registry source '{}' targets backend '{}' which is not configured",
            source_uri.raw,
            source_uri.scheme
        )
    })?;
    Ok((source_uri, backend))
}

/// Join every cascade source URI into a comma-separated list for
/// error messages. Used when an alias is not found in any layer.
fn format_sources(aliases: &secretenv_core::AliasMap) -> String {
    aliases.sources().map(|u| u.raw.as_str()).collect::<Vec<_>>().join(", ")
}

// ---- setup --------------------------------------------------------------

async fn cmd_setup(
    args: &SetupArgs,
    target_config: Option<&std::path::Path>,
) -> Result<crate::reports::SetupReport> {
    let opts = crate::setup::SetupOpts {
        registry_uri: args.registry_uri.clone(),
        region: args.region.clone(),
        profile: args.profile.clone(),
        account: args.account.clone(),
        vault_address: args.vault_address.clone(),
        vault_namespace: args.vault_namespace.clone(),
        gcp_project: args.gcp_project.clone(),
        gcp_impersonate_service_account: args.gcp_impersonate_service_account.clone(),
        azure_vault_url: args.azure_vault_url.clone(),
        azure_tenant: args.azure_tenant.clone(),
        azure_subscription: args.azure_subscription.clone(),
        force: args.force,
        skip_doctor: args.skip_doctor,
        target: target_config.map(std::path::Path::to_path_buf),
    };
    crate::setup::run_setup(&opts).await?;
    Ok(crate::reports::SetupReport {
        force: args.force,
        outcome: crate::reports::CommandOutcome::Ok,
    })
}

// ---- profile ------------------------------------------------------------

async fn cmd_profile(
    pc: &ProfileCommand,
    target_config: Option<&std::path::Path>,
) -> Result<crate::reports::ProfileReport> {
    // The profiles dir sits next to the active config.toml. If the user
    // passed `--config <path>`, use that path's parent; otherwise fall
    // back to the XDG-default location. Both paths go through the
    // `profiles_dir_for` core helper so the logic matches the loader.
    let config_path: std::path::PathBuf = match target_config {
        Some(p) => p.to_path_buf(),
        None => secretenv_core::default_config_path_xdg()?,
    };
    let opts = crate::profile::ProfileOpts {
        profiles_dir: secretenv_core::profiles_dir_for(&config_path),
    };

    let subcommand = match pc {
        ProfileCommand::Install { name, url } => {
            crate::profile::install(name, url.as_deref(), &opts).await?;
            "install"
        }
        ProfileCommand::List { json } => {
            let installed = crate::profile::list(&opts)?;
            render_profile_list(&installed, *json)?;
            "list"
        }
        ProfileCommand::Update { name } => {
            if let Some(n) = name {
                let outcome = crate::profile::update_one(n, &opts).await?;
                match outcome {
                    crate::profile::UpdateOutcome::UpToDate => {
                        eprintln!("Profile '{n}' is already up to date.");
                    }
                    crate::profile::UpdateOutcome::Refreshed => {
                        eprintln!("Profile '{n}' refreshed.");
                    }
                }
            } else {
                let reports = crate::profile::update_all(&opts).await?;
                render_profile_update_reports(&reports)?;
            }
            "update"
        }
        ProfileCommand::Uninstall { name } => {
            crate::profile::uninstall(name, &opts)?;
            "uninstall"
        }
    };
    Ok(crate::reports::ProfileReport { subcommand, outcome: crate::reports::CommandOutcome::Ok })
}

fn render_profile_list(installed: &[crate::profile::InstalledProfile], json: bool) -> Result<()> {
    if json {
        let json =
            serde_json::to_string_pretty(&installed).context("serializing profile list to JSON")?;
        println!("{json}");
        return Ok(());
    }
    if installed.is_empty() {
        println!("No profiles installed.");
        return Ok(());
    }
    println!("{:<24} {:<20} SOURCE", "NAME", "INSTALLED");
    for p in installed {
        println!("{:<24} {:<20} {}", p.name, p.installed_at, p.source_url);
    }
    Ok(())
}

fn render_profile_update_reports(reports: &[crate::profile::UpdateReport]) -> Result<()> {
    if reports.is_empty() {
        println!("No profiles installed.");
        return Ok(());
    }
    let mut had_error = false;
    for r in reports {
        match &r.outcome {
            Ok(crate::profile::UpdateOutcome::UpToDate) => {
                println!("{:<24} up to date", r.name);
            }
            Ok(crate::profile::UpdateOutcome::Refreshed) => {
                println!("{:<24} refreshed", r.name);
            }
            Err(e) => {
                had_error = true;
                println!("{:<24} ERROR: {e:#}", r.name);
            }
        }
    }
    if had_error {
        anyhow::bail!("one or more profile updates failed");
    }
    Ok(())
}

// ---- completions --------------------------------------------------------

fn cmd_completions(args: &CompletionsArgs) -> Result<crate::reports::CompletionsReport> {
    use std::io::IsTerminal as _;

    let mut cmd = Cli::command();
    let bin = "secretenv";
    let mut buf: Vec<u8> = Vec::new();
    match args.shell {
        Shell::Bash => {
            clap_complete::generate(clap_complete::shells::Bash, &mut cmd, bin, &mut buf);
        }
        Shell::Zsh => {
            clap_complete::generate(clap_complete::shells::Zsh, &mut cmd, bin, &mut buf);
        }
        Shell::Fish => {
            clap_complete::generate(clap_complete::shells::Fish, &mut cmd, bin, &mut buf);
        }
    }

    if let Some(path) = &args.output {
        std::fs::write(path, &buf)
            .with_context(|| format!("writing completion script to '{}'", path.display()))?;
        // Best-effort chmod 0o644. On non-Unix this is a no-op.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o644)).with_context(
                || format!("chmod 0o644 on completion script '{}'", path.display()),
            )?;
        }
        eprintln!("wrote {} completion script to '{}'", args.shell.name(), path.display());
    } else {
        std::io::Write::write_all(&mut std::io::stdout(), &buf)
            .context("writing completion script to stdout")?;
        // If we're printing to a TTY, the user ran this interactively
        // — point them at the canonical install location. Silent on
        // redirect (the usual `secretenv completions zsh > _secretenv`
        // pipeline).
        if std::io::stdout().is_terminal() {
            eprintln!();
            eprintln!("{}", args.shell.install_hint());
        }
    }
    Ok(crate::reports::CompletionsReport { outcome: crate::reports::CommandOutcome::Ok })
}

impl Shell {
    const fn name(self) -> &'static str {
        match self {
            Self::Bash => "bash",
            Self::Zsh => "zsh",
            Self::Fish => "fish",
        }
    }

    const fn install_hint(self) -> &'static str {
        match self {
            Self::Bash => {
                "# install: add to ~/.bashrc (or /etc/bash_completion.d/):\n\
                 #   source <(secretenv completions bash)"
            }
            Self::Zsh => {
                "# install (replace PATH with a directory in your fpath):\n\
                 #   secretenv completions zsh > \"$HOME/.zsh/completions/_secretenv\"\n\
                 # then ensure your ~/.zshrc has:\n\
                 #   fpath=(~/.zsh/completions $fpath)\n\
                 #   autoload -U compinit && compinit"
            }
            Self::Fish => {
                "# install:\n\
                 #   secretenv completions fish > \"$HOME/.config/fish/completions/secretenv.fish\""
            }
        }
    }
}

// Avoid unused-import warnings on FromStr when RegistrySelection::from_str
// isn't called through the trait method directly.
const _: fn() = || {
    let _ = <RegistrySelection as FromStr>::from_str;
};

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use std::collections::HashMap;

    use secretenv_core::{BackendConfig, RegistryConfig};

    use super::*;

    fn config_with_default() -> Config {
        Config {
            registries: HashMap::from([(
                "default".to_owned(),
                RegistryConfig { sources: vec!["local:///tmp/r.toml".to_owned()] },
            )]),
            backends: HashMap::from([(
                "local".to_owned(),
                BackendConfig { backend_type: "local".into(), raw_fields: HashMap::new() },
            )]),
            mcp: None,
        }
    }

    #[test]
    fn selection_prefers_explicit_flag() {
        let cfg = config_with_default();
        let sel = resolve_selection(Some("prod"), None, &cfg).unwrap();
        match sel {
            RegistrySelection::Name(n) => assert_eq!(n, "prod"),
            RegistrySelection::Uri(_) => panic!("expected Name"),
        }
    }

    #[test]
    fn selection_uses_env_when_flag_absent() {
        let cfg = config_with_default();
        let sel = resolve_selection(None, Some("shared"), &cfg).unwrap();
        match sel {
            RegistrySelection::Name(n) => assert_eq!(n, "shared"),
            RegistrySelection::Uri(_) => panic!("expected Name"),
        }
    }

    #[test]
    fn selection_falls_back_to_default_when_no_flag_or_env() {
        let cfg = config_with_default();
        let sel = resolve_selection(None, None, &cfg).unwrap();
        match sel {
            RegistrySelection::Name(n) => assert_eq!(n, "default"),
            RegistrySelection::Uri(_) => panic!("expected Name"),
        }
    }

    #[test]
    fn selection_errors_when_nothing_configured() {
        let cfg = Config::default();
        let err = resolve_selection(None, None, &cfg).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("no registry selected"), "clear error: {msg}");
    }

    #[test]
    fn selection_interprets_triple_slash_as_uri() {
        let cfg = Config::default();
        let sel = resolve_selection(Some("local:///tmp/r.toml"), None, &cfg).unwrap();
        match sel {
            RegistrySelection::Uri(u) => assert_eq!(u.scheme, "local"),
            RegistrySelection::Name(_) => panic!("expected Uri"),
        }
    }

    #[test]
    fn selection_treats_empty_env_as_absent() {
        let cfg = config_with_default();
        let sel = resolve_selection(None, Some(""), &cfg).unwrap();
        match sel {
            RegistrySelection::Name(n) => assert_eq!(n, "default"),
            RegistrySelection::Uri(_) => panic!("expected Name"),
        }
    }

    // Pre-v0.14 `serialize_registry(backend_type, map)` helper tests
    // were removed when the dispatch moved to the `Backend` trait
    // (Phase 3 BREAKING #3). Per-backend serialization round-trips
    // are now tested inside each backend's own crate; the
    // alphabetical-ordering invariant is preserved by `BTreeMap`'s
    // intrinsic ordering and is no longer a CLI-layer concern.
}