use std::collections::{BTreeMap, HashMap, HashSet};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::schema::{Conversation, Memory};
use crate::sqlite_store::{AgentNote, NoteKind, SqliteStore};
pub const DEFAULT_WINDOW: &str = "24h";
pub const MAX_ITEMS_PER_SECTION: usize = 5;
const MAX_WINDOW_MINUTES: i64 = 3652 * 24 * 60;
const NO_PROJECT: &str = "(no project)";
const TIME_FORMAT: &str = "%Y-%m-%d %H:%M";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Window {
pub since: DateTime<Utc>,
pub until: DateTime<Utc>,
}
impl Window {
pub fn parse(text: &str, until: DateTime<Utc>) -> Result<Window, String> {
let text = text.trim();
let invalid = || {
format!(
"invalid window '{text}': give a whole number of minutes, hours or days \
up to ten years, like 90m, 24h or 7d"
)
};
let mut chars = text.chars();
let minutes_per_unit = match chars.next_back() {
Some('m') => 1,
Some('h') => 60,
Some('d') => 24 * 60,
_ => return Err(invalid()),
};
let count = chars.as_str();
if count.is_empty() || !count.bytes().all(|b| b.is_ascii_digit()) {
return Err(invalid());
}
let minutes = count
.parse::<i64>()
.ok()
.and_then(|count| count.checked_mul(minutes_per_unit))
.filter(|minutes| (1..=MAX_WINDOW_MINUTES).contains(minutes))
.ok_or_else(invalid)?;
Ok(Window {
since: until - Duration::minutes(minutes),
until,
})
}
fn describe(&self) -> String {
format!(
"{} to {} UTC",
self.since.format(TIME_FORMAT),
self.until.format(TIME_FORMAT)
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DigestItem {
pub text: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub reason: String,
pub count: usize,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DigestSection {
pub items: Vec<DigestItem>,
pub omitted: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ProjectDigest {
pub project: Option<String>,
pub noted_sessions: usize,
pub unnoted_sessions: usize,
pub decided: DigestSection,
pub abandoned: DigestSection,
pub blocked_on_user: DigestSection,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Digest {
pub window: Window,
pub project: Option<String>,
pub projects: Vec<ProjectDigest>,
}
impl Digest {
pub fn read(
store: &SqliteStore,
window: Window,
project: Option<&str>,
) -> anyhow::Result<Digest> {
let notes = store.notes_created_between(window.since, window.until, project)?;
let noted: HashSet<Uuid> = store
.noted_session_ids()?
.iter()
.map(|session| Conversation::claude_code_id(session))
.collect();
let unnoted: Vec<Option<String>> = store
.claude_code_sessions_between(window.since, window.until, project)?
.into_iter()
.filter(|session| !noted.contains(&session.conversation_id))
.map(|session| session.project_path)
.collect();
Ok(Digest::assemble(
window,
project.map(str::to_string),
¬es,
&unnoted,
))
}
pub fn assemble(
window: Window,
project: Option<String>,
notes: &[(Memory, AgentNote)],
unnoted: &[Option<String>],
) -> Digest {
let mut projects: BTreeMap<(bool, String), ProjectBuilder> = BTreeMap::new();
for (index, (memory, note)) in notes.iter().enumerate() {
let builder = projects
.entry(project_key(&memory.project_path))
.or_default();
builder.sessions.insert(&memory.source_id);
match note.kind {
NoteKind::SessionEnd | NoteKind::Decision => {
builder.decided.add(¬e.decision, ¬e.reason, index)
}
NoteKind::DeadEnd => builder.abandoned.add(¬e.decision, ¬e.reason, index),
NoteKind::Fact => {}
}
for dead_end in ¬e.dead_ends {
builder.abandoned.add(dead_end, "", index);
}
for blocked in ¬e.blocked_on_user {
builder.blocked_on_user.add(blocked, "", index);
}
}
for project in unnoted {
projects.entry(project_key(project)).or_default().unnoted += 1;
}
let projects = projects
.into_iter()
.filter_map(|((unnamed, name), builder)| builder.finish((!unnamed).then_some(name)))
.collect();
Digest {
window,
project,
projects,
}
}
pub fn render(&self) -> String {
let span = self.window.describe();
let scope = self
.project
.as_ref()
.map(|project| format!(" for {project}"))
.unwrap_or_default();
if self.projects.is_empty() {
return format!("Nothing recorded{scope} from {span}.");
}
let mut out = format!("Agent digest{scope}, {span}");
for project in &self.projects {
out.push_str("\n\n");
project.render_into(&mut out);
}
out
}
}
impl ProjectDigest {
fn render_into(&self, out: &mut String) {
let mut counts = Vec::new();
if self.noted_sessions > 0 {
counts.push(sessions(self.noted_sessions, "with notes"));
}
if self.unnoted_sessions > 0 {
counts.push(sessions(self.unnoted_sessions, "without a note"));
}
out.push_str(self.project.as_deref().unwrap_or(NO_PROJECT));
out.push_str(": ");
out.push_str(&counts.join(", "));
for (title, section) in [
("Decided", &self.decided),
("Tried and abandoned", &self.abandoned),
("Blocked on you", &self.blocked_on_user),
] {
if section.items.is_empty() {
continue;
}
out.push_str(&format!("\n {title}:"));
for item in §ion.items {
out.push_str(&format!("\n - {}", item.text));
if item.count > 1 {
out.push_str(&format!(" ({} notes)", item.count));
}
if !item.reason.is_empty() {
out.push_str(&format!("\n why: {}", item.reason));
}
}
if section.omitted > 0 {
out.push_str(&format!("\n and {} more", section.omitted));
}
}
}
}
fn sessions(count: usize, what: &str) -> String {
let noun = if count == 1 { "session" } else { "sessions" };
format!("{count} {noun} {what}")
}
fn project_key(project: &Option<String>) -> (bool, String) {
(project.is_none(), project.clone().unwrap_or_default())
}
fn merge_key(text: &str) -> String {
text.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.trim_end_matches(['.', '!', '?', ',', ';', ':'])
.trim_end()
.to_lowercase()
}
#[derive(Default)]
struct SectionBuilder {
items: Vec<DigestItem>,
by_key: HashMap<String, (usize, usize)>,
}
impl SectionBuilder {
fn add(&mut self, text: &str, reason: &str, note: usize) {
let key = merge_key(text);
if key.is_empty() {
return;
}
match self.by_key.get_mut(&key) {
Some((at, last_note)) => {
let item = &mut self.items[*at];
if *last_note != note {
item.count += 1;
*last_note = note;
}
if item.reason.is_empty() {
item.reason = reason.to_string();
}
}
None => {
self.by_key.insert(key, (self.items.len(), note));
self.items.push(DigestItem {
text: text.to_string(),
reason: reason.to_string(),
count: 1,
});
}
}
}
fn finish(mut self) -> DigestSection {
let omitted = self.items.len().saturating_sub(MAX_ITEMS_PER_SECTION);
self.items.truncate(MAX_ITEMS_PER_SECTION);
DigestSection {
items: self.items,
omitted,
}
}
}
#[derive(Default)]
struct ProjectBuilder<'a> {
sessions: HashSet<&'a str>,
unnoted: usize,
decided: SectionBuilder,
abandoned: SectionBuilder,
blocked_on_user: SectionBuilder,
}
impl ProjectBuilder<'_> {
fn finish(self, project: Option<String>) -> Option<ProjectDigest> {
let digest = ProjectDigest {
project,
noted_sessions: self.sessions.len(),
unnoted_sessions: self.unnoted,
decided: self.decided.finish(),
abandoned: self.abandoned.finish(),
blocked_on_user: self.blocked_on_user.finish(),
};
let shows_something = digest.unnoted_sessions > 0
|| !digest.decided.items.is_empty()
|| !digest.abandoned.items.is_empty()
|| !digest.blocked_on_user.items.is_empty();
shows_something.then_some(digest)
}
}
#[cfg(test)]
mod tests {
use chrono::TimeZone;
use super::*;
use crate::schema::{AGENT_NOTE_SOURCE, Conversation, MemoryType};
use crate::store::Store;
fn now() -> DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 11, 2, 8, 0, 0).unwrap()
}
fn hours_ago(hours: i64) -> DateTime<Utc> {
now() - Duration::hours(hours)
}
fn day() -> Window {
Window::parse("24h", now()).unwrap()
}
fn note(
store: &SqliteStore,
session: &str,
project: &str,
hours: i64,
note: AgentNote,
) -> Memory {
let mut memory = Memory::new(
note.render(),
note.kind.memory_type(),
AGENT_NOTE_SOURCE.to_string(),
session.to_string(),
)
.with_project_path((!project.is_empty()).then(|| project.to_string()));
memory.created_at = hours_ago(hours);
store.store_memory(&memory).unwrap();
memory
}
fn transcript_line(store: &SqliteStore, path: &str, session: &str, project: &str, hours: i64) {
let mut memory = Memory::new(
format!("{path} {hours}"),
MemoryType::Episodic,
"claude-code".to_string(),
path.to_string(),
)
.with_project_path(Some(project.to_string()));
memory.conversation_id = Some(Conversation::claude_code_id(session));
memory.session_at = Some(hours_ago(hours));
store.store_memory(&memory).unwrap();
}
fn strings(items: &[&str]) -> Vec<String> {
items.iter().map(|item| item.to_string()).collect()
}
fn three_projects() -> SqliteStore {
let store = SqliteStore::in_memory("m".to_string()).unwrap();
let mut cache = AgentNote::new(NoteKind::SessionEnd, "keep the build cache per worktree");
cache.reason = "a shared cache mixed crates between branches".to_string();
cache.dead_ends = strings(&["one shared target dir"]);
cache.open_items = strings(&["rerun the flaky test"]);
cache.blocked_on_user = strings(&["approve the signing key"]);
note(&store, "s1", "-srv-app", 20, cache);
transcript_line(&store, "/p/-srv-app/s1.jsonl", "s1", "-srv-app", 21);
note(
&store,
"s2",
"-srv-app",
18,
AgentNote::new(NoteKind::Decision, "Keep the build cache per worktree."),
);
let mut raced = AgentNote::new(NoteKind::DeadEnd, "One shared target dir");
raced.reason = "two builds raced on it".to_string();
note(&store, "s2", "-srv-app", 17, raced);
transcript_line(&store, "/p/-srv-app/s9.jsonl", "s9", "-srv-app", 3);
note(
&store,
"s0",
"-srv-app",
30,
AgentNote::new(NoteKind::Decision, "an older decision"),
);
transcript_line(&store, "/p/-srv-app/s0.jsonl", "s0", "-srv-app", 2);
let retired = note(
&store,
"s8",
"-srv-app",
5,
AgentNote::new(NoteKind::Decision, "a retired decision"),
);
store.retire_memory(retired.id, "test").unwrap();
let mut router = AgentNote::new(NoteKind::SessionEnd, "split the router table by concern");
router.blocked_on_user = strings(&[
"pick a port",
"name the crate",
"confirm the license",
"review the API shape",
"choose a release date",
"approve the CI secret",
"sign off the docs",
]);
note(&store, "s3", "-srv-web", 9, router);
note(
&store,
"s4",
"-srv-web",
8,
AgentNote::new(NoteKind::Fact, "the port is 7300"),
);
transcript_line(&store, "/p/-srv-tools/s5.jsonl", "s5", "-srv-tools", 6);
transcript_line(&store, "/p/-srv-tools/s6.jsonl", "s6", "-srv-tools", 4);
transcript_line(
&store,
"/p/-srv-tools/s6/subagents/agent-a.jsonl",
"s6/a",
"-srv-tools",
4,
);
transcript_line(&store, "/p/-srv-tools/s7.jsonl", "s7", "-srv-tools", 30);
let mut toolchain = AgentNote::new(NoteKind::SessionEnd, "pin the toolchain");
toolchain.blocked_on_user = strings(&["Ship on Friday?", "ship on friday"]);
note(&store, "s5", "-srv-tools", 5, toolchain);
note(
&store,
"s10",
"",
7,
AgentNote::new(NoteKind::Decision, "retire the old sync timer"),
);
store
}
#[test]
fn notes_from_three_projects_give_the_expected_text() {
let store = three_projects();
let digest = Digest::read(&store, day(), None).unwrap();
assert_eq!(
digest.render(),
"Agent digest, 2026-11-01 08:00 to 2026-11-02 08:00 UTC\n\
\n\
-srv-app: 2 sessions with notes, 1 session without a note\n\
\x20 Decided:\n\
\x20 - Keep the build cache per worktree. (2 notes)\n\
\x20 why: a shared cache mixed crates between branches\n\
\x20 Tried and abandoned:\n\
\x20 - One shared target dir (2 notes)\n\
\x20 why: two builds raced on it\n\
\x20 Blocked on you:\n\
\x20 - approve the signing key\n\
\n\
-srv-tools: 1 session with notes, 1 session without a note\n\
\x20 Decided:\n\
\x20 - pin the toolchain\n\
\x20 Blocked on you:\n\
\x20 - Ship on Friday?\n\
\n\
-srv-web: 2 sessions with notes\n\
\x20 Decided:\n\
\x20 - split the router table by concern\n\
\x20 Blocked on you:\n\
\x20 - pick a port\n\
\x20 - name the crate\n\
\x20 - confirm the license\n\
\x20 - review the API shape\n\
\x20 - choose a release date\n\
\x20 and 2 more\n\
\n\
(no project): 1 session with notes\n\
\x20 Decided:\n\
\x20 - retire the old sync timer"
);
}
#[test]
fn a_project_filter_keeps_one_project() {
let store = three_projects();
let digest = Digest::read(&store, day(), Some("-srv-tools")).unwrap();
assert_eq!(
digest.render(),
"Agent digest for -srv-tools, 2026-11-01 08:00 to 2026-11-02 08:00 UTC\n\
\n\
-srv-tools: 1 session with notes, 1 session without a note\n\
\x20 Decided:\n\
\x20 - pin the toolchain\n\
\x20 Blocked on you:\n\
\x20 - Ship on Friday?"
);
}
#[test]
fn an_empty_window_prints_one_line() {
let store = three_projects();
let window = Window::parse("90m", now() - Duration::days(30)).unwrap();
assert_eq!(
Digest::read(&store, window, None).unwrap().render(),
"Nothing recorded from 2026-10-03 06:30 to 2026-10-03 08:00 UTC."
);
let empty = SqliteStore::in_memory("m".to_string()).unwrap();
assert_eq!(
Digest::read(&empty, day(), Some("-srv-app"))
.unwrap()
.render(),
"Nothing recorded for -srv-app from 2026-11-01 08:00 to 2026-11-02 08:00 UTC."
);
}
#[test]
fn a_digest_survives_json() {
let digest = Digest::read(&three_projects(), day(), None).unwrap();
let json = serde_json::to_string(&digest).unwrap();
assert_eq!(serde_json::from_str::<Digest>(&json).unwrap(), digest);
}
#[test]
fn a_window_is_minutes_hours_or_days() {
for (text, span) in [
("90m", Duration::minutes(90)),
("24h", Duration::hours(24)),
(" 7d ", Duration::days(7)),
] {
assert_eq!(
Window::parse(text, now()),
Ok(Window {
since: now() - span,
until: now(),
}),
"{text}"
);
}
for text in ["", "24", "h", "0h", "-1h", "1.5h", "24x", "99999999999d"] {
assert!(Window::parse(text, now()).is_err(), "{text:?}");
}
}
}