Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): read subagent-preamble bodies only until one names the page
Djalma Júniorcc3ae402a9cc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a6bcb0b2..7632815e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,24 +11,27 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]+### Fixed+- Fixed SessionEnd loading every observation of the session into memory, up to+ three times, on the hook path. One production claude-code session held+ 948,136 observations, so ending it deserialized close to a million rows+ (bodies included) per read. The lifecycle-only decision is now one `EXISTS`+ query, and the summary page and the auto-handoff are rendered from bounded+ reads taken in one read transaction: SQL aggregates for the counts and the+ "last of a kind" markers, the 250 first and 250 last rows the raw list+ prints, and early-exit scans for the first or last prompt that passes the+ usual filters; subagent-preamble prompt bodies are read one at a time and+ only until one names the page. The page, the handoff and the lifecycle-only+ decision are unchanged byte for byte (an equivalence test holds them to the+ original row-list code on sessions of every shape). What still grows with+ the session is what the page itself lists: the title of every user prompt.+ The PreCompact and PostCompaction checkpoint page uses the same bounded+ reads. The writer's lifecycle-only re-check and the reader now build their+ query from one shared predicate. (#PRNUM)+## [3.0.1] - 2026-10-15### Fixed-- Fixed SessionEnd loading every observation of the session into memory, up- to three times, on the hook path. One production claude-code session held- 948,136 observations, so ending it deserialized close to a million rows- (bodies included) per read. The lifecycle-only decision is now one- `EXISTS` query, and the summary page and the auto-handoff are rendered from- bounded reads taken in one read transaction: SQL aggregates for the counts- and the "last of a kind" markers, the 250 first and 250 last rows the raw- list prints, and early-exit scans for the first or last prompt that passes- the usual filters. The page, the handoff and the lifecycle-only decision are- unchanged byte for byte (an equivalence test holds them to the original- row-list code on sessions of every shape). What still grows with the session- is what the page itself lists: the title of every user prompt. The PreCompact- and PostCompaction checkpoint page uses the same bounded reads. The writer's- lifecycle-only re-check and the reader now build their query from one shared- predicate. (#PRNUM)- Fixed the WinSW v2.12.0 service-account example using the v3`<username>` element. WinSW v2.12.0 expects separate `<domain>` and `<user>`elements; it ignored `<username>` and installed the service asdiff --git a/crates/ai-memory-hooks/src/session_end_equivalence.rs b/crates/ai-memory-hooks/src/session_end_equivalence.rsindex f2492143..4f5f095e 100644--- a/crates/ai-memory-hooks/src/session_end_equivalence.rs+++ b/crates/ai-memory-hooks/src/session_end_equivalence.rs@@ -1282,6 +1282,50 @@ async fn a_huge_session_reads_a_bounded_number_of_rows() {fx.assert_equivalent("12k rows", sid).await;}+/// Subagent preambles carry the only prompt bodies a SessionEnd reads, and a+/// session can hold thousands of them: the title is settled by the first+/// usable one, so the bodies after it are never read.+#[tokio::test]+async fn subagent_preamble_bodies_stop_at_the_first_usable_one() {+ let fx = fixture().await;+ let filler = "x".repeat(4096);+ let unusable = format!("<ide_opened_file>{filler}\n\n");+ let usable = format!("Review the diff in src/lib.rs\n{filler}");+ let preambles = 2_000;+ for (name, leading_unusable) in [("first usable", 0), ("three unusable first", 3)] {+ let mut rows = vec![start(0)];+ for i in 0..preambles {+ let body = if i < leading_unusable {+ &unusable+ } else {+ &usable+ };+ rows.push(row(+ ObservationKind::UserPrompt,+ SUBAGENT_PREAMBLE,+ body,+ 1 + i as i64,+ ));+ }+ rows.push(end(1 + preambles as i64));+ let sid = fx.seed(&rows).await;++ let (_, stats) = SessionDigest::load_with_stats(&fx.store.reader, sid)+ .await+ .unwrap();+ assert_eq!(+ stats.prompt_titles, preambles,+ "{name}: every title is kept"+ );+ assert_eq!(+ stats.prompt_bodies_read,+ leading_unusable + 1,+ "{name}: bodies read past the one that named the page"+ );+ fx.assert_equivalent(name, sid).await;+ }+}+/// The Rust predicate the original code used and the existence query the/// router asks now classify every observation kind alike. (The writer's/// lifecycle-only re-check is pinned to the same query indiff --git a/crates/ai-memory-hooks/src/synth.rs b/crates/ai-memory-hooks/src/synth.rsindex 096bda3d..4a0eeb2d 100644--- a/crates/ai-memory-hooks/src/synth.rs+++ b/crates/ai-memory-hooks/src/synth.rs@@ -21,7 +21,7 @@ use ai_memory_core::{};use ai_memory_store::{ObservationOrder, ReaderPool, SessionKindSummary, SessionLine, SessionObservationSnapshot,- SessionPromptTitle, StoreError, StoreResult,+ StoreError, StoreResult,};use jiff::Timestamp;use jiff::tz::TimeZone;@@ -175,6 +175,8 @@ pub struct DigestLoadStats {pub rows_read: usize,/// User prompts whose title the digest keeps.pub prompt_titles: usize,+ /// Prompt bodies read to settle the page title (one resident at a time).+ pub prompt_bodies_read: usize,}impl SessionDigest {@@ -315,19 +317,19 @@ fn build_digest(// Bodies only for a title that could be the subagent preamble: the title// rule is the one reader of a prompt body.- let prompt_rows: Vec<SessionPromptTitle> = snapshot.prompt_titles(SUBAGENT_PROMPT_PREAMBLE)?;- let title = match title_from_prompts(- prompt_rows- .iter()- .map(|p| (p.title.as_str(), p.body.as_deref().unwrap_or(""))),- ) {+ let mut title_scan = PromptTitleScan::default();+ let mut prompt_bodies_read = 0;+ let prompt_titles = snapshot.prompt_titles(SUBAGENT_PROMPT_PREAMBLE, |title, body| {+ prompt_bodies_read += usize::from(body.is_some());+ title_scan.push(title, body.unwrap_or(""))+ })?;+ let title = match title_scan.finish() {PromptTitle::Found(title) => title,PromptTitle::RejectedPreamble => format!("Session {session_id}"),PromptTitle::Unusable => snapshot.scan(ObservationOrder::Asc, &[], None, fallback_title)?.unwrap_or_else(|| title_without_candidate(session_id, total)),};- let prompt_titles: Vec<String> = prompt_rows.into_iter().map(|p| p.title).collect();let tools = snapshot.tool_titles()?;let tool_counts: BTreeMap<String, usize> = tools.completed.into_iter().collect();@@ -382,6 +384,7 @@ fn build_digest(let stats = DigestLoadStats {rows_read: snapshot.rows_read(),prompt_titles: prompt_titles.len(),+ prompt_bodies_read,};Ok((SessionDigest {@@ -410,6 +413,19 @@ enum PromptTitle {Unusable,}+/// [`PromptTitleScan`] over a whole prompt list: the row-list form the+/// test-only digest builder walks.+#[cfg(test)]+fn title_from_prompts<'a>(prompts: impl Iterator<Item = (&'a str, &'a str)>) -> PromptTitle {+ let mut scan = PromptTitleScan::default();+ for (title, body) in prompts {+ if !scan.push(title, body) {+ break;+ }+ }+ scan.finish()+}+/// Title for a synthesised session page.////// Prefers the first user prompt that reads as something a person wrote.@@ -441,28 +457,44 @@ enum PromptTitle {/// any other usable observation title, then the session's own path. The/// literal "session" remains only for the case where there is nothing else/// at all.-fn title_from_prompts<'a>(prompts: impl Iterator<Item = (&'a str, &'a str)>) -> PromptTitle {- let mut rejected_subagent_preamble = false;- for (title, body) in prompts {+///+/// Fed one prompt at a time, so a caller streaming prompts from the store+/// holds one body at most and stops reading bodies once the title is settled.+#[derive(Default)]+struct PromptTitleScan {+ found: Option<String>,+ rejected_subagent_preamble: bool,+}++impl PromptTitleScan {+ /// Feed the next prompt in capture order. Returns `false` once the title+ /// is found: later prompts cannot change it.+ fn push(&mut self, title: &str, body: &str) -> bool {if title.trim() == SUBAGENT_PROMPT_PREAMBLE {- rejected_subagent_preamble = true;- if let Some(title) = body+ self.rejected_subagent_preamble = true;+ if let Some(line) = body.lines().map(str::trim).find(|line| !line.is_empty() && !looks_like_title_scaffolding(line)){- return PromptTitle::Found(truncate_for_title(title));+ self.found = Some(truncate_for_title(line));+ return false;}- continue;+ return true;}if !title.is_empty() && !looks_like_scaffolding(title) {- return PromptTitle::Found(title.to_string());+ self.found = Some(title.to_string());+ return false;}+ true}- if rejected_subagent_preamble {- PromptTitle::RejectedPreamble- } else {- PromptTitle::Unusable++ fn finish(self) -> PromptTitle {+ match self.found {+ Some(title) => PromptTitle::Found(title),+ None if self.rejected_subagent_preamble => PromptTitle::RejectedPreamble,+ None => PromptTitle::Unusable,+ }}}diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 31b5bc16..27d63198 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -95,9 +95,9 @@ pub use reader::{ReindexTargetStatus, RelatedNode, RelatedPage, RrfContributions, SESSION_LINE_TITLE_CHARS,SUBSTANTIVE_OBSERVATION_KIND_SQL, ScopeRow, SearchExplain, SessionConsolidationQueue,SessionConsolidationSummary, SessionDependentRows, SessionEndDisposition, SessionKindSummary,- SessionLine, SessionObservationSnapshot, SessionPromptTitle, SessionSummary, SessionToolTitles,- SettledPage, StatusCounts, StorageStatus, StoredEmbedding, StoredPageBody, StreamTimings,- VectorQuery, WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,+ SessionLine, SessionObservationSnapshot, SessionSummary, SessionToolTitles, SettledPage,+ StatusCounts, StorageStatus, StoredEmbedding, StoredPageBody, StreamTimings, VectorQuery,+ WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,};pub use retrieval_tuning::{RetrievalTuning, is_session_recall_query};pub use scope::{diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 8cc61304..8ed59deb 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -11952,16 +11952,6 @@ pub struct SessionToolTitles {pub titles: Vec<String>,}-/// A user prompt's title, plus its body when the caller asked for it.-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct SessionPromptTitle {- /// The prompt's stored title.- pub title: String,- /// The body, loaded only for a title containing the `body_for_titles_like`- /// marker the caller passed (a superset the caller filters exactly).- pub body: Option<String>,-}-/// What a page prints about one observation, without the body.#[derive(Debug, Clone, PartialEq, Eq)]pub struct SessionLine {@@ -12080,8 +12070,13 @@ impl SessionObservationSnapshot<'_> {Ok(out)}- /// Every user prompt's title in capture order, with the body only for a- /// title that contains `body_for_titles_like`.+ /// Every user prompt's title in capture order.+ ///+ /// `visit` sees each prompt in that order, with its body only when the+ /// title contains `body_for_titles_like` (a superset the caller filters+ /// exactly), until it returns `false`; later prompts contribute their+ /// title alone. At most one body is resident at a time, so a session full+ /// of subagent preambles costs one body, not all of them.////// The titles are the one part of a SessionEnd that grows with the/// session: the page it renders lists each of them, so the output cannot@@ -12094,31 +12089,27 @@ impl SessionObservationSnapshot<'_> {pub fn prompt_titles(&self,body_for_titles_like: &str,- ) -> StoreResult<Vec<SessionPromptTitle>> {+ mut visit: impl FnMut(&str, Option<&str>) -> bool,+ ) -> StoreResult<Vec<String>> {let mut stmt = self.conn.prepare_cached(- "SELECT title, CASE WHEN instr(title, ?3) > 0 THEN body END \- FROM observations \- WHERE session_id = ?1 AND kind = ?2 \- ORDER BY created_at ASC, rowid ASC",+ "SELECT title, CASE WHEN instr(title, ?3) > 0 THEN body END FROM observations WHERE session_id = ?1 AND kind = ?2 ORDER BY created_at ASC, rowid ASC",)?;- let rows = stmt.query_map(- params![- self.session_id,- ObservationKind::UserPrompt.as_str(),- body_for_titles_like,- ],- |row| {- Ok(SessionPromptTitle {- title: row.get(0)?,- body: row.get(1)?,- })- },- )?;- let mut out = Vec::new();- for row in rows {- out.push(row?);+ let mut rows = stmt.query(params![+ self.session_id,+ ObservationKind::UserPrompt.as_str(),+ body_for_titles_like,+ ])?;+ let mut titles = Vec::new();+ let mut visiting = true;+ while let Some(row) = rows.next()? {+ let title: String = row.get(0)?;+ if visiting {+ let body: Option<String> = row.get(1)?;+ visiting = visit(&title, body.as_deref());+ }+ titles.push(title);}- Ok(out)+ Ok(titles)}/// The first `limit` rows of the session, oldest first, as page lines.