second-brain-cli 0.13.5

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
use std::fs::File;
use std::io::Read;
use std::os::fd::AsRawFd;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use chrono::{DateTime, SecondsFormat, Utc};
use second_brain_core::machine;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::asked::is_plain_id;
use super::context::{self, MAX_CONTEXT_CHARS};
use super::{daemon, project};

const WINDOW: Duration = Duration::from_secs(2 * 60 * 60);

const INTERVAL: Duration = Duration::from_secs(5);

/// Longer than `WINDOW`, so a file idle this long holds only ids that have
/// left the window and pruning it can never lead to a repeat.
const KEEP: Duration = Duration::from_secs(3 * 60 * 60);

const QUERY_LIMIT: &str = "50";

const MAX_NOTES: usize = 5;

const SHORT_SESSION_CHARS: usize = 8;

const HEADER: &str = "Notes other sessions in this project wrote in the last two hours; \
                      check them before relying on them:";

pub(super) fn run(event: &'static str, input: &Value) -> Option<Value> {
    let text = section(input, MAX_CONTEXT_CHARS, SystemTime::now())?;
    Some(context::reply(event, text))
}

/// Sibling notes not yet shown to this session (or subagent), fitted into
/// `room` characters and recorded as shown before they are returned. Every
/// doubt, a busy record included, shows nothing.
pub(super) fn section(input: &Value, room: usize, now: SystemTime) -> Option<String> {
    let own_session = input["session_id"].as_str()?;
    let key = key(own_session, input["agent_id"].as_str())?;
    let project = project::of(input)?;
    let now_ms = u64::try_from(now.duration_since(UNIX_EPOCH).ok()?.as_millis()).ok()?;
    let dir = machine::data_dir().ok()?.join("hooks").join("siblings");
    let record = Record::lock(&dir, &key)?;
    let shown = record.read()?;
    if shown.throttled(now_ms) {
        return None;
    }
    let rendered =
        window(&project, now).and_then(|notes| render(&notes, own_session, &shown, room));
    let emitted = rendered
        .as_ref()
        .map_or_else(Vec::new, |(_, ids)| ids.clone());
    if !record.write(&shown.after(emitted, now_ms)) {
        return None;
    }
    prune(&dir, now);
    rendered.map(|(text, _)| text)
}

/// A subagent's hook output reaches the subagent, not its parent, so each
/// subagent keeps its own record.
fn key(session_id: &str, agent_id: Option<&str>) -> Option<String> {
    if !is_plain_id(session_id) {
        return None;
    }
    match agent_id {
        None => Some(session_id.to_string()),
        Some(agent_id) => is_plain_id(agent_id).then(|| format!("{session_id}.{agent_id}")),
    }
}

fn window(project: &str, now: SystemTime) -> Option<Vec<Value>> {
    let since = DateTime::<Utc>::from(now.checked_sub(WINDOW)?)
        .to_rfc3339_opts(SecondsFormat::Millis, true);
    let reply = daemon::get(
        "/v1/notes",
        &[
            ("project", project),
            ("since", &since),
            ("limit", QUERY_LIMIT),
        ],
    )?;
    reply["notes"].as_array().cloned()
}

/// The header and, in the daemon's newest-first order, up to `MAX_NOTES`
/// unshown notes from other sessions that fit whole, with their ids. A note
/// that does not fit waits for a later injection, unless it is the first
/// and too long for any injection; only that one is cut short. Recorded
/// lines are never shown again, so cutting a burst into fragments would
/// lose them.
fn render(
    notes: &[Value],
    own_session: &str,
    shown: &Shown,
    room: usize,
) -> Option<(String, Vec<String>)> {
    let mut left = room.checked_sub(HEADER.chars().count())?;
    let mut text = HEADER.to_string();
    let mut emitted = Vec::new();
    let unshown = notes
        .iter()
        .filter(|note| {
            note["session_id"]
                .as_str()
                .is_some_and(|s| s != own_session)
        })
        .filter_map(|note| {
            let id = note["id"].as_str().filter(|id| !id.is_empty())?;
            (!shown.has(id)).then_some((id, line(note)?))
        });
    let largest = MAX_CONTEXT_CHARS - HEADER.chars().count();
    for (id, (prefix, body)) in unshown {
        let whole = format!("{prefix}{body}");
        let length = whole.chars().count();
        let fitted = if length < left {
            Some(whole)
        } else if emitted.is_empty() && length >= largest {
            context::fit(left, &[(prefix, body)]).pop().flatten()
        } else {
            None
        };
        let Some(fitted) = fitted else {
            break;
        };
        left -= fitted.chars().count() + 1;
        text.push('\n');
        text.push_str(&fitted);
        emitted.push(id.to_string());
        if emitted.len() == MAX_NOTES {
            break;
        }
    }
    (!emitted.is_empty()).then_some((text, emitted))
}

fn line(note: &Value) -> Option<(String, String)> {
    let kind = context::one_line(note["kind"].as_str()?);
    let session: String = note["session_id"]
        .as_str()?
        .chars()
        .take(SHORT_SESSION_CHARS)
        .collect();
    let mut body = context::one_line(note["decision"].as_str()?);
    if body.is_empty() {
        return None;
    }
    let reason = context::one_line(note["reason"].as_str().unwrap_or_default());
    if !reason.is_empty() {
        body.push_str(" Why: ");
        body.push_str(&reason);
    }
    let dead_ends: Vec<String> = note["dead_ends"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(Value::as_str)
        .map(context::one_line)
        .filter(|dead_end| !dead_end.is_empty())
        .collect();
    if !dead_ends.is_empty() {
        body.push_str(" Dead ends: ");
        body.push_str(&dead_ends.join("; "));
    }
    Some((format!("- [{kind}, session {session}] "), body))
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct ShownId {
    id: String,
    at_ms: u64,
}

/// Every daemon check, failed ones included, counts against `INTERVAL`, so
/// a hung daemon delays one tool call per interval, not every one.
#[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
struct Shown {
    ids: Vec<ShownId>,
    checked_at_ms: u64,
}

impl Shown {
    /// A clock that went back never throttles.
    fn throttled(&self, now_ms: u64) -> bool {
        now_ms
            .checked_sub(self.checked_at_ms)
            .is_some_and(|since| u128::from(since) < INTERVAL.as_millis())
    }

    fn has(&self, id: &str) -> bool {
        self.ids.iter().any(|shown| shown.id == id)
    }

    /// A note shown at `at_ms` was created no later than that, so it has
    /// left the window once `WINDOW` has passed and its id can go.
    fn after(&self, emitted: Vec<String>, now_ms: u64) -> Shown {
        let mut ids: Vec<ShownId> = self
            .ids
            .iter()
            .filter(|shown| {
                now_ms
                    .checked_sub(shown.at_ms)
                    .is_none_or(|age| u128::from(age) < WINDOW.as_millis())
            })
            .cloned()
            .collect();
        ids.extend(emitted.into_iter().map(|id| ShownId { id, at_ms: now_ms }));
        Shown {
            ids,
            checked_at_ms: now_ms,
        }
    }
}

/// One session's record, exclusively locked for as long as this value
/// lives. Writes replace the file by rename, so a reader never sees half a
/// record; whoever locked the replaced file finds out and opens it again.
struct Record {
    file: File,
    path: PathBuf,
}

impl Record {
    /// `None` when another run of the same session holds the lock: that run
    /// shows whatever is new, and waiting would only delay this tool call.
    fn lock(dir: &Path, key: &str) -> Option<Record> {
        if let Err(e) = std::fs::create_dir_all(dir) {
            eprintln!("sb hook: creating {} failed: {e}", dir.display());
            return None;
        }
        let path = dir.join(format!("{key}.json"));
        for _ in 0..3 {
            let file = match File::options()
                .read(true)
                .write(true)
                .create(true)
                .truncate(false)
                .open(&path)
            {
                Ok(file) => file,
                Err(e) => {
                    eprintln!("sb hook: opening {} failed: {e}", path.display());
                    return None;
                }
            };
            if !try_lock(&file) {
                return None;
            }
            if is_current(&file, &path) {
                return Some(Record { file, path });
            }
        }
        None
    }

    fn read(&self) -> Option<Shown> {
        let mut text = String::new();
        if let Err(e) = (&self.file).read_to_string(&mut text) {
            eprintln!("sb hook: reading {} failed: {e}", self.path.display());
            return None;
        }
        if text.is_empty() {
            return Some(Shown::default());
        }
        match serde_json::from_str(&text) {
            Ok(shown) => Some(shown),
            Err(e) => {
                eprintln!("sb hook: {} is not a record: {e}", self.path.display());
                None
            }
        }
    }

    /// False when the record could not be written; the caller then shows
    /// nothing, because an unrecorded line would be shown again.
    fn write(&self, shown: &Shown) -> bool {
        let staged = self.path.with_extension("tmp");
        let written = serde_json::to_vec(shown)
            .map_err(std::io::Error::from)
            .and_then(|bytes| std::fs::write(&staged, bytes))
            .and_then(|()| std::fs::rename(&staged, &self.path));
        if let Err(e) = &written {
            eprintln!("sb hook: writing {} failed: {e}", self.path.display());
        }
        written.is_ok()
    }
}

fn try_lock(file: &File) -> bool {
    // SAFETY: flock takes a descriptor `file` keeps open for the call.
    unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) == 0 }
}

/// False when `path` was replaced or removed after `file` was opened.
fn is_current(file: &File, path: &Path) -> bool {
    match (file.metadata(), std::fs::metadata(path)) {
        (Ok(held), Ok(named)) => held.dev() == named.dev() && held.ino() == named.ino(),
        _ => false,
    }
}

/// Removes only files it can lock, so a run that holds a record never has
/// it unlinked underneath it.
fn prune(dir: &Path, now: SystemTime) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        if !idle(entry.metadata(), now) {
            continue;
        }
        let path = entry.path();
        let Ok(file) = File::open(&path) else {
            continue;
        };
        if try_lock(&file)
            && is_current(&file, &path)
            && idle(file.metadata(), now)
            && let Err(e) = std::fs::remove_file(&path)
        {
            eprintln!("sb hook: pruning {} failed: {e}", path.display());
        }
    }
}

/// Checked again on the locked file, because a run may have renamed a
/// fresh record over the path since the directory was listed.
fn idle(metadata: std::io::Result<std::fs::Metadata>, now: SystemTime) -> bool {
    metadata
        .and_then(|m| m.modified())
        .is_ok_and(|at| now.duration_since(at).is_ok_and(|age| age > KEEP))
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::super::asked::MAX_ID_LEN;
    use super::*;

    const OWN: &str = "b1b2c3d4-0000-4000-8000-00000000000b";
    const OTHER: &str = "a1b2c3d4-0000-4000-8000-00000000000a";

    fn shown(ids: &[(&str, u64)], checked_at_ms: u64) -> Shown {
        Shown {
            ids: ids
                .iter()
                .map(|&(id, at_ms)| ShownId {
                    id: id.to_string(),
                    at_ms,
                })
                .collect(),
            checked_at_ms,
        }
    }

    fn note(id: &str, session: &str, decision: &str) -> Value {
        json!({
            "id": id,
            "kind": "dead_end",
            "decision": decision,
            "reason": "",
            "dead_ends": [],
            "open_items": [],
            "blocked_on_user": [],
            "session_id": session,
            "project": "-p",
            "session_at": null,
            "created_at": "2026-11-02T10:00:00Z",
        })
    }

    #[test]
    fn notes_from_other_sessions_not_yet_shown_are_rendered_newest_first() {
        let notes = [
            note("n3", OTHER, "third"),
            note("n2", OWN, "own"),
            note("n1", OTHER, "first"),
            note("n0", OTHER, "already shown"),
        ];
        let (text, emitted) = render(&notes, OWN, &shown(&[("n0", 1)], 1), 1500).unwrap();
        assert_eq!(
            text,
            format!(
                "{HEADER}\n- [dead_end, session a1b2c3d4] third\n- [dead_end, session a1b2c3d4] first"
            )
        );
        assert_eq!(emitted, ["n3", "n1"]);
    }

    #[test]
    fn reason_and_dead_ends_are_joined_onto_one_line() {
        let mut full = note("n1", OTHER, "kept\n the  cache");
        full["reason"] = json!(" reads are\thot ");
        full["dead_ends"] = json!(["a  lru", " ", "no\ncache"]);
        let (prefix, body) = line(&full).unwrap();
        assert_eq!(prefix, "- [dead_end, session a1b2c3d4] ");
        assert_eq!(
            body,
            "kept the cache Why: reads are hot Dead ends: a lru; no cache"
        );
    }

    #[test]
    fn notes_without_a_decision_or_id_are_skipped() {
        let mut no_id = note("n1", OTHER, "x");
        no_id["id"] = json!("");
        let notes = [no_id, note("n2", OTHER, "  "), note("n3", OTHER, "kept")];
        let (_, emitted) = render(&notes, OWN, &Shown::default(), 1500).unwrap();
        assert_eq!(emitted, ["n3"]);
        assert_eq!(render(&notes[..2], OWN, &Shown::default(), 1500), None);
    }

    #[test]
    fn only_a_note_no_injection_could_hold_is_cut() {
        let prefix_len = "- [dead_end, session a1b2c3d4] ".chars().count();
        let room = HEADER.chars().count() + 1 + prefix_len + 10;
        let notes = [
            note("n2", OTHER, &"long ".repeat(400)),
            note("n1", OTHER, "short"),
        ];
        let (text, emitted) = render(&notes, OWN, &Shown::default(), room).unwrap();
        assert!(text.chars().count() <= room, "{text}");
        assert_eq!(emitted, ["n2"]);
        assert_eq!(text.lines().count(), 2, "{text}");
        assert!(text.ends_with("long…"), "{text}");
        assert_eq!(
            render(&notes, OWN, &Shown::default(), HEADER.chars().count()),
            None
        );
    }

    #[test]
    fn a_note_a_full_injection_could_hold_waits_rather_than_being_cut() {
        let notes = [note("n1", OTHER, &"word ".repeat(140))];
        assert_eq!(
            render(&notes, OWN, &Shown::default(), MAX_CONTEXT_CHARS / 2),
            None
        );
        let (text, emitted) = render(&notes, OWN, &Shown::default(), MAX_CONTEXT_CHARS).unwrap();
        assert_eq!(emitted, ["n1"]);
        assert!(!text.contains('…'), "{text}");
    }

    #[test]
    fn a_burst_shows_the_newest_whole_lines_up_to_the_cap_and_leaves_the_rest() {
        let notes: Vec<Value> = (0..8)
            .map(|n| {
                note(
                    &format!("n{n}"),
                    OTHER,
                    &format!("{n}{}", " word".repeat(30)),
                )
            })
            .collect();
        let (text, emitted) = render(&notes, OWN, &Shown::default(), 1500).unwrap();
        assert_eq!(emitted, ["n0", "n1", "n2", "n3", "n4"]);
        assert!(!text.contains('…'), "{text}");

        let long: Vec<Value> = (0..8)
            .map(|n| {
                note(
                    &format!("n{n}"),
                    OTHER,
                    &format!("{n}{}", " word".repeat(80)),
                )
            })
            .collect();
        let (text, emitted) = render(&long, OWN, &Shown::default(), 1500).unwrap();
        assert_eq!(emitted, ["n0", "n1", "n2"]);
        assert!(!text.contains('…'), "{text}");
        assert!(text.chars().count() <= 1500, "{text}");
    }

    #[test]
    fn shown_ids_are_kept_for_the_whole_window_whatever_the_query_returns() {
        let window = u64::try_from(WINDOW.as_millis()).unwrap();
        let now = window + 10_000;
        let before = shown(
            &[("left", 9_999), ("inside", 10_001), ("future", now + 5)],
            1,
        );
        assert_eq!(
            before.after(vec!["new".to_string()], now),
            shown(
                &[("inside", 10_001), ("future", now + 5), ("new", now)],
                now
            )
        );
    }

    #[test]
    fn checks_are_throttled_to_one_per_interval() {
        let interval = u64::try_from(INTERVAL.as_millis()).unwrap();
        let shown = shown(&[], 10_000);
        assert!(shown.throttled(10_000));
        assert!(shown.throttled(10_000 + interval - 1));
        assert!(!shown.throttled(10_000 + interval));
        assert!(!shown.throttled(9_000));
        assert!(!Shown::default().throttled(interval));
    }

    #[test]
    fn keys_are_plain_ids_and_name_the_subagent() {
        assert_eq!(key("s-1", None).as_deref(), Some("s-1"));
        assert_eq!(key("s-1", Some("agent_7")).as_deref(), Some("s-1.agent_7"));
        let long = "a".repeat(MAX_ID_LEN + 1);
        for bad in ["", "../escape", "a/b", ".", "a b", "a.b", long.as_str()] {
            assert_eq!(key(bad, None), None, "{bad:?}");
            assert_eq!(key("s-1", Some(bad)), None, "{bad:?}");
        }
    }

    #[test]
    fn a_held_record_cannot_be_locked_again() {
        let dir = tempfile::tempdir().unwrap();
        let held = Record::lock(dir.path(), "s-1").unwrap();
        assert!(Record::lock(dir.path(), "s-1").is_none());
        assert!(Record::lock(dir.path(), "s-2").is_some());
        drop(held);
        assert!(Record::lock(dir.path(), "s-1").is_some());
    }

    #[test]
    fn a_written_record_reads_back_and_a_damaged_one_reads_as_doubt() {
        let dir = tempfile::tempdir().unwrap();
        let shown = shown(&[("n1", 7)], 7);
        let record = Record::lock(dir.path(), "s-1").unwrap();
        assert_eq!(record.read(), Some(Shown::default()));
        assert!(record.write(&shown));
        drop(record);
        assert_eq!(Record::lock(dir.path(), "s-1").unwrap().read(), Some(shown));

        std::fs::write(dir.path().join("s-1.json"), "{not json").unwrap();
        assert_eq!(Record::lock(dir.path(), "s-1").unwrap().read(), None);
    }

    #[test]
    fn a_record_replaced_while_waiting_is_opened_again() {
        let dir = tempfile::tempdir().unwrap();
        let stale = Record::lock(dir.path(), "s-1").unwrap();
        assert!(stale.write(&shown(&[("n1", 7)], 7)));
        assert!(!is_current(&stale.file, &stale.path));
        drop(stale);
        let fresh = Record::lock(dir.path(), "s-1").unwrap();
        assert!(is_current(&fresh.file, &fresh.path));
        assert!(fresh.read().unwrap().has("n1"));
    }

    #[test]
    fn pruning_removes_idle_records_but_not_held_or_recent_ones() {
        let dir = tempfile::tempdir().unwrap();
        let now = SystemTime::now();
        for key in ["idle", "held", "recent"] {
            assert!(
                Record::lock(dir.path(), key)
                    .unwrap()
                    .write(&Shown::default())
            );
        }
        let age = |key: &str, at: SystemTime| {
            File::options()
                .write(true)
                .open(dir.path().join(format!("{key}.json")))
                .unwrap()
                .set_modified(at)
                .unwrap();
        };
        let old = now - KEEP - Duration::from_secs(60);
        age("idle", old);
        age("held", old);
        age("recent", now - KEEP + Duration::from_secs(60));
        let held = Record::lock(dir.path(), "held").unwrap();

        prune(dir.path(), now);
        assert!(!dir.path().join("idle.json").exists());
        assert!(dir.path().join("held.json").exists());
        assert!(dir.path().join("recent.json").exists());
        drop(held);
    }
}