obsidianlog-cli 0.2.1

Long-term, tamper-evident operational log archival on Sia: client-side encrypted, zstd-compressed, hash-chained, and queryable. CLI to serve ingest, query, and verify logs, plus an interactive setup wizard. Installs the `obsidianlog` binary.
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
//! `obsidianlog init` — interactive setup wizard.
//!
//! Generates a fresh AES-256 key from the OS CSPRNG, collects a Sia app key
//! if the Sia backend is chosen, and persists both together as one
//! [`CredentialBundle`] (OS keychain, falling back to a `0600` secrets file)
//! — see ADR-0015. Prompts for the archive's configuration and writes
//! `config.toml`. Idempotent: re-running detects an existing config/bundle
//! and offers to reuse them or rotate.

use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
#[cfg(feature = "sia")]
use dialoguer::Password;
use dialoguer::theme::ColorfulTheme;
use dialoguer::{Confirm, Input, Select};

use obsidianlog_store::encrypt::EncryptionKey;

use crate::cli::InitArgs;
use crate::config::{
    CURRENT_CREDENTIAL_VERSION, ChunkingConfig, Config, ConfigLoadOutcome, IndexdConfig,
    LocalConfig, ServeConfig,
};
use crate::keystore::{BundleCreateOutcome, BundleStore, CredentialBundle, DefaultBundleStore};

/// Default indexer for the "hosted" onboarding path: the Sia Foundation's
/// own hosted indexer (50GB free tier, no infrastructure for us to run or
/// fund — see ADR-0007). Editable at the prompt, so entering a different URL
/// here is how a self-hosted or third-party indexer (BYO) is chosen instead.
const DEFAULT_SIA_INDEXER_URL: &str = "https://sia.storage";

/// Run the setup wizard against the real credential store.
pub fn run(args: InitArgs, config_path: Option<PathBuf>) -> Result<()> {
    run_with(&args, config_path.as_deref(), &DefaultBundleStore::new())
}

/// The answers driving a `config.toml`, gathered either interactively or
/// (`--non-interactive`) from an existing/default config. Decoupled from both
/// CLI-arg parsing and terminal I/O, so it's directly unit-testable.
struct InitAnswers {
    bucket: String,
    local: LocalConfig,
    indexd: Option<IndexdConfig>,
    bind: String,
    window_secs: u64,
    /// The Sia AppKey collected *this run*, if the Sia backend was chosen
    /// interactively. `None` means "nothing new to add to the credential
    /// bundle" — true for the local backend, and always true for
    /// `--non-interactive` (which never freshly chooses Sia; see
    /// `from_config`).
    sia_app_key: Option<[u8; 32]>,
}

impl InitAnswers {
    fn from_config(config: &Config) -> Self {
        Self {
            bucket: config.bucket.clone(),
            local: config.local.clone(),
            indexd: config.indexd.clone(),
            bind: config.serve.bind.clone(),
            window_secs: config.chunking.window_secs,
            sia_app_key: None,
        }
    }

    /// Prompt interactively, using `base` (the existing config, or
    /// [`Config::default`] on first run) to pre-fill each default.
    fn prompt(base: &Config) -> Result<Self> {
        let theme = ColorfulTheme::default();

        let bucket: String = Input::with_theme(&theme)
            .with_prompt("Storage bucket / namespace")
            .default(base.bucket.clone())
            .interact_text()
            .context("reading the bucket name")?;

        let backends = [
            "local (no Sia node needed)",
            "sia (archive to the Sia network)",
        ];
        let backend_idx = Select::with_theme(&theme)
            .with_prompt("Storage backend")
            .items(backends)
            .default(if base.indexd.is_some() { 1 } else { 0 })
            .interact()
            .context("reading the storage backend choice")?;

        let (local, indexd, sia_app_key) = if backend_idx == 0 {
            let data_dir: String = Input::with_theme(&theme)
                .with_prompt("Local storage directory")
                .default(base.local.data_dir.display().to_string())
                .interact_text()
                .context("reading the storage directory")?;
            (
                LocalConfig {
                    data_dir: PathBuf::from(data_dir),
                },
                None,
                None,
            )
        } else {
            let url: String = Input::with_theme(&theme)
                .with_prompt(
                    "indexd application API URL (the default is Sia Storage's hosted \
                     indexer — enter a different URL to bring your own indexer instead)",
                )
                .default(sia_url_default(base))
                .interact_text()
                .context("reading the indexd URL")?;

            let sia_app_key = onboard_sia(&theme, &url)?;

            (
                base.local.clone(),
                Some(IndexdConfig {
                    url,
                    bucket: bucket.clone(),
                }),
                Some(sia_app_key),
            )
        };

        let bind: String = Input::with_theme(&theme)
            .with_prompt("Ingest server bind address")
            .default(base.serve.bind.clone())
            .interact_text()
            .context("reading the bind address")?;

        let window_secs: u64 = Input::with_theme(&theme)
            .with_prompt("Chunk time window (seconds)")
            .default(base.chunking.window_secs)
            .interact_text()
            .context("reading the chunk window")?;

        Ok(Self {
            bucket,
            local,
            indexd,
            bind,
            window_secs,
            sia_app_key,
        })
    }

    fn into_config(self) -> Config {
        Config {
            bucket: self.bucket,
            local: self.local,
            indexd: self.indexd,
            serve: ServeConfig { bind: self.bind },
            chunking: ChunkingConfig {
                window_secs: self.window_secs,
            },
            credential_store_version: Some(CURRENT_CREDENTIAL_VERSION),
        }
    }
}

/// The indexd URL to pre-fill the prompt with: the previously configured
/// one on re-run, otherwise [`DEFAULT_SIA_INDEXER_URL`].
fn sia_url_default(base: &Config) -> String {
    base.indexd
        .as_ref()
        .map(|i| i.url.clone())
        .unwrap_or_else(|| DEFAULT_SIA_INDEXER_URL.to_string())
}

/// Resolves what recovery phrase to actually use: `seed` (in any casing,
/// with surrounding whitespace ignored) generates and returns a fresh one;
/// anything else is validated locally — no network call — before it's ever
/// handed to `onboard`. `onboard` only parses the phrase *after* the
/// browser approval step completes, so without this check, a typo would
/// silently burn a full approval round-trip (and one of a possibly-limited
/// number of app-connection slots on the indexer) on an attempt that was
/// always going to fail.
#[cfg(feature = "sia")]
fn resolve_recovery_phrase(input: &str) -> Result<String> {
    if input.trim().eq_ignore_ascii_case("seed") {
        let generated = obsidianlog_store::backend::sia::generate_recovery_phrase();
        println!(
            "\nYour new recovery phrase — this is your master key, save it securely, it \
             is never stored by obsidianlog:\n\n    {generated}\n"
        );
        Ok(generated)
    } else {
        obsidianlog_store::backend::sia::validate_recovery_phrase(input).context(
            "that doesn't look like a valid Sia recovery phrase — type `seed` to generate a \
             new one instead",
        )?;
        Ok(input.to_string())
    }
}

/// Run the interactive Sia onboarding flow against `url`: prompt for a
/// recovery phrase (or generate one), request approval, and register —
/// blocking until the user approves. Returns the derived `AppKey`.
///
/// Without the `sia` feature, this build can't reach `indexd` at all; fails
/// clearly instead of prompting for a phrase that will never be usable.
#[cfg(feature = "sia")]
fn onboard_sia(theme: &ColorfulTheme, url: &str) -> Result<[u8; 32]> {
    let recovery_phrase: String = Password::with_theme(theme)
        .with_prompt("Sia recovery phrase (type `seed` to generate a new one)")
        .interact()
        .context("reading the recovery phrase")?;

    let recovery_phrase = resolve_recovery_phrase(&recovery_phrase)?;

    println!("\nConnecting to {url}...");
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .context("building the async runtime for Sia onboarding")?;
    runtime
        .block_on(obsidianlog_store::backend::sia::onboard(
            url,
            &recovery_phrase,
            |approval_url| {
                println!("\nOpen this URL and approve the app in your Sia account:\n");
                println!("    {approval_url}\n");
                println!("Waiting for approval (this blocks until you approve)...");
            },
        ))
        .context("onboarding with the Sia indexer")
}

#[cfg(not(feature = "sia"))]
fn onboard_sia(_theme: &ColorfulTheme, _url: &str) -> Result<[u8; 32]> {
    anyhow::bail!(
        "this build of obsidianlog was compiled without Sia support; rebuild with \
         `cargo build --features sia` to onboard a Sia indexer"
    )
}

/// What continuing past a legacy (pre-0.2) config abandons, and the prompt
/// asking whether to proceed. See ADR-0015 and [`Config::load_for_init`].
const LEGACY_CONFIG_MESSAGE: &str = "This directory has a pre-0.2 obsidianlog credential setup \
(an encryption key and a Sia app key stored as two separate OS keychain items). obsidianlog \
0.2 stores them as a single bundled item instead, and there is no automatic migration.\n\n\
To keep reading archives created under the old setup, use obsidianlog v0.1.1.\n\
To start fresh under the new layout: previously archived data will no longer be decryptable, \
since it was encrypted under a key this new setup won't reuse.";

/// Handle a config predating the credential-storage format marker: requires
/// explicit confirmation (`--force`, or an interactive prompt) before
/// treating this as a fresh install — never silently proceeds.
fn handle_legacy_config(args: &InitArgs) -> Result<()> {
    if args.force {
        eprintln!("warning: {LEGACY_CONFIG_MESSAGE}");
        return Ok(());
    }
    if args.non_interactive {
        anyhow::bail!(
            "{LEGACY_CONFIG_MESSAGE}\n\nRun with --force to start fresh non-interactively."
        );
    }
    println!("{LEGACY_CONFIG_MESSAGE}\n");
    let proceed = Confirm::new()
        .with_prompt("Start fresh under the new credential storage layout?")
        .default(false)
        .interact()
        .context("reading the confirmation")?;
    anyhow::ensure!(proceed, "aborted: legacy setup was not replaced");
    Ok(())
}

/// Core wizard logic, decoupled from which [`BundleStore`] is used, so
/// tests can inject [`crate::keystore::MockBundleStore`] and never touch the
/// real keychain or filesystem.
fn run_with(args: &InitArgs, config_path: Option<&Path>, store: &dyn BundleStore) -> Result<()> {
    let resolved_config_path = match config_path {
        Some(p) => p.to_path_buf(),
        None => Config::default_path()?,
    };

    let existing_config = match Config::load_for_init(config_path)? {
        ConfigLoadOutcome::Missing => None,
        ConfigLoadOutcome::Current(config) => Some(config),
        ConfigLoadOutcome::Legacy(_) => {
            handle_legacy_config(args)?;
            None
        }
    };

    // Set only by the non-force branch below, when it already reads the
    // bundle for the integrity/reuse check. Threaded into `finish_init` so
    // a declined-reuse or incomplete-setup re-run never re-probes with
    // create()/read() for something this run already confirmed — see
    // `merge_known_bundle`.
    let mut known_bundle: Option<CredentialBundle> = None;

    if let Some(config) = &existing_config {
        if args.force {
            // --force is already explicit opt-in: skip the "is setup
            // complete?" preflight read entirely (it only exists to pick a
            // reuse/rotate prompt below, both of which --force bypasses)
            // and warn once. `finish_init` does the one read this rotation
            // actually needs, to preserve any existing Sia key.
            eprintln!(
                "warning: rotating the encryption key — previously archived data will no \
                 longer be decryptable with the new key"
            );
        } else {
            let indexd_configured = config.indexd.is_some();
            // The one retained integrity check (ADR-0015): confirms the
            // bundle actually still exists before declaring "already
            // initialized", catching a credential manually deleted from the
            // keychain after setup. Not claimed to add zero keychain calls
            // on a re-run — only zero calls beyond what this correctness
            // check already requires.
            let existing_bundle = store.read()?;
            let setup_complete = existing_bundle
                .as_ref()
                .is_some_and(|b| !indexd_configured || b.sia_app_key.is_some());

            if setup_complete {
                let reuse = if args.non_interactive {
                    true
                } else {
                    Confirm::new()
                        .with_prompt(format!(
                            "Existing setup found (config at {}, credentials in {}). Reuse it?",
                            resolved_config_path.display(),
                            store.describe()
                        ))
                        .default(true)
                        .interact()
                        .context("reading the reuse confirmation")?
                };
                if reuse {
                    println!(
                        "Already initialized: config at {}, credentials in {}.",
                        resolved_config_path.display(),
                        store.describe()
                    );
                    println!("Nothing to do.");
                    return Ok(());
                }

                // Confirm interactively before reconfiguring. This does
                // NOT rotate the encryption key — only `--force` does that
                // — it just re-collects settings and, if a new Sia app key
                // is chosen, adds it to the existing bundle.
                if !args.non_interactive {
                    let proceed = Confirm::new()
                        .with_prompt(
                            "This will reconfigure the existing setup. The encryption key \
                             stays the same; only newly chosen settings are applied. \
                             Continue?",
                        )
                        .default(false)
                        .interact()
                        .context("reading the reconfiguration confirmation")?;
                    anyhow::ensure!(proceed, "aborted: reconfiguration was not confirmed");
                }
            } else {
                eprintln!("warning: existing setup is incomplete — completing it fresh");
            }

            known_bundle = existing_bundle;
        }
    }

    finish_init(
        args,
        &resolved_config_path,
        existing_config.as_ref(),
        known_bundle,
        store,
    )
}

/// The status line to print for a repair (not a fresh install) — whether
/// that's discovered via a create-only attempt reporting `AlreadyExists`,
/// or already known going in (see [`merge_known_bundle`]): explains why the
/// wizard just re-collected every answer — the config file was missing, or
/// the setup was incomplete — without implying the encryption key rotated.
/// `sia_key_freshly_saved` is true only when a new Sia app key was just
/// merged into the bundle, which is the one case where something in the
/// bundle actually did change.
fn repair_status_message(sia_key_freshly_saved: bool) -> &'static str {
    if sia_key_freshly_saved {
        "Existing encryption key preserved; Sia app key saved."
    } else {
        "Existing credentials preserved; rebuilding configuration."
    }
}

/// Decide what (if anything) to write into a bundle whose current contents
/// are already known this run — `run_with` read it once for the
/// integrity/reuse check, so `finish_init` doesn't need to probe for it
/// again with `create()` or `read()`. Merges in a newly chosen Sia app key
/// while preserving the encryption key exactly (overwriting any Sia key
/// that was already there, same as the create()-then-repair path); `None`
/// means nothing actually needs to change, so no write is needed at all.
fn merge_known_bundle(
    known: CredentialBundle,
    sia_app_key: Option<[u8; 32]>,
) -> Option<CredentialBundle> {
    sia_app_key.map(|sia_app_key| CredentialBundle {
        encryption_key: known.encryption_key,
        sia_app_key: Some(sia_app_key),
    })
}

fn finish_init(
    args: &InitArgs,
    config_path: &Path,
    existing: Option<&Config>,
    known_bundle: Option<CredentialBundle>,
    store: &dyn BundleStore,
) -> Result<()> {
    let base = existing.cloned().unwrap_or_default();
    let answers = if args.non_interactive {
        InitAnswers::from_config(&base)
    } else {
        InitAnswers::prompt(&base)?
    };

    if args.force {
        // Rotation is always read-modify-write, regardless of whether a
        // bundle previously existed (an orphaned one is still respected):
        // replace only the encryption key, preserve any existing Sia key
        // unless a new one was freshly chosen this run.
        let key = EncryptionKey::generate().context("generating a new encryption key")?;
        let bundle = if let Some(sia_app_key) = answers.sia_app_key {
            // Already have everything needed — no read required.
            CredentialBundle {
                encryption_key: *key.expose_secret(),
                sia_app_key: Some(sia_app_key),
            }
        } else {
            let existing_bundle = store.read()?;
            CredentialBundle {
                encryption_key: *key.expose_secret(),
                sia_app_key: existing_bundle.and_then(|b| b.sia_app_key),
            }
        };
        store
            .write(&bundle)
            .context("persisting the credential bundle")?;
    } else if let Some(known) = known_bundle {
        // `run_with` already confirmed this exact bundle exists (the
        // integrity/reuse check's read) — reuse it instead of re-probing
        // with create() (which would just report AlreadyExists) or read()
        // again.
        match merge_known_bundle(known, answers.sia_app_key) {
            Some(merged) => {
                store
                    .write(&merged)
                    .context("persisting the credential bundle")?;
                println!("{}", repair_status_message(true));
            }
            None => println!("{}", repair_status_message(false)),
        }
    } else {
        // No prior read to reuse (a genuinely fresh config, or a bundle
        // possibly deleted separately from it) — try create-only first: a
        // genuinely fresh install (local or Sia) succeeds here in one call
        // (ADR-0015). If a bundle already exists, this is a repair —
        // reviewer-flagged (#72): never silently regenerate/overwrite an
        // existing encryption key.
        let key = EncryptionKey::generate().context("generating a new encryption key")?;
        let candidate = CredentialBundle {
            encryption_key: *key.expose_secret(),
            sia_app_key: answers.sia_app_key,
        };
        let outcome = store
            .create(&candidate)
            .context("persisting the credential bundle")?;
        if outcome == BundleCreateOutcome::AlreadyExists {
            if let Some(sia_app_key) = answers.sia_app_key {
                // Repair that also introduces new credential material: the
                // rarer case, deliberately not optimized for call count —
                // read the real existing bundle so the preserved encryption
                // key is never guessed or lost (ADR-0015).
                let existing_bundle = store.read()?;
                let merged = CredentialBundle {
                    encryption_key: existing_bundle
                        .map(|b| b.encryption_key)
                        .unwrap_or(candidate.encryption_key),
                    sia_app_key: Some(sia_app_key),
                };
                store
                    .write(&merged)
                    .context("persisting the credential bundle")?;
                println!("{}", repair_status_message(true));
            } else {
                // Pure-reuse repair — nothing new to add, leave the
                // existing bundle untouched. The wizard still re-asked
                // every question (the config file was missing, so there
                // was nowhere else to read the old answers from) — this
                // line is what tells the user the key itself wasn't
                // touched, so that doesn't read as a silent rotation.
                println!("{}", repair_status_message(false));
            }
        }
    }

    answers.into_config().save(Some(config_path))?;

    println!("obsidianlog initialized.");
    println!("  config:      {}", config_path.display());
    println!("  credentials: {}", store.describe());
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::InitArgs;
    use crate::config::LocalConfig;
    use crate::keystore::MockBundleStore;

    fn args(non_interactive: bool, force: bool) -> InitArgs {
        InitArgs {
            non_interactive,
            force,
        }
    }

    #[test]
    fn sia_url_defaults_to_the_hosted_indexer_when_unconfigured() {
        assert_eq!(sia_url_default(&Config::default()), DEFAULT_SIA_INDEXER_URL);
    }

    #[test]
    fn sia_url_default_reuses_a_previously_configured_indexer() {
        let config = Config {
            indexd: Some(IndexdConfig {
                url: "https://my-own-indexer.example.com".to_string(),
                bucket: "obsidianlog".to_string(),
            }),
            ..Config::default()
        };
        assert_eq!(
            sia_url_default(&config),
            "https://my-own-indexer.example.com"
        );
    }

    #[test]
    fn fresh_init_generates_a_key_and_writes_a_config() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        let store = MockBundleStore::empty();

        run_with(&args(true, false), Some(&config_path), &store).unwrap();

        let bundle = store.read().unwrap().expect("bundle must be created");
        assert_ne!(bundle.encryption_key, [0u8; 32]);
        assert!(
            bundle.sia_app_key.is_none(),
            "local backend by default: no Sia app key"
        );

        let config = Config::load(Some(&config_path)).unwrap();
        assert_eq!(config.bucket, Config::default().bucket);
        assert!(config.indexd.is_none());
    }

    #[test]
    fn rerunning_non_interactively_is_idempotent_and_keeps_the_same_key() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        let store = MockBundleStore::empty();

        run_with(&args(true, false), Some(&config_path), &store).unwrap();
        let first_key = store.read().unwrap().unwrap().encryption_key;

        run_with(&args(true, false), Some(&config_path), &store).unwrap();
        let second_key = store.read().unwrap().unwrap().encryption_key;

        assert_eq!(
            first_key, second_key,
            "a non-forced re-run must reuse the existing key, not rotate it"
        );
    }

    #[test]
    fn force_rotates_the_key_and_rewrites_the_config() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        let store = MockBundleStore::empty();

        run_with(&args(true, false), Some(&config_path), &store).unwrap();
        let first_key = store.read().unwrap().unwrap().encryption_key;

        run_with(&args(true, true), Some(&config_path), &store).unwrap();
        let second_key = store.read().unwrap().unwrap().encryption_key;

        assert_ne!(first_key, second_key, "--force must generate a new key");
    }

    #[test]
    fn a_bundle_without_a_config_is_repaired_by_writing_a_fresh_config() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        let store = MockBundleStore::seeded(CredentialBundle {
            encryption_key: [0x11; 32],
            sia_app_key: None,
        });

        assert!(!config_path.exists());
        run_with(&args(true, false), Some(&config_path), &store).unwrap();
        assert!(config_path.exists());
    }

    /// Regression test: a user who deletes only `config.toml` (the
    /// credential bundle remains) and re-runs `init` without `--force` must
    /// get the *same* encryption key back, not a silently rotated one.
    /// Flagged by the Month 2 reviewer (#72).
    #[test]
    fn repair_path_reuses_an_existing_key_without_force() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        let store = MockBundleStore::seeded(CredentialBundle {
            encryption_key: [0x77; 32],
            sia_app_key: None,
        });

        assert!(!config_path.exists());
        run_with(&args(true, false), Some(&config_path), &store).unwrap();

        assert!(config_path.exists(), "the missing config must be repaired");
        assert_eq!(
            store.read().unwrap().unwrap().encryption_key,
            [0x77; 32],
            "the repair path must reuse the existing key when config.toml is missing but \
             the bundle still exists, without --force"
        );
    }

    /// A repair that also introduces new credential material (the Sia
    /// backend is chosen while a local-only bundle already exists) must
    /// preserve the existing encryption key exactly, not generate a new
    /// one — this is the deliberately-not-single-call case (ADR-0015).
    #[test]
    fn repair_with_a_newly_chosen_sia_key_preserves_the_existing_encryption_key() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        let store = MockBundleStore::seeded(CredentialBundle {
            encryption_key: [0x99; 32],
            sia_app_key: None,
        });

        // Simulate "Sia was freshly chosen this run" directly against
        // finish_init, since InitAnswers::prompt needs a real terminal.
        let answers = InitAnswers {
            bucket: "obsidianlog".to_string(),
            local: LocalConfig::default(),
            indexd: Some(IndexdConfig {
                url: "https://sia.storage".to_string(),
                bucket: "obsidianlog".to_string(),
            }),
            bind: "127.0.0.1:7080".to_string(),
            window_secs: 3600,
            sia_app_key: Some([0x24; 32]),
        };

        let outcome = store
            .create(&CredentialBundle {
                encryption_key: [0x00; 32], // candidate — must NOT be the one persisted
                sia_app_key: answers.sia_app_key,
            })
            .unwrap();
        assert_eq!(outcome, BundleCreateOutcome::AlreadyExists);
        if let Some(sia_app_key) = answers.sia_app_key {
            let existing = store.read().unwrap();
            let merged = CredentialBundle {
                encryption_key: existing.map(|b| b.encryption_key).unwrap(),
                sia_app_key: Some(sia_app_key),
            };
            store.write(&merged).unwrap();
        }

        let bundle = store.read().unwrap().unwrap();
        assert_eq!(
            bundle.encryption_key, [0x99; 32],
            "the pre-existing encryption key must be preserved exactly"
        );
        assert_eq!(bundle.sia_app_key, Some([0x24; 32]));

        let _ = config_path; // config write path is covered by other tests
    }

    #[test]
    fn non_interactive_preserves_custom_settings_from_the_existing_config_on_reuse() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        let store = MockBundleStore::empty();

        // Seed a config with a non-default bucket, as if a prior interactive
        // run had customized it.
        let custom = Config {
            bucket: "custom-bucket".to_string(),
            local: LocalConfig {
                data_dir: dir.path().join("archive"),
            },
            ..Config::default()
        };
        custom.save(Some(&config_path)).unwrap();
        store
            .write(&CredentialBundle {
                encryption_key: [0x22; 32],
                sia_app_key: None,
            })
            .unwrap();

        // A plain re-run (no force) must leave it untouched.
        run_with(&args(true, false), Some(&config_path), &store).unwrap();
        let reloaded = Config::load(Some(&config_path)).unwrap();
        assert_eq!(reloaded.bucket, "custom-bucket");
    }

    #[test]
    fn non_interactive_rerun_never_disturbs_an_existing_sia_app_key() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        let store = MockBundleStore::empty();

        // Seed a config that already points at Sia, plus its bundled key.
        let custom = Config {
            indexd: Some(IndexdConfig {
                url: "https://indexd.example.com".to_string(),
                bucket: "obsidianlog".to_string(),
            }),
            ..Config::default()
        };
        custom.save(Some(&config_path)).unwrap();
        store
            .write(&CredentialBundle {
                encryption_key: [0x33; 32],
                sia_app_key: Some([0x44; 32]),
            })
            .unwrap();

        run_with(&args(true, false), Some(&config_path), &store).unwrap();

        assert_eq!(
            store.read().unwrap().unwrap().sia_app_key,
            Some([0x44; 32]),
            "a non-interactive reuse must never touch the Sia app key"
        );
    }

    #[test]
    fn a_configured_sia_backend_missing_its_app_key_is_treated_as_incomplete() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        let store = MockBundleStore::empty(); // no bundle at all yet

        let custom = Config {
            indexd: Some(IndexdConfig {
                url: "https://indexd.example.com".to_string(),
                bucket: "obsidianlog".to_string(),
            }),
            ..Config::default()
        };
        custom.save(Some(&config_path)).unwrap();

        // Non-interactive + incomplete (no bundle at all) still succeeds —
        // an encryption key gets generated since none existed yet — but it
        // must NOT silently switch the configured backend back to local —
        // --non-interactive can't prompt for a new app key, so it leaves
        // indexd as configured. The missing app key surfaces as a clear
        // error later, when something actually tries to connect
        // (resolve_backend), not silently here.
        run_with(&args(true, false), Some(&config_path), &store).unwrap();
        let reloaded = Config::load(Some(&config_path)).unwrap();
        assert!(
            reloaded.indexd.is_some(),
            "non-interactive completion must not silently change the configured backend"
        );
        assert!(
            store.read().unwrap().unwrap().sia_app_key.is_none(),
            "non-interactive mode never collects a new Sia app key"
        );
    }

    /// When a bundle already exists but is missing its Sia key (config
    /// points at Sia, but nothing was ever added — an "incomplete" setup),
    /// `run_with` already reads the bundle once to make that determination.
    /// `finish_init` must reuse that exact read rather than re-probing with
    /// `create()`/`read()` again — non-interactive can't add the missing
    /// key anyway, so this run should touch the store exactly once total.
    /// Caught via GPT-relayed analysis of a real macOS keychain-prompt
    /// count during ADR-0015 verification.
    #[test]
    fn incomplete_setup_with_a_known_bundle_does_not_re_probe_the_store() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        let store = MockBundleStore::seeded(CredentialBundle {
            encryption_key: [0x66; 32],
            sia_app_key: None,
        });

        let custom = Config {
            indexd: Some(IndexdConfig {
                url: "https://indexd.example.com".to_string(),
                bucket: "obsidianlog".to_string(),
            }),
            ..Config::default()
        };
        custom.save(Some(&config_path)).unwrap();

        run_with(&args(true, false), Some(&config_path), &store).unwrap();

        assert_eq!(store.read_calls(), 1, "must read the bundle exactly once");
        assert_eq!(
            store.create_calls(),
            0,
            "must not re-probe with create() once the bundle is already known from that read"
        );
        assert_eq!(
            store.write_calls(),
            0,
            "nothing changed (non-interactive can't add the missing Sia key), so nothing \
             should be written"
        );
        assert_eq!(
            store.read().unwrap().unwrap().encryption_key,
            [0x66; 32],
            "the known bundle's encryption key must be untouched"
        );
    }

    #[test]
    fn merge_known_bundle_preserves_the_key_and_adds_a_freshly_chosen_sia_key() {
        let known = CredentialBundle {
            encryption_key: [0x11; 32],
            sia_app_key: None,
        };
        let merged = merge_known_bundle(known, Some([0x22; 32])).unwrap();
        assert_eq!(merged.encryption_key, [0x11; 32]);
        assert_eq!(merged.sia_app_key, Some([0x22; 32]));
    }

    #[test]
    fn merge_known_bundle_overwrites_a_previously_saved_sia_key() {
        let known = CredentialBundle {
            encryption_key: [0x11; 32],
            sia_app_key: Some([0x99; 32]),
        };
        let merged = merge_known_bundle(known, Some([0x22; 32])).unwrap();
        assert_eq!(merged.sia_app_key, Some([0x22; 32]));
    }

    #[test]
    fn merge_known_bundle_is_a_noop_when_nothing_new_was_chosen() {
        let known = CredentialBundle {
            encryption_key: [0x11; 32],
            sia_app_key: None,
        };
        assert!(merge_known_bundle(known, None).is_none());
    }

    #[test]
    fn legacy_config_is_rejected_without_force() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        std::fs::write(&config_path, "bucket = \"legacy\"\n").unwrap();
        let store = MockBundleStore::empty();

        let err = run_with(&args(true, false), Some(&config_path), &store).unwrap_err();
        assert!(err.to_string().contains("pre-0.2"), "{err}");
        assert!(
            store.read().unwrap().is_none(),
            "must not touch the keychain when refusing a legacy config"
        );
    }

    /// `--force` must read the bundle exactly once (to preserve any existing
    /// Sia key before overwriting) — not once as a preflight "is setup
    /// complete?" check and again inside the rotation itself. Caught during
    /// real macOS verification of ADR-0015: the preflight read is discarded
    /// and only affects which warning gets printed, so it's a wasted
    /// keychain round-trip whenever `--force` is already explicit.
    #[test]
    fn force_rotation_does_not_perform_a_redundant_preflight_read() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        Config::default().save(Some(&config_path)).unwrap();
        let store = MockBundleStore::seeded(CredentialBundle {
            encryption_key: [0x55; 32],
            sia_app_key: None,
        });

        run_with(&args(true, true), Some(&config_path), &store).unwrap();

        assert_eq!(
            store.read_calls(),
            1,
            "--force must read the bundle exactly once, not as a discarded preflight check \
             plus a second read inside the rotation"
        );
        assert_eq!(store.write_calls(), 1);
    }

    /// `seed` (any casing) must still trigger phrase generation — a bare
    /// case mismatch shouldn't fall through to "treat this as a literal
    /// phrase" and fail with a confusing mnemonic-parse error.
    #[cfg(feature = "sia")]
    #[test]
    fn resolve_recovery_phrase_treats_seed_case_insensitively() {
        for input in ["seed", "SEED", "Seed", " seed "] {
            let resolved = resolve_recovery_phrase(input).unwrap();
            assert_ne!(
                resolved, input,
                "{input:?} must generate a fresh phrase, not be treated as a literal one"
            );
            // A generated phrase is a real multi-word BIP-39 mnemonic.
            assert!(resolved.split_whitespace().count() > 1);
        }
    }

    /// A malformed phrase must be rejected locally — before any network
    /// call — so a typo never burns a browser approval round-trip or an
    /// account's limited app-connection slot on a guaranteed-to-fail
    /// registration attempt.
    #[cfg(feature = "sia")]
    #[test]
    fn resolve_recovery_phrase_rejects_an_invalid_phrase() {
        let err = resolve_recovery_phrase("not a real recovery phrase").unwrap_err();
        assert!(
            err.to_string()
                .contains("doesn't look like a valid Sia recovery phrase"),
            "{err}"
        );
    }

    /// A create-only `AlreadyExists` result means the wizard just re-asked
    /// every question without the encryption key actually rotating — this
    /// message is what tells the user that, so "why did it ask me
    /// everything again?" doesn't read as "did it just reset my key?"
    #[test]
    fn repair_status_message_reflects_whether_a_sia_key_was_freshly_saved() {
        assert_eq!(
            repair_status_message(false),
            "Existing credentials preserved; rebuilding configuration."
        );
        assert_eq!(
            repair_status_message(true),
            "Existing encryption key preserved; Sia app key saved."
        );
    }

    #[test]
    fn legacy_config_is_replaced_with_force() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.toml");
        std::fs::write(&config_path, "bucket = \"legacy\"\n").unwrap();
        let store = MockBundleStore::empty();

        run_with(&args(true, true), Some(&config_path), &store).unwrap();

        let reloaded = Config::load(Some(&config_path)).unwrap();
        assert_eq!(
            reloaded.credential_store_version,
            Some(CURRENT_CREDENTIAL_VERSION)
        );
        assert!(store.read().unwrap().is_some());
    }
}