second-brain-cli 0.12.0

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
use anyhow::{Context, Result};
use second_brain_sync::peers;
use second_brain_sync::protocol::SyncHeader;
use second_brain_sync::session::{self, Exported, Imported, Local, read_checked_header};
use second_brain_sync::ssh::SshTransport;
use serde_json::Value;

use crate::api;

pub(crate) fn cmd_sync_trust(host: &str) -> Result<()> {
    use std::io::Write;

    let scan = std::process::Command::new("ssh-keyscan")
        .arg("-T")
        .arg("10")
        .arg(host)
        .output()
        .context("running ssh-keyscan (is openssh-client installed?)")?;

    if !scan.status.success() {
        let stderr = String::from_utf8_lossy(&scan.stderr);
        anyhow::bail!(
            "ssh-keyscan {host} failed (exit {}): {}",
            scan.status,
            stderr.trim()
        );
    }

    let raw = String::from_utf8(scan.stdout).context("ssh-keyscan returned non-UTF8 output")?;
    let lines = second_brain_sync::ssh::parse_keyscan_output(&raw);

    if lines.is_empty() {
        anyhow::bail!("ssh-keyscan {host} returned no host keys — host unreachable or filtered");
    }

    // pipe the canonical keyscan lines through ssh-keygen -lf - so the displayed
    // fingerprint exactly matches what OpenSSH would compute on connect.
    let canonical: String = lines
        .iter()
        .map(second_brain_sync::ssh::compose_known_host_entry)
        .collect();

    let mut fp_child = std::process::Command::new("ssh-keygen")
        .arg("-lf")
        .arg("-")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::inherit())
        .spawn()
        .context("running ssh-keygen (is openssh-client installed?)")?;

    {
        let stdin = fp_child.stdin.take().unwrap();
        let mut writer = std::io::BufWriter::new(stdin);
        writer.write_all(canonical.as_bytes())?;
    }

    let fp_out = fp_child.wait_with_output()?;
    if !fp_out.status.success() {
        anyhow::bail!("ssh-keygen -lf failed: exit {}", fp_out.status);
    }
    let fingerprints = String::from_utf8_lossy(&fp_out.stdout);

    eprintln!("Host: {host}");
    eprintln!("Fetched {} key(s). Fingerprints:", lines.len());
    for fp_line in fingerprints.lines() {
        eprintln!("  {fp_line}");
    }
    eprintln!();
    eprintln!("Verify these fingerprints out-of-band before trusting them.");
    eprint!("Pin to ~/.second-brain/known_hosts? [y/N] ");
    std::io::stderr().flush().ok();

    let mut answer = String::new();
    std::io::stdin()
        .read_line(&mut answer)
        .context("reading confirmation")?;
    let trimmed = answer.trim();
    if !trimmed.eq_ignore_ascii_case("y") && !trimmed.eq_ignore_ascii_case("yes") {
        eprintln!("aborted; nothing written.");
        return Ok(());
    }

    let path = second_brain_sync::ssh::known_hosts_path()?;
    second_brain_sync::ssh::append_known_host(&path, &lines)?;
    eprintln!(
        "pinned {} key(s) for {host} -> {}",
        lines.len(),
        path.display()
    );
    Ok(())
}

pub(crate) fn cmd_sync_export(after_seq: u64) -> Result<()> {
    let api_base = api::base_url();
    let client = api::sync_client(std::time::Duration::from_secs(120))?;

    #[derive(serde::Deserialize)]
    struct ExportResp {
        records: Vec<serde_json::Value>,
        max_seq: u64,
    }

    // Page the export the same way the push path does: an unlimited request makes the
    // daemon buffer the whole changelog as bytes, then as a String, then as parsed JSON,
    // which on a memory-capped peer gets the process OOM-killed mid-response and shows up
    // here as a closed connection. The log is ordered by local_seq, so paging preserves
    // the global ordering the importer relies on.
    const BATCH_SIZE: usize = 2000;

    let encryptor = default_sync_encryptor()?;
    let stdout = std::io::stdout();
    let mut writer = std::io::BufWriter::new(stdout.lock());

    let mut cursor = after_seq;
    let mut total = 0u64;
    let mut header_written = false;

    loop {
        use std::io::Write;
        let resp: ExportResp = api::daemon_ok(
            client
                .post(format!("{api_base}/v1/sync/export"))
                .json(&export_request(cursor, BATCH_SIZE))
                .send()
                .context("calling sync/export on daemon")?,
        )
        .context("sync/export returned error")?
        .json()?;

        // Written only once the daemon has accepted our versions, so a refused
        // export leaves the stream header-less and the reader refuses it too.
        if !header_written {
            writeln!(writer, "{}", SyncHeader::local().to_line())?;
            writer.flush()?;
            header_written = true;
        }

        if resp.records.is_empty() {
            break;
        }

        let batch_count = resp.records.len();

        for record in &resp.records {
            let plaintext = serde_json::to_vec(record)?;
            let line = second_brain_sync::crypto::seal_line(&encryptor, &plaintext)?;
            writer.write_all(line.as_bytes())?;
            writer.write_all(b"\n")?;
        }
        writer.flush()?;

        total += batch_count as u64;
        cursor = resp.max_seq;

        if batch_count < BATCH_SIZE {
            break;
        }
    }

    eprintln!("exported {total} records through seq {cursor}");
    Ok(())
}

pub(crate) fn cmd_sync_key() -> Result<()> {
    let path = second_brain_sync::crypto::default_key_path()?;
    let key = second_brain_sync::crypto::load_or_create_key(&path)?;
    let enc = second_brain_sync::crypto::XChaChaEncryptor::new(key);
    println!("{}", enc.key_base64());
    eprintln!("key file: {}", path.display());
    eprintln!(
        "copy this base64 value into ~/.second-brain/sync.key on each paired device \
         (run `sb sync-key` once on a device to generate, then replicate it everywhere)."
    );
    Ok(())
}

pub(crate) fn cmd_sync_import() -> Result<()> {
    const BATCH_SIZE: usize = 500;

    let stdin = std::io::stdin();
    let mut reader = std::io::BufReader::new(stdin.lock());
    let header = read_checked_header(&mut reader, "the sender")?;
    let api_base = api::base_url();
    let client = api::sync_client(std::time::Duration::from_secs(600))?;

    #[derive(serde::Deserialize)]
    struct ImportResp {
        created: u64,
        updated: u64,
        deleted: u64,
        skipped: u64,
        errors: u64,
        max_seq: u64,
    }

    let mut totals = (0u64, 0u64, 0u64, 0u64, 0u64, 0u64);
    let mut batch: Vec<serde_json::Value> = Vec::with_capacity(BATCH_SIZE);
    // Tracks the lowest watermark from any batch that reported errors, so a
    // failing batch cannot let a later successful batch advance the cursor past
    // the point where data may be missing.
    let mut min_error_watermark: Option<u64> = None;

    let flush_batch = |batch: &mut Vec<serde_json::Value>,
                       totals: &mut (u64, u64, u64, u64, u64, u64),
                       min_error_watermark: &mut Option<u64>|
     -> Result<()> {
        if batch.is_empty() {
            return Ok(());
        }
        let resp: ImportResp = api::daemon_ok(
            client
                .post(format!("{api_base}/v1/sync/import"))
                .json(&serde_json::json!({"header": header, "records": *batch}))
                .send()
                .context("calling sync/import on daemon")?,
        )
        .context("sync/import returned error")?
        .json()?;
        totals.0 += resp.created;
        totals.1 += resp.updated;
        totals.2 += resp.deleted;
        totals.3 += resp.skipped;
        totals.4 += resp.errors;
        if resp.errors > 0 {
            let candidate = resp.max_seq.saturating_sub(1);
            *min_error_watermark = Some(
                min_error_watermark
                    .map(|prev| prev.min(candidate))
                    .unwrap_or(candidate),
            );
        } else {
            totals.5 = totals.5.max(resp.max_seq);
        }
        batch.clear();
        Ok(())
    };

    let encryptor = default_sync_encryptor()?;
    for line in std::io::BufRead::lines(reader) {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }
        let plaintext = second_brain_sync::crypto::open_line(&encryptor, &line)?;
        batch.push(serde_json::from_slice(&plaintext)?);

        if batch.len() >= BATCH_SIZE {
            flush_batch(&mut batch, &mut totals, &mut min_error_watermark)?;
        }
    }

    flush_batch(&mut batch, &mut totals, &mut min_error_watermark)?;

    // If any batch had errors, the watermark must not advance past the lowest
    // failing point, regardless of how many later batches succeeded.
    if let Some(err_wm) = min_error_watermark {
        totals.5 = totals.5.min(err_wm);
    }

    eprintln!(
        "imported: {} created, {} updated, {} deleted, {} skipped, {} errors (through seq {})",
        totals.0, totals.1, totals.2, totals.3, totals.4, totals.5
    );
    Ok(())
}

pub(crate) fn cmd_sync_status() -> Result<()> {
    let api_base = api::base_url();
    let client = api::client(std::time::Duration::from_secs(30))?;

    #[derive(serde::Deserialize)]
    struct PeerInfo {
        peers: Vec<PeerState>,
    }
    #[derive(serde::Deserialize)]
    struct PeerState {
        peer_id: String,
        last_seq: u64,
        last_sync_at: String,
    }

    let resp: PeerInfo = api::daemon_ok(
        client
            .get(format!("{api_base}/v1/sync/status"))
            .send()
            .context("getting sync status from daemon")?,
    )?
    .json()?;

    if resp.peers.is_empty() {
        println!("no sync peers configured");
    } else {
        for state in &resp.peers {
            println!(
                "peer: {}, last_seq: {}, last_sync: {}",
                state.peer_id, state.last_seq, state.last_sync_at
            );
        }
    }
    Ok(())
}

pub(crate) fn cmd_sync_backfill() -> Result<()> {
    let api_base = api::base_url();
    let client = api::client(std::time::Duration::from_secs(30))?;

    #[derive(serde::Deserialize)]
    struct BackfillResp {
        backfilled: usize,
        #[serde(default)]
        tombstones_backfilled: usize,
    }

    let resp: BackfillResp = api::daemon_ok(
        client
            .post(format!("{api_base}/v1/sync/backfill"))
            .send()
            .context("calling backfill on daemon")?,
    )?
    .json()?;

    eprintln!(
        "backfilled {} create entries, {} delete entries",
        resp.backfilled, resp.tombstones_backfilled
    );
    Ok(())
}

pub(crate) fn cmd_sync_compact(ops: &[String], dry_run: bool) -> Result<()> {
    let api_base = api::base_url();
    let client = api::client(std::time::Duration::from_secs(30))?;

    #[derive(serde::Deserialize)]
    struct CompactResp {
        groups_with_duplicates: u64,
        rows_deleted: u64,
        max_local_seq_before: u64,
        max_local_seq_after: u64,
    }

    let resp: CompactResp = api::daemon_ok(
        client
            .post(format!("{api_base}/v1/sync/compact"))
            .json(&serde_json::json!({"ops": ops, "dry_run": dry_run}))
            .send()
            .context("calling compact on daemon")?,
    )?
    .json()?;

    if resp.max_local_seq_before != resp.max_local_seq_after {
        anyhow::bail!(
            "compact reported MAX(local_seq) moved from {} to {} -- aborting, this must never happen",
            resp.max_local_seq_before,
            resp.max_local_seq_after
        );
    }

    if dry_run {
        eprintln!(
            "dry run: {} groups have duplicates, {} rows would be deleted (max_local_seq {} unaffected)",
            resp.groups_with_duplicates, resp.rows_deleted, resp.max_local_seq_after
        );
    } else {
        eprintln!(
            "compacted {} groups, deleted {} duplicate rows (max_local_seq {} unchanged)",
            resp.groups_with_duplicates, resp.rows_deleted, resp.max_local_seq_after
        );
    }
    Ok(())
}

pub(crate) fn cmd_sync(peer_host: &str, args: &[String]) -> Result<()> {
    let data_dir = second_brain_core::machine::data_dir()?;
    let sb_binary = peer_sb(args, &data_dir, peer_host)?;
    let local = DaemonApi {
        client: api::sync_client(std::time::Duration::from_secs(600))?,
        base: api::base_url(),
    };
    let transport = SshTransport::new(peer_host, &sb_binary)?;
    let encryptor = default_sync_encryptor()?;
    session::sync(&local, &transport, &encryptor, &data_dir, &|line| {
        eprintln!("{line}")
    })
}

/// `--sb-path` first, then the peer's `sync-peers` entry, so `sb sync` reaches
/// a peer the way the daemon does.
fn peer_sb(args: &[String], data_dir: &std::path::Path, peer_host: &str) -> Result<String> {
    let flag = args
        .iter()
        .position(|arg| arg == "--sb-path")
        .and_then(|i| args.get(i + 1));
    if let Some(sb) = flag {
        return Ok(sb.clone());
    }
    Ok(peers::configured_peer(data_dir, peer_host)
        .context("reading sync-peers")?
        .map_or_else(|| "sb".to_string(), |peer| peer.sb))
}

struct DaemonApi {
    client: reqwest::blocking::Client,
    base: String,
}

impl Local for DaemonApi {
    fn cursors(&self) -> Result<Vec<(String, u64)>> {
        #[derive(serde::Deserialize)]
        struct PeerInfo {
            peers: Vec<PeerState>,
        }
        #[derive(serde::Deserialize)]
        struct PeerState {
            peer_id: String,
            last_seq: u64,
        }

        let status: PeerInfo = self
            .client
            .get(format!("{}/v1/sync/status", self.base))
            .send()?
            .json()?;
        Ok(status
            .peers
            .into_iter()
            .map(|p| (p.peer_id, p.last_seq))
            .collect())
    }

    fn set_cursor(&self, peer_id: &str, last_seq: u64) -> Result<()> {
        self.client
            .post(format!("{}/v1/sync/state", self.base))
            .json(&serde_json::json!({"peer_id": peer_id, "last_seq": last_seq}))
            .send()?;
        Ok(())
    }

    fn import(&self, header: &SyncHeader, records: &[Value]) -> Result<Imported> {
        #[derive(serde::Deserialize)]
        struct ImportResp {
            created: u64,
            updated: u64,
            deleted: u64,
            skipped: u64,
            max_seq: u64,
            #[serde(default)]
            skipped_by_reason: std::collections::BTreeMap<String, u64>,
        }

        let resp: ImportResp = api::daemon_ok(
            self.client
                .post(format!("{}/v1/sync/import", self.base))
                .json(&serde_json::json!({"header": header, "records": records}))
                .send()
                .context("posting import to daemon")?,
        )
        .context("import returned error")?
        .json()?;
        Ok(Imported {
            created: resp.created,
            updated: resp.updated,
            deleted: resp.deleted,
            skipped: resp.skipped,
            dangling: Imported::dangling_in(&resp.skipped_by_reason),
            max_seq: resp.max_seq,
        })
    }

    fn export(&self, after_seq: u64, limit: usize) -> Result<Exported> {
        #[derive(serde::Deserialize)]
        struct ExportResp {
            records: Vec<Value>,
            max_seq: u64,
        }

        let export: ExportResp = api::daemon_ok(
            self.client
                .post(format!("{}/v1/sync/export", self.base))
                .json(&export_request(after_seq, limit))
                .send()
                .context("getting export from daemon")?,
        )
        .context("export returned error")?
        .json()?;
        Ok(Exported {
            records: export.records,
            max_seq: export.max_seq,
        })
    }
}

fn export_request(after_seq: u64, limit: usize) -> serde_json::Value {
    serde_json::json!({"after_seq": after_seq, "limit": limit, "header": SyncHeader::local()})
}

fn default_sync_encryptor() -> Result<second_brain_sync::crypto::XChaChaEncryptor> {
    let path = second_brain_sync::crypto::default_key_path()?;
    let key = second_brain_sync::crypto::load_or_create_key(&path)?;
    Ok(second_brain_sync::crypto::XChaChaEncryptor::new(key))
}

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

    #[test]
    fn sb_sync_finds_the_peers_sb_like_the_daemon_unless_told() {
        let dir = tempfile::tempdir().unwrap();
        let none: Vec<String> = Vec::new();
        assert_eq!(peer_sb(&none, dir.path(), "user@pi").unwrap(), "sb");
        std::fs::write(dir.path().join(peers::PEERS_FILE), "user@pi /opt/sb\n").unwrap();
        assert_eq!(peer_sb(&none, dir.path(), "user@pi").unwrap(), "/opt/sb");
        let flag = vec!["--sb-path".to_string(), "/usr/bin/sb".to_string()];
        assert_eq!(
            peer_sb(&flag, dir.path(), "user@pi").unwrap(),
            "/usr/bin/sb"
        );
    }
}