second-brain-cli 0.13.3

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
use std::thread;
use std::time::Duration;

use anyhow::{Context, Result, bail, ensure};
use chrono::Utc;
use qrcode::QrCode;
use qrcode::render::unicode::Dense1x2;
use second_brain_core::keys::move_aside_for_pairing;
use second_brain_core::machine;
use second_brain_sync::pairing::{JOIN_PENDING_FILE, JoinCode, reachable};
use serde::Deserialize;
use zeroize::{Zeroize, Zeroizing};

use super::recovery::show_phrase;
use super::restore::{daemon_answers, restart_daemon, wait_until_down};
use super::setup::daemon_ready;
use crate::{api, daemon};

const USAGE: &str = "usage: sb pair [--port <port>] [--restore-keys] | sb pair <code> [--host <host>] \
     [--discard-local] | sb pair --stop-waiting";
const POLL: Duration = Duration::from_secs(1);

#[derive(Debug, PartialEq, Eq)]
pub(crate) enum PairArgs {
    Host {
        port: Option<u16>,
        /// Hand this device's keys to a restore instead of adding a device.
        restore_keys: bool,
    },
    Join {
        code: String,
        host: Option<String>,
        /// Move this device's store aside and take the pairing bootstrap.
        discard_local: bool,
    },
    /// Ingest now instead of waiting for a bootstrap from the pairing device.
    StopWaiting,
}

impl PairArgs {
    pub(crate) fn parse(args: &[String]) -> Result<Self> {
        let mut words = Vec::new();
        let mut host = None;
        let mut port = None;
        let mut restore_keys = false;
        let mut discard_local = false;
        if args.iter().any(|a| a == "--stop-waiting") {
            ensure!(
                args.len() == 1,
                "--stop-waiting takes nothing else; {USAGE}"
            );
            return Ok(Self::StopWaiting);
        }
        let mut rest = args.iter();
        while let Some(arg) = rest.next() {
            match arg.as_str() {
                "--host" => host = Some(rest.next().context(USAGE)?.clone()),
                "--restore-keys" => restore_keys = true,
                "--discard-local" => discard_local = true,
                "--port" => {
                    let value = rest.next().context(USAGE)?;
                    port = Some(
                        value
                            .parse()
                            .with_context(|| format!("{value:?} is not a port; {USAGE}"))?,
                    );
                }
                flag if flag.starts_with("--") => bail!("{USAGE}"),
                word => words.push(word.to_string()),
            }
        }
        if words.is_empty() {
            if host.is_some() {
                bail!("--host goes with the code shown on the other device; {USAGE}");
            }
            if discard_local {
                bail!("--discard-local goes with the code shown on the other device; {USAGE}");
            }
            return Ok(Self::Host { port, restore_keys });
        }
        if port.is_some() || restore_keys {
            bail!("--port and --restore-keys are for the device that shows the code; {USAGE}");
        }
        Ok(Self::Join {
            code: words.join(" "),
            host,
            discard_local,
        })
    }
}

#[derive(Deserialize)]
struct Founded {
    identity: String,
    phrase: String,
    fingerprint: String,
}

impl Drop for Founded {
    fn drop(&mut self) {
        self.phrase.zeroize();
    }
}

#[derive(Deserialize)]
struct Device {
    machine_id: String,
    name: String,
}

#[derive(Deserialize)]
struct Status {
    state: String,
    code: Option<String>,
    invite: Option<String>,
    retired: u32,
    expires_in_secs: u64,
    device: Option<Device>,
    last_error: Option<String>,
}

impl Drop for Status {
    fn drop(&mut self) {
        self.code.zeroize();
        self.invite.zeroize();
    }
}

#[derive(Deserialize)]
struct Started {
    #[serde(flatten)]
    status: Status,
    addresses: Vec<String>,
    port: u16,
    default_port: bool,
    founded: Option<Founded>,
}

#[derive(Deserialize)]
struct Joined {
    identity: String,
    host: Device,
    epochs: usize,
    moved: bool,
    known_hosts: Vec<String>,
    warning: Option<String>,
}

pub(crate) fn cmd_pair(args: &[String]) -> Result<()> {
    match PairArgs::parse(args)? {
        PairArgs::Host { port, restore_keys } => host(port, restore_keys),
        PairArgs::Join {
            code,
            host,
            discard_local: false,
        } => join(code, host),
        PairArgs::Join {
            code,
            host,
            discard_local: true,
        } => discard_local_and_join(code, host),
        PairArgs::StopWaiting => {
            if stop_waiting()? {
                eprintln!("this device no longer waits for its first sync and ingests from now on");
            } else {
                eprintln!("this device was not waiting for its first sync");
            }
            Ok(())
        }
    }
}

/// Ends a pending bootstrap; true when one was pending.
pub(crate) fn stop_waiting() -> Result<bool> {
    let client = api::client(Duration::from_secs(30))?;
    let body: serde_json::Value = api::daemon_ok(
        client
            .post(format!("{}/v1/pair/stop-waiting", api::base_url()))
            .send()
            .context("asking the daemon to stop waiting for its first sync")?,
    )?
    .json()
    .context("reading the daemon's answer")?;
    Ok(body["cancelled"] == serde_json::Value::Bool(true))
}

fn host(port: Option<u16>, restore_keys: bool) -> Result<()> {
    let client = api::client(Duration::from_secs(60))?;
    let base = api::base_url();
    let started: Started = api::daemon_ok(
        client
            .post(format!("{base}/v1/pair/start"))
            .json(&serde_json::json!({ "port": port, "restore_keys": restore_keys }))
            .send()
            .context("asking the daemon to open a pairing listener")?,
    )?
    .json()
    .context("reading the pairing listener's details")?;
    if let Some(founded) = &started.founded {
        println!(
            "This device had no sync identity, so it started one ({}).",
            founded.identity
        );
        print!("{}", *show_phrase(&founded.phrase, &founded.fingerprint));
    }
    let target = join_target(&started.addresses, started.port, started.default_port);
    let shown = |status: &Status| {
        if restore_keys {
            show_restore_code(status, &target)
        } else {
            show_code(status, &target)
        }
    };
    print!("{}", shown(&started.status)?);
    let mut retired = started.status.retired;
    let mut last_error = None;
    loop {
        thread::sleep(POLL);
        let status: Status = api::daemon_ok(
            client
                .get(format!("{base}/v1/pair/status"))
                .send()
                .context("asking the daemon how pairing is going")?,
        )?
        .json()
        .context("reading the pairing status")?;
        if status.last_error.is_some() && status.last_error != last_error {
            last_error.clone_from(&status.last_error);
            eprintln!(
                "a device proved the code but did not join: {}",
                status.last_error.as_deref().unwrap_or_default()
            );
        }
        match status.state.as_str() {
            "waiting" if status.retired != retired => {
                retired = status.retired;
                println!("\nThree wrong codes were tried, so that code is retired.");
                print!("{}", shown(&status)?);
            }
            "waiting" => {}
            "paired" => {
                let device = status
                    .device
                    .as_ref()
                    .context("the daemon named no device")?;
                println!("Paired {} ({}).", device.name, device.machine_id);
                return Ok(());
            }
            "handed_over" => {
                let device = status
                    .device
                    .as_ref()
                    .context("the daemon named no device")?;
                println!("Handed this device's keys to {}.", device.name);
                return Ok(());
            }
            "expired" => bail!("no device joined within 10 minutes; run `sb pair` again"),
            _ => bail!("the pairing listener was closed; run `sb pair` again"),
        }
    }
}

fn join_target(addresses: &[String], port: u16, default_port: bool) -> String {
    let host = addresses.first().map_or("<this device>", String::as_str);
    if default_port {
        host.to_string()
    } else if host.contains(':') {
        format!("[{host}]:{port}")
    } else {
        format!("{host}:{port}")
    }
}

fn show_restore_code(status: &Status, target: &str) -> Result<String> {
    let code = status.code.as_deref().context("the daemon sent no code")?;
    let minutes = status.expires_in_secs.div_ceil(60);
    Ok(format!(
        "\nThis device hands every sync key it holds to a device restoring a backup, and adds \
         no device.\nCode, open for {minutes} more minutes:\n\n    {code}\n\n\
         On the restoring device run:\n\n    sb restore <backup-dir> --code {code} --host {target}\n"
    ))
}

fn show_code(status: &Status, target: &str) -> Result<String> {
    let code = status.code.as_deref().context("the daemon sent no code")?;
    let invite = status
        .invite
        .as_deref()
        .context("the daemon sent no invite")?;
    let qr = QrCode::new(invite.as_bytes())
        .context("drawing the pairing QR")?
        .render::<Dense1x2>()
        .dark_color(Dense1x2::Light)
        .light_color(Dense1x2::Dark)
        .quiet_zone(true)
        .build();
    let minutes = status.expires_in_secs.div_ceil(60);
    Ok(format!(
        "\nPairing code, open for {minutes} more minutes:\n\n    {code}\n\n\
         On the new device run:\n\n    sb pair {code} --host {target}\n\n\
         or scan this invite:\n\n{qr}\n"
    ))
}

fn join(mut code: String, host: Option<String>) -> Result<()> {
    let client = api::client(Duration::from_secs(120))?;
    let sent = client
        .post(format!("{}/v1/pair/join", api::base_url()))
        .json(&serde_json::json!({ "code": code, "host": host }))
        .send();
    code.zeroize();
    let joined: Joined = api::daemon_ok(sent.context("asking the daemon to join")?)?
        .json()
        .context("reading the pairing result")?;
    println!("{}", describe_join(&joined));
    Ok(())
}

/// Moves this device's store aside, restarts the daemon on an empty one
/// that waits for its bootstrap, then joins: nothing it held is merged into
/// the identity it joins. The moved store stays readable for 90 days.
/// Nothing moves until the code parses and the pairing device answers.
fn discard_local_and_join(code: String, host: Option<String>) -> Result<()> {
    let code = Zeroizing::new(code);
    discard_preflight(&code, host.as_deref())?;
    ensure!(
        daemon_answers(),
        "the daemon is not running; start it with `sb start`, then run this again"
    );
    let data_dir = machine::data_dir()?;
    eprintln!("stopping the daemon so this device's store can be moved aside");
    daemon::control(daemon::Action::Stop)
        .context("stopping the daemon; stop it with `sb stop` and run this again")?;
    wait_until_down()?;
    let moved = move_aside_for_pairing(
        &data_dir,
        Utc::now().timestamp_micros(),
        &[JOIN_PENDING_FILE],
    );
    if moved.is_ok() || data_dir.join("brain.db").exists() {
        restart_daemon();
    } else {
        eprintln!("the daemon stays stopped, since the data dir is not where it starts from");
    }
    let aside = moved.context("moving this device's store aside")?;
    eprintln!(
        "moved this device's store to {}; it is deleted after 90 days, and until then \
         POST /v1/maintenance/plaintext-copy with {{\"aside\": \"{}\"}} writes a readable copy",
        aside.display(),
        aside.file_name().unwrap_or_default().to_string_lossy()
    );
    let next = |what: &str| {
        format!(
            "{what}; `sb pair <code>` joins from the empty store, with this code while the other \
             device still shows it; the earlier store is at {}, and moving it back in place of \
             the empty one with the daemon stopped undoes the discard",
            aside.display()
        )
    };
    if !daemon_ready()? {
        bail!(next("the daemon did not come up"));
    }
    join(code.to_string(), host).with_context(|| next("the join failed"))
}

/// Refuses a discard whose code does not parse or whose pairing device does
/// not answer, before anything is stopped or moved.
fn discard_preflight(code: &str, host: Option<&str>) -> Result<()> {
    let addresses = JoinCode::parse(code)?.addresses(host)?;
    ensure!(
        !addresses.is_empty(),
        "--discard-local needs --host <host>, as `sb pair` shows on the pairing device, so that \
         device is checked before anything moves; nothing was moved"
    );
    reachable(&addresses).context("nothing was moved")
}

fn describe_join(joined: &Joined) -> String {
    let mut out = format!(
        "Paired with {} ({}) into sync identity {}; this device opens {} key epochs.",
        joined.host.name, joined.host.machine_id, joined.identity, joined.epochs
    );
    if joined.moved {
        out.push_str(
            "\nThis device left its earlier identity; its memories stay and sync into this one.",
        );
    }
    if joined.known_hosts.is_empty() {
        if joined.warning.is_none() {
            out.push_str(&format!(
                "\n{} runs no sshd this device can see, so it syncs by reaching this device.",
                joined.host.name
            ));
        }
    } else {
        out.push_str(&format!(
            "\nPinned {}'s ssh host key in ~/.second-brain/known_hosts for: {}.",
            joined.host.name,
            joined
                .known_hosts
                .iter()
                .filter_map(|entry| entry.split_whitespace().next())
                .collect::<std::collections::BTreeSet<_>>()
                .into_iter()
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }
    if let Some(warning) = &joined.warning {
        out.push_str(&format!("\nWarning: {warning}"));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn words(line: &str) -> Vec<String> {
        line.split_whitespace().map(str::to_string).collect()
    }

    #[test]
    fn arguments_parse_into_hosting_or_joining() {
        assert_eq!(
            PairArgs::parse(&[]).unwrap(),
            PairArgs::Host {
                port: None,
                restore_keys: false
            }
        );
        assert_eq!(
            PairArgs::parse(&words("--port 7300")).unwrap(),
            PairArgs::Host {
                port: Some(7300),
                restore_keys: false
            }
        );
        assert_eq!(
            PairArgs::parse(&words("--restore-keys --port 7300")).unwrap(),
            PairArgs::Host {
                port: Some(7300),
                restore_keys: true
            }
        );
        assert_eq!(
            PairArgs::parse(&words("acid-able-act-add --host desk")).unwrap(),
            PairArgs::Join {
                code: "acid-able-act-add".into(),
                host: Some("desk".into()),
                discard_local: false
            }
        );
        assert_eq!(
            PairArgs::parse(&words("acid able act add")).unwrap(),
            PairArgs::Join {
                code: "acid able act add".into(),
                host: None,
                discard_local: false
            }
        );
        assert_eq!(
            PairArgs::parse(&words("--discard-local acid-able-act-add")).unwrap(),
            PairArgs::Join {
                code: "acid-able-act-add".into(),
                host: None,
                discard_local: true
            }
        );
        assert_eq!(
            PairArgs::parse(&words("--stop-waiting")).unwrap(),
            PairArgs::StopWaiting
        );
        for bad in [
            "--stop-waiting code",
            "--port 7300 --stop-waiting",
            "--host desk",
            "--port",
            "--port many",
            "code --port 7300",
            "--verbose",
            "code --host",
            "--discard-local",
            "code --restore-keys",
            "--stop-waiting --restore-keys",
        ] {
            assert!(PairArgs::parse(&words(bad)).is_err(), "{bad}");
        }
    }

    #[test]
    fn the_join_command_names_the_port_only_when_it_is_not_the_default() {
        let addresses = vec!["192.0.2.4".to_string(), "desk".to_string()];
        assert_eq!(join_target(&addresses, 7201, true), "192.0.2.4");
        assert_eq!(join_target(&addresses, 40001, false), "192.0.2.4:40001");
        assert_eq!(
            join_target(&["fe80::1".into()], 40001, false),
            "[fe80::1]:40001"
        );
    }

    #[test]
    fn the_shown_code_carries_the_join_command_and_a_qr() {
        let status = Status {
            state: "waiting".into(),
            code: Some("acid-able-act-add".into()),
            invite: Some("sb-pair:00112233445566778899aabbccddeeff@desk:7201".into()),
            retired: 0,
            expires_in_secs: 599,
            device: None,
            last_error: None,
        };
        let shown = show_code(&status, "desk").unwrap();
        assert!(
            shown.contains("sb pair acid-able-act-add --host desk"),
            "{shown}"
        );
        assert!(shown.contains("10 more minutes"), "{shown}");
        assert!(
            shown.contains('\u{2580}') || shown.contains('\u{2584}'),
            "{shown}"
        );
    }

    #[test]
    fn a_discard_with_a_bad_code_or_no_listener_stops_before_touching_anything() {
        assert!(discard_preflight("not a pairing code", None).is_err());
        let err = discard_preflight("acid-able-act-add", None).unwrap_err();
        assert!(format!("{err:#}").contains("--host"), "{err:#}");
        let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = closed.local_addr().unwrap().port();
        drop(closed);
        let err =
            discard_preflight("acid-able-act-add", Some(&format!("127.0.0.1:{port}"))).unwrap_err();
        assert!(format!("{err:#}").contains("nothing was moved"), "{err:#}");
    }

    #[test]
    fn the_restore_code_names_the_restore_command_and_no_join() {
        let status = Status {
            state: "waiting".into(),
            code: Some("acid-able-act-add".into()),
            invite: Some("sb-pair:00112233445566778899aabbccddeeff@desk:7201".into()),
            retired: 0,
            expires_in_secs: 599,
            device: None,
            last_error: None,
        };
        let shown = show_restore_code(&status, "desk").unwrap();
        assert!(
            shown.contains("sb restore <backup-dir> --code acid-able-act-add --host desk"),
            "{shown}"
        );
        assert!(!shown.contains("sb pair acid"), "{shown}");
    }

    #[test]
    fn a_join_report_names_the_pinned_hosts_and_a_move() {
        let joined = Joined {
            identity: "f-tag".into(),
            host: Device {
                machine_id: "m-1".into(),
                name: "desk".into(),
            },
            epochs: 2,
            moved: true,
            known_hosts: vec![
                "desk ssh-ed25519 AAAA".into(),
                "192.0.2.2 ssh-ed25519 AAAA".into(),
                "desk ssh-rsa BBBB".into(),
            ],
            warning: None,
        };
        let shown = describe_join(&joined);
        assert!(shown.contains("opens 2 key epochs"), "{shown}");
        assert!(shown.contains("left its earlier identity"), "{shown}");
        assert!(shown.contains("for: 192.0.2.2, desk."), "{shown}");
    }

    #[test]
    fn a_join_whose_host_keys_were_not_pinned_shows_the_warning() {
        let joined: Joined = serde_json::from_value(serde_json::json!({
            "identity": "f-tag",
            "host": {"machine_id": "m-1", "name": "desk"},
            "epochs": 1,
            "moved": false,
            "devices": 1,
            "known_hosts": [],
            "warning": "the host keys were not pinned, so ssh will ask you to trust desk",
        }))
        .unwrap();
        let shown = describe_join(&joined);
        assert!(shown.starts_with("Paired with desk"), "{shown}");
        assert!(
            shown.contains("Warning: the host keys were not pinned"),
            "{shown}"
        );
        assert!(!shown.contains("runs no sshd"), "{shown}");

        let without: Joined = serde_json::from_value(serde_json::json!({
            "identity": "f-tag",
            "host": {"machine_id": "m-1", "name": "desk"},
            "epochs": 1,
            "moved": false,
            "known_hosts": [],
        }))
        .unwrap();
        assert!(!describe_join(&without).contains("Warning"));

        let pinned_but_unacked: Joined = serde_json::from_value(serde_json::json!({
            "identity": "f-tag",
            "host": {"machine_id": "m-1", "name": "desk"},
            "epochs": 1,
            "moved": false,
            "known_hosts": ["desk ssh-ed25519 AAAA"],
            "warning": "the join is done, but desk was not told the join succeeded",
        }))
        .unwrap();
        let shown = describe_join(&pinned_but_unacked);
        assert!(shown.contains("Pinned desk's ssh host key"), "{shown}");
        assert!(shown.contains("Warning: the join is done"), "{shown}");
    }
}