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);
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))
}
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(¬es, 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)
}
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()
}
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,
}
#[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
struct Shown {
ids: Vec<ShownId>,
checked_at_ms: u64,
}
impl Shown {
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)
}
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,
}
}
}
struct Record {
file: File,
path: PathBuf,
}
impl Record {
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
}
}
}
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 {
unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) == 0 }
}
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,
}
}
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());
}
}
}
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(¬es, 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(¬es, OWN, &Shown::default(), 1500).unwrap();
assert_eq!(emitted, ["n3"]);
assert_eq!(render(¬es[..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(¬es, 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(¬es, 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(¬es, OWN, &Shown::default(), MAX_CONTEXT_CHARS / 2),
None
);
let (text, emitted) = render(¬es, 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(¬es, 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);
}
}