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
mod common;

use std::process::Output;

use common::{Answer, Daemon, Home, LIMIT, assert_silent, closed_port, daemon, run_hook};
use serde_json::{Value, json};

const SESSION: &str = "5b0c2f9e-3d41-4f6a-9c1e-7a2b8d4e6f10";
const CWD: &str = "/home/dev/my_app";
const PROJECT: &str = "-home-dev-my-app";
const MAX_CONTEXT_CHARS: usize = 1500;
const PROMPT: &str = "why does the parser drop trailing comments in config files?";
const ID_LINE: &str = "This session's id for second-brain notes:";

fn prompt_input(prompt: &str) -> Value {
    json!({
        "session_id": SESSION,
        "transcript_path": "/tmp/transcript.jsonl",
        "cwd": CWD,
        "permission_mode": "default",
        "hook_event_name": "UserPromptSubmit",
        "prompt": prompt
    })
}

fn start_input(event: &str) -> Value {
    let mut input = json!({
        "session_id": SESSION,
        "transcript_path": "/tmp/transcript.jsonl",
        "cwd": CWD,
        "permission_mode": "default",
        "hook_event_name": event,
    });
    if event == "SessionStart" {
        input["source"] = json!("startup");
    } else {
        input["agent_id"] = json!("agent-1");
        input["agent_type"] = json!("Explore");
    }
    input
}

fn memory(id: &str, project: Option<&str>, session_at: Option<&str>, content: &str) -> Value {
    json!({
        "id": id,
        "content": content,
        "memory_type": "fact",
        "confidence": 0.9,
        "source": "claude-code",
        "created_at": "2026-10-31T08:00:00+00:00",
        "score": 0.8,
        "relevance": 0.7,
        "project_path": project,
        "machine_id": "m1",
        "machine_name": "workstation",
        "tier": "long",
        "session_at": session_at
    })
}

const FIRST: &str = "3f2a1b4c-5d6e-4f70-8a9b-0c1d2e3f4a5b";
const SECOND: &str = "4a3b2c1d-6e5f-4071-9b8a-1d0c3f2e5b4a";
const THIRD: &str = "5b4c3d2e-7f60-4172-ac9b-2e1d4a3f6c5b";
const FOURTH: &str = "6c5d4e3f-8071-4273-bdac-3f2e5b4a7d6c";

const BAR: f64 = 0.52;

fn ranked(memories: Vec<Value>) -> Value {
    json!({"memories": memories, "scope": "project", "abstain_bar": BAR})
}

fn four_memories() -> Value {
    ranked(vec![
        memory(
            FIRST,
            Some(PROJECT),
            Some("2026-10-30T09:15:00+00:00"),
            &format!(
                "the parser\n\n  strips comments {}",
                "after the value ".repeat(60)
            ),
        ),
        memory(SECOND, None, None, &"comment tokens are kept ".repeat(40)),
        memory(
            THIRD,
            Some("-srv-other"),
            Some("2026-10-01T23:00:00Z"),
            "fixtures live under tests/data",
        ),
        memory(FOURTH, Some(PROJECT), None, "never shown"),
    ])
}

fn context(output: &Output, event: &str) -> String {
    assert_eq!(output.status.code(), Some(0), "{output:?}");
    let reply: Value = serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
        panic!("{e}: {}", String::from_utf8_lossy(&output.stdout));
    });
    assert_eq!(
        reply["hookSpecificOutput"]["hookEventName"], event,
        "{reply}"
    );
    reply["hookSpecificOutput"]["additionalContext"]
        .as_str()
        .unwrap_or_else(|| panic!("{reply}"))
        .to_string()
}

fn prompt(home: &Home, api: &str, input: &Value) -> Output {
    run_hook(home, api, "prompt", &input.to_string()).0
}

fn only_request_body(daemon: &Daemon) -> Value {
    let requests = daemon.requests();
    assert_eq!(requests.len(), 1, "{requests:?}");
    assert!(
        requests[0].target.starts_with("POST /v1/recall "),
        "{}",
        requests[0].target
    );
    serde_json::from_str(&requests[0].body).unwrap()
}

#[test]
fn slash_commands_and_short_prompts_skip_the_daemon() {
    let home = Home::new();
    let daemon = daemon(Answer::Json(four_memories().to_string()));
    for text in [
        "/review the parser changes from yesterday please",
        "   /compact keep the parser discussion and nothing else",
        "fix the parser",
        "  short one here    ",
    ] {
        assert_silent(&prompt(&home, &daemon.base, &prompt_input(text)));
    }
    let mut no_cwd = prompt_input(PROMPT);
    no_cwd.as_object_mut().unwrap().remove("cwd");
    assert_silent(&prompt(&home, &daemon.base, &no_cwd));
    assert!(daemon.requests().is_empty());
}

#[test]
fn a_ranked_reply_injects_at_most_three_memories_with_ids_projects_and_dates() {
    let home = Home::new();
    let daemon = daemon(Answer::Json(four_memories().to_string()));
    let text = context(
        &prompt(&home, &daemon.base, &prompt_input(PROMPT)),
        "UserPromptSubmit",
    );
    assert!(text.chars().count() <= MAX_CONTEXT_CHARS, "{text}");
    let lines: Vec<&str> = text.lines().collect();
    assert_eq!(lines.len(), 4, "{text}");
    assert!(lines[0].contains("second-brain"), "{text}");
    assert!(lines[0].contains("verify"), "{text}");
    assert!(
        lines[1].starts_with(&format!(
            "- [{FIRST}] ({PROJECT}, session 2026-10-30) the parser strips comments after the value"
        )),
        "{text}"
    );
    assert!(lines[1].ends_with('…'), "{text}");
    assert!(
        lines[2].starts_with(&format!(
            "- [{SECOND}] (no project, session date unknown) comment tokens are kept"
        )),
        "{text}"
    );
    assert!(lines[2].ends_with('…'), "{text}");
    assert_eq!(
        lines[3],
        format!("- [{THIRD}] (-srv-other, session 2026-10-01) fixtures live under tests/data")
    );
    assert!(!text.contains(FOURTH), "{text}");
    assert!(!text.contains("  "), "{text}");

    let body = only_request_body(&daemon);
    assert_eq!(body["query"], PROMPT, "{body}");
    assert_eq!(body["limit"], 3, "{body}");
    assert_eq!(body["current_project"], PROJECT, "{body}");
    assert_eq!(body["record_access"], false, "{body}");
    assert_eq!(body["exclude_session"], SESSION, "{body}");
    assert_eq!(body["budget_ms"], 1200, "{body}");
    assert_eq!(body["rerank_top"], 5, "{body}");
    assert_eq!(body["rerank_doc_chars"], 512, "{body}");
    assert_eq!(body["project_pass"], false, "{body}");
    let bearer = format!("authorization: bearer {}", "t".repeat(32));
    assert!(daemon.requests()[0].head.contains(&bearer));
}

#[test]
fn a_long_prompt_is_cut_to_a_thousand_characters_on_a_char_boundary() {
    let home = Home::new();
    let daemon = daemon(Answer::Json(ranked(vec![]).to_string()));
    let long = "ünïcode prompt ".repeat(100);
    assert_silent(&prompt(&home, &daemon.base, &prompt_input(&long)));
    let query = only_request_body(&daemon)["query"]
        .as_str()
        .unwrap()
        .to_string();
    assert_eq!(query.chars().count(), 1000);
    assert!(long.starts_with(&query));
}

#[test]
fn memories_without_room_for_their_content_are_dropped() {
    let home = Home::new();
    let long_project = format!("-{}", "deep-".repeat(400));
    let memories = (0..3)
        .map(|n| {
            memory(
                &format!("{n}a3b2c1d-6e5f-4071-9b8a-1d0c3f2e5b4a"),
                Some(&long_project),
                None,
                "content",
            )
        })
        .collect();
    let daemon = daemon(Answer::Json(ranked(memories).to_string()));
    assert_silent(&prompt(&home, &daemon.base, &prompt_input(PROMPT)));
}

#[test]
fn unranked_empty_or_failed_recalls_inject_nothing() {
    let home = Home::new();
    let mut degraded = four_memories();
    degraded["degraded"] = json!("text-fallback");
    for answer in [
        Answer::Json(degraded.to_string()),
        Answer::Json(ranked(vec![]).to_string()),
        Answer::Status(503, four_memories().to_string()),
        Answer::Json("not json".to_string()),
    ] {
        let daemon = daemon(answer);
        assert_silent(&prompt(&home, &daemon.base, &prompt_input(PROMPT)));
        assert_eq!(daemon.requests().len(), 1);
    }
}

#[test]
fn a_down_or_hung_daemon_injects_only_the_session_id_in_time() {
    let home = Home::new();
    let hung = daemon(Answer::Never);
    for api in [closed_port(), hung.base.clone()] {
        let (output, took) = run_hook(&home, &api, "prompt", &prompt_input(PROMPT).to_string());
        assert_silent(&output);
        assert!(took < LIMIT, "{took:?}");
    }
    let (output, took) = run_hook(
        &home,
        &hung.base,
        "session-start",
        &start_input("SessionStart").to_string(),
    );
    assert_eq!(context(&output, "SessionStart"), id_line());
    assert!(took < LIMIT, "{took:?}");
}

#[test]
fn a_starting_daemon_injects_only_the_session_id_and_prints_no_error() {
    let home = Home::new();
    let starting = daemon(Answer::Routed(common::starting));
    let (output, took) = run_hook(
        &home,
        &starting.base,
        "prompt",
        &prompt_input(PROMPT).to_string(),
    );
    assert_silent(&output);
    assert_eq!(String::from_utf8_lossy(&output.stderr), "", "{output:?}");
    assert!(took < LIMIT, "{took:?}");
    let (output, took) = run_hook(
        &home,
        &starting.base,
        "session-start",
        &start_input("SessionStart").to_string(),
    );
    assert_eq!(context(&output, "SessionStart"), id_line());
    assert_eq!(String::from_utf8_lossy(&output.stderr), "", "{output:?}");
    assert!(took < LIMIT, "{took:?}");
}

fn id_line() -> String {
    format!("{ID_LINE} {SESSION}")
}

fn open_items_request(daemon: &Daemon) -> common::Request {
    let requests = daemon.requests();
    let open: Vec<_> = requests
        .iter()
        .filter(|request| !request.target.contains("since="))
        .collect();
    assert_eq!(open.len(), 1, "{requests:?}");
    open[0].clone()
}

fn note(open_items: &[&str], blocked_on_user: &[&str]) -> Value {
    json!({
        "id": "0d6f3c1a-8b9e-4f2d-a7c5-1e3b5d7f9a20",
        "kind": "session-end",
        "decision": "kept the parser",
        "reason": "",
        "dead_ends": [],
        "open_items": open_items,
        "blocked_on_user": blocked_on_user,
        "session_id": SESSION,
        "project": PROJECT,
        "session_at": null,
        "created_at": "2026-11-02T10:00:00Z"
    })
}

fn notes(notes: Vec<Value>) -> Answer {
    Answer::Json(json!({ "notes": notes }).to_string())
}

fn two_sessions() -> Answer {
    notes(vec![
        note(
            &["finish the  parser\n tests", "wire the flag"],
            &["pick a license"],
        ),
        note(
            &["wire the flag", "update docs"],
            &["pick a license", "approve the deploy", "rotate the key"],
        ),
    ])
}

fn assert_open_and_blocked(event: &str, hook: &str) {
    let home = Home::new();
    let daemon = daemon(two_sessions());
    let (output, _) = run_hook(&home, &daemon.base, hook, &start_input(event).to_string());
    let text = context(&output, event);
    assert!(text.chars().count() <= MAX_CONTEXT_CHARS, "{text}");
    let lines: Vec<&str> = text.lines().collect();
    assert_eq!(lines[0], id_line(), "{text}");
    assert!(lines[1].contains("second-brain"), "{text}");
    assert_eq!(
        lines[2..],
        [
            "Waiting on the user:",
            "- pick a license",
            "- approve the deploy",
            "- rotate the key",
            "Open items:",
            "- finish the parser tests",
            "- wire the flag",
        ],
        "{text}"
    );

    let target = &open_items_request(&daemon).target;
    assert!(target.starts_with("GET /v1/notes?"), "{target}");
    assert!(target.contains(&format!("project={PROJECT}")), "{target}");
    assert!(target.contains("limit=10"), "{target}");
    assert!(!target.contains("session_id"), "{target}");
}

#[test]
fn session_start_injects_open_and_blocked_items_deduplicated_and_capped() {
    assert_open_and_blocked("SessionStart", "session-start");
}

#[test]
fn subagent_start_injects_the_same_items_under_its_own_event() {
    assert_open_and_blocked("SubagentStart", "subagent-start");
}

#[test]
fn a_section_without_entries_is_left_out() {
    let home = Home::new();
    let daemon = daemon(notes(vec![note(&[], &["pick a license"])]));
    let (output, _) = run_hook(
        &home,
        &daemon.base,
        "session-start",
        &start_input("SessionStart").to_string(),
    );
    let text = context(&output, "SessionStart");
    let lines: Vec<&str> = text.lines().collect();
    assert_eq!(
        lines[2..],
        ["Waiting on the user:", "- pick a license"],
        "{text}"
    );
}

#[test]
fn long_entries_are_cut_to_fit_the_budget() {
    let home = Home::new();
    let long = "an open item that goes on ".repeat(40);
    let entries: Vec<String> = (0..5).map(|n| format!("{n} {long}")).collect();
    let entries: Vec<&str> = entries.iter().map(String::as_str).collect();
    let daemon = daemon(notes(vec![note(&entries, &[])]));
    let (output, _) = run_hook(
        &home,
        &daemon.base,
        "session-start",
        &start_input("SessionStart").to_string(),
    );
    let text = context(&output, "SessionStart");
    assert!(text.chars().count() <= MAX_CONTEXT_CHARS, "{text}");
    let items: Vec<&str> = text.lines().filter(|l| l.starts_with("- ")).collect();
    assert_eq!(items.len(), 5, "{text}");
    for (n, item) in items.iter().enumerate() {
        assert!(item.starts_with(&format!("- {n} an open item")), "{text}");
        assert!(item.ends_with('…'), "{text}");
    }
}

#[test]
fn no_notes_or_no_entries_inject_only_the_session_id() {
    let home = Home::new();
    for answer in [
        notes(vec![]),
        notes(vec![note(&[], &[]), note(&["  "], &[])]),
        Answer::Status(400, json!({"error": "bad"}).to_string()),
    ] {
        let daemon = daemon(answer);
        let (output, _) = run_hook(
            &home,
            &daemon.base,
            "session-start",
            &start_input("SessionStart").to_string(),
        );
        assert_eq!(context(&output, "SessionStart"), id_line());
        open_items_request(&daemon);
    }
    let daemon = daemon(two_sessions());
    let mut no_cwd = start_input("SubagentStart");
    no_cwd.as_object_mut().unwrap().remove("cwd");
    let (output, _) = run_hook(&home, &daemon.base, "subagent-start", &no_cwd.to_string());
    assert_eq!(context(&output, "SubagentStart"), id_line());
    no_cwd.as_object_mut().unwrap().remove("session_id");
    let (output, _) = run_hook(&home, &daemon.base, "subagent-start", &no_cwd.to_string());
    assert_silent(&output);
    assert!(daemon.requests().is_empty());
}

#[test]
fn without_a_session_id_session_start_injects_the_open_items_alone() {
    let home = Home::new();
    let daemon = daemon(two_sessions());
    let mut input = start_input("SessionStart");
    input.as_object_mut().unwrap().remove("session_id");
    let (output, _) = run_hook(&home, &daemon.base, "session-start", &input.to_string());
    let text = context(&output, "SessionStart");
    assert!(!text.contains(ID_LINE), "{text}");
    assert!(
        text.lines().next().unwrap().contains("second-brain"),
        "{text}"
    );
    assert_eq!(daemon.requests().len(), 1);
}

#[test]
fn a_reply_without_a_bar_injects_nothing() {
    let home = Home::new();
    let mut unbarred = four_memories();
    unbarred.as_object_mut().unwrap().remove("abstain_bar");
    let daemon = daemon(Answer::Json(unbarred.to_string()));
    let output = prompt(&home, &daemon.base, &prompt_input(PROMPT));
    assert_silent(&output);
}

#[test]
fn memories_below_the_bar_are_left_out() {
    let home = Home::new();
    let mut below = memory(SECOND, None, None, "a weak match");
    below["relevance"] = json!(BAR - 0.01);
    let mut at_bar = memory(THIRD, None, None, "a match at the bar");
    at_bar["relevance"] = json!(BAR);
    let reply = ranked(vec![
        memory(FIRST, None, None, "a strong match"),
        below,
        at_bar,
    ]);
    let daemon = daemon(Answer::Json(reply.to_string()));
    let output = prompt(&home, &daemon.base, &prompt_input(PROMPT));
    let text = context(&output, "UserPromptSubmit");
    assert!(text.contains(FIRST), "{text}");
    assert!(text.contains(THIRD), "{text}");
    assert!(!text.contains(SECOND), "{text}");
}

const TRANSCRIPT_PROJECT: &str = "-home-dev-launch";

fn launched_elsewhere(mut input: Value) -> Value {
    input["transcript_path"] = json!(format!(
        "/home/dev/.claude/projects/{TRANSCRIPT_PROJECT}/{SESSION}.jsonl"
    ));
    input
}

#[test]
fn the_transcript_directory_names_the_project_over_the_cwd() {
    let home = Home::new();
    let recall = daemon(Answer::Json(four_memories().to_string()));
    prompt(
        &home,
        &recall.base,
        &launched_elsewhere(prompt_input(PROMPT)),
    );
    assert_eq!(
        only_request_body(&recall)["current_project"],
        TRANSCRIPT_PROJECT
    );

    let start = daemon(two_sessions());
    run_hook(
        &home,
        &start.base,
        "session-start",
        &launched_elsewhere(start_input("SessionStart")).to_string(),
    );
    let requests = start.requests();
    assert!(!requests.is_empty());
    for request in requests {
        assert!(
            request
                .target
                .contains(&format!("project={TRANSCRIPT_PROJECT}")),
            "{}",
            request.target
        );
    }
}

#[test]
fn a_prompt_that_starts_with_an_absolute_path_is_not_a_slash_command() {
    let home = Home::new();
    let daemon = daemon(Answer::Json(four_memories().to_string()));
    prompt(
        &home,
        &daemon.base,
        &prompt_input("/srv/app/main.rs panics on start, why does it?"),
    );
    assert_eq!(daemon.requests().len(), 1);
}