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);
}