second-brain-cli 0.13.2

Memory layer for AI coding agents: ingest, recall, and sync across machines
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
use std::io::IsTerminal;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};

use second_brain_sync::pairing::JOIN_PENDING_FILE;
use zeroize::{Zeroize, Zeroizing};

use super::ingest::not_run;
use super::pair;
use super::recovery::RecoveryState;
use crate::{api, bins, claude_code, claude_hooks, claude_mcp, daemon, launchd};

pub(crate) fn cmd_setup() -> Result<()> {
    let os = daemon::Os::current();
    let caller = daemon::Caller::current();
    daemon::check_setup_caller(os, caller.uid)?;
    let account = match os {
        daemon::Os::MacOs => Some(launchd::Account::from_uid(caller.uid)?),
        daemon::Os::Linux => None,
    };
    let home = match &account {
        Some(account) => account.home.clone(),
        None => PathBuf::from(std::env::var("HOME").context("HOME not set")?),
    };

    let unit_active =
        os == daemon::Os::Linux && daemon::user_unit_active(&caller, &mut daemon::SystemExec);
    daemon::check_bind_free(
        daemon::DEFAULT_BIND,
        || match os {
            daemon::Os::Linux => Ok(unit_active),
            daemon::Os::MacOs => launchd::is_loaded(
                &launchd::Daemon::new(launchd::DEFAULT_LABEL),
                &mut launchd::System,
            ),
        },
        |port| daemon::port_holder(port, &mut daemon::SystemExec),
    )?;

    eprintln!("=== second-brain setup ===\n");

    // 1. Create data directory
    let db_dir = home.join(".second-brain");
    std::fs::create_dir_all(&db_dir)?;
    eprintln!("[1/6] data dir: {}", db_dir.display());

    // 2. Locate binaries
    let (api_bin, mcp_bin, cli_bin) = bins::locate_binaries()?;
    eprintln!("[2/6] binaries:");
    eprintln!("  api: {}", api_bin.display());
    eprintln!("  mcp: {}", mcp_bin.display());
    eprintln!("  cli: {}", cli_bin.display());

    let db_path = db_dir.join("brain.db");
    let interactive = std::io::stdin().is_terminal() && std::io::stderr().is_terminal();
    let asked = if ask_before_start(fresh_install(&db_path), interactive) {
        let choice = ask_identity()?;
        record_identity_choice(&db_dir, &choice)?;
        Some(choice)
    } else {
        None
    };
    let record = match &account {
        Some(account) => install_launchd(account, &api_bin, &db_path, &db_dir, &caller)?,
        None => install_systemd(&home, &api_bin, &db_path, unit_active, &caller)?,
    };

    let config_dir = claude_code::config_dir(std::env::var_os("CLAUDE_CONFIG_DIR"));
    let settings = claude_hooks::settings_path(config_dir.as_deref().map(Path::as_os_str), &home);
    let claude = claude_code::Claude::current(
        std::env::var_os("PATH").as_deref(),
        &home,
        config_dir.as_deref(),
    );
    let mcp = claude_mcp::register(&mcp_bin, &claude, &mut daemon::SystemExec)?;
    eprintln!("[4/6] claude code MCP: {}", mcp.report());

    match claude_hooks::register(&settings, &cli_bin) {
        Ok(hooks) => eprintln!("[5/6] claude code hooks: {}", hooks.report()),
        Err(e) => eprintln!("[5/6] claude code hooks: warning: {e:#}"),
    }

    // 6. Wait for daemon, run first ingest
    eprintln!("[6/6] running first ingest...");
    if !daemon_ready()? {
        eprintln!(
            "  the daemon is still starting after {}s; check it with `sb status` and run `sb ingest` once it is up",
            READY_LIMIT.as_secs()
        );
        if asked == Some(IdentityChoice::Join) {
            eprintln!("{JOIN_WAITING}");
        }
        return Ok(());
    }

    offer_pairing(asked.as_ref(), interactive);

    let client = api::client(std::time::Duration::from_secs(600))?;
    match client
        .post(format!("{}/v1/ingest", api::base_url()))
        .json(&serde_json::json!({}))
        .send()
    {
        Ok(resp) if resp.status().is_success() => {
            let body: serde_json::Value = resp.json().unwrap_or_default();
            if let Some(held) = not_run(&body) {
                eprintln!("  {held}");
            } else {
                eprintln!(
                    "  ingested: {} memories, {} conversations",
                    body["new_memories"], body["new_conversations"]
                );
            }
        }
        Ok(resp) => eprintln!("  ingest warning: {}", resp.status()),
        Err(e) => eprintln!("  ingest warning: {e}"),
    }

    if let Err(e) = crate::commands::recovery::offer_once() {
        eprintln!("  recovery phrase warning: {e:#}");
    }

    eprintln!("\n=== setup complete ===");
    eprintln!("daemon:  {}", daemon::status_hint(&record));
    eprintln!("recall:  sb recall \"your query\"");
    eprintln!("status:  sb status");

    Ok(())
}

fn install_systemd(
    home: &Path,
    api_bin: &Path,
    db_path: &Path,
    unit_active: bool,
    caller: &daemon::Caller,
) -> Result<daemon::ServiceRecord> {
    let systemd_dir = daemon::user_unit_dir(home);
    std::fs::create_dir_all(&systemd_dir)?;
    let service_path = systemd_dir.join(daemon::DEFAULT_UNIT);

    let service_content = daemon::unit_file(api_bin, db_path);

    std::fs::write(&service_path, &service_content)?;
    let record = daemon::ServiceRecord::user_default();
    daemon::save_record(&daemon::record_path()?, &record)?;
    eprintln!("[3/6] systemd service: {}", service_path.display());

    let mut exec = daemon::SystemExec;
    match daemon::start_user_unit(unit_active, caller, &mut exec) {
        daemon::Start::Started => eprintln!("  enabled and started"),
        daemon::Start::Restarted => eprintln!("  enabled and restarted on the new binary"),
        daemon::Start::Failed { command, detail } => eprintln!(
            "  warning: `{command}` failed ({detail}); start the daemon manually: {}",
            api_bin.display()
        ),
    }

    let user = launchd::Account::from_uid(caller.uid)
        .map(|account| account.name)
        .unwrap_or_else(|_| caller.uid.to_string());
    match daemon::ensure_linger(&user, &mut exec) {
        daemon::Linger::AlreadyOn => {}
        daemon::Linger::Enabled => {
            eprintln!("  linger enabled, so the daemon keeps running after logout")
        }
        daemon::Linger::Failed(warning) => eprintln!("  warning: {warning}"),
    }
    Ok(record)
}

const READY_LIMIT: std::time::Duration = std::time::Duration::from_secs(300);

const READY_PROGRESS: std::time::Duration = std::time::Duration::from_secs(15);

const READY_POLL: std::time::Duration = std::time::Duration::from_millis(500);

#[derive(Debug, PartialEq, Eq)]
enum Readiness {
    Ready,
    Starting(String),
    Down,
}

/// `answered` is the `/health` status and JSON body, None when nothing
/// answered.
fn readiness(answered: Option<(u16, serde_json::Value)>) -> Readiness {
    match answered {
        Some((200, health)) => match api::starting_reason(&health) {
            Some(reason) => Readiness::Starting(reason.to_string()),
            None => Readiness::Ready,
        },
        _ => Readiness::Down,
    }
}

/// Waits up to `READY_LIMIT` for the daemon to answer `/health` as ready,
/// reporting progress on stderr.
pub(crate) fn daemon_ready() -> Result<bool> {
    let api = api::base_url();
    let probe = api::open_client(std::time::Duration::from_secs(2))?;
    let started = std::time::Instant::now();
    Ok(wait_for_daemon(
        || started.elapsed(),
        || {
            readiness(
                probe
                    .get(format!("{api}/health"))
                    .send()
                    .ok()
                    .map(|r| (r.status().as_u16(), r.json().unwrap_or_default())),
            )
        },
        std::thread::sleep,
        |waited, reason| match reason {
            Some(reason) => eprintln!(
                "  waiting for the daemon to finish starting ({}s): {reason}",
                waited.as_secs()
            ),
            None => eprintln!(
                "  waiting for the daemon to finish starting ({}s)",
                waited.as_secs()
            ),
        },
    ))
}

/// The daemon serves `/health` with state "starting" while it opens the store
/// and rebuilds indexes, which can take minutes on a large store.
fn wait_for_daemon(
    mut elapsed: impl FnMut() -> std::time::Duration,
    mut probe: impl FnMut() -> Readiness,
    mut pause: impl FnMut(std::time::Duration),
    mut progress: impl FnMut(std::time::Duration, Option<&str>),
) -> bool {
    let mut next_report = READY_PROGRESS;
    loop {
        let reason = match probe() {
            Readiness::Ready => return true,
            Readiness::Starting(reason) => Some(reason),
            Readiness::Down => None,
        };
        let waited = elapsed();
        if waited >= READY_LIMIT {
            return false;
        }
        if waited >= next_report {
            progress(next_report, reason.as_deref());
            next_report += READY_PROGRESS;
        }
        pause(READY_POLL);
    }
}

fn install_launchd(
    account: &launchd::Account,
    api_bin: &Path,
    db_path: &Path,
    data_dir: &Path,
    caller: &daemon::Caller,
) -> Result<daemon::ServiceRecord> {
    let target = launchd::Daemon::new(launchd::DEFAULT_LABEL);
    let plist = launchd::render_plist(&launchd::PlistSpec {
        label: &target.label,
        program: api_bin,
        account,
        db: db_path,
        bind: daemon::DEFAULT_BIND,
    })?;
    eprintln!(
        "[3/6] launchd daemon: {} (sudo asks for your password)",
        target.plist.display()
    );
    launchd::install(
        &launchd::Install {
            daemon: &target,
            plist: &plist,
            staged: &data_dir.join(format!("{}.plist", target.label)),
            backup: &data_dir.join(format!("{}.plist.previous", target.label)),
            log_dir: &account.log_dir(),
            record_path: &daemon::record_path()?,
        },
        caller,
        &mut launchd::System,
    )?;
    eprintln!("  loaded, logs in {}", account.log_dir().display());
    Ok(target.record())
}

const PAIR_HINT: &str = "  to join a sync identity another device already runs instead of starting a new one, \
     run `sb pair <code> --host <host>` with the code `sb pair` shows there";

const JOIN_WAITING: &str = "  this device waits to join a sync identity, and nothing is ingested until it does: \
     join with `sb pair <code> --host <host>` and the code `sb pair` shows on the other device, \
     or run `sb pair --stop-waiting` to start alone";

/// Joins through `sb pair` when the user chose to, before the service
/// started (`asked`) or now. Failures are reported, never fatal, so setup
/// goes on to its ingest step either way.
fn offer_pairing(asked: Option<&IdentityChoice>, interactive: bool) {
    let has_identity = if asked == Some(&IdentityChoice::New) {
        None
    } else {
        match has_sync_identity() {
            Ok(has) => Some(has),
            Err(e) => {
                eprintln!("  pairing: cannot tell whether this device has a sync identity: {e:#}");
                None
            }
        }
    };
    match offer_after_ready(asked, has_identity, interactive) {
        IdentityOffer::Skip => {}
        IdentityOffer::Hint => eprintln!("{PAIR_HINT}"),
        IdentityOffer::Join => {
            if let Err(e) = join_from_prompt() {
                eprintln!("  pairing failed: {e:#}\n{JOIN_WAITING}");
            }
        }
        IdentityOffer::Ask => {
            if let Err(e) = ask_and_join() {
                eprintln!(
                    "  pairing: {e:#}\n  join later with `sb pair <code> --host <host>`, or run \
                     `sb pair --stop-waiting` if this device waits to join one"
                );
            }
        }
    }
}

fn has_sync_identity() -> Result<bool> {
    let client = api::client(std::time::Duration::from_secs(30))?;
    let state: RecoveryState = api::daemon_ok(
        client
            .get(format!("{}/v1/keys/recovery", api::base_url()))
            .send()
            .context("asking the daemon for its sync identity")?,
    )?
    .json()
    .context("reading the daemon's sync identity")?;
    Ok(state.identity.is_some())
}

fn ask_and_join() -> Result<()> {
    match ask_identity()? {
        IdentityChoice::New => start_alone(),
        IdentityChoice::Join => join_from_prompt(),
    }
}

/// Ends a wait to join that an earlier run of setup began.
fn start_alone() -> Result<()> {
    if pair::stop_waiting()? {
        eprintln!("  this device no longer waits to join an identity");
    }
    Ok(())
}

fn ask_identity() -> Result<IdentityChoice> {
    eprint!(
        "  does this device start a new sync identity, or join one your other device runs?\n    \
         1) start a new identity (`sb pair` here later adds devices)\n    \
         2) join an existing device\n  choice [1]: "
    );
    loop {
        let answer = read_answer()?;
        match identity_choice(&answer) {
            Some(choice) => return Ok(choice),
            None => eprint!("  answer 1 or 2: "),
        }
    }
}

fn join_from_prompt() -> Result<()> {
    eprint!("  the code `sb pair` shows on the other device: ");
    let code = Zeroizing::new(read_answer()?);
    eprint!("  that device's host, as shown after --host (Enter for none): ");
    let host = read_answer()?;
    let mut args = join_args(&code, &host).context("no code entered")?;
    let joined = pair::cmd_pair(&args);
    args.zeroize();
    joined
}

fn read_answer() -> Result<String> {
    let mut answer = String::new();
    std::io::stdin()
        .read_line(&mut answer)
        .context("reading the answer")?;
    Ok(answer)
}

#[derive(Debug, PartialEq, Eq)]
enum IdentityOffer {
    /// This device already belongs to a sync identity.
    Skip,
    Ask,
    /// No terminal to answer on, so the join command is named instead.
    Hint,
    /// The user chose to join before the service started; only the code and
    /// host are left to ask.
    Join,
}

/// A fresh install has no store yet, so the identity question can come
/// before the daemon starts ingesting into one.
fn fresh_install(db_path: &Path) -> bool {
    matches!(db_path.try_exists(), Ok(false))
}

fn ask_before_start(fresh: bool, interactive: bool) -> bool {
    fresh && interactive
}

/// The daemon reads the marker once at start, so a stale one from an
/// earlier run that chose to join is removed when this run starts anew.
fn record_identity_choice(db_dir: &Path, choice: &IdentityChoice) -> Result<()> {
    let marker = db_dir.join(JOIN_PENDING_FILE);
    match choice {
        IdentityChoice::Join => {
            std::fs::write(&marker, "").with_context(|| format!("writing {}", marker.display()))
        }
        IdentityChoice::New => match std::fs::remove_file(&marker) {
            Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
                Err(e).with_context(|| format!("removing {}", marker.display()))
            }
            _ => Ok(()),
        },
    }
}

/// `asked` is the answer given before the service started, if one was.
fn offer_after_ready(
    asked: Option<&IdentityChoice>,
    has_identity: Option<bool>,
    interactive: bool,
) -> IdentityOffer {
    match (asked, has_identity) {
        (None, _) => identity_offer(has_identity, interactive),
        (Some(IdentityChoice::Join), Some(true)) | (Some(IdentityChoice::New), _) => {
            IdentityOffer::Skip
        }
        (Some(IdentityChoice::Join), _) => IdentityOffer::Join,
    }
}

/// `has_identity` is None when the daemon could not say.
fn identity_offer(has_identity: Option<bool>, interactive: bool) -> IdentityOffer {
    match (has_identity, interactive) {
        (Some(true), _) => IdentityOffer::Skip,
        (_, true) => IdentityOffer::Ask,
        (_, false) => IdentityOffer::Hint,
    }
}

#[derive(Debug, PartialEq, Eq)]
enum IdentityChoice {
    New,
    Join,
}

/// None when the answer is neither, so the question is asked again.
fn identity_choice(answer: &str) -> Option<IdentityChoice> {
    match answer.trim().to_ascii_lowercase().as_str() {
        "" | "1" | "n" | "new" => Some(IdentityChoice::New),
        "2" | "j" | "join" => Some(IdentityChoice::Join),
        _ => None,
    }
}

/// The `sb pair` arguments that join with `code` through `host`; None
/// without a code.
fn join_args(code: &str, host: &str) -> Option<Vec<String>> {
    let code = code.trim();
    if code.is_empty() {
        return None;
    }
    let mut args = vec![code.to_string()];
    let host = host.trim();
    if !host.is_empty() {
        args.extend(["--host".to_string(), host.to_string()]);
    }
    Some(args)
}

#[cfg(test)]
mod wait_tests {
    use std::cell::{Cell, RefCell};
    use std::time::Duration;

    use super::*;

    fn simulate(
        mut probe: impl FnMut(Duration) -> Readiness,
    ) -> (bool, Vec<(Duration, Option<String>)>, Duration) {
        let clock = Cell::new(Duration::ZERO);
        let reports = RefCell::new(Vec::new());
        let ready = wait_for_daemon(
            || clock.get(),
            || probe(clock.get()),
            |d| clock.set(clock.get() + d),
            |at, reason| reports.borrow_mut().push((at, reason.map(str::to_string))),
        );
        (ready, reports.into_inner(), clock.get())
    }

    fn ready_at(at: Duration) -> impl FnMut(Duration) -> Readiness {
        move |now| {
            if now >= at {
                Readiness::Ready
            } else {
                Readiness::Down
            }
        }
    }

    #[test]
    fn a_cold_start_is_waited_out_for_five_minutes_with_progress_every_fifteen_seconds() {
        let (ready, reports, stopped) = simulate(|_| Readiness::Down);
        assert!(!ready);
        assert!(stopped >= Duration::from_secs(300), "{stopped:?}");
        assert!(stopped < Duration::from_secs(301), "{stopped:?}");
        let expected: Vec<_> = (1..20)
            .map(|n| (Duration::from_secs(15 * n), None))
            .collect();
        assert_eq!(reports, expected);
    }

    #[test]
    fn a_daemon_that_comes_up_ends_the_wait() {
        let (ready, reports, stopped) = simulate(ready_at(Duration::from_secs(40)));
        assert!(ready);
        assert_eq!(
            reports,
            [
                (Duration::from_secs(15), None),
                (Duration::from_secs(30), None)
            ]
        );
        assert!(stopped < Duration::from_secs(41), "{stopped:?}");
    }

    #[test]
    fn a_starting_daemon_is_waited_for_with_its_reason_in_the_progress_line() {
        let (ready, reports, stopped) = simulate(|now| {
            if now >= Duration::from_secs(40) {
                Readiness::Ready
            } else {
                Readiness::Starting(format!(
                    "rebuilding search indexes for 23594 memories, {}s so far",
                    now.as_secs()
                ))
            }
        });
        assert!(ready);
        assert!(stopped >= Duration::from_secs(40), "{stopped:?}");
        assert!(stopped < Duration::from_secs(41), "{stopped:?}");
        assert_eq!(
            reports,
            [
                (
                    Duration::from_secs(15),
                    Some("rebuilding search indexes for 23594 memories, 15s so far".to_string())
                ),
                (
                    Duration::from_secs(30),
                    Some("rebuilding search indexes for 23594 memories, 30s so far".to_string())
                ),
            ]
        );
    }

    #[test]
    fn a_daemon_still_starting_after_the_limit_is_not_ready() {
        let (ready, _, stopped) =
            simulate(|_| Readiness::Starting("opening the database".to_string()));
        assert!(!ready);
        assert!(stopped >= Duration::from_secs(300), "{stopped:?}");
    }

    #[test]
    fn health_is_ready_only_when_it_answers_200_and_is_not_starting() {
        let reason = "rebuilding search indexes for 23594 memories, 212s so far";
        let starting = serde_json::json!({
            "status": "starting",
            "version": "0.12.0",
            "state": "starting",
            "reason": reason,
            "since": "2026-11-02T08:00:00Z",
            "serving": {"state": "starting", "reason": reason}
        });
        let ok = serde_json::json!({"status": "ok", "state": "ok", "serving": {"state": "ok"}});
        let failing = serde_json::json!({"status": "ok", "state": "failing", "reason": "x"});
        let cases = [
            (
                Some((200, starting)),
                Readiness::Starting(reason.to_string()),
            ),
            (Some((200, ok)), Readiness::Ready),
            (Some((200, failing)), Readiness::Ready),
            (Some((200, serde_json::Value::Null)), Readiness::Ready),
            (
                Some((
                    503,
                    serde_json::json!({"error": "the daemon is starting: x"}),
                )),
                Readiness::Down,
            ),
            (None, Readiness::Down),
        ];
        for (answered, expected) in cases {
            assert_eq!(readiness(answered.clone()), expected, "{answered:?}");
        }
    }
}

#[cfg(test)]
mod pairing_offer_tests {
    use super::super::pair::PairArgs;
    use super::*;

    #[test]
    fn pairing_is_offered_only_to_a_device_without_an_identity() {
        let cases = [
            (Some(true), true, IdentityOffer::Skip),
            (Some(true), false, IdentityOffer::Skip),
            (Some(false), true, IdentityOffer::Ask),
            (Some(false), false, IdentityOffer::Hint),
            (None, true, IdentityOffer::Ask),
            (None, false, IdentityOffer::Hint),
        ];
        for (has_identity, interactive, expected) in cases {
            assert_eq!(
                identity_offer(has_identity, interactive),
                expected,
                "{has_identity:?} {interactive}"
            );
        }
    }

    #[test]
    fn the_answer_picks_a_new_identity_by_default_or_joining() {
        let cases = [
            ("", Some(IdentityChoice::New)),
            ("1\n", Some(IdentityChoice::New)),
            (" New ", Some(IdentityChoice::New)),
            ("n", Some(IdentityChoice::New)),
            ("2", Some(IdentityChoice::Join)),
            ("join\n", Some(IdentityChoice::Join)),
            ("J", Some(IdentityChoice::Join)),
            ("3", None),
            ("maybe", None),
        ];
        for (answer, expected) in cases {
            assert_eq!(identity_choice(answer), expected, "{answer:?}");
        }
    }

    #[test]
    fn a_join_goes_through_the_same_arguments_as_sb_pair() {
        let args = join_args(" alpha bravo charlie delta \n", " laptop.local\n").unwrap();
        assert_eq!(
            PairArgs::parse(&args).unwrap(),
            PairArgs::Join {
                code: "alpha bravo charlie delta".to_string(),
                host: Some("laptop.local".to_string()),
                discard_local: false,
            }
        );
        let without_host = join_args("alpha bravo charlie delta", "\n").unwrap();
        assert_eq!(
            PairArgs::parse(&without_host).unwrap(),
            PairArgs::Join {
                code: "alpha bravo charlie delta".to_string(),
                host: None,
                discard_local: false,
            }
        );
        assert_eq!(join_args("  \n", "laptop.local"), None);
    }

    #[test]
    fn the_hint_names_the_join_command() {
        assert!(PAIR_HINT.contains("sb pair <code> --host <host>"));
    }

    #[test]
    fn only_a_fresh_interactive_install_is_asked_before_the_daemon_starts() {
        let cases = [
            (true, true, true),
            (true, false, false),
            (false, true, false),
            (false, false, false),
        ];
        for (fresh, interactive, expected) in cases {
            assert_eq!(
                ask_before_start(fresh, interactive),
                expected,
                "{fresh} {interactive}"
            );
        }
    }

    #[test]
    fn an_answer_given_before_the_daemon_started_decides_the_offer_after_it() {
        let cases = [
            (Some(IdentityChoice::New), None, IdentityOffer::Skip),
            (Some(IdentityChoice::New), Some(false), IdentityOffer::Skip),
            (Some(IdentityChoice::Join), Some(false), IdentityOffer::Join),
            (Some(IdentityChoice::Join), None, IdentityOffer::Join),
            (Some(IdentityChoice::Join), Some(true), IdentityOffer::Skip),
        ];
        for interactive in [true, false] {
            for (asked, has_identity, expected) in &cases {
                assert_eq!(
                    offer_after_ready(asked.as_ref(), *has_identity, interactive),
                    *expected,
                    "{asked:?} {has_identity:?} {interactive}"
                );
            }
        }
        for has_identity in [Some(true), Some(false), None] {
            for interactive in [true, false] {
                assert_eq!(
                    offer_after_ready(None, has_identity, interactive),
                    identity_offer(has_identity, interactive),
                    "{has_identity:?} {interactive}"
                );
            }
        }
    }

    #[test]
    fn a_fresh_install_is_one_without_a_store() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("brain.db");
        assert!(fresh_install(&db));
        std::fs::write(&db, "").unwrap();
        assert!(!fresh_install(&db));
    }

    #[test]
    fn choosing_to_join_marks_the_data_dir_for_the_daemon_and_a_new_identity_clears_it() {
        let dir = tempfile::tempdir().unwrap();
        let marker = dir.path().join(JOIN_PENDING_FILE);
        record_identity_choice(dir.path(), &IdentityChoice::New).unwrap();
        assert!(!marker.exists());
        record_identity_choice(dir.path(), &IdentityChoice::Join).unwrap();
        assert!(marker.is_file());
        record_identity_choice(dir.path(), &IdentityChoice::New).unwrap();
        assert!(!marker.exists());
    }

    #[test]
    fn a_failed_join_says_nothing_is_ingested_and_names_both_ways_out() {
        assert!(
            JOIN_WAITING.contains("nothing is ingested"),
            "{JOIN_WAITING}"
        );
        assert!(
            JOIN_WAITING.contains("`sb pair <code> --host <host>`"),
            "{JOIN_WAITING}"
        );
        assert!(JOIN_WAITING.contains("`sb pair`"), "{JOIN_WAITING}");
        assert!(
            JOIN_WAITING.contains("`sb pair --stop-waiting`"),
            "{JOIN_WAITING}"
        );
    }
}