Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat: write a page summary on both session-page write paths (#477)
Samir Hanna Verza488a0b6b3ee9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6d03a39e..b39ec404 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- Gave session pages a `summary` in their frontmatter, which the retrieval+ layer already preferred over the page body when describing a non-FTS hit.+ #463 made that `COALESCE` prefer a summary, but no write path produced one:+ measured against a live 1.31.1 instance, 0 of 25 substantive pages had the+ field, so every descriptor fell back to the body. All three writers now fill+ it — the zero-LLM `SessionEnd` synthesis, the single-page consolidator, and+ the batch one — because zero-LLM is the documented default and `multi_page`+ defaults to false, so covering either alone would have missed the pages most+ installs actually hold. (#473)++ On the zero-LLM path the summary came from counts the renderer already had+ and was discarding: prompts, completed tool calls per tool, and elapsed time+ ("2 prompts, 34 completed tool calls across Bash, Edit and Read, over 18m").+ That is what a page cannot state about itself — a reader deciding whether to+ open it now sees how much work it holds, not only what it opened with. The+ page is tallied once and the count lent to both the body renderer and the+ summary, and `PostToolUse` stays the only counted kind so a completed call is+ not double-counted.++ On the LLM paths it became an optional field on the consolidator's structured+ output, costing no additional model call since the call already happens, with+ `#[serde(default)]` so stored outputs from earlier runs still deserialise.+ Both system prompts now request it and describe the shape it has to keep; the+ batch prompt previously forbade the key outright.++ A model-supplied summary is validated before it is written, because the+ reader prefers `summary` over the body and then drops headings, metadata+ bullets, list items and title repeats — falling back to echoing its raw+ input when nothing survives. A structurally wrong summary is therefore not+ ignored but reproduced verbatim as the descriptor, displacing usable body+ text with no error anywhere. Anything the reader would discard is dropped at+ the boundary instead, leaving the page on its body-derived descriptor.++ The fallback is unchanged and still serves hand-written pages and everything+ written before this. New writes only: no backfill, no migration.+- `ai-memory status` now reports server-side hook-ingestion countersalongside the client spool section: events accepted, accepted-but-droppedby capture policy, shed because ingest capacity was exhausted, shed by thediff --git a/crates/ai-memory-consolidate/prompts/single_consolidate_system.md b/crates/ai-memory-consolidate/prompts/single_consolidate_system.mdindex 2d3a2480..33971870 100644--- a/crates/ai-memory-consolidate/prompts/single_consolidate_system.md+++ b/crates/ai-memory-consolidate/prompts/single_consolidate_system.md@@ -100,13 +100,20 @@ schema, and nothing else:{"title": "<page title>","body_markdown": "<markdown body>",- "tags": ["tag-1", "tag-2"]+ "tags": ["tag-1", "tag-2"],+ "summary": "<one line of plain prose>"}```- Field names are EXACT and case-sensitive. Use `body_markdown`,not `body` or `content`. `tags` may be `[]` but the key mustbe present.+- `summary` is ONE line of plain prose saying what the page covers, for+ readers who see it beside the title in a listing. It must NOT be a+ heading, a `- **key:** value` bullet, a list item, or a repeat of the+ title — a summary shaped like any of those is discarded and the page is+ described worse than if you had omitted it. Omit the key rather than+ guessing.## Output formatdiff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rsindex b430e1bd..1bddcf03 100644--- a/crates/ai-memory-consolidate/src/consolidator.rs+++ b/crates/ai-memory-consolidate/src/consolidator.rs@@ -609,6 +609,9 @@ fn build_update("kind".into(),serde_json::Value::String(upd.kind.as_str().into()),);+ if let Some(summary) = usable_summary(upd.summary.as_deref(), &upd.title) {+ fm.insert("summary".into(), serde_json::Value::String(summary));+ }if !upd.tags.is_empty() {fm.insert("tags".into(),@@ -847,7 +850,8 @@ fn build_batch_request_with_slots(- \"tags\" (array of string) required — may be empty `[]`, but the key must be present\n\- \"entities\" (array of string) required — may be empty `[]`, but the key must be present; see below\n\- \"slot_kind\" (string) optional — ONLY for `_slots/*`; one of \"state\" or \"invariant\"; this is the SLOT WRITE REGIME, NOT a tier value\n\- No other keys except optional `slot_kind` on `_slots/*`. No `body`, no `content`, no `summary`. Field names \+ - \"summary\" (string) optional — ONE line of plain prose saying what the page covers, shown beside the title in listings. NOT a heading, NOT a `- **key:** value` bullet, NOT a list item, NOT a repeat of the title: a summary shaped like any of those is discarded and the page ends up described worse than if you had omitted it. Omit the key rather than guessing.\n\+ No other keys except optional `slot_kind` on `_slots/*` and optional `summary`. No `body`, no `content`. Field names \are case-sensitive and the `_markdown` suffix matters.\n\\n## `entities` field — the specific nouns the page is about\n\Up to 10 short names (max 64 chars each), lowercase, taken from \@@ -1183,6 +1187,40 @@ fn clip_current_body_for_prompt(s: &str, max_chars: usize) -> String {out}+/// Accept a model-supplied `summary` only when the reader can actually use it.+///+/// The store prefers `summary` over the page body and then runs it through the+/// same line filter it applies to a body: headings, `- **key:** value`+/// metadata bullets, other list markers, and lines repeating the title are all+/// dropped, and when nothing survives the filter echoes its raw input. So a+/// structurally wrong summary is not ignored — it is reproduced verbatim as+/// the descriptor, in place of the body text that would otherwise have been+/// used, and nothing reports an error.+///+/// A JSON schema cannot express that constraint, and this value is+/// model-controlled, so it is enforced here: anything the reader would discard+/// is dropped at the boundary and the page keeps its body-derived descriptor.+fn usable_summary(raw: Option<&str>, title: &str) -> Option<String> {+ let text = raw?.trim();+ if text.is_empty() || text.contains('\n') {+ return None;+ }+ if text.starts_with('#')+ || text.starts_with("---")+ || text.starts_with("___")+ || text.starts_with("***")+ || text.starts_with("- ")+ || text.starts_with("* ")+ || text.starts_with("+ ")+ {+ return None;+ }+ if text == title.trim() {+ return None;+ }+ Some(text.to_owned())+}+fn build_frontmatter(page: &ConsolidatedPage) -> serde_json::Value {let mut map = serde_json::Map::new();map.insert(@@ -1198,6 +1236,9 @@ fn build_frontmatter(page: &ConsolidatedPage) -> serde_json::Value {.collect();map.insert("tags".into(), serde_json::Value::Array(tags));}+ if let Some(summary) = usable_summary(page.summary.as_deref(), &page.title) {+ map.insert("summary".into(), serde_json::Value::String(summary));+ }map.insert("consolidated".into(), serde_json::Value::Bool(true));serde_json::Value::Object(map)}@@ -1582,6 +1623,105 @@ mod tests {assert!(!slug.ends_with('-'));}+ fn update_with_summary(summary: Option<&str>) -> crate::types::ConsolidatedPageUpdate {+ crate::types::ConsolidatedPageUpdate {+ path: "concepts/queue.md".into(),+ tier: Tier::Semantic,+ kind: crate::types::PageKind::Fact,+ title: "Bound the scheduler queue".into(),+ body_markdown: "Body prose.".into(),+ summary: summary.map(str::to_owned),+ tags: Vec::new(),+ slot_kind: SlotKind::State,+ entities: Vec::new(),+ }+ }++ fn frontmatter_for(summary: Option<&str>) -> serde_json::Value {+ let (req, _) = build_update(+ WorkspaceId::new(),+ ProjectId::new(),+ &update_with_summary(summary),+ true,+ &ai_memory_core::ActorContext::default(),+ None,+ )+ .expect("build_update");+ req.frontmatter+ }++ #[test]+ fn a_usable_summary_reaches_the_frontmatter_trimmed() {+ let fm = frontmatter_for(Some(" Bounded the queue so backpressure is testable. "));+ assert_eq!(+ fm["summary"],+ "Bounded the queue so backpressure is testable."+ );+ }++ #[test]+ fn summaries_the_reader_would_discard_are_not_written() {+ // Each of these is legal JSON and legal per the schema, and each one+ // would be echoed verbatim as the descriptor — replacing the page's+ // body-derived one — because the reader's filter drops every line and+ // then falls back to its raw input. Dropping them here keeps the page+ // on the body text instead.+ for bad in [+ "",+ " ",+ "- **session_id:** `9f2c`",+ "## What this page covers",+ "- bounded the queue",+ "* bounded the queue",+ "first line\nsecond line",+ "Bound the scheduler queue", // identical to the title+ ] {+ assert!(+ frontmatter_for(Some(bad)).get("summary").is_none(),+ "should not have been written: {bad:?}"+ );+ }+ assert!(frontmatter_for(None).get("summary").is_none());+ }++ #[test]+ fn the_single_page_builder_surfaces_a_summary_too() {+ // `consolidate_session` — the default path, and the one the serve+ // worker uses — goes through `ConsolidatedPage`, not the batch type.+ let page = ConsolidatedPage {+ title: "Bound the scheduler queue".into(),+ body_markdown: "Body prose.".into(),+ tags: Vec::new(),+ summary: Some("Bounded the queue so backpressure is testable.".into()),+ };+ assert_eq!(+ build_frontmatter(&page)["summary"],+ "Bounded the queue so backpressure is testable."+ );++ let unusable = ConsolidatedPage {+ summary: Some("- **session_id:** `9f2c`".into()),+ ..page+ };+ assert!(build_frontmatter(&unusable).get("summary").is_none());+ }++ #[test]+ fn both_prompts_ask_for_the_summary_and_describe_its_shape() {+ // The batch prompt used to say "no `summary`" outright; a model+ // obeying that never supplies the field, and the whole write path is+ // dead code. Assert both prompts request it, so that cannot regress+ // back into silence.+ for prompt in [BATCH_SYSTEM_PROMPT, SYSTEM_PROMPT] {+ assert!(prompt.contains("summary"), "prompt must request `summary`");+ assert!(+ !prompt.contains("no `summary`"),+ "prompt must not forbid `summary`"+ );+ }+ assert!(SYSTEM_PROMPT.contains("ONE line of plain prose"));+ }+#[test]fn slot_update_defaults_to_state_frontmatter() {let update = crate::types::ConsolidatedPageUpdate {@@ -1590,6 +1730,7 @@ mod tests {kind: crate::types::PageKind::Fact,title: "Current focus".into(),body_markdown: "Ship the slot-kind PR.".into(),+ summary: None,tags: Vec::new(),slot_kind: SlotKind::State,entities: Vec::new(),@@ -1614,6 +1755,7 @@ mod tests {kind: crate::types::PageKind::Fact,title: "X".into(),body_markdown: "body".into(),+ summary: None,tags: Vec::new(),slot_kind: SlotKind::State,entities: Vec::new(),@@ -1651,6 +1793,7 @@ mod tests {kind: crate::types::PageKind::Fact,title: "Entities".into(),body_markdown: "body".into(),+ summary: None,tags: Vec::new(),slot_kind: SlotKind::State,entities: vec![@@ -1686,6 +1829,7 @@ mod tests {kind: crate::types::PageKind::Fact,title: "Project context".into(),body_markdown: "This repo uses a markdown wiki as source of truth.".into(),+ summary: None,tags: Vec::new(),slot_kind: SlotKind::Invariant,entities: Vec::new(),diff --git a/crates/ai-memory-consolidate/src/types.rs b/crates/ai-memory-consolidate/src/types.rsindex 74c5fbf2..9d21d817 100644--- a/crates/ai-memory-consolidate/src/types.rs+++ b/crates/ai-memory-consolidate/src/types.rs@@ -16,6 +16,12 @@ pub struct ConsolidatedPage {/// Up to ~5 short tags surfaced into the page's frontmatter.#[serde(default)]pub tags: Vec<String>,+ /// One line of plain prose saying what this page covers, shown beside the+ /// title in retrieval listings. See [`ConsolidatedPageUpdate::summary`]+ /// for the shape it has to keep. Defaults to absent so existing stored+ /// outputs still deserialise.+ #[serde(default)]+ pub summary: Option<String>,}/// Semantic classification of one consolidated page. Surfaced into@@ -117,6 +123,14 @@ pub struct ConsolidatedPageUpdate {pub title: String,/// New markdown body.pub body_markdown: String,+ /// One line of plain prose saying what this page covers, shown beside+ /// the title in retrieval listings. Write a complete sentence: not a+ /// heading, not a `- **key:** value` bullet, and not a repeat of the+ /// title — the reader drops all three and would fall back to echoing+ /// this field verbatim. Omit it rather than guessing. Defaults to absent+ /// so existing structured outputs still deserialise.+ #[serde(default)]+ pub summary: Option<String>,/// Optional tags surfaced into frontmatter.#[serde(default)]pub tags: Vec<String>,diff --git a/crates/ai-memory-hooks/src/synth.rs b/crates/ai-memory-hooks/src/synth.rsindex ca52447d..ed460b77 100644--- a/crates/ai-memory-hooks/src/synth.rs+++ b/crates/ai-memory-hooks/src/synth.rs@@ -28,8 +28,23 @@ pub fn synthesize_session_page(session_id: SessionId,observations: &[Observation],) -> NewPage {+ // One tally for the whole page: the body renderer and the summary builder+ // describe the same session and must not scan it twice to do so.+ let tally = tally_session(observations);let title = derive_title(observations);- let body = render_body(session_id, observations, &title);+ let body = render_body(session_id, observations, &title, &tally);+ let mut frontmatter_json = serde_json::json!({+ "title": title,+ "session_id": session_id.to_string(),+ "tier": "episodic",+ });+ let summary = session_summary(&tally);+ if !summary.is_empty() {+ // Insert only when there is something to say. The store's hit+ // descriptor prefers `summary` over the body, so writing a blank one+ // would trade real body text for nothing.+ frontmatter_json["summary"] = serde_json::Value::String(summary);+ }let path = PagePath::new(format!("sessions/{session_id}.md")).expect("hard-coded sessions/<uuid>.md is always valid");NewPage {@@ -39,11 +54,7 @@ pub fn synthesize_session_page(title: title.clone(),body,tier: Tier::Episodic,- frontmatter_json: serde_json::json!({- "title": title,- "session_id": session_id.to_string(),- "tier": "episodic",- }),+ frontmatter_json,pinned: false,links: Vec::new(),author_id: None,@@ -66,17 +77,39 @@ fn derive_title(observations: &[Observation]) -> String {"session".to_string()}-fn render_body(session_id: SessionId, observations: &[Observation], title: &str) -> String {- let mut tool_counts: BTreeMap<&str, usize> = BTreeMap::new();- let mut prompts: Vec<&Observation> = Vec::new();- let mut start: Option<&Observation> = None;- let mut end: Option<&Observation> = None;+/// The per-session counts that both the rendered body and the frontmatter+/// summary are built from.+struct SessionTally<'a> {+ /// Completed calls per tool name, keyed for stable ordering.+ tool_counts: BTreeMap<&'a str, usize>,+ /// User prompts in arrival order.+ prompts: Vec<&'a Observation>,+ /// First `SessionStart`, if the session recorded one.+ start: Option<&'a Observation>,+ /// Last `SessionEnd`, if the session recorded one.+ end: Option<&'a Observation>,+}+/// Tally a session's observations once.+///+/// [`render_body`] and [`session_summary`] both need these counts, and+/// [`synthesize_session_page`] computes them once and lends them to both — so+/// a page costs one pass over its observations, not two, and the body and the+/// summary cannot describe the same session differently. It also keeps the+/// summary from having to parse the counts back out of the markdown the body+/// just rendered them into.+fn tally_session(observations: &[Observation]) -> SessionTally<'_> {+ let mut tally = SessionTally {+ tool_counts: BTreeMap::new(),+ prompts: Vec::new(),+ start: None,+ end: None,+ };for obs in observations {match obs.kind {- ObservationKind::SessionStart => start = Some(obs),- ObservationKind::SessionEnd => end = Some(obs),- ObservationKind::UserPrompt => prompts.push(obs),+ ObservationKind::SessionStart => tally.start = Some(obs),+ ObservationKind::SessionEnd => tally.end = Some(obs),+ ObservationKind::UserPrompt => tally.prompts.push(obs),// Count only PostToolUse — each tool call produces both a// PreToolUse and a PostToolUse observation, so counting both// doubles every reported number ("Bash: 4" for two real calls).@@ -84,11 +117,129 @@ fn render_body(session_id: SessionId, observations: &[Observation], title: &str)// that never produced a post (cancellations) are intentionally// excluded.ObservationKind::PostToolUse if !obs.title.is_empty() => {- *tool_counts.entry(obs.title.as_str()).or_insert(0) += 1;+ *tally.tool_counts.entry(obs.title.as_str()).or_insert(0) += 1;}_ => {}}}+ tally+}++/// How many tools to name individually before summarising the rest as a count.+const SUMMARY_MAX_NAMED_TOOLS: usize = 3;++/// One line of plain prose describing what the session did, or empty when it+/// did nothing worth stating.+///+/// This lands in `frontmatter.summary`, which the store prefers over the body+/// when building the descriptor for a non-FTS hit. It is **not** used+/// verbatim: the reader runs it through the same line filter it applies to a+/// body, which drops headings, `- **key:** value` metadata bullets, and any+/// line that merely repeats the title. When every line is dropped the filter+/// falls back to echoing its raw input, so a summary written in the same house+/// style as the metadata block above would be reproduced verbatim as the+/// descriptor — displacing the body text that would otherwise have been used,+/// silently and with no error anywhere.+///+/// Hence: one line, plain prose, no leading marker.+fn session_summary(tally: &SessionTally<'_>) -> String {+ let mut parts: Vec<String> = Vec::new();++ if !tally.prompts.is_empty() {+ parts.push(format!(+ "{} prompt{}",+ tally.prompts.len(),+ plural(tally.prompts.len())+ ));+ }++ let calls: usize = tally.tool_counts.values().sum();+ if calls > 0 {+ // Name the busiest tools first; ties fall back to the map's+ // alphabetical order so the same session always renders the same way.+ let mut by_calls: Vec<(&str, usize)> =+ tally.tool_counts.iter().map(|(k, v)| (*k, *v)).collect();+ by_calls.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(b.0)));+ let named: Vec<&str> = by_calls+ .iter()+ .take(SUMMARY_MAX_NAMED_TOOLS)+ .map(|(name, _)| *name)+ .collect();+ let tools = if by_calls.len() > SUMMARY_MAX_NAMED_TOOLS {+ format!(+ "{} and {} more",+ join_and(&named),+ by_calls.len() - SUMMARY_MAX_NAMED_TOOLS+ )+ } else {+ join_and(&named)+ };+ parts.push(format!(+ "{calls} completed tool call{} across {tools}",+ plural(calls)+ ));+ }++ if let (Some(start), Some(end)) = (tally.start, tally.end)+ && let Some(spent) =+ format_duration(end.created_at.as_second() - start.created_at.as_second())+ {+ parts.push(format!("over {spent}"));+ }++ if parts.is_empty() {+ return String::new();+ }+ format!("{}.", parts.join(", "))+}++/// `""` or `"s"` for a count.+fn plural(n: usize) -> &'static str {+ if n == 1 { "" } else { "s" }+}++/// `"Bash"`, `"Bash and Edit"`, `"Bash, Edit and Read"`.+fn join_and(names: &[&str]) -> String {+ match names {+ [] => String::new(),+ [only] => (*only).to_string(),+ [rest @ .., last] => format!("{} and {last}", rest.join(", ")),+ }+}++/// Human-readable elapsed time, or `None` when the session was not measurably+/// long (a clock that did not advance, or ran backwards).+fn format_duration(seconds: i64) -> Option<String> {+ if seconds <= 0 {+ return None;+ }+ if seconds < 60 {+ return Some(format!("{seconds}s"));+ }+ let minutes = seconds / 60;+ if minutes < 60 {+ return Some(format!("{minutes}m"));+ }+ let (hours, rest) = (minutes / 60, minutes % 60);+ Some(if rest == 0 {+ format!("{hours}h")+ } else {+ format!("{hours}h {rest}m")+ })+}++fn render_body(+ session_id: SessionId,+ observations: &[Observation],+ title: &str,+ tally: &SessionTally<'_>,+) -> String {+ let SessionTally {+ tool_counts,+ prompts,+ start,+ end,+ } = tally;let mut buf = String::with_capacity(2048);buf.push_str(&format!("# {title}\n\n"));@@ -113,7 +264,7 @@ fn render_body(session_id: SessionId, observations: &[Observation], title: &str)if !tool_counts.is_empty() {buf.push_str("## Tool calls\n\n");- for (name, count) in &tool_counts {+ for (name, count) in tool_counts {buf.push_str(&format!("- `{name}`: {count}\n"));}buf.push('\n');@@ -193,6 +344,169 @@ mod tests {}}+ fn obs_at(kind: ObservationKind, title: &str, at: &str) -> Observation {+ let mut o = obs(kind, title);+ o.created_at = at.parse::<Timestamp>().expect("fixture timestamp");+ o+ }++ #[test]+ fn the_summary_states_the_shape_of_the_session() {+ let observations = vec![+ obs_at(+ ObservationKind::SessionStart,+ "session",+ "2026-08-24T10:00:00Z",+ ),+ obs(ObservationKind::UserPrompt, "bound the scheduler queue"),+ obs(ObservationKind::UserPrompt, "make the test deterministic"),+ // Pre+Post pairs: three completed calls, not six.+ obs(ObservationKind::PreToolUse, "Bash"),+ obs(ObservationKind::PostToolUse, "Bash"),+ obs(ObservationKind::PreToolUse, "Bash"),+ obs(ObservationKind::PostToolUse, "Bash"),+ obs(ObservationKind::PreToolUse, "Edit"),+ obs(ObservationKind::PostToolUse, "Edit"),+ obs_at(+ ObservationKind::SessionEnd,+ "session",+ "2026-08-24T10:18:00Z",+ ),+ ];+ assert_eq!(+ session_summary(&tally_session(&observations)),+ "2 prompts, 3 completed tool calls across Bash and Edit, over 18m."+ );+ }++ #[test]+ fn the_summary_is_shaped_so_the_reader_does_not_drop_it() {+ // The store prefers `summary` over the body and then runs it through+ // the same line filter it applies to a body: headings, `- **key:**+ // value` metadata bullets, and lines repeating the title are all+ // dropped, and when nothing survives it echoes its raw input. A+ // summary shaped like the metadata block this very module renders+ // would therefore be reproduced verbatim as the descriptor, in place+ // of body text that would have been usable. Assert the shape that+ // keeps that from happening.+ let observations = vec![+ obs_at(+ ObservationKind::SessionStart,+ "session",+ "2026-08-24T10:00:00Z",+ ),+ obs(ObservationKind::UserPrompt, "bound the scheduler queue"),+ obs(ObservationKind::PostToolUse, "Bash"),+ obs_at(+ ObservationKind::SessionEnd,+ "session",+ "2026-08-24T10:05:00Z",+ ),+ ];+ let summary = session_summary(&tally_session(&observations));++ assert!(!summary.contains('\n'), "must stay one line: {summary:?}");+ assert!(+ !summary.starts_with('#')+ && !summary.starts_with("---")+ && !summary.starts_with("___")+ && !summary.starts_with("***"),+ "must not read as a structural line: {summary:?}"+ );+ assert!(+ !(summary.starts_with("- **") && summary.contains(":**")),+ "must not read as a metadata bullet: {summary:?}"+ );+ assert!(+ !summary.starts_with("- ") && !summary.starts_with("* ") && !summary.starts_with("+ "),+ "must not open with a list marker: {summary:?}"+ );+ assert_ne!(+ summary,+ derive_title(&observations),+ "a summary equal to the title is dropped as a repeat"+ );+ }++ #[test]+ fn a_session_with_nothing_to_report_gets_no_summary() {+ // An empty summary must stay out of the frontmatter entirely: a blank+ // one still wins the store's COALESCE and would cost the page its+ // body-derived descriptor.+ // Fixed, equal timestamps: `obs` stamps `Timestamp::now()`, so two+ // calls straddling a second boundary would make this a session that+ // lasted `1s` and give it a summary after all.+ let lifecycle_only = vec![+ obs_at(+ ObservationKind::SessionStart,+ "session-start",+ "2026-08-24T10:00:00Z",+ ),+ obs_at(+ ObservationKind::SessionEnd,+ "session-end",+ "2026-08-24T10:00:00Z",+ ),+ ];+ assert_eq!(session_summary(&tally_session(&lifecycle_only)), "");++ let page = synthesize_session_page(+ WorkspaceId::new(),+ ProjectId::new(),+ SessionId::new(),+ &lifecycle_only,+ );+ assert!(page.frontmatter_json.get("summary").is_none());+ }++ #[test]+ fn the_synthesised_page_carries_the_summary() {+ let observations = vec![+ obs_at(+ ObservationKind::SessionStart,+ "session",+ "2026-08-24T10:00:00Z",+ ),+ obs(ObservationKind::UserPrompt, "bound the scheduler queue"),+ obs(ObservationKind::PostToolUse, "Bash"),+ obs_at(+ ObservationKind::SessionEnd,+ "session",+ "2026-08-24T10:05:00Z",+ ),+ ];+ let page = synthesize_session_page(+ WorkspaceId::new(),+ ProjectId::new(),+ SessionId::new(),+ &observations,+ );+ assert_eq!(+ page.frontmatter_json["summary"],+ serde_json::json!("1 prompt, 1 completed tool call across Bash, over 5m.")+ );+ }++ #[test]+ fn many_tools_are_named_by_volume_then_counted() {+ let mut observations = vec![obs(ObservationKind::UserPrompt, "do the thing")];+ for (tool, calls) in [+ ("Bash", 5),+ ("Edit", 4),+ ("Read", 3),+ ("Grep", 2),+ ("Glob", 1),+ ] {+ for _ in 0..calls {+ observations.push(obs(ObservationKind::PostToolUse, tool));+ }+ }+ assert_eq!(+ session_summary(&tally_session(&observations)),+ "1 prompt, 15 completed tool calls across Bash, Edit and Read and 2 more."+ );+ }+#[test]fn title_falls_back_through_kinds() {let no_prompt = vec![obs(ObservationKind::PostToolUse, "Edit")];diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex b5b3adb5..d55163df 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -2526,6 +2526,88 @@ mod tests {);}+ /// The body a session page is synthesised with, minus the frontmatter.+ /// Written out in full because the point of the test below is what a+ /// reader can learn from this page *without* opening it.+ const SESSION_BODY: &str = concat!(+ "# Bound the scheduler queue\n",+ "\n",+ "## Session metadata\n",+ "\n",+ "- **session_id:** `9f2c1d0e`\n",+ "- **started_at:** 2026-08-24T10:00:00Z\n",+ "- **ended_at:** 2026-08-24T10:18:00Z\n",+ "- **observations:** 41\n",+ "\n",+ "## Prompts\n",+ "\n",+ "1. Bound the scheduler queue\n",+ "2. Make the backpressure test deterministic\n",+ );++ #[tokio::test]+ async fn a_written_summary_changes_what_the_descriptor_tells_the_reader() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "ai-memory", None)+ .await+ .unwrap();++ // Same page twice. The only difference is that one was written by a+ // path that fills `summary` and the other by one that does not.+ let mut without = sample_page(ws, proj, "without-summary.md", SESSION_BODY);+ without.title = "Bound the scheduler queue".into();+ store.writer.upsert_page(without).await.unwrap();++ let mut with = sample_page(ws, proj, "with-summary.md", SESSION_BODY);+ with.title = "Bound the scheduler queue".into();+ with.frontmatter_json = serde_json::json!({+ "summary": "2 prompts, 34 completed tool calls across Bash, Edit and Read, over 18m.",+ });+ store.writer.upsert_page(with).await.unwrap();++ let hits = store+ .reader+ .recent_pages_for_project(ws, proj, 10)+ .await+ .unwrap();+ let descriptor = |path: &str| {+ hits.iter()+ .find(|h| h.path.as_str() == path)+ .map(|h| h.snippet.clone())+ .unwrap_or_else(|| panic!("{path} should be listed"))+ };+ let without = descriptor("without-summary.md");+ let with = descriptor("with-summary.md");++ assert_ne!(without, with);++ // Without a summary the descriptor is the best the body affords: the+ // prompts after the first, since the first repeats the title. That is+ // real signal, and it is what #463 already delivers.+ assert!(+ without.contains("Make the backpressure test deterministic"),+ "body-derived descriptor should reach the prompts: {without:?}"+ );+ // What it cannot say is how much work the session was. Those counts+ // exist only at write time, and the summary is what carries them.+ assert!(+ !without.contains("34 completed tool calls"),+ "the body never states the totals: {without:?}"+ );+ assert!(+ with.contains("2 prompts") && with.contains("34 completed tool calls"),+ "summary-derived descriptor should state the session's shape: {with:?}"+ );+ }+#[tokio::test]async fn frontmatter_summary_wins_over_the_body_lede() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 1e962fa0..b67ebe2d 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -7727,6 +7727,24 @@ mod tests {};use crate::Store;+ #[test]+ fn a_metadata_styled_descriptor_source_is_echoed_verbatim() {+ // Every line here is a metadata bullet, so all of them are skipped+ // and nothing accumulates. The fallback then echoes the raw input —+ // the result is not empty, it is the unusable input reproduced whole.+ //+ // This is the failure mode for a writer that fills frontmatter+ // `summary` in the same house style it renders a session page's+ // metadata block in. Because `summary` wins the COALESCE, such a+ // page trades a usable body-derived descriptor for this, and nothing+ // anywhere reports an error. Writers must emit plain prose.+ let metadata_styled = "- **session_id:** `9f2c`\n- **observations:** 2";+ assert_eq!(+ page_descriptor(metadata_styled, "Some title"),+ metadata_styled+ );+ }+use ai_memory_core::{AgentKind, Handoff, HandoffContent, HandoffId, HandoffLifecycle, HandoffOrigin,HandoffScope, HandoffState, NewHandoff, NewSession, OwnerFilter, ProjectId, SessionId,