secrets-vault 2.0.0

AES-256-GCM encrypted key-value vault with PBKDF2 key derivation. Store API keys and tokens securely instead of plaintext dotfiles.
Documentation
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
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use std::{env, fs, process};

use clap::{Parser, Subcommand};
use rpassword::prompt_password;
use zeroize::Zeroizing;

use secrets_vault::{
    is_v1, is_v2, is_valid_key, parse_env_lines, random_bytes, random_salt, v2_create, v2_salt,
    MasterSecret, Vault, VaultError, VaultReader,
};

mod backend;
mod gsm;
mod inbox;
mod keychain;
mod registry;
mod session;

use backend::Backend;

#[derive(Parser)]
#[command(name = "secrets", version = "2.0.0")]
#[command(about = "Encrypted secret manager — AES-256-GCM + PBKDF2")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Store a secret (prompts if no value given)
    Set {
        key: String,
        value: Option<String>,
        /// Read the value from stdin (explicit; a piped/redirected stdin is
        /// also auto-detected without this flag). Errors if a positional
        /// value is also given.
        #[arg(long, conflicts_with = "value")]
        stdin: bool,
        /// Namespace under a project (stored internally as project/KEY)
        #[arg(long, short)]
        project: Option<String>,
        /// Store in Google Secret Manager (requires --project = GCP project id)
        #[arg(long)]
        gsm: bool,
        /// Write to the external backend configured in .secrets.toml's [backend]
        /// block (AWS / Vault / Doppler / 1Password / …) instead of the local vault.
        #[arg(long)]
        remote: bool,
        /// Seal into the write-only inbox (no Touch ID) instead of the vault. Merge
        /// later with one tap (`secrets inbox merge`). Local-vault only.
        #[arg(long)]
        inbox: bool,
    },
    /// Generate a random secret and store it — value is NEVER printed
    Gen {
        /// Secret name
        key: String,
        /// Number of random bytes (hex-encoded; default 32 → 64 hex chars)
        #[arg(long, default_value_t = 32)]
        bytes: usize,
        /// Overwrite if the key already exists (local only)
        #[arg(long)]
        force: bool,
        /// Namespace under a project (stored internally as project/KEY)
        #[arg(long, short)]
        project: Option<String>,
        /// Store in Google Secret Manager (requires --project = GCP project id)
        #[arg(long)]
        gsm: bool,
        /// Write to the external backend configured in .secrets.toml's [backend]
        /// block (AWS / Vault / Doppler / …) instead of the local vault.
        #[arg(long)]
        remote: bool,
        /// Seal into the write-only inbox (no Touch ID) instead of the vault. Merge
        /// later with one tap (`secrets inbox merge`). Local-vault only.
        #[arg(long)]
        inbox: bool,
    },
    /// Retrieve a secret (stdout, no trailing newline)
    Get {
        key: String,
        /// Namespace under a project (stored internally as project/KEY)
        #[arg(long, short)]
        project: Option<String>,
    },
    /// Remove a secret
    Delete { key: String },
    /// List all stored key names
    List {
        /// Read the plaintext name index (NO unlock / Touch ID) instead of the vault
        #[arg(long)]
        names_only: bool,
    },
    /// Check whether a key exists — names only, NO Touch ID, no value exposure.
    /// Prints `true`/`false`; exits 0 if present, 1 if not. Lets an agent avoid
    /// generating a duplicate secret without unlocking the vault.
    Has {
        key: String,
        /// Namespace under a project (checks project/KEY)
        #[arg(long, short)]
        project: Option<String>,
    },
    /// Output as shell exports or JSON
    Env {
        #[arg(long)]
        json: bool,
    },
    /// Import KEY=VALUE lines from stdin
    Import,
    /// Export all as KEY=VALUE
    Export,
    /// Store the vault passphrase in the biometric Keychain (Touch ID on read)
    Unlock {
        /// Strict mode: enrolled biometry ONLY (no watch/passcode fallback),
        /// self-invalidates on fingerprint change, and forces a FRESH tap on every
        /// read (no grace window). Trades convenience for max security.
        #[arg(long)]
        strict: bool,
    },
    /// Remove the biometric Keychain entry (re-lock)
    Lock,
    /// Start a session-unlock broker: ONE Touch ID, then `secrets exec` runs
    /// tap-free for the lifetime (ssh-agent model). For unattended drains —
    /// the passphrase stays in the broker's memory, never in a child env.
    Session {
        /// Broker lifetime in minutes (it self-terminates after this).
        #[arg(default_value = "60")]
        minutes: u64,
    },
    /// INTERNAL: the detached session-broker serve loop. Reads the passphrase
    /// from stdin (a pipe — never argv/env) and serves it on the socket. Not
    /// for direct use; `secrets session` spawns it.
    #[command(hide = true, name = "__session-serve")]
    SessionServe {
        minutes: u64,
    },
    /// Run a command with ONLY a project's secrets in its environment.
    ///   secrets exec <project> -- <command> [args...]
    Exec {
        /// Project name — selects the secret list from .secrets.toml
        project: String,
        /// Human justification shown on the approval prompt ("why do you need this?").
        /// Surfaces on the Touch ID sheet and the aiconductor consent slab so the
        /// approver sees intent, not just a bare biometric scan. Optional; when
        /// omitted the prompt still shows agent/project/keys/command.
        #[arg(long)]
        reason: Option<String>,
        /// Command and arguments (everything after `--`)
        #[arg(last = true)]
        command: Vec<String>,
    },
    /// Authorize an agent to access a project (Touch ID gated)
    Authorize {
        agent: String,
        project: String,
        /// Timed session grant in minutes (default: permanent)
        #[arg(long)]
        session_minutes: Option<u64>,
    },
    /// Revoke an agent's access to a project (Touch ID gated)
    Revoke { agent: String, project: String },
    /// List registered projects and agent grants (Touch ID gated)
    ListProjects,
    /// Write-only inbox for agent-generated secrets (AGENT_SECRET_LIFECYCLE.md)
    Inbox {
        #[command(subcommand)]
        sub: InboxCmd,
    },
    /// Migrate the vault (and grant registry) from v1 to the QVLT v2 format —
    /// per-entry encryption, so reads decrypt ONLY the requested key. One
    /// unlock; the v1 file is preserved as vault.qvlt.v1.bak.
    Migrate,
    /// Re-derive all vault keys under a fresh salt (full decrypt → re-encrypt).
    /// Ends any live session broker first. Run after revoking a party who may
    /// have held the master secret — and delete the old backups it warns about.
    Rekey,
}

#[derive(Subcommand)]
enum InboxCmd {
    /// Generate the inbox keypair (identity → Keychain, recipient → inbox.pub).
    /// Idempotent and tap-free; also lazy-runs on the first `--inbox` write.
    Init,
    /// Show pending entries — names + new/⚠overwrite (from the name index). No Touch ID.
    List,
    /// Open + merge all pending entries into the vault — ONE Touch ID tap. Wipes the
    /// inbox; entries that fail to open stay behind. Overwrites are reported.
    Merge,
    /// Reject a pending entry by name (removes it without merging). No Touch ID.
    Drop { name: String },
}

fn vault_path() -> std::path::PathBuf {
    if let Ok(dir) = env::var("SECRETS_DIR") {
        return std::path::PathBuf::from(dir).join("vault.qvlt");
    }
    dirs::home_dir()
        .expect("HOME not set")
        .join(".config")
        .join("secrets")
        .join("vault.qvlt")
}

fn secrets_dir() -> PathBuf {
    if let Ok(dir) = env::var("SECRETS_DIR") {
        return PathBuf::from(dir);
    }
    dirs::home_dir()
        .expect("HOME not set")
        .join(".config")
        .join("secrets")
}

/// Load a project's manifest from `.secrets.toml` (current dir) or the global
/// `<secrets-dir>/projects.toml`: the secret NAMES it needs, plus which `Backend`
/// supplies the values. Name list comes from `[backend].secrets`, `[gsm].secrets`,
/// `[projects.<name>].secrets`, or a flat top-level `secrets = [...]`.
///
/// Backend selection (first match wins):
/// 1. `[backend]` table → `kind = "vault" | "gsm" | "command"` (see `backend::from_table`).
/// 2. `[gsm].project` → Google Secret Manager (backward-compatible shorthand).
/// 3. otherwise → the local biometric vault.
///
/// Only NAMES ever leave the manifest — values stay in the vault or the external manager.
fn load_manifest(project: &str) -> Result<(Vec<String>, Backend), String> {
    let candidates = [PathBuf::from(".secrets.toml"), secrets_dir().join("projects.toml")];
    let path = candidates.iter().find(|p| p.exists()).ok_or_else(|| {
        "no .secrets.toml in this directory (or projects.toml in your secrets dir)".to_string()
    })?;
    let content =
        fs::read_to_string(path).map_err(|e| format!("reading {}: {e}", path.display()))?;
    let table: toml::Table = content
        .parse()
        .map_err(|e| format!("invalid TOML in {}: {e}", path.display()))?;

    let arr = table
        .get("projects")
        .and_then(|p| p.get(project))
        .and_then(|s| s.get("secrets"))
        .or_else(|| table.get("backend").and_then(|b| b.get("secrets"))) // [backend].secrets
        .or_else(|| table.get("gsm").and_then(|g| g.get("secrets"))) // [gsm].secrets
        .or_else(|| table.get("secrets")) // flat top-level
        .ok_or_else(|| {
            format!("no secret list for '{project}' (expected [backend].secrets, [gsm].secrets, [projects.{project}].secrets, or a top-level secrets = [...])")
        })?;
    let names: Vec<String> = arr
        .as_array()
        .ok_or_else(|| "`secrets` must be an array of names".to_string())?
        .iter()
        .filter_map(|v| v.as_str().map(str::to_string))
        .collect();
    if names.is_empty() {
        return Err(format!("project '{project}' lists no secrets"));
    }

    Ok((names, select_backend(&table)?))
}

/// Choose a `Backend` from a parsed manifest table (first match wins):
/// explicit `[backend]` → `[gsm].project` shorthand → local vault.
fn select_backend(table: &toml::Table) -> Result<Backend, String> {
    if let Some(bt) = table.get("backend").and_then(|b| b.as_table()) {
        backend::from_table(bt)
    } else if let Some(gcp) = table.get("gsm").and_then(|g| g.get("project")).and_then(|p| p.as_str()) {
        Ok(Backend::Gsm(gsm::GsmConfig {
            project: gcp.to_string(),
            account: table
                .get("gsm")
                .and_then(|g| g.get("account"))
                .and_then(|a| a.as_str())
                .map(String::from)
                .or_else(|| env::var("SECRETS_GSM_ACCOUNT").ok()),
            impersonate: table
                .get("gsm")
                .and_then(|g| g.get("impersonate"))
                .and_then(|a| a.as_str())
                .map(String::from)
                .or_else(|| env::var("SECRETS_GSM_IMPERSONATE").ok()),
        }))
    } else {
        Ok(Backend::Vault)
    }
}

/// Read just the backend from the manifest — for `set --remote` / `gen --remote`,
/// which write a value but don't need the project's secret-name list. Errors if no
/// manifest exists or it selects the local vault (there's nothing "remote" to write).
fn manifest_backend() -> Result<Backend, String> {
    let candidates = [PathBuf::from(".secrets.toml"), secrets_dir().join("projects.toml")];
    let path = candidates.iter().find(|p| p.exists()).ok_or_else(|| {
        "no .secrets.toml in this directory (or projects.toml in your secrets dir)".to_string()
    })?;
    let content =
        fs::read_to_string(path).map_err(|e| format!("reading {}: {e}", path.display()))?;
    let table: toml::Table = content
        .parse()
        .map_err(|e| format!("invalid TOML in {}: {e}", path.display()))?;
    let be = select_backend(&table)?;
    if !be.is_external() {
        return Err("no external [backend] in .secrets.toml — nothing to write with --remote".into());
    }
    Ok(be)
}

/// Obtain the master passphrase: `SECRETS_PASSPHRASE` env → biometric Keychain read
/// (the native Touch ID sheet surfaces even from a headless/agent process and blocks
/// until the human taps — verified) → TTY prompt if we have a terminal → else fail
/// closed. Note: a single read here covers a whole `exec` batch (all keys decrypt in
/// one vault-open after this), so an exec does exactly ONE keychain read.
/// Marker file recording that the Keychain item was stored in strict mode, so
/// reads attach a zero-reuse LAContext. The item's own ACL (BiometryCurrentSet) is
/// the hard enforcement — this only controls the read-side reuse behavior.
fn strict_marker_path() -> PathBuf {
    secrets_dir().join("strict")
}

fn is_strict_mode() -> bool {
    strict_marker_path().exists()
}

/// Passphrase acquisition with a custom reason line for the OS Touch ID sheet —
/// so an `exec` can show "read DATABASE_URL for 'promeasure' (agent claude)…" instead
/// of the generic default. The string is display-only; the keychain ACL is the real
/// enforcement. Values never leave this function.
fn get_passphrase_prompted(prompt: &str) -> Zeroizing<String> {
    if let Ok(pass) = env::var("SECRETS_PASSPHRASE") {
        return Zeroizing::new(pass);
    }
    // NOTE (v2): the session broker serves individual VALUES (session.rs), not
    // the passphrase — so there is deliberately no broker hook here. Callers
    // that can use the broker (exec/get with a project) try it BEFORE asking
    // for the passphrase at all.
    match keychain::read(prompt, is_strict_mode()) {
        Ok(Some(p)) => return Zeroizing::new(p),
        Ok(None) => {} // no Keychain item yet (run `secrets unlock`)
        Err(e) => eprintln!("(keychain unavailable: {e})"),
    }
    if atty::is(atty::Stream::Stdin) {
        return prompt_only_passphrase();
    }
    // Headless and the vault isn't unlocked into the Keychain — fail closed.
    eprintln!("Vault is locked and there's no terminal to prompt on.");
    eprintln!("Run `secrets unlock` once (stores the master key behind Touch ID); after");
    eprintln!("that the Touch ID sheet surfaces even from a headless agent invocation.");
    process::exit(1);
}

/// Build the reason line shown on the OS Touch ID sheet for an `exec` unlock.
/// Always names the keys + project (the "what"); adds the agent (the "who") and the
/// human `--reason` (the "why") when known. This is the enrichment that turns the
/// "basic" bare biometric popup into something the human can actually judge.
fn exec_prompt(project: &str, keys: &[String], agent: Option<&str>, reason: Option<&str>) -> String {
    let key_list = if keys.is_empty() {
        "secrets".to_string()
    } else if keys.len() <= 4 {
        keys.join(", ")
    } else {
        format!("{} +{} more", keys[..4].join(", "), keys.len() - 4)
    };
    let mut s = format!("Unlock {key_list} for project “{project}");
    if let Some(a) = agent {
        s.push_str(&format!(" — requested by {a}"));
    }
    if let Some(r) = reason.filter(|r| !r.is_empty()) {
        s.push_str(&format!("\nReason: {r}"));
    }
    s
}

/// Passphrase from env or a TTY prompt only — never the Keychain. Used by
/// `unlock` (which is *setting* the Keychain entry) to avoid a circular read.
fn prompt_only_passphrase() -> Zeroizing<String> {
    if let Ok(pass) = env::var("SECRETS_PASSPHRASE") {
        return Zeroizing::new(pass);
    }
    Zeroizing::new(prompt_password("Vault passphrase: ").unwrap_or_else(|e| {
        eprintln!("Error reading passphrase: {e}");
        process::exit(1);
    }))
}

/// Read a secret value from an interactive TTY, echoing a bullet (•) per
/// character so the typist sees the *length* accumulate — feedback the silent
/// rpassword prompt never gave. The value itself is never echoed. Handles
/// Backspace/Delete (erase one char), Enter (submit), Ctrl-C (abort 130),
/// Ctrl-D (submit what's typed). Falls back to the silent prompt when stdin
/// isn't a real terminal or raw mode can't be entered, so piped/redirected
/// callers are unaffected.
///
/// macOS-only raw path (libc is a macOS-target dep here for sysctl); other
/// platforms keep the silent prompt.
#[cfg(target_os = "macos")]
fn read_masked(prompt: &str) -> String {
    use std::io::Write;
    use std::os::unix::io::AsRawFd;

    // Only drive raw mode on an interactive terminal; else defer to rpassword.
    if !atty::is(atty::Stream::Stdin) {
        return prompt_password(prompt).unwrap_or_default();
    }
    let fd = io::stdin().as_raw_fd();

    let mut orig: libc::termios = unsafe { std::mem::zeroed() };
    if unsafe { libc::tcgetattr(fd, &mut orig) } != 0 {
        return prompt_password(prompt).unwrap_or_default();
    }
    let mut raw = orig; // libc::termios is Copy — `orig` stays valid for restore
    raw.c_lflag &= !(libc::ICANON | libc::ECHO);
    raw.c_cc[libc::VMIN] = 1;
    raw.c_cc[libc::VTIME] = 0;
    if unsafe { libc::tcsetattr(fd, libc::TCSANOW, &raw) } != 0 {
        return prompt_password(prompt).unwrap_or_default();
    }

    // RAII: restore the terminal on every *normal* exit path (return / panic
    // unwind). Ctrl-C uses process::exit, which skips Drop, so that arm
    // restores explicitly before exiting.
    struct TermGuard {
        fd: libc::c_int,
        orig: libc::termios,
    }
    impl Drop for TermGuard {
        fn drop(&mut self) {
            unsafe { libc::tcsetattr(self.fd, libc::TCSANOW, &self.orig) };
        }
    }
    let _guard = TermGuard { fd, orig };

    let mut err = io::stderr();
    let _ = write!(err, "{prompt}");
    let _ = err.flush();

    // Zeroizing so the plaintext buffer is wiped on drop.
    let mut buf: Zeroizing<Vec<u8>> = Zeroizing::new(Vec::new());
    let mut byte = [0u8; 1];
    loop {
        let n = unsafe { libc::read(fd, byte.as_mut_ptr() as *mut libc::c_void, 1) };
        if n <= 0 {
            break; // EOF / read error
        }
        match byte[0] {
            b'\n' | b'\r' => {
                let _ = write!(err, "\r\n");
                let _ = err.flush();
                break;
            }
            3 => {
                // Ctrl-C: restore the terminal ourselves (exit skips Drop), then abort.
                unsafe { libc::tcsetattr(fd, libc::TCSANOW, &orig) };
                let _ = write!(err, "\r\n");
                let _ = err.flush();
                process::exit(130);
            }
            4 => break, // Ctrl-D: submit what's been typed so far
            0x7f | 0x08 => {
                // Backspace/Delete: drop one whole UTF-8 char, erase one bullet.
                if !buf.is_empty() {
                    while let Some(&b) = buf.last() {
                        buf.pop();
                        if (b & 0xC0) != 0x80 {
                            break; // stopped at the lead byte
                        }
                    }
                    let _ = write!(err, "\x08 \x08");
                    let _ = err.flush();
                }
            }
            b => {
                buf.push(b);
                // One bullet per character: skip UTF-8 continuation bytes.
                if (b & 0xC0) != 0x80 {
                    let _ = write!(err, "");
                    let _ = err.flush();
                }
            }
        }
    }
    // `_guard` drops here → terminal restored.
    String::from_utf8_lossy(&buf).into_owned()
}

#[cfg(not(target_os = "macos"))]
fn read_masked(prompt: &str) -> String {
    prompt_password(prompt).unwrap_or_default()
}

/// Legacy v1 whole-vault save — used ONLY by `VaultView::V1` (pre-migration
/// vaults keep the v1 format on write, spec §8).
fn save_vault(vault: &Vault, passphrase: &str) {
    let path = vault_path();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).ok();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(parent, fs::Permissions::from_mode(0o700)).ok();
        }
    }

    let encrypted = vault.encrypt(passphrase).unwrap_or_else(|e| {
        eprintln!("Error encrypting: {e}");
        process::exit(1);
    });

    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        let mut file = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(&path)
            .unwrap_or_else(|e| {
                eprintln!("Error writing vault: {e}");
                process::exit(1);
            });
        io::Write::write_all(&mut file, &encrypted).unwrap();
        write_index(vault);
        return;
    }

    #[cfg(not(unix))]
    {
        fs::write(&path, &encrypted).unwrap_or_else(|e| {
            eprintln!("Error writing vault: {e}");
            process::exit(1);
        });
        write_index(vault);
    }
}

// ── QVLT v2 key material + helpers (QVLT2_SPEC.md §5) ──

fn migrate_hint() {
    eprintln!("note: this vault is in the legacy v1 format (every read decrypts everything).");
    eprintln!("      Run `secrets migrate` once to upgrade to per-entry encryption.");
}

/// Read the vault file, if it exists (any version).
fn read_vault_bytes() -> Option<Vec<u8>> {
    match fs::read(vault_path()) {
        Ok(d) => Some(d),
        Err(e) if e.kind() == io::ErrorKind::NotFound => None,
        Err(e) => {
            eprintln!("Error reading vault: {e}");
            process::exit(1);
        }
    }
}

/// An unlocked vault, dispatched on on-disk format.
///
/// v2: the passphrase was zeroized at derivation (spec G4); reads decrypt one
/// record at a time; writes splice without touching unrelated ciphertext.
/// v1 (pre-`secrets migrate`): legacy whole-blob semantics, passphrase kept as
/// the working key so `save` and the legacy registry container still work.
enum VaultView {
    V2 { master: MasterSecret, reader: VaultReader },
    V1 { pass: Zeroizing<String>, vault: Vault },
}

/// Build a view from an already-obtained passphrase (consumed; zeroized here
/// for v2). Missing vault file → a fresh EMPTY v2 vault is created and
/// persisted immediately, so the salt (and thus the registry key) is stable
/// from the very first unlock.
fn view_from_passphrase(pass: Zeroizing<String>) -> VaultView {
    match read_vault_bytes() {
        Some(d) if is_v2(&d) => {
            let salt = v2_salt(&d).unwrap_or_else(|e| {
                eprintln!("Error: {e}");
                process::exit(1);
            });
            let master = MasterSecret::derive(&pass, &salt);
            drop(pass);
            let reader = open_reader(d, &master);
            VaultView::V2 { master, reader }
        }
        Some(d) if is_v1(&d) => {
            migrate_hint();
            let vault = match Vault::decrypt(&d, &pass) {
                Ok(v) => v,
                Err(VaultError::DecryptionFailed) => {
                    eprintln!("Error: wrong passphrase");
                    process::exit(1);
                }
                Err(e) => {
                    eprintln!("Error: {e}");
                    process::exit(1);
                }
            };
            VaultView::V1 { pass, vault }
        }
        Some(_) => {
            eprintln!("Error: vault file is not a recognized QVLT format");
            process::exit(1);
        }
        None => {
            // New vault → born v2 under a fresh salt, persisted NOW.
            let master = MasterSecret::derive(&pass, &random_salt());
            drop(pass);
            let out = v2_create(&master, &[]).unwrap_or_else(|e| {
                eprintln!("Error creating vault: {e}");
                process::exit(1);
            });
            write_v2_vault(&out, &[]);
            let reader = open_reader(out, &master);
            VaultView::V2 { master, reader }
        }
    }
}

/// ONE passphrase acquisition (env / Touch ID Keychain / TTY) → unlocked view.
fn unlock_view(prompt: &str) -> VaultView {
    view_from_passphrase(get_passphrase_prompted(prompt))
}

impl VaultView {
    fn contains(&self, name: &str) -> bool {
        match self {
            Self::V2 { reader, .. } => reader.contains(name),
            Self::V1 { vault, .. } => vault.get(name).is_some(),
        }
    }

    fn names(&self) -> Vec<String> {
        match self {
            Self::V2 { reader, .. } => reader.names().map(String::from).collect(),
            Self::V1 { vault, .. } => vault.keys().map(String::from).collect(),
        }
    }

    /// Decrypt ONE value (v2: exactly one record — G1). None = not present.
    fn get_one(&self, name: &str) -> Option<Zeroizing<Vec<u8>>> {
        match self {
            Self::V2 { master, reader } => match reader.decrypt_one(master, name) {
                Ok(v) => Some(v),
                Err(VaultError::NotFound) => None,
                Err(e) => {
                    eprintln!("Error: {e}");
                    process::exit(1);
                }
            },
            Self::V1 { vault, .. } => {
                vault.get(name).map(|v| Zeroizing::new(v.as_bytes().to_vec()))
            }
        }
    }

    /// Apply upserts + deletes in one atomic write. v2 splices (untouched
    /// entries are never decrypted — G3); v1 keeps legacy full re-encrypt.
    fn write(&mut self, upserts: Vec<(String, Zeroizing<Vec<u8>>)>, deletes: Vec<String>) {
        match self {
            Self::V2 { master, reader } => {
                let out = reader.splice(master, &upserts, &deletes).unwrap_or_else(|e| {
                    eprintln!("Error encrypting: {e}");
                    process::exit(1);
                });
                let mut names: std::collections::BTreeSet<String> =
                    reader.names().map(String::from).collect();
                for d in &deletes {
                    names.remove(d);
                }
                for (n, _) in &upserts {
                    names.insert(n.clone());
                }
                let names: Vec<String> = names.into_iter().collect();
                write_v2_vault(&out, &names);
                *reader = open_reader(out, master); // view stays consistent
            }
            Self::V1 { pass, vault } => {
                for d in &deletes {
                    vault.delete(d);
                }
                for (n, v) in upserts {
                    vault.set(n, String::from_utf8_lossy(&v).into_owned());
                }
                save_vault(vault, pass);
            }
        }
    }

    /// Full decrypt — ONLY for the inherently whole-vault ops (env/export/
    /// legacy list of values). Discouraged elsewhere.
    fn decrypt_all(&self) -> Vault {
        match self {
            Self::V2 { master, reader } => reader.decrypt_all(master).unwrap_or_else(|e| {
                eprintln!("Error: {e}");
                process::exit(1);
            }),
            Self::V1 { vault, .. } => vault.clone(),
        }
    }

    fn registry_load(&self, dir: &Path) -> Result<registry::Registry, String> {
        match self {
            Self::V2 { master, .. } => registry::Registry::load_raw(dir, &master.registry_key()),
            Self::V1 { pass, .. } => registry::Registry::load_v1(dir, pass),
        }
    }

    fn registry_save(&self, reg: &registry::Registry, dir: &Path) -> Result<(), String> {
        match self {
            Self::V2 { master, .. } => reg.save_raw(dir, &master.registry_key()),
            Self::V1 { pass, .. } => reg.save_v1(dir, pass),
        }
    }
}

/// Open + MAC-verify a v2 image, exiting with the standard message on failure.
fn open_reader(data: Vec<u8>, master: &MasterSecret) -> VaultReader {
    match VaultReader::open(data, master) {
        Ok(r) => r,
        Err(VaultError::DecryptionFailed) => {
            eprintln!("Error: wrong passphrase (or tampered vault)");
            process::exit(1);
        }
        Err(e) => {
            eprintln!("Error: {e}");
            process::exit(1);
        }
    }
}

/// Atomic v2 vault write (spec §5.2 step 4): 0600 temp in the secrets dir,
/// fsync the file, rename over vault.qvlt, fsync the DIRECTORY (without it the
/// rename itself can be lost on crash). Refreshes the plaintext name index.
fn write_v2_vault(bytes: &[u8], names: &[String]) {
    let path = vault_path();
    let parent = path.parent().expect("vault path has a parent").to_path_buf();
    fs::create_dir_all(&parent).ok();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(&parent, fs::Permissions::from_mode(0o700)).ok();
    }
    let tmp = parent.join(".vault.qvlt.tmp");
    #[cfg(unix)]
    let mut file = {
        use std::os::unix::fs::OpenOptionsExt;
        fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(&tmp)
            .unwrap_or_else(|e| {
                eprintln!("Error writing vault: {e}");
                process::exit(1);
            })
    };
    #[cfg(not(unix))]
    let mut file = fs::File::create(&tmp).unwrap_or_else(|e| {
        eprintln!("Error writing vault: {e}");
        process::exit(1);
    });
    io::Write::write_all(&mut file, bytes).unwrap_or_else(|e| {
        eprintln!("Error writing vault: {e}");
        process::exit(1);
    });
    file.sync_all().ok();
    drop(file);
    fs::rename(&tmp, &path).unwrap_or_else(|e| {
        eprintln!("Error replacing vault: {e}");
        process::exit(1);
    });
    if let Ok(dir) = fs::File::open(&parent) {
        dir.sync_all().ok(); // directory fsync — makes the rename durable
    }
    write_index_names(names);
}

/// Plaintext index of vault KEY NAMES (never values) at `<secrets-dir>/index.json`,
/// refreshed on every vault save. Lets an agent answer "do we already have KEY?"
/// (`secrets has`) and enumerate names (`secrets list --names-only`) with NO Touch
/// ID and zero value exposure — names aren't secret (the manifest lists them too).
/// Newline-delimited, owner-only 0600. Best-effort: the encrypted vault stays the
/// source of truth; the index is only a no-unlock existence hint.
fn index_path() -> PathBuf {
    secrets_dir().join("index.json")
}

fn write_index(vault: &Vault) {
    let names: Vec<String> = vault.keys().map(String::from).collect();
    write_index_names(&names);
}

fn write_index_names(names: &[String]) {
    let body = names.join("\n");
    let path = index_path();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).ok();
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        if let Ok(mut f) = fs::OpenOptions::new()
            .write(true).create(true).truncate(true).mode(0o600).open(&path)
        {
            io::Write::write_all(&mut f, body.as_bytes()).ok();
        }
    }
    #[cfg(not(unix))]
    {
        fs::write(&path, body.as_bytes()).ok();
    }
}

fn read_index() -> Vec<String> {
    fs::read_to_string(index_path())
        .map(|s| s.lines().filter(|l| !l.is_empty()).map(String::from).collect())
        .unwrap_or_default()
}

/// Validate key (+ project) and build the storage key: `project/KEY` or `KEY`.
fn scoped_key(project: &Option<String>, key: &str) -> String {
    if !is_valid_key(key) {
        eprintln!("Invalid key: '{key}' (use A-Z, 0-9, _, -)");
        process::exit(1);
    }
    match project {
        Some(p) => {
            if !secrets_vault::is_valid_project(p) {
                eprintln!("Invalid project: '{p}' (use A-Z, 0-9, _, -, .)");
                process::exit(1);
            }
            format!("{p}/{key}")
        }
        None => key.to_string(),
    }
}

/// Build a GSM config for a GCP project, taking the acting account / impersonation
/// from the environment (override the active gcloud account if it lacks perms).
fn gsm_config(project: String) -> gsm::GsmConfig {
    gsm::GsmConfig {
        project,
        account: env::var("SECRETS_GSM_ACCOUNT").ok(),
        impersonate: env::var("SECRETS_GSM_IMPERSONATE").ok(),
    }
}

/// Directory both `secrets` and `aiconductor` use for the approval handshake.
/// A plain same-user dir (no App Group entitlement / provisioning profile).
/// COORDINATION: aiconductor must watch this same path.
fn approval_dir() -> PathBuf {
    if let Ok(d) = env::var("SECRETS_APPROVAL_DIR") {
        return PathBuf::from(d);
    }
    dirs::home_dir()
        .expect("HOME not set")
        .join(".secrets")
        .join("pending_approvals")
}

/// Request real-time approval via aiconductor and return whether a valid grant
/// now exists. SECURITY: the `[id]_response.json` file is an UNTRUSTED "re-check"
/// signal — a same-user agent could forge it. The approval is real ONLY if a
/// grant now appears in the encrypted `registry.enc`, which only aiconductor (with
/// the human's biometric) can write. We re-read the registry with the passphrase
/// we already hold — no second CLI prompt.
fn ipc_approval(
    agent: &str,
    project: &str,
    command: &str,
    keys: &[String],
    reason: Option<&str>,
    reg_dir: &Path,
    view: &VaultView,
) -> bool {
    let dir = approval_dir();
    if fs::create_dir_all(&dir).is_err() {
        eprintln!("Could not create approval dir {}", dir.display());
        return false;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = fs::set_permissions(&dir, fs::Permissions::from_mode(0o700));
    }

    let id = to_hex(&random_bytes(16));
    let req_path = dir.join(format!("{id}.json"));
    let resp_path = dir.join(format!("{id}_response.json"));

    let mut req = serde_json::json!({
        "id": id, "agent": agent, "project": project, "command": command, "keys": keys,
    });
    // Human justification (`--reason`), shown on the aiconductor consent slab. Omitted
    // from the wire when absent so the field only appears when there's a real reason.
    if let Some(r) = reason.filter(|r| !r.is_empty()) {
        req["reason"] = serde_json::Value::String(r.to_string());
    }
    if fs::write(&req_path, serde_json::to_vec_pretty(&req).unwrap_or_default()).is_err() {
        eprintln!("Could not write approval request.");
        return false;
    }

    eprintln!("Waiting for approval in aiconductor… ({agent}{project})");
    let timeout = env::var("SECRETS_APPROVAL_TIMEOUT_SECS")
        .ok()
        .and_then(|s| s.parse::<u64>().ok())
        .unwrap_or(30);
    let start = Instant::now();
    let granted = loop {
        if resp_path.exists() {
            // Untrusted signal → re-read the encrypted registry (the real boundary).
            let reg = view.registry_load(reg_dir).unwrap_or_default();
            break reg.grant_for(agent, project, registry::now()).is_some();
        }
        if start.elapsed().as_secs() >= timeout {
            eprintln!("Approval timed out (is aiconductor running?).");
            break false;
        }
        std::thread::sleep(Duration::from_millis(100));
    };

    let _ = fs::remove_file(&req_path);
    let _ = fs::remove_file(&resp_path);
    granted
}

fn to_hex(bytes: &[u8]) -> String {
    use std::fmt::Write as _;
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        let _ = write!(s, "{b:02x}");
    }
    s
}

/// Loud stderr warning for the `secrets env` vault-dump footgun.
fn eval_warning() {
    let (red, bold, off) = if atty::is(atty::Stream::Stderr) {
        ("\x1b[1;31m", "\x1b[1m", "\x1b[0m")
    } else {
        ("", "", "")
    };
    eprintln!("{red}⚠️  WARNING:{off} `secrets env` dumps your ENTIRE vault into the shell");
    eprintln!("   environment — every secret is then exposed to ALL child processes");
    eprintln!("   (including untrusted npm/pip postinstall scripts).");
    eprintln!("   Use {bold}secrets exec <project> -- <cmd>{off} for scoped, child-only injection.");
}

fn main() {
    let cli = Cli::parse();
    match cli.command {
        Commands::Set { key, value, stdin, project, gsm, remote, inbox } => {
            if !is_valid_key(&key) {
                eprintln!("Invalid key: '{key}' (use A-Z, 0-9, _, -)");
                process::exit(1);
            }
            let value = match value {
                Some(v) => v,
                None => {
                    // Explicit --stdin, or an auto-detected non-TTY stdin, reads
                    // the value from stdin (never argv). An interactive TTY gets
                    // the masked prompt (bullets show length; value never echoed).
                    if stdin || atty::isnt(atty::Stream::Stdin) {
                        // Read the ENTIRE payload to EOF. Multi-line values (e.g. a
                        // pretty-printed JSON service-account key) must NOT be
                        // truncated at the first newline — read_line did exactly
                        // that, storing only `{`. Strip a single trailing newline so
                        // the common `echo secret | secrets set` case stores `secret`
                        // (not `secret\n`); internal newlines are preserved verbatim.
                        let mut buf = String::new();
                        io::stdin().read_to_string(&mut buf).expect("Failed to read stdin");
                        let trimmed = buf.strip_suffix('\n').unwrap_or(&buf);
                        let trimmed = trimmed.strip_suffix('\r').unwrap_or(trimmed);
                        trimmed.to_string()
                    } else {
                        read_masked(&format!("Enter value for {key}: "))
                    }
                }
            };
            if value.is_empty() {
                eprintln!("Error: empty value");
                process::exit(1);
            }
            if inbox {
                if gsm || remote {
                    eprintln!("--inbox seals into the local vault inbox; not valid with --gsm/--remote.");
                    process::exit(1);
                }
                let storage = scoped_key(&project, &key);
                match inbox::append(&secrets_dir(), &storage, &value) {
                    Ok(count) => eprintln!(
                        "Sealed {storage} into the inbox ({count} pending) — no Touch ID. \
                         Merge later: secrets inbox merge"
                    ),
                    Err(e) => {
                        eprintln!("Inbox error: {e}");
                        process::exit(1);
                    }
                }
            } else if remote {
                let be = manifest_backend().unwrap_or_else(|e| {
                    eprintln!("Error: {e}");
                    process::exit(1);
                });
                match be.add(&key, &value) {
                    Ok(()) => eprintln!("Stored {key}{}.", be.label()),
                    Err(e) => {
                        eprintln!("{} error: {e}", be.label());
                        process::exit(1);
                    }
                }
            } else if gsm {
                let proj = project.unwrap_or_else(|| {
                    eprintln!("--gsm requires --project <gcp-project>");
                    process::exit(1);
                });
                let cfg = gsm_config(proj);
                match gsm::add(&cfg, &key, &value) {
                    Ok(()) => eprintln!("Stored {key} → GSM project '{}'.", cfg.project),
                    Err(e) => {
                        eprintln!("GSM error: {e}");
                        process::exit(1);
                    }
                }
            } else {
                let storage = scoped_key(&project, &key);
                let mut view = unlock_view("Unlock your secrets vault");
                view.write(
                    vec![(storage.clone(), Zeroizing::new(value.into_bytes()))],
                    vec![],
                );
                eprintln!("Stored: {storage}");
            }
        }

        Commands::Gen { key, bytes, force, project, gsm, remote, inbox } => {
            if !is_valid_key(&key) {
                eprintln!("Invalid key: '{key}' (use A-Z, 0-9, _, -)");
                process::exit(1);
            }
            if bytes == 0 || bytes > 1024 {
                eprintln!("Error: --bytes must be between 1 and 1024");
                process::exit(1);
            }
            // Random bytes → hex. The value is NEVER printed (no stdout, no
            // scrollback, no shell history): the agent only handles the name.
            let value = to_hex(&random_bytes(bytes));
            if inbox {
                if gsm || remote {
                    eprintln!("--inbox seals into the local vault inbox; not valid with --gsm/--remote.");
                    process::exit(1);
                }
                // new-vs-overwrite is decided at merge against the unlocked vault, so
                // --force is irrelevant here; the inbox always accepts the seal.
                let _ = force;
                let storage = scoped_key(&project, &key);
                match inbox::append(&secrets_dir(), &storage, &value) {
                    Ok(count) => eprintln!(
                        "Generated {storage} ({bytes} bytes) → sealed into the inbox ({count} pending), \
                         value never printed. Merge later: secrets inbox merge"
                    ),
                    Err(e) => {
                        eprintln!("Inbox error: {e}");
                        process::exit(1);
                    }
                }
            } else if remote {
                let be = manifest_backend().unwrap_or_else(|e| {
                    eprintln!("Error: {e}");
                    process::exit(1);
                });
                match be.add(&key, &value) {
                    Ok(()) => eprintln!(
                        "Generated {key} ({bytes} bytes) → {} — value never printed.",
                        be.label()
                    ),
                    Err(e) => {
                        eprintln!("{} error: {e}", be.label());
                        process::exit(1);
                    }
                }
            } else if gsm {
                let proj = project.unwrap_or_else(|| {
                    eprintln!("--gsm requires --project <gcp-project>");
                    process::exit(1);
                });
                let cfg = gsm_config(proj);
                match gsm::add(&cfg, &key, &value) {
                    Ok(()) => eprintln!(
                        "Generated {key} ({bytes} bytes) → GSM project '{}' — value never printed.",
                        cfg.project
                    ),
                    Err(e) => {
                        eprintln!("GSM error: {e}");
                        process::exit(1);
                    }
                }
            } else {
                let storage = scoped_key(&project, &key);
                let mut view = unlock_view("Unlock your secrets vault");
                // Existence check needs NO value decryption in v2.
                if view.contains(&storage) && !force {
                    eprintln!("'{storage}' already exists — use --force to regenerate (overwrites).");
                    process::exit(1);
                }
                view.write(
                    vec![(storage.clone(), Zeroizing::new(value.into_bytes()))],
                    vec![],
                );
                eprintln!("Generated {storage} ({bytes} random bytes, hex) — value stored, never printed.");
            }
        }

        Commands::Get { key, project } => {
            let storage = scoped_key(&project, &key);
            // Session broker first (v2, per-key, grant-checked server-side):
            // a granted agent inside a session window reads tap-free; everyone
            // else silently falls through to the Touch ID path below.
            if let Some(p) = &project {
                if let Some(value) = session::request_value(&secrets_dir(), p, &key) {
                    io::Write::write_all(&mut io::stdout(), &value).ok();
                    return;
                }
            }
            let view = unlock_view(&format!("Read {storage} from your secrets vault"));
            match view.get_one(&storage) {
                Some(value) => {
                    io::Write::write_all(&mut io::stdout(), &value).ok();
                }
                None => {
                    eprintln!("Not found: {key}");
                    process::exit(1);
                }
            }
        }

        Commands::Delete { key } => {
            let mut view = unlock_view(&format!("Delete {key} from your secrets vault"));
            if !view.contains(&key) {
                eprintln!("Not found: {key}");
                process::exit(1);
            }
            // v2: removal is a splice — no value (this one or any other) is decrypted.
            view.write(vec![], vec![key.clone()]);
            eprintln!("Deleted: {key}");
        }

        Commands::List { names_only } => {
            if names_only {
                // No unlock: read the plaintext name index.
                for key in read_index() {
                    println!("{key}");
                }
            } else {
                // Authenticated listing: MAC-verified names. v2 decrypts NO values.
                let view = unlock_view("List your secrets vault");
                let names = view.names();
                write_index_names(&names); // self-heal the index
                for key in &names {
                    println!("{key}");
                }
            }
        }

        Commands::Has { key, project } => {
            let storage = scoped_key(&project, &key);
            let exists = read_index().iter().any(|k| k == &storage);
            println!("{exists}");
            process::exit(if exists { 0 } else { 1 });
        }

        Commands::Env { json } => {
            // The `eval $(secrets env)` footgun — warn loudly (to stderr, so it
            // doesn't pollute the eval'd stdout). The shell-exports form is the one
            // people pipe into `eval`, so target that path.
            if !json {
                eval_warning();
            }
            let view = unlock_view("Dump your ENTIRE secrets vault (env)");
            let vault = view.decrypt_all();
            if json {
                print!("{}", vault.to_json());
            } else {
                print!("{}", vault.to_shell_exports());
            }
        }

        Commands::Import => {
            let mut input = String::new();
            io::stdin()
                .read_to_string(&mut input)
                .expect("Failed to read stdin");
            let pairs = parse_env_lines(&input);
            let count = pairs.len();
            let upserts: Vec<(String, Zeroizing<Vec<u8>>)> = pairs
                .into_iter()
                .map(|(k, v)| (k, Zeroizing::new(v.into_bytes())))
                .collect();
            // v2: one splice — existing entries are never decrypted (G3).
            let mut view = unlock_view("Import secrets into your vault");
            view.write(upserts, vec![]);
            eprintln!("Imported {count} secrets");
        }

        Commands::Export => {
            // The KEY=VALUE line format is newline-delimited, so it cannot faithfully
            // carry a value that itself contains newlines (a multi-line JSON key would
            // be split across physical lines and `import` — which parses line-by-line —
            // would only recover the first fragment). Rather than silently corrupt such
            // a value, warn loudly to stderr (stdout stays clean for redirection).
            let view = unlock_view("Export your ENTIRE secrets vault");
            let vault = view.decrypt_all();
            for (key, value) in vault.iter() {
                if value.contains('\n') {
                    eprintln!(
                        "warning: '{key}' is multi-line; the KEY=VALUE export format cannot \
                         round-trip it via `import`. Use `secrets get {key}` to retrieve it intact."
                    );
                }
                println!("{key}={value}");
            }
        }

        Commands::Unlock { strict } => {
            let pass = prompt_only_passphrase();
            // If a vault already exists, verify the passphrase opens it before
            // storing — don't lock in a wrong passphrase.
            if let Ok(data) = fs::read(vault_path()) {
                let ok = if is_v2(&data) {
                    v2_salt(&data)
                        .map(|salt| {
                            let m = MasterSecret::derive(&pass, &salt);
                            VaultReader::open(data, &m).is_ok()
                        })
                        .unwrap_or(false)
                } else {
                    Vault::decrypt(&data, &pass).is_ok()
                };
                if !ok {
                    eprintln!("Wrong passphrase — nothing stored.");
                    process::exit(1);
                }
            }
            match keychain::store(&pass, strict) {
                Ok(()) => {
                    // Persist (or clear) the strict marker so reads match the ACL.
                    let marker = strict_marker_path();
                    if strict {
                        if let Some(parent) = marker.parent() {
                            fs::create_dir_all(parent).ok();
                        }
                        let _ = fs::write(&marker, b"1");
                        eprintln!(
                            "Unlocked (STRICT). Enrolled biometry only, no reuse — a fresh Touch ID tap is required on every access."
                        );
                    } else {
                        let _ = fs::remove_file(&marker);
                        eprintln!(
                            "Unlocked. Master key stored in the biometric Keychain — Touch ID required on read (with the system reuse grace)."
                        );
                    }
                }
                Err(e) => {
                    eprintln!("Keychain store failed: {e}");
                    process::exit(1);
                }
            }
        }

        Commands::Lock => match keychain::delete() {
            Ok(()) => {
                let _ = fs::remove_file(strict_marker_path());
                session::end(&secrets_dir());   // also kill any live session broker
                eprintln!("Locked. Biometric Keychain entry removed.");
            }
            Err(e) => {
                eprintln!("Keychain delete failed: {e}");
                process::exit(1);
            }
        },

        Commands::Session { minutes } => {
            // ONE Touch ID here (the Keychain read), then hand the passphrase to
            // a detached broker over a pipe. The broker derives the master
            // secret and zeroizes the passphrase at startup; it serves per-key,
            // grant-checked values — never the passphrase (QVLT2_SPEC.md §6).
            let Some(data) = read_vault_bytes() else {
                eprintln!("No vault yet — nothing to serve. Store a secret first.");
                process::exit(1);
            };
            if !is_v2(&data) {
                // A v1 vault must never revive the passphrase-dispenser broker.
                migrate_hint();
                eprintln!("`secrets session` requires a v2 vault.");
                process::exit(1);
            }
            let pass = get_passphrase_prompted("Start a secrets session (unattended drain)");
            let salt = v2_salt(&data).unwrap_or_else(|e| {
                eprintln!("Error: {e}");
                process::exit(1);
            });
            let master = MasterSecret::derive(&pass, &salt);
            if VaultReader::open(data, &master).is_err() {
                eprintln!("Wrong passphrase — session not started.");
                process::exit(1);
            }
            drop(master);
            // Spawn the detached serve loop; pass the secret via its stdin (pipe),
            // never argv/env. The child re-execs THIS binary's hidden subcommand.
            let exe = env::current_exe().unwrap_or_else(|_| PathBuf::from("secrets"));
            let mut child = process::Command::new(exe)
                .arg("__session-serve")
                .arg(minutes.to_string())
                .stdin(process::Stdio::piped())
                .stdout(process::Stdio::null())
                .stderr(process::Stdio::null())
                .spawn()
                .unwrap_or_else(|e| {
                    eprintln!("Failed to start session broker: {e}");
                    process::exit(1);
                });
            if let Some(mut sin) = child.stdin.take() {
                use std::io::Write as _;
                let _ = sin.write_all(pass.as_bytes());
                // dropping sin closes the pipe → the child stops reading
            }
            // Detach so the broker isn't reaped when this parent (and its shell)
            // exits. We don't wait on it.
            eprintln!(
                "Session started — `secrets exec` runs tap-free for {minutes} min. \
                 `secrets lock` ends it early."
            );
        }

        Commands::SessionServe { minutes } => {
            // Detached broker child. Read the passphrase from stdin (the pipe the
            // parent wrote), then serve it on the socket until expiry/END.
            use std::io::Read as _;
            let mut pass = String::new();
            if std::io::stdin().read_to_string(&mut pass).is_err() {
                process::exit(1);
            }
            let pass = Zeroizing::new(pass);
            if pass.is_empty() {
                process::exit(1);
            }
            session::detach();
            if let Err(e) = session::serve(&secrets_dir(), minutes, pass) {
                eprintln!("session broker: {e}");
                process::exit(1);
            }
            return;
        }

        Commands::Exec { project, reason, command } => {
            if command.is_empty() {
                eprintln!("Usage: secrets exec <project> -- <command> [args...]");
                process::exit(2);
            }
            if !secrets_vault::is_valid_project(&project) {
                eprintln!("Invalid project: '{project}'");
                process::exit(1);
            }
            let (names, be) = load_manifest(&project).unwrap_or_else(|e| {
                eprintln!("Error: {e}");
                process::exit(1);
            });

            let dir = secrets_dir();
            let mut cmd = process::Command::new(&command[0]);
            cmd.args(&command[1..]);
            cmd.env_remove("SECRETS_PASSPHRASE");

            // Session-broker fast path (v2): ask the key server for each
            // declared key. The broker enforces caller identity + grant +
            // manifest SERVER-SIDE and audits every request, so a fully-served
            // batch needs no tap and no client-side registry check. Any miss
            // (no broker, denied, unknown key) → fall through to the Touch ID
            // path for the whole batch.
            let mut broker_served: Option<Vec<(String, Zeroizing<Vec<u8>>)>> = None;
            if matches!(be, Backend::Vault) {
                let mut got = Vec::with_capacity(names.len());
                for name in &names {
                    match session::request_value(&dir, &project, name) {
                        Some(v) => got.push((name.clone(), v)),
                        None => {
                            got.clear();
                            break;
                        }
                    }
                }
                if got.len() == names.len() && !names.is_empty() {
                    broker_served = Some(got);
                }
            }

            let mut injected = 0usize;
            let mut missing: Vec<&str> = Vec::new();

            if let Some(served) = &broker_served {
                eprintln!(
                    "secrets exec: {} secret(s) via session broker (grant-checked, tap-free)",
                    served.len()
                );
                for (name, value) in served {
                    cmd.env(name, std::ffi::OsStr::new(&String::from_utf8_lossy(value).into_owned()));
                    injected += 1;
                }
            } else {
                // Resolve the calling agent up front — it feeds both the enriched
                // Touch ID prompt (the "who") and the approval enforcement below.
                let agent = registry::resolve_agent();

                // One Touch ID: unlock once (native sheet surfaces even headless);
                // the same key material covers the registry AND the per-key vault
                // reads — no second prompt. The sheet names the keys/project/agent
                // and the human --reason instead of a bare "authenticate" default.
                let prompt = exec_prompt(&project, &names, agent.as_deref(), reason.as_deref());
                let view = unlock_view(&prompt);
                let reg = view.registry_load(&dir).unwrap_or_else(|e| {
                    eprintln!("Error: {e}");
                    process::exit(1);
                });

                // Enforcement: a recognized agent must hold a valid grant for this
                // project — or earn one via real-time approval in aiconductor
                // (registry-anchored, NOT the forgeable response file). The request
                // lists the ENTIRE key batch, so the human reviews/authorizes all
                // of it in one consent. A human / unrecognized operator who
                // satisfied Touch ID proceeds.
                if let Some(agent) = agent {
                    if reg.grant_for(&agent, &project, registry::now()).is_none()
                        && !ipc_approval(
                            &agent, &project, &command[0], &names, reason.as_deref(), &dir, &view,
                        )
                    {
                        eprintln!("'{agent}' was not granted access to '{project}'.");
                        eprintln!("Or pre-authorize out-of-band:  secrets authorize {agent} {project}");
                        process::exit(1);
                    }
                    eprintln!("secrets exec: agent '{agent}' authorized for '{project}'.");
                }

                // Inject the project-scoped values under their clean env-var names.
                // Values go ONLY into the child's env, never argv.
                match &be {
                    Backend::Vault => {
                        // v2: decrypt EXACTLY the declared keys (G2) — nothing else
                        // in the vault is ever materialized.
                        for name in &names {
                            let skey = format!("{project}/{name}");
                            match view.get_one(&skey) {
                                Some(value) => {
                                    cmd.env(
                                        name,
                                        std::ffi::OsStr::new(
                                            &String::from_utf8_lossy(&value).into_owned(),
                                        ),
                                    );
                                    injected += 1;
                                }
                                None => missing.push(name.as_str()),
                            }
                        }
                        if !missing.is_empty() {
                            eprintln!("warning: not in vault, skipped: {}", missing.join(", "));
                        }
                    }
                    external => {
                        eprintln!(
                            "secrets exec: pulling {} secret(s) from {}",
                            names.len(),
                            external.label()
                        );
                        for name in &names {
                            match external.access(name) {
                                // Value already has its trailing newline handled by the
                                // backend; goes ONLY into the child's env, never argv.
                                Ok(value) => {
                                    cmd.env(name, value);
                                    injected += 1;
                                }
                                Err(e) => {
                                    eprintln!("  ! {name}: {e}");
                                    missing.push(name.as_str());
                                }
                            }
                        }
                        if !missing.is_empty() {
                            eprintln!(
                                "warning: could not fetch from {}, skipped: {}",
                                external.label(),
                                missing.join(", ")
                            );
                        }
                    }
                }
            }
            eprintln!(
                "secrets exec: injecting {injected} secret(s) into `{}` (project: {project})",
                command[0]
            );

            let mut child = cmd.spawn().unwrap_or_else(|e| {
                eprintln!("Failed to spawn `{}`: {e}", command[0]);
                process::exit(127);
            });

            let status = child.wait().unwrap_or_else(|e| {
                eprintln!("Failed waiting for child: {e}");
                process::exit(1);
            });

            // Forward the child's exact exit code so CI/scripts see the real
            // result (signal → 128 + signo, matching shell convention).
            #[cfg(unix)]
            let code = {
                use std::os::unix::process::ExitStatusExt;
                status
                    .code()
                    .or_else(|| status.signal().map(|s| 128 + s))
                    .unwrap_or(1)
            };
            #[cfg(not(unix))]
            let code = status.code().unwrap_or(1);
            process::exit(code);
        }

        Commands::Authorize { agent, project, session_minutes } => {
            let view = unlock_view(&format!("Authorize '{agent}' for project '{project}'")); // Touch ID
            let dir = secrets_dir();
            let mut reg = view.registry_load(&dir).unwrap_or_else(|e| {
                eprintln!("Error: {e}");
                process::exit(1);
            });
            let scope = match session_minutes {
                Some(m) => registry::Scope::Session { expires: registry::now() + m * 60 },
                None => registry::Scope::Always,
            };
            reg.set_grant(&agent, &project, scope);
            view.registry_save(&reg, &dir).unwrap_or_else(|e| {
                eprintln!("Error: {e}");
                process::exit(1);
            });
            match session_minutes {
                Some(m) => eprintln!("Authorized '{agent}' → '{project}' for {m} min."),
                None => eprintln!("Authorized '{agent}' → '{project}' (permanent)."),
            }
        }

        Commands::Revoke { agent, project } => {
            let view = unlock_view(&format!("Revoke '{agent}' from project '{project}'"));
            let dir = secrets_dir();
            let mut reg = view.registry_load(&dir).unwrap_or_else(|e| {
                eprintln!("Error: {e}");
                process::exit(1);
            });
            if reg.revoke(&agent, &project) {
                view.registry_save(&reg, &dir).unwrap_or_else(|e| {
                    eprintln!("Error: {e}");
                    process::exit(1);
                });
                eprintln!("Revoked '{agent}' → '{project}'.");
            } else {
                eprintln!("No grant for '{agent}' → '{project}'.");
                process::exit(1);
            }
        }

        Commands::ListProjects => {
            let view = unlock_view("List projects and agent grants");
            let dir = secrets_dir();
            let reg = view.registry_load(&dir).unwrap_or_else(|e| {
                eprintln!("Error: {e}");
                process::exit(1);
            });
            if reg.projects.is_empty() && reg.grants.is_empty() {
                println!("(registry empty — no projects or grants yet)");
            } else {
                let now = registry::now();
                if !reg.projects.is_empty() {
                    println!("Projects:");
                    for (name, meta) in &reg.projects {
                        println!("  {name}{} ({} keys)", meta.gcp_project, meta.keys.len());
                    }
                }
                println!("Grants:");
                for (agent, projs) in &reg.grants {
                    for (project, grant) in projs {
                        let scope = match grant.scope {
                            registry::Scope::Always => "permanent".to_string(),
                            registry::Scope::Session { expires } if expires > now => {
                                format!("session, {}m left", (expires - now) / 60)
                            }
                            registry::Scope::Session { .. } => "expired".to_string(),
                        };
                        println!("  {agent}{project} [{scope}]");
                    }
                }
            }
        }

        Commands::Migrate => {
            let dir = secrets_dir();
            let Some(data) = read_vault_bytes() else {
                eprintln!("No vault to migrate — a new vault is created as v2 automatically.");
                process::exit(1);
            };
            if is_v2(&data) {
                // Vault already v2 — still convert a straggler v1 registry.
                let reg_path = registry::Registry::path(&dir);
                let reg_is_v1 = fs::read(&reg_path)
                    .map(|d| d.starts_with(b"QVLT"))
                    .unwrap_or(false);
                if !reg_is_v1 {
                    eprintln!("Vault is already QVLT v2 — nothing to migrate.");
                    return;
                }
                let salt = v2_salt(&data).unwrap_or_else(|e| {
                    eprintln!("Error: {e}");
                    process::exit(1);
                });
                let pass = get_passphrase_prompted("Migrate the grant registry to v2");
                let reg = registry::Registry::load_v1(&dir, &pass).unwrap_or_else(|e| {
                    eprintln!("Error: {e}");
                    process::exit(1);
                });
                let master = MasterSecret::derive(&pass, &salt);
                drop(pass);
                if VaultReader::open(data, &master).is_err() {
                    eprintln!("Error: wrong passphrase");
                    process::exit(1);
                }
                reg.save_raw(&dir, &master.registry_key()).unwrap_or_else(|e| {
                    eprintln!("Error: {e}");
                    process::exit(1);
                });
                eprintln!("Registry converted to the v2 raw-key container.");
                return;
            }
            if !is_v1(&data) {
                eprintln!("Error: vault file is not a recognized QVLT format");
                process::exit(1);
            }

            // ONE unlock: decrypt the v1 vault (this is the last-ever full
            // decrypt), convert the registry with the same passphrase, then
            // derive the v2 master under a FRESH salt and zeroize.
            let pass = get_passphrase_prompted("Migrate vault to v2 (per-entry encryption)");
            let vault = match Vault::decrypt(&data, &pass) {
                Ok(v) => v,
                Err(VaultError::DecryptionFailed) => {
                    eprintln!("Error: wrong passphrase");
                    process::exit(1);
                }
                Err(e) => {
                    eprintln!("Error: {e}");
                    process::exit(1);
                }
            };
            let reg_path = registry::Registry::path(&dir);
            let legacy_reg = if fs::read(&reg_path)
                .map(|d| d.starts_with(b"QVLT"))
                .unwrap_or(false)
            {
                Some(registry::Registry::load_v1(&dir, &pass).unwrap_or_else(|e| {
                    eprintln!("Error: {e}");
                    process::exit(1);
                }))
            } else {
                None
            };
            let master = MasterSecret::derive(&pass, &random_salt());
            drop(pass);

            let entries: Vec<(String, Zeroizing<Vec<u8>>)> = vault
                .iter()
                .map(|(k, v)| (k.to_string(), Zeroizing::new(v.as_bytes().to_vec())))
                .collect();
            let count = entries.len();
            let out = v2_create(&master, &entries).unwrap_or_else(|e| {
                eprintln!("Error encrypting v2 vault: {e}");
                process::exit(1);
            });

            // Preserve the v1 ciphertext as a backup FIRST (0600), then the
            // atomic v2 replace. `rekey` will nag about this file until deleted.
            let backup = vault_path().with_extension("qvlt.v1.bak");
            #[cfg(unix)]
            {
                use std::os::unix::fs::OpenOptionsExt;
                if let Ok(mut f) = fs::OpenOptions::new()
                    .write(true)
                    .create(true)
                    .truncate(true)
                    .mode(0o600)
                    .open(&backup)
                {
                    io::Write::write_all(&mut f, &data).ok();
                }
            }
            #[cfg(not(unix))]
            fs::write(&backup, &data).ok();

            let names: Vec<String> = vault.keys().map(String::from).collect();
            write_v2_vault(&out, &names);
            if let Some(reg) = legacy_reg {
                reg.save_raw(&dir, &master.registry_key()).unwrap_or_else(|e| {
                    eprintln!("Error converting registry: {e}");
                    process::exit(1);
                });
            }
            // A live v1 broker is a passphrase dispenser — kill it.
            session::end(&dir);

            eprintln!("Migrated {count} secret(s) to QVLT v2 (per-entry encryption).");
            eprintln!("Reads now decrypt ONLY the requested key; writes splice without reading.");
            eprintln!("v1 backup kept at {} — delete it once confident:", backup.display());
            eprintln!("  trash {}", backup.display());
        }

        Commands::Rekey => {
            let dir = secrets_dir();
            let Some(data) = read_vault_bytes() else {
                eprintln!("No vault to rekey.");
                process::exit(1);
            };
            if is_v1(&data) {
                migrate_hint();
                eprintln!("`secrets rekey` requires a v2 vault.");
                process::exit(1);
            }
            let salt = v2_salt(&data).unwrap_or_else(|e| {
                eprintln!("Error: {e}");
                process::exit(1);
            });
            let pass = get_passphrase_prompted("Rekey your secrets vault (fresh salt)");
            let old_master = MasterSecret::derive(&pass, &salt);
            let new_master = MasterSecret::derive(&pass, &random_salt());
            drop(pass);

            let reader = open_reader(data, &old_master);
            let vault = reader.decrypt_all(&old_master).unwrap_or_else(|e| {
                eprintln!("Error: {e}");
                process::exit(1);
            });
            let reg = registry::Registry::load_raw(&dir, &old_master.registry_key())
                .unwrap_or_default();

            // A live broker holds keys derived from the OLD salt — every
            // request after the rewrite would fail its MAC check. End it now,
            // loudly (spec §5.1).
            if session::socket_path(&dir).exists() {
                session::end(&dir);
                eprintln!("(ended the live session broker — its keys predate the rekey)");
            }

            let entries: Vec<(String, Zeroizing<Vec<u8>>)> = vault
                .iter()
                .map(|(k, v)| (k.to_string(), Zeroizing::new(v.as_bytes().to_vec())))
                .collect();
            let out = v2_create(&new_master, &entries).unwrap_or_else(|e| {
                eprintln!("Error encrypting: {e}");
                process::exit(1);
            });
            let names: Vec<String> = vault.keys().map(String::from).collect();
            write_v2_vault(&out, &names);
            reg.save_raw(&dir, &new_master.registry_key()).unwrap_or_else(|e| {
                eprintln!("Error re-encrypting registry: {e}");
                process::exit(1);
            });
            eprintln!("Rekeyed {} secret(s) under a fresh salt.", entries.len());

            // A rekey that leaves old-key ciphertext on disk has not revoked
            // anything — name every stale sibling loudly (spec §5.1).
            let mut stale: Vec<PathBuf> = Vec::new();
            for cand in [vault_path().with_extension("qvlt.v1.bak"), dir.join(".vault.qvlt.tmp")] {
                if cand.exists() {
                    stale.push(cand);
                }
            }
            if !stale.is_empty() {
                eprintln!("⚠️  STALE CIPHERTEXT still on disk — the old key material opens these:");
                for s in &stale {
                    eprintln!("   {}", s.display());
                }
                eprintln!("   Delete them (trash <file>) or this rekey revokes nothing.");
            }
        }

        Commands::Inbox { sub } => {
            let dir = secrets_dir();
            match sub {
                InboxCmd::Init => match inbox::ensure_recipient(&dir) {
                    Ok(_) => eprintln!(
                        "Inbox ready — recipient at {} (identity in the Keychain).",
                        inbox::pub_path(&dir).display()
                    ),
                    Err(e) => {
                        eprintln!("Error: {e}");
                        process::exit(1);
                    }
                },

                InboxCmd::List => {
                    let entries = inbox::read_entries(&dir).unwrap_or_default();
                    if entries.is_empty() {
                        eprintln!("Inbox empty — nothing pending.");
                    } else {
                        // new-vs-overwrite from the plaintext name index — no Touch ID.
                        let index = read_index();
                        eprintln!("{} pending (review, then `secrets inbox merge`):", entries.len());
                        for e in &entries {
                            let tag = if index.iter().any(|k| k == &e.name) {
                                "⚠ OVERWRITE"
                            } else {
                                "new"
                            };
                            println!("  {}  [{tag}]", e.name);
                        }
                    }
                }

                InboxCmd::Drop { name } => match inbox::drop_entry(&dir, &name) {
                    Ok(true) => eprintln!("Dropped pending '{name}'."),
                    Ok(false) => {
                        eprintln!("No pending entry named '{name}'.");
                        process::exit(1);
                    }
                    Err(e) => {
                        eprintln!("Error: {e}");
                        process::exit(1);
                    }
                },

                InboxCmd::Merge => {
                    let entries = match inbox::read_entries(&dir) {
                        Ok(e) => e,
                        Err(e) => {
                            eprintln!("Error: {e}");
                            process::exit(1);
                        }
                    };
                    if entries.is_empty() {
                        eprintln!("Inbox empty — nothing to merge.");
                        return;
                    }

                    // ONE tap (non-strict): open the inbox identity + the vault master
                    // under a single shared auth context. Strict mode → a fresh tap each.
                    let vals = match keychain::read_accounts(
                        &["inbox-identity", "vault-master"],
                        is_strict_mode(),
                    ) {
                        Ok(v) => v,
                        Err(e) => {
                            eprintln!("Keychain error: {e}");
                            process::exit(1);
                        }
                    };

                    let identity_str = match vals.first().cloned().flatten() {
                        Some(s) => s,
                        None => {
                            eprintln!("Inbox identity not found — run `secrets inbox init` first.");
                            process::exit(1);
                        }
                    };
                    let identity: age::x25519::Identity = match identity_str.parse() {
                        Ok(i) => i,
                        Err(e) => {
                            eprintln!("Corrupt inbox identity: {e}");
                            process::exit(1);
                        }
                    };

                    // Master: env override → the keychain read above.
                    let master = match env::var("SECRETS_PASSPHRASE")
                        .ok()
                        .or_else(|| vals.get(1).cloned().flatten())
                    {
                        Some(m) => Zeroizing::new(m),
                        None => {
                            eprintln!("Vault is locked — run `secrets unlock` first.");
                            process::exit(1);
                        }
                    };

                    // One unlock covers the whole merge; v2 splices the batch in
                    // without decrypting any existing entry.
                    let mut view = view_from_passphrase(master);
                    let mut new_keys: Vec<String> = Vec::new();
                    let mut overwrites: Vec<String> = Vec::new();
                    let mut failed: Vec<(String, String)> = Vec::new();
                    let mut upserts: Vec<(String, Zeroizing<Vec<u8>>)> = Vec::new();

                    for e in &entries {
                        match inbox::open(&identity, &e.sealed) {
                            Ok(value) => {
                                if view.contains(&e.name) {
                                    overwrites.push(e.name.clone());
                                } else {
                                    new_keys.push(e.name.clone());
                                }
                                upserts.push((e.name.clone(), Zeroizing::new(value.into_bytes())));
                            }
                            Err(err) => failed.push((e.name.clone(), err)),
                        }
                    }

                    if new_keys.is_empty() && overwrites.is_empty() {
                        eprintln!("Nothing merged — all entries failed to open:");
                        for (n, err) in &failed {
                            eprintln!("{n}: {err}");
                        }
                        process::exit(1);
                    }

                    view.write(upserts, vec![]); // also refreshes the name index

                    // Keep only entries that failed to open; remove the merged ones.
                    use std::collections::HashSet;
                    let merged: HashSet<&String> =
                        new_keys.iter().chain(overwrites.iter()).collect();
                    let leftover: Vec<&inbox::Entry> =
                        entries.iter().filter(|e| !merged.contains(&e.name)).collect();
                    if let Err(e) = inbox::rewrite(&dir, &leftover) {
                        eprintln!("(warning: could not rewrite inbox: {e})");
                    }

                    eprintln!(
                        "Merged {} new + {} overwrite into the vault:",
                        new_keys.len(),
                        overwrites.len()
                    );
                    for n in &new_keys {
                        eprintln!("  + {n} (new)");
                    }
                    for n in &overwrites {
                        eprintln!("{n} (OVERWRITE)");
                    }
                    for (n, err) in &failed {
                        eprintln!("{n}: {err} (left in inbox)");
                    }
                }
            }
        }
    }
}