svault-ai 0.6.0

AI-aware secret access layer — enforces structured requests and detects suspicious patterns
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
mod audit;
mod client;
mod config;
mod crypto;
mod daemon;
mod meta;
mod passphrase;
mod policy;
mod portable;
mod recovery;
mod session;
mod tui;
mod usage;
mod vault;

use anyhow::Result;
use clap::{Parser, Subcommand};
use console::style;
use dialoguer::{Confirm, Input, Password, Select};
use std::path::{Path, PathBuf};

use crypto::VaultKey;
use meta::{AccessConfig, AllowAgent, LoginMethod, VaultMeta, VaultSettings};
use vault::{list_vault_dirs, Vault, SVAULT_DIR};

#[derive(Parser)]
#[command(name = "svault", about = "AI-aware secret access layer", version)]
struct Cli {
    /// Run with no subcommand to launch the interactive TUI.
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Create a new encrypted vault in .svault/<name>/
    #[command(alias = "init")]
    Create {
        #[arg(long)]
        name: Option<String>,
    },
    /// View or change a vault's settings (description, agents, rate limit, auto-lock, login)
    Settings {
        /// Vault name (positional). Omit to use the only vault or pick interactively.
        vault: Option<String>,
    },
    /// Manage secrets: add | get | list | remove
    Secret {
        action: String,
        name: Option<String>,
        /// Vault name. Omit to use the only vault or pick interactively.
        #[arg(long, short = 'v')]
        vault: Option<String>,
    },
    /// List all vaults in .svault/
    Vaults,
    /// Unlock vault — caches the derived key for this session
    Unlock {
        /// Vault name (positional). Omit to use the only vault or pick interactively.
        vault: Option<String>,
    },
    /// Lock vault — clears the cached key
    Lock {
        /// Lock all vaults
        #[arg(long)]
        all: bool,
        /// Vault name (positional). Omit to use the only vault or pick interactively.
        vault: Option<String>,
    },
    /// Show lock status of all vaults
    Status,
    /// Wire Svault into your AI platform (Step 4)
    Install {
        #[arg(long, default_value = "auto")]
        platform: String,
        #[arg(long)]
        project: bool,
    },
    /// Request a secret through the policy engine — the agent path.
    Get {
        name: String,
        #[arg(long)]
        scope: String,
        #[arg(long)]
        reason: String,
        /// Identify the caller. Falls back to $SVAULT_CALLER, then "default".
        #[arg(long)]
        caller: Option<String>,
        #[arg(long, short = 'v')]
        vault: Option<String>,
    },
    /// Inspect the policy engine: `policy check <caller>` or `policy init`.
    Policy {
        /// Action: check | init
        action: String,
        /// Caller name (for `check`).
        caller: Option<String>,
    },
    /// Recover a vault with its recovery code and set a new passphrase
    Recover {
        /// Vault name (positional). Omit to use the only vault or pick interactively.
        vault: Option<String>,
    },
    /// Export a vault to a portable encrypted bundle
    Export {
        /// Vault name (positional). Omit to use the only vault or pick interactively.
        vault: Option<String>,
        /// Output file (default: <name>.svault-export.json)
        #[arg(long)]
        out: Option<String>,
    },
    /// Import a vault from a bundle created by `svault export`
    Import {
        /// Path to the .svault-export.json bundle
        file: String,
        /// Import under this name instead of the bundle's own (auto-suffixed if it also exists)
        #[arg(long)]
        name: Option<String>,
    },
    /// Background unlock daemon (Unix): run | start | stop | status | doctor
    Daemon {
        /// Action: run | start | stop | status | doctor
        action: String,
        /// For `doctor`: clean up stale socket / pid files.
        #[arg(long)]
        fix: bool,
    },
}

fn main() -> Result<()> {
    let cli = Cli::parse();
    let Some(command) = cli.command else {
        // No subcommand → interactive TUI.
        return tui::run();
    };
    match command {
        Commands::Create { name } => cmd_create(name),
        Commands::Settings { vault } => cmd_settings(vault.as_deref()),
        Commands::Secret {
            action,
            name,
            vault,
        } => cmd_secret(&action, name.as_deref(), vault.as_deref()),
        Commands::Vaults => cmd_vaults(),
        Commands::Unlock { vault } => cmd_unlock(vault.as_deref()),
        Commands::Lock { all, vault } => cmd_lock(all, vault.as_deref()),
        Commands::Status => cmd_status(),
        Commands::Install { platform, .. } => {
            println!(
                "{} Install for '{}' coming in Step 4",
                style("pending:").yellow(),
                platform
            );
            Ok(())
        }
        Commands::Get {
            name,
            scope,
            reason,
            caller,
            vault,
        } => cmd_get(&name, &scope, &reason, caller.as_deref(), vault.as_deref()),
        Commands::Policy { action, caller } => cmd_policy(&action, caller.as_deref()),
        Commands::Recover { vault } => cmd_recover(vault.as_deref()),
        Commands::Export { vault, out } => cmd_export(vault.as_deref(), out.as_deref()),
        Commands::Import { file, name } => cmd_import(&file, name.as_deref()),
        Commands::Daemon { action, fix } => cmd_daemon(&action, fix),
    }
}

fn cmd_daemon(action: &str, fix: bool) -> Result<()> {
    match action {
        "run" => daemon::run(),
        "start" => daemon::start(),
        "stop" => daemon::stop(),
        "status" => daemon::status(),
        "doctor" => daemon::doctor(fix),
        _ => {
            eprintln!(
                "{} Unknown action '{}'. Use: run | start | stop | status | doctor",
                style("error:").red(),
                action
            );
            std::process::exit(1);
        }
    }
}

/// The directory leaf name (== vault name) the daemon keys vaults by.
fn vault_leaf(dir: &Path) -> String {
    dir.file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_default()
}

// ── Commands ─────────────────────────────────────────────────────────────────

fn cmd_create(name_arg: Option<String>) -> Result<()> {
    println!(
        "{}",
        style("┌─ New Vault ─────────────────────────────┐").dim()
    );

    let storage = prompt_storage_backend()?;

    let default_name = std::env::current_dir()
        .ok()
        .and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
        .unwrap_or_else(|| "my-vault".to_string());

    let name: String = match name_arg {
        Some(n) => n,
        None => Input::new()
            .with_prompt("  Vault name")
            .default(default_name)
            .interact_text()?,
    };

    let vault_dir = PathBuf::from(SVAULT_DIR).join(&name);
    if vault_dir.exists() {
        let existing = VaultMeta::load_unverified(&vault_dir)
            .map(|m| m.storage)
            .unwrap_or_else(|_| "local".to_string());
        eprintln!(
            "{} a vault named '{}' already exists ({}:{}) — names must be unique across storage backends",
            style("error:").red(),
            name,
            existing,
            name,
        );
        std::process::exit(1);
    }

    let description: String = Input::new()
        .with_prompt("  Description")
        .allow_empty(true)
        .interact_text()?;

    let allow_agent = prompt_allow_agent(None)?;

    let rate_limit: String = Input::new()
        .with_prompt("  Rate limit")
        .default("10/hour".to_string())
        .interact_text()?;

    let autolock = Confirm::new()
        .with_prompt("  Auto-lock when idle?")
        .default(true)
        .interact()?;

    let autolock_timer: String = if autolock {
        Input::new()
            .with_prompt("  Auto-lock timer (e.g. 1d, 12h, 30m)")
            .default("1d".to_string())
            .interact_text()?
    } else {
        "1d".to_string()
    };

    let login_method = prompt_login_method(None)?;

    println!();
    let passphrase = Password::new().with_prompt("  Passphrase").interact()?;

    if let Some(w) = passphrase::check(&passphrase) {
        println!("{} {}", style("warning:").yellow(), w.0);
        if !Confirm::new()
            .with_prompt("  Continue anyway?")
            .default(false)
            .interact()?
        {
            return Ok(());
        }
    }

    let confirm = Password::new()
        .with_prompt("  Confirm passphrase")
        .interact()?;
    if passphrase != confirm {
        eprintln!("{} Passphrases do not match", style("error:").red());
        std::process::exit(1);
    }

    println!("\n  Creating vault...");

    let mut meta = VaultMeta::new(
        name.clone(),
        description,
        AccessConfig {
            allow_agent,
            rate_limit,
        },
        VaultSettings {
            autolock,
            autolock_timer,
            login_method,
        },
    );
    meta.storage = storage.to_string();
    let vault = Vault::init(&vault_dir, &passphrase, meta)?;

    // Generate a recovery code and wrap the vault key under it. Shown once.
    let recovery_code = recovery::generate_code();
    recovery::write(&vault_dir, vault.key(), &recovery_code)?;
    usage::human(&vault_dir, "vault.create", None);

    println!();
    println!(
        "  {:<14} {}",
        style("Name").dim(),
        style(format!("{}:{}", storage, &name)).bold().cyan()
    );
    println!("  {:<14} {}", style("Storage").dim(), style(storage).cyan());
    println!(
        "  {:<14} {}",
        style("Location").dim(),
        style(format!("{}/", vault_dir.display())).cyan()
    );
    println!();
    println!("{} Vault '{}' created", style("ok:").green().bold(), name);
    println!(
        "{}",
        style("  vault.enc + meta.yaml are safe to commit — encrypted at rest.").dim()
    );
    println!(
        "{}",
        style(format!("  git add {}/", vault_dir.display())).dim()
    );

    println!();
    println!("{}", style("  RECOVERY CODE").yellow().bold());
    println!("  {}", style(&recovery_code).bold());
    println!(
        "{}",
        style("  This is the ONLY time this code is shown — it is not stored in plaintext.")
            .yellow()
    );
    println!(
        "{}",
        style("  Save it now in a password manager (or on paper, offline).").dim()
    );
    println!(
        "{}",
        style("  It is the only way back in if you lose your passphrase — run 'svault recover'.")
            .dim()
    );

    // Require an explicit acknowledgment that the code was saved — the code is
    // not recoverable once this screen is gone.
    println!();
    while !Confirm::new()
        .with_prompt("  I have saved my recovery code")
        .default(false)
        .interact()?
    {
        println!(
            "{}",
            style("  Save it first — it cannot be retrieved later.").yellow()
        );
    }
    Ok(())
}

/// Interactive settings editor — re-prompts each field with the current value
/// as the default, then re-signs meta.yaml. Requires the passphrase.
fn cmd_settings(vault_name: Option<&str>) -> Result<()> {
    let vault_dir = resolve_vault_dir(vault_name)?;
    let preview = VaultMeta::load_unverified(&vault_dir)?;

    let vault = open_unlocked_or_prompt(&vault_dir, &preview.name)?;

    let mut meta = vault.meta.clone();

    println!(
        "{}",
        style(format!(
            "┌─ Settings · {} ──────────────────────┐",
            meta.name
        ))
        .dim()
    );
    println!(
        "  {:<16} {}",
        style("Description").dim(),
        if meta.description.is_empty() {
            "-".into()
        } else {
            meta.description.clone()
        }
    );
    println!(
        "  {:<16} {}",
        style("Allow agent").dim(),
        meta.access.allow_agent
    );
    println!(
        "  {:<16} {}",
        style("Rate limit").dim(),
        meta.access.rate_limit
    );
    println!(
        "  {:<16} {}",
        style("Auto-lock").dim(),
        meta.settings.autolock
    );
    println!(
        "  {:<16} {}",
        style("Auto-lock timer").dim(),
        meta.settings.autolock_timer
    );
    println!(
        "  {:<16} {}",
        style("Login method").dim(),
        meta.settings.login_method
    );
    println!();

    meta.description = Input::new()
        .with_prompt("  Description")
        .allow_empty(true)
        .with_initial_text(&meta.description)
        .interact_text()?;

    meta.access.allow_agent = prompt_allow_agent(Some(&meta.access.allow_agent))?;

    meta.access.rate_limit = Input::new()
        .with_prompt("  Rate limit")
        .with_initial_text(&meta.access.rate_limit)
        .interact_text()?;

    meta.settings.autolock = Confirm::new()
        .with_prompt("  Auto-lock when idle?")
        .default(meta.settings.autolock)
        .interact()?;

    if meta.settings.autolock {
        meta.settings.autolock_timer = Input::new()
            .with_prompt("  Auto-lock timer (e.g. 1d, 12h, 30m)")
            .with_initial_text(&meta.settings.autolock_timer)
            .interact_text()?;
    }

    meta.settings.login_method = prompt_login_method(Some(meta.settings.login_method))?;

    vault.save_meta(&meta)?;
    usage::human(&vault_dir, "settings.update", None);

    println!();
    println!(
        "{} Settings for '{}' updated",
        style("ok:").green().bold(),
        meta.name
    );
    Ok(())
}

fn cmd_unlock(vault_name: Option<&str>) -> Result<()> {
    let vault_dir = resolve_vault_dir(vault_name)?;
    let meta = VaultMeta::load_unverified(&vault_dir)?;
    let leaf = vault_leaf(&vault_dir);

    let daemon_has = client::unlocked_vaults().iter().any(|n| n == &leaf);
    if daemon_has || session::is_unlocked(&vault_dir) {
        println!(
            "{} Vault '{}' is already unlocked",
            style("ok:").green(),
            meta.name
        );
        return Ok(());
    }

    let passphrase = Password::new()
        .with_prompt(format!("  Passphrase for '{}'", meta.name))
        .interact()?;

    // Prefer the daemon: it validates the passphrase and holds the derived key
    // in memory — no .session file is written.
    if let Some(res) = client::unlock(&leaf, &passphrase) {
        res.map_err(|e| {
            eprintln!("{} {}", style("error:").red(), e);
            std::process::exit(1);
            #[allow(unreachable_code)]
            e
        })?;
        usage::human(&vault_dir, "unlock", None);
        println!(
            "{} Vault '{}' unlocked",
            style("ok:").green().bold(),
            meta.name
        );
        println!(
            "{}",
            style("  Key held by the daemon (in memory, no file written). Run 'svault lock' to clear it.").dim()
        );
        return Ok(());
    }

    // No daemon — fall back to the file session, caching the derived key
    // (never the passphrase) at mode 0600.
    let vault = Vault::open(&vault_dir, &passphrase).map_err(|e| {
        eprintln!("{} {}", style("error:").red(), e);
        std::process::exit(1);
        #[allow(unreachable_code)]
        e
    })?;

    session::unlock_with_key(&vault_dir, vault.key().bytes())?;
    usage::human(&vault_dir, "unlock", None);

    println!(
        "{} Vault '{}' unlocked",
        style("ok:").green().bold(),
        meta.name
    );
    println!(
        "{}",
        style("  Session active — derived key cached in .svault/<name>/.session (mode 0600, not the passphrase)").dim()
    );
    println!("{}", style("  Run 'svault lock' to clear it.").dim());
    Ok(())
}

fn cmd_lock(lock_all: bool, vault_name: Option<&str>) -> Result<()> {
    if lock_all {
        // Lock both the daemon's in-memory keys and any file sessions.
        let daemon_count = client::lock_all().unwrap_or(0);
        let file_count = session::lock_all(std::path::Path::new(SVAULT_DIR))?;
        let count = daemon_count + file_count;
        if count == 0 {
            println!("{}", style("All vaults already locked.").dim());
        } else {
            println!("{} Locked {} vault(s)", style("ok:").yellow().bold(), count);
        }
        return Ok(());
    }

    let vault_dir = resolve_vault_dir(vault_name)?;
    let meta = VaultMeta::load_unverified(&vault_dir)?;
    let leaf = vault_leaf(&vault_dir);
    // Clear the key from the daemon (if up) and the file session (if present).
    client::lock(&leaf);
    session::lock(&vault_dir)?;
    usage::human(&vault_dir, "lock", None);
    println!(
        "{} Vault '{}' locked",
        style("ok:").yellow().bold(),
        meta.name
    );
    Ok(())
}

fn cmd_status() -> Result<()> {
    let dirs = list_vault_dirs();
    if dirs.is_empty() {
        println!(
            "{}",
            style("No vaults found. Run 'svault create' to make one.").dim()
        );
        return Ok(());
    }

    println!(
        "{:<26} {:<12} {}",
        style("VAULT").bold(),
        style("STATUS").bold(),
        style("DESCRIPTION").bold()
    );
    println!("{}", style("".repeat(60)).dim());

    let daemon_unlocked = client::unlocked_vaults();
    for dir in &dirs {
        if let Ok(meta) = VaultMeta::load_unverified(dir) {
            let in_daemon = daemon_unlocked.contains(&vault_leaf(dir));
            let status = if in_daemon {
                style("unlocked (daemon)").green().to_string()
            } else if session::is_unlocked(dir) {
                style("unlocked").green().to_string()
            } else {
                style("locked").dim().to_string()
            };
            println!(
                "{:<26} {:<12} {}",
                style(format!("{}:{}", meta.storage, meta.name)).cyan(),
                status,
                if meta.description.is_empty() {
                    "-".into()
                } else {
                    meta.description.clone()
                },
            );
        }
    }
    Ok(())
}

fn cmd_secret(action: &str, name: Option<&str>, vault_name: Option<&str>) -> Result<()> {
    let vault_dir = resolve_vault_dir(vault_name)?;
    let meta_preview = VaultMeta::load_unverified(&vault_dir)?;
    let leaf = vault_leaf(&vault_dir);

    // Read path: when a daemon holds the key, serve `secret get` with no prompt.
    if action == "get" {
        if let Some(secret_name) = name {
            if let Some(outcome) = client::get(&leaf, secret_name) {
                match outcome {
                    client::GetOutcome::Value(value) => {
                        usage::human(&vault_dir, "secret.get", Some(secret_name));
                        println!("{value}");
                        return Ok(());
                    }
                    client::GetOutcome::NotFound => {
                        eprintln!(
                            "{} Secret '{}' not found",
                            style("error:").red(),
                            secret_name
                        );
                        std::process::exit(1);
                    }
                    // Daemon up but vault locked — fall through to the prompt path.
                    client::GetOutcome::NotUnlocked => {}
                }
            }
        }
    }

    // Use the cached session key if unlocked, otherwise prompt for the passphrase.
    let cached = session::is_unlocked(&vault_dir) && session::get_key(&vault_dir).is_some();
    let vault = open_unlocked_or_prompt(&vault_dir, &meta_preview.name)?;
    if !cached {
        println!(
            "{}",
            style("  Tip: run 'svault unlock' to cache the key for this session").dim()
        );
    }

    match action {
        "add" => {
            let secret_name: String = match name {
                Some(n) => n.to_string(),
                None => Input::new().with_prompt("  Secret name").interact_text()?,
            };
            let value = Password::new()
                .with_prompt(format!("  Value for '{secret_name}'"))
                .interact()?;
            vault.add_secret(&secret_name, &value)?;
            usage::human(&vault_dir, "secret.add", Some(&secret_name));
            println!(
                "{} Secret '{}' added",
                style("ok:").green().bold(),
                secret_name
            );
        }
        "get" => {
            let Some(secret_name) = name else {
                eprintln!(
                    "{} Provide a secret name: svault secret get <NAME>",
                    style("error:").red()
                );
                std::process::exit(1);
            };
            match vault.get_secret(secret_name)? {
                Some(value) => {
                    usage::human(&vault_dir, "secret.get", Some(secret_name));
                    println!("{value}");
                }
                None => {
                    eprintln!(
                        "{} Secret '{}' not found",
                        style("error:").red(),
                        secret_name
                    );
                    std::process::exit(1);
                }
            }
        }
        "list" => {
            let names = vault.list_secret_names()?;
            if names.is_empty() {
                println!("{}", style("No secrets stored yet.").dim());
            } else {
                println!(
                    "{}",
                    style(format!("Secrets in '{}':", vault.meta.name)).bold()
                );
                for n in &names {
                    println!("  {}", style(n).cyan());
                }
            }
        }
        "remove" => {
            let secret_name: String = match name {
                Some(n) => n.to_string(),
                None => Input::new()
                    .with_prompt("  Secret name to remove")
                    .interact_text()?,
            };
            if Confirm::new()
                .with_prompt(format!("  Remove '{secret_name}'?"))
                .default(false)
                .interact()?
            {
                if vault.remove_secret(&secret_name)? {
                    usage::human(&vault_dir, "secret.remove", Some(&secret_name));
                    println!("{} Secret '{}' removed", style("ok:").yellow(), secret_name);
                } else {
                    eprintln!(
                        "{} Secret '{}' not found",
                        style("error:").red(),
                        secret_name
                    );
                }
            }
        }
        _ => {
            eprintln!(
                "{} Unknown action '{}'. Use: add | get | list | remove",
                style("error:").red(),
                action
            );
            std::process::exit(1);
        }
    }
    Ok(())
}

fn cmd_vaults() -> Result<()> {
    let dirs = list_vault_dirs();
    if dirs.is_empty() {
        println!(
            "{}",
            style("No vaults found. Run 'svault create' to make one.").dim()
        );
        return Ok(());
    }
    println!(
        "{:<12} {:<20} {:<28} {:<18} {:<12} {}",
        style("STORAGE").bold(),
        style("NAME").bold(),
        style("DESCRIPTION").bold(),
        style("ALLOW AGENT").bold(),
        style("RATE LIMIT").bold(),
        style("CREATED").bold(),
    );
    println!("{}", style("".repeat(98)).dim());
    for dir in &dirs {
        if let Ok(meta) = VaultMeta::load_unverified(dir) {
            let created = &meta.created_at[..10];
            println!(
                "{:<12} {:<20} {:<28} {:<18} {:<12} {}",
                meta.storage,
                style(&meta.name).cyan(),
                if meta.description.is_empty() {
                    "-".into()
                } else {
                    meta.description.clone()
                },
                meta.access.allow_agent.to_string(),
                meta.access.rate_limit,
                created,
            );
        }
    }
    Ok(())
}

/// The agent path: a structured, policy-gated secret request.
/// On allow, the secret value is printed to stdout (so agents can capture it)
/// and all status goes to stderr. Every request is recorded to the audit log.
fn cmd_get(
    name: &str,
    scope: &str,
    reason: &str,
    caller_arg: Option<&str>,
    vault_name: Option<&str>,
) -> Result<()> {
    let vault_dir = resolve_vault_dir(vault_name)?;
    let meta = VaultMeta::load_unverified(&vault_dir)?;

    let caller = caller_arg
        .map(|s| s.to_string())
        .or_else(|| std::env::var("SVAULT_CALLER").ok())
        .unwrap_or_else(|| "default".to_string());

    let loaded = policy::load();
    let req = policy::Request {
        vault: &meta.name,
        vault_dir: &vault_dir,
        secret: name,
        scope,
        reason,
        caller: &caller,
    };
    let decision = policy::evaluate(loaded.as_ref(), &meta, &req);

    // Audit the decision either way — never log the secret value.
    let (decision_str, rule) = match &decision {
        policy::Decision::Allow(_) => ("allow", "ok".to_string()),
        policy::Decision::Deny(_, why) => ("deny", why.clone()),
    };
    audit::record(
        &vault_dir,
        &audit::Entry::now(
            &caller,
            name,
            scope,
            &decision.tier().to_string(),
            decision_str,
            &rule,
            reason,
        ),
    )?;
    // Also record it on the unified usage timeline as an agent action.
    usage::agent(
        &vault_dir,
        &caller,
        &format!("get.{decision_str}"),
        Some(name),
    );

    match decision {
        policy::Decision::Deny(_, why) => {
            eprintln!("{} {}", style("denied:").red().bold(), why);
            eprintln!(
                "{}",
                style(format!("  caller={caller} secret={name} scope={scope}")).dim()
            );
            std::process::exit(1);
        }
        policy::Decision::Allow(tier) => {
            let leaf = vault_leaf(&vault_dir);
            // Prefer the daemon — the key is already in memory, so no prompt.
            if let Some(outcome) = client::get(&leaf, name) {
                match outcome {
                    client::GetOutcome::Value(value) => {
                        eprintln!(
                            "{} {} (caller={caller}, scope={scope}, tier={tier})",
                            style("granted:").green().bold(),
                            name
                        );
                        println!("{value}");
                        return Ok(());
                    }
                    client::GetOutcome::NotFound => {
                        eprintln!("{} Secret '{}' not found", style("error:").red(), name);
                        std::process::exit(1);
                    }
                    // Daemon up but vault locked — fall through to the prompt path.
                    client::GetOutcome::NotUnlocked => {}
                }
            }
            let vault = open_unlocked_or_prompt(&vault_dir, &meta.name)?;
            match vault.get_secret(name)? {
                Some(value) => {
                    eprintln!(
                        "{} {} (caller={caller}, scope={scope}, tier={tier})",
                        style("granted:").green().bold(),
                        name
                    );
                    println!("{value}");
                    Ok(())
                }
                None => {
                    eprintln!("{} Secret '{}' not found", style("error:").red(), name);
                    std::process::exit(1);
                }
            }
        }
    }
}

/// `svault policy check <caller>` and `svault policy init`.
fn cmd_policy(action: &str, caller: Option<&str>) -> Result<()> {
    match action {
        "check" => {
            let Some(caller) = caller else {
                eprintln!(
                    "{} Usage: svault policy check <caller>",
                    style("error:").red()
                );
                std::process::exit(1);
            };
            let Some(policy) = policy::load() else {
                println!(
                    "{}",
                    style("No svault.policy.yaml found — running in fallback mode (meta.yaml allow_agent / rate_limit).").dim()
                );
                println!("{}", style("Run 'svault policy init' to create one.").dim());
                return Ok(());
            };
            cmd_policy_check(&policy, caller)
        }
        "init" => cmd_policy_init(),
        _ => {
            eprintln!(
                "{} Unknown action '{}'. Use: check | init",
                style("error:").red(),
                action
            );
            std::process::exit(1);
        }
    }
}

fn cmd_policy_check(policy: &policy::Policy, caller: &str) -> Result<()> {
    let Some(rule) = policy.caller(caller) else {
        eprintln!(
            "{} Caller '{}' is not defined and there is no 'default' caller",
            style("error:").red(),
            caller
        );
        std::process::exit(1);
    };

    println!(
        "{}",
        style(format!("┌─ Policy · {caller} ──────────────────────────┐")).dim()
    );
    println!(
        "  {:<14} {}",
        style("Scopes").dim(),
        if rule.scopes.is_empty() {
            "(none)".to_string()
        } else {
            rule.scopes.join(", ")
        }
    );
    println!("  {:<14} {}", style("Rate limit").dim(), rule.rate_limit);
    println!();

    let accessible = policy.accessible(caller);
    if accessible.is_empty() {
        println!(
            "{}",
            style("This caller cannot retrieve any classified secret.").dim()
        );
    } else {
        println!(
            "{:<18} {:<22} {:<12} {}",
            style("VAULT").bold(),
            style("SECRET").bold(),
            style("SCOPE").bold(),
            style("TIER").bold()
        );
        println!("{}", style("".repeat(60)).dim());
        for (vault, secret, scope, tier) in &accessible {
            println!(
                "{:<18} {:<22} {:<12} {}",
                style(vault).cyan(),
                secret,
                scope,
                tier
            );
        }
    }

    // Audit summary across all vaults.
    let mut total = 0usize;
    let mut denied = 0usize;
    for dir in list_vault_dirs() {
        for e in audit::all(&dir).unwrap_or_default() {
            if e.caller == caller {
                total += 1;
                if e.decision == "deny" {
                    denied += 1;
                }
            }
        }
    }
    println!();
    println!(
        "{} {} request(s) logged, {} denied",
        style("audit:").dim(),
        total,
        denied
    );
    Ok(())
}

/// Scaffold a `svault.policy.yaml` from the vaults that exist today.
fn cmd_policy_init() -> Result<()> {
    let path = Path::new(policy::POLICY_FILE);
    if path.exists() {
        eprintln!(
            "{} {} already exists",
            style("error:").red(),
            policy::POLICY_FILE
        );
        std::process::exit(1);
    }

    let mut out = String::from(
        "version: 1\n\n# Callers that may request secrets via 'svault get'.\n\
         callers:\n  claude-code:\n    scopes: [misc]\n    rate_limit: 20/hour\n\
         \x20\x20default:\n    scopes: []\n    rate_limit: 5/hour\n\n\
         # Per-vault secret classification. tier: low | medium | high.\nvaults:\n",
    );

    let dirs = list_vault_dirs();
    if dirs.is_empty() {
        out.push_str("  # No vaults yet — add entries after 'svault create'.\n");
    }
    for dir in &dirs {
        let Ok(meta) = VaultMeta::load_unverified(dir) else {
            continue;
        };
        out.push_str(&format!("  {}:\n    secrets:\n", meta.name));
        for n in unlocked_secret_names(dir) {
            out.push_str(&format!("      {n}: {{ scope: misc, tier: low }}\n"));
        }
        out.push_str("      \"*\": { scope: misc, tier: low }\n");
    }

    std::fs::write(path, out)?;
    println!(
        "{} Wrote {}",
        style("ok:").green().bold(),
        policy::POLICY_FILE
    );
    println!(
        "{}",
        style("  Edit scopes and tiers, then commit it — it holds no secrets.").dim()
    );
    Ok(())
}

/// Best-effort secret-name listing for `policy init`: only when the vault is
/// already unlocked (cached session), otherwise empty so we just emit "*".
fn unlocked_secret_names(vault_dir: &Path) -> Vec<String> {
    if !session::is_unlocked(vault_dir) {
        return vec![];
    }
    let Some(key) = session::get_key(vault_dir) else {
        return vec![];
    };
    Vault::open_with_key(vault_dir, VaultKey::from_bytes(key))
        .and_then(|v| v.list_secret_names())
        .unwrap_or_default()
}

// ── Recovery, export, import ────────────────────────────────────────────────

fn cmd_recover(vault_name: Option<&str>) -> Result<()> {
    let vault_dir = resolve_vault_dir(vault_name)?;
    let meta = VaultMeta::load_unverified(&vault_dir)?;

    if !recovery::exists(&vault_dir) {
        eprintln!(
            "{} Vault '{}' has no recovery file — it predates recovery support.",
            style("error:").red(),
            meta.name
        );
        std::process::exit(1);
    }

    let code = Password::new()
        .with_prompt(format!("  Recovery code for '{}'", meta.name))
        .interact()?;

    // Confirm the code opens this vault before asking for a new passphrase.
    recovery::unlock_with_code(&vault_dir, &code).unwrap_or_else(|e| {
        eprintln!("{} {}", style("error:").red(), e);
        std::process::exit(1);
    });

    println!(
        "{} Recovery code accepted — set a new passphrase.",
        style("ok:").green()
    );
    let new_pass = Password::new().with_prompt("  New passphrase").interact()?;
    if let Some(w) = passphrase::check(&new_pass) {
        println!("{} {}", style("warning:").yellow(), w.0);
    }
    let confirm = Password::new()
        .with_prompt("  Confirm passphrase")
        .interact()?;
    if new_pass != confirm {
        eprintln!("{} Passphrases do not match", style("error:").red());
        std::process::exit(1);
    }

    recovery::recover_and_rekey(&vault_dir, &code, &new_pass)?;
    usage::human(&vault_dir, "recover", None);
    // Drop any stale cached session (it holds the old, now-invalid key).
    session::lock(&vault_dir).ok();

    println!(
        "{} Passphrase reset for '{}'. Recovery code unchanged.",
        style("ok:").green().bold(),
        meta.name
    );
    Ok(())
}

fn cmd_export(vault_name: Option<&str>, out: Option<&str>) -> Result<()> {
    let vault_dir = resolve_vault_dir(vault_name)?;
    let meta = VaultMeta::load_unverified(&vault_dir)?;

    let json = portable::build_bundle(&vault_dir, &meta.name, &meta.storage).unwrap_or_else(|e| {
        eprintln!("{} {}", style("error:").red(), e);
        std::process::exit(1);
    });

    let out_path = out
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from(format!("{}.svault-export.json", meta.name)));
    std::fs::write(&out_path, json)?;

    // Keep the bundle out of git so it can't be pushed by mistake.
    let out_dir = out_path.parent().filter(|p| !p.as_os_str().is_empty());
    portable::ensure_export_gitignored(out_dir.unwrap_or_else(|| Path::new(".")));
    usage::human(&vault_dir, "export", None);

    println!(
        "{} Exported '{}' to {}",
        style("ok:").green().bold(),
        meta.name,
        out_path.display()
    );
    println!(
        "{}",
        style("  The bundle is encrypted — import it with 'svault import'.").dim()
    );
    Ok(())
}

fn cmd_import(file: &str, name: Option<&str>) -> Result<()> {
    let raw = std::fs::read_to_string(file).unwrap_or_else(|e| {
        eprintln!("{} cannot read {}: {}", style("error:").red(), file, e);
        std::process::exit(1);
    });

    let bundle = portable::parse_bundle(&raw).unwrap_or_else(|e| {
        eprintln!("{} {}", style("error:").red(), e);
        std::process::exit(1);
    });
    let base = Path::new(SVAULT_DIR);

    // Resolve a free name: the requested name (or the bundle's own), suffixed if
    // it's already taken — so re-importing onto the same machine never errors.
    let desired = name.unwrap_or(&bundle.name);
    let target = portable::unique_vault_name(base, desired);
    let renamed = target != bundle.name;
    if target != desired {
        println!(
            "{} '{}' already exists — importing as '{}'",
            style("note:").cyan(),
            desired,
            target
        );
    }

    portable::import_bundle_as(&raw, base, &target).unwrap_or_else(|e| {
        eprintln!("{} {}", style("error:").red(), e);
        std::process::exit(1);
    });
    let dir = base.join(&target);

    // If the name changed, meta.name still says the bundle's original name and
    // is HMAC-signed — re-sign it with the vault key so the directory and
    // metadata agree. That needs the passphrase.
    if renamed {
        let passphrase = Password::new()
            .with_prompt(format!(
                "  Passphrase for '{}' (to finish importing as '{}')",
                bundle.name, target
            ))
            .interact()
            .unwrap_or_else(|e| {
                let _ = std::fs::remove_dir_all(&dir);
                eprintln!("{} {}", style("error:").red(), e);
                std::process::exit(1);
            });
        match Vault::open(&dir, &passphrase) {
            Ok(vault) => {
                let mut meta = vault.meta.clone();
                meta.name = target.clone();
                if let Err(e) = vault.save_meta(&meta) {
                    let _ = std::fs::remove_dir_all(&dir);
                    eprintln!("{} could not finalize rename: {}", style("error:").red(), e);
                    std::process::exit(1);
                }
            }
            Err(_) => {
                // Don't leave a half-imported vault whose name doesn't match.
                let _ = std::fs::remove_dir_all(&dir);
                eprintln!(
                    "{} wrong passphrase — import cancelled. Re-run to try again.",
                    style("error:").red()
                );
                std::process::exit(1);
            }
        }
    }

    usage::human(&dir, "import", None);

    println!(
        "{} Imported '{}' into {}/{}/",
        style("ok:").green().bold(),
        target,
        SVAULT_DIR,
        target
    );
    if !renamed {
        println!(
            "{}",
            style("  Unlock it with its original passphrase (or 'svault recover').").dim()
        );
    }
    Ok(())
}

// ── Helpers ───────────────────────────────────────────────────────────────────

/// Resolve which vault a command targets.
/// - explicit `--vault <name>`: use it (error if it does not exist)
/// - no flag, one vault: use it
/// - no flag, many vaults: prompt the user to pick one
fn resolve_vault_dir(vault_name: Option<&str>) -> Result<PathBuf> {
    if let Some(n) = vault_name {
        let dir = PathBuf::from(SVAULT_DIR).join(n);
        if !dir.join("meta.yaml").exists() {
            eprintln!(
                "{} Vault '{}' not found in {}/",
                style("error:").red(),
                n,
                SVAULT_DIR
            );
            std::process::exit(1);
        }
        return Ok(dir);
    }

    let dirs = list_vault_dirs();
    match dirs.len() {
        0 => {
            eprintln!(
                "{} No vault found. Run {} first.",
                style("error:").red(),
                style("svault create").bold()
            );
            std::process::exit(1);
        }
        1 => Ok(dirs[0].clone()),
        _ => {
            let names: Vec<String> = dirs
                .iter()
                .map(|d| {
                    VaultMeta::load_unverified(d)
                        .map(|m| m.name)
                        .unwrap_or_else(|_| d.display().to_string())
                })
                .collect();
            let idx = Select::new()
                .with_prompt("  Which vault?")
                .items(&names)
                .default(0)
                .interact()?;
            Ok(dirs[idx].clone())
        }
    }
}

/// Open a vault for a local (non-daemon) operation, preferring the cached
/// session *key* so the passphrase is neither re-entered nor stored on disk.
/// Falls back to a passphrase prompt when the vault is locked or the cached
/// session is stale/invalid.
fn open_unlocked_or_prompt(vault_dir: &Path, vault_name: &str) -> Result<Vault> {
    if session::is_unlocked(vault_dir) {
        if let Some(key) = session::get_key(vault_dir) {
            if let Ok(v) = Vault::open_with_key(vault_dir, VaultKey::from_bytes(key)) {
                return Ok(v);
            }
            let _ = session::lock(vault_dir); // stale/invalid cached key — drop it
        }
    }
    let passphrase = Password::new()
        .with_prompt(format!("  Passphrase for '{vault_name}'"))
        .interact()?;
    Vault::open(vault_dir, &passphrase).map_err(|e| {
        eprintln!("{} {}", style("error:").red(), e);
        std::process::exit(1);
        #[allow(unreachable_code)]
        e
    })
}

/// Prompt for agent access. `current` pre-selects the matching choice when editing.
fn prompt_allow_agent(current: Option<&AllowAgent>) -> Result<AllowAgent> {
    let choices = &[
        "yes — all agents",
        "no — block all agents",
        "list — specific agents only",
    ];
    let (default_idx, default_list) = match current {
        Some(AllowAgent::Bool(true)) => (0, String::new()),
        Some(AllowAgent::Bool(false)) => (1, String::new()),
        Some(AllowAgent::List(agents)) => (2, agents.join(", ")),
        None => (0, String::new()),
    };

    let idx = Select::new()
        .with_prompt("  Allow agent access")
        .items(choices)
        .default(default_idx)
        .interact()?;

    Ok(match idx {
        0 => AllowAgent::Bool(true),
        1 => AllowAgent::Bool(false),
        _ => {
            let raw: String = Input::new()
                .with_prompt("  Agent names (comma-separated)")
                .with_initial_text(&default_list)
                .interact_text()?;
            AllowAgent::List(
                raw.split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect(),
            )
        }
    })
}

/// Prompt for login method. Only passphrase works today — yubikey and google
/// auth are shown but fall back to passphrase with a notice.
/// Where the encrypted vault lives. Only local storage is implemented today;
/// remote (Soluzy cloud / self-hosted) is a reserved placeholder for a later step.
/// Storage backend ids, indexed to match the picker order. Only "local" is
/// wired today; the rest are reserved placeholders (remote sync is coming soon).
const STORAGE_IDS: [&str; 4] = ["local", "cloud", "self-hosted", "s3"];

fn prompt_storage_backend() -> Result<&'static str> {
    let choices = &[
        "local — encrypted vault on this machine (default)",
        "Soluzy cloud (coming soon)",
        "self-hosted (coming soon)",
        "S3 / MinIO (coming soon)",
    ];

    let idx = Select::new()
        .with_prompt("  Storage")
        .items(choices)
        .default(0)
        .interact()?;

    if idx != 0 {
        println!(
            "{} Remote storage isn't wired yet — the vault is created with the \
             '{}' target but data stays local until remote sync ships.",
            style("note:").cyan(),
            STORAGE_IDS[idx],
        );
    }
    Ok(STORAGE_IDS[idx])
}

fn prompt_login_method(current: Option<LoginMethod>) -> Result<LoginMethod> {
    let choices = &[
        "passphrase",
        "yubikey (coming soon)",
        "google auth (coming soon)",
    ];
    let default_idx = match current {
        Some(LoginMethod::Passphrase) | None => 0,
        Some(LoginMethod::Yubikey) => 1,
        Some(LoginMethod::GoogleAuth) => 2,
    };

    let idx = Select::new()
        .with_prompt("  Login method")
        .items(choices)
        .default(default_idx)
        .interact()?;

    if idx != 0 {
        println!(
            "{} Only passphrase is available right now — using passphrase.",
            style("note:").cyan()
        );
    }
    Ok(LoginMethod::Passphrase)
}