Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(core): brief excerpts read leading prose across blocks
Victor Alencare00931e03176
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7f10e44f..ac9eeb40 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,7 +15,7 @@ version in [`docs/changelog/`](docs/changelog/):- Changed how the opt-in session-start brief (`[briefing]inject_on_session_start`) spends `max_chars`. Every pinned, `_rules/` and`_slots/` page now gets a short excerpt first, taken from its frontmatter- `abstract:` or `summary:` or else its first paragraph, and the budget left+ `abstract:` or `summary:` or else the prose it opens with, and the budget leftdeepens pages to a longer excerpt and then the whole body, pinned and`_slots/` pages first. Before, the brief printed whole bodies in order, so onelong `_rules/` page was cut with a `[truncated by ...]` note and every pagediff --git a/crates/ai-memory-core/src/excerpt.rs b/crates/ai-memory-core/src/excerpt.rsindex 4046ee6a..80a910bf 100644--- a/crates/ai-memory-core/src/excerpt.rs+++ b/crates/ai-memory-core/src/excerpt.rs@@ -7,8 +7,10 @@//!//! L0 prefers the frontmatter `abstract:` (the page's own one-line pointer),//! L1 prefers `summary:` (the longer operator summary). Both fall back to the-//! first paragraph of prose, which is the same walk A2 compaction uses for its-//! L1 line, plus the profile digest's skip of ADR metadata fields.+//! prose the page opens with, read across paragraphs and lists up to the clip,+//! skipping headings and the ADR metadata fields the profile digest skips. A+//! rules page often opens with a sentence about itself; reading on is what+//! puts its first rules in the excerpt.use crate::profile::is_metadata_field;use crate::sanitize::truncate_utf8_bytes;@@ -28,10 +30,10 @@ const COMPACTION_FOOTER_PREFIX: &str = "_Extractively compacted from a cold epis/// no frontmatter pointer and no prose to fall back on.#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct PageExcerpt {- /// Short pointer: `abstract`, else `summary`, else the first paragraph,+ /// Short pointer: `abstract`, else `summary`, else the leading prose,/// clipped to [`BRIEF_L0_MAX_BYTES`].pub l0: Option<String>,- /// Longer pointer: `summary`, else `abstract`, else the first paragraph,+ /// Longer pointer: `summary`, else `abstract`, else the leading prose,/// clipped to [`BRIEF_L1_MAX_BYTES`].pub l1: Option<String>,}@@ -42,7 +44,7 @@ pub struct PageExcerpt {pub fn excerpt_from_page(frontmatter: &serde_json::Value, body: &str) -> PageExcerpt {let abstract_ = frontmatter_nonempty(frontmatter, "abstract");let summary = frontmatter_nonempty(frontmatter, "summary");- let paragraph = || first_prose_paragraph(body);+ let paragraph = || leading_prose(body);let l0 = abstract_.or(summary).map(str::to_owned)@@ -56,30 +58,36 @@ pub fn excerpt_from_page(frontmatter: &serde_json::Value, body: &str) -> PageExcPageExcerpt { l0, l1 }}-/// The first paragraph of prose in `body`, whitespace collapsed to single-/// spaces. Within each blank-line-separated block, leading headings, lone-/// `---` rules and ADR metadata fields (`**Status:** Accepted`) are skipped;-/// a block with nothing left moves the walk on to the next one.+/// The prose `body` opens with, whitespace collapsed to single spaces and+/// read across paragraphs and list items. Headings, lone `---` rules and ADR+/// metadata fields (`**Status:** Accepted`) are skipped wherever they sit, and+/// so is the A2 compaction footer. Reading stops once there is more than the+/// longest clip can carry.#[must_use]-pub fn first_prose_paragraph(body: &str) -> Option<String> {- body.split("\n\n").find_map(|block| {- let trimmed = block.trim();- if trimmed.starts_with(COMPACTION_FOOTER_PREFIX) {- return None;+pub fn leading_prose(body: &str) -> Option<String> {+ let mut prose = String::new();+ for block in body.split("\n\n") {+ let block = block.trim();+ if block.starts_with(COMPACTION_FOOTER_PREFIX) {+ continue;}- let prose: Vec<&str> = trimmed- .lines()- .map(str::trim)- .skip_while(|line| {- line.is_empty()- || line.starts_with('#')- || *line == "---"- || is_metadata_field(line)- })- .collect();- let collapsed = collapse_whitespace(&prose.join(" "));- (!collapsed.is_empty()).then_some(collapsed)- })+ for line in block.lines().map(str::trim) {+ if line.is_empty() || line.starts_with('#') || line == "---" || is_metadata_field(line)+ {+ continue;+ }+ for word in line.split_whitespace() {+ if !prose.is_empty() {+ prose.push(' ');+ }+ prose.push_str(word);+ }+ if prose.len() > BRIEF_L1_MAX_BYTES {+ return Some(prose);+ }+ }+ }+ (!prose.is_empty()).then_some(prose)}/// A frontmatter string value, trimmed, or `None` when the key is absent,@@ -198,7 +206,45 @@ mod tests {json!({}),"First line\n wraps here.\n\nSecond paragraph.",);- assert_eq!(e.l0.as_deref(), Some("First line wraps here."));+ assert_eq!(+ e.l0.as_deref(),+ Some("First line wraps here. Second paragraph.")+ );+ }++ #[test]+ fn rules_after_a_preface_reach_the_excerpt() {+ // A rules page that opens with a sentence about itself: the rules+ // are what an agent needs, so the excerpt runs on into the list.+ let body = "# Security\n\nThis page collects the security rules.\n\n\+ - NEVER commit secrets to git\n- Rotate tokens monthly\n";+ let e = excerpt(json!({}), body);+ assert_eq!(+ e.l0.as_deref(),+ Some(+ "This page collects the security rules. \+ - NEVER commit secrets to git - Rotate tokens monthly"+ )+ );+ }++ #[test]+ fn headings_and_metadata_inside_the_page_are_not_prose() {+ let body = "Intro sentence.\n\n## Rules\n\n**Status:** Accepted\n- keep it boring";+ let e = excerpt(json!({}), body);+ assert_eq!(e.l0.as_deref(), Some("Intro sentence. - keep it boring"));+ }++ #[test]+ fn l1_carries_more_of_a_long_page_than_l0() {+ let body = (0..60)+ .map(|i| format!("Sentence number {i}."))+ .collect::<Vec<_>>()+ .join("\n\n");+ let e = excerpt(json!({}), &body);+ let (l0, l1) = (e.l0.unwrap(), e.l1.unwrap());+ assert!(l1.len() > l0.len() + 200, "L1 must add depth: {l0} / {l1}");+ assert!(l1.starts_with(l0.trim_end_matches('…')));}#[test]@@ -243,9 +289,10 @@ mod tests {"The writer actor owns every SQLite write.\n\n## Retained facts\n\n- `WriterHandle`\n\n{footer_only}");let e = excerpt(json!({"compacted": true}), &compacted);+ // The retained facts are prose to the excerpt; the footer is not.assert_eq!(e.l0.as_deref(),- Some("The writer actor owns every SQLite write.")+ Some("The writer actor owns every SQLite write. - `WriterHandle`"));}}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex fb99d671..5311f665 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -224,7 +224,8 @@ from hook paths.project's pinned, `_rules/` and `_slots/` pages, packed into `[briefing]max_chars` (clamped to 1500-20000) with no LLM call. Every page first gets anextractive L0 excerpt (`ai_memory_core::excerpt`: frontmatter `abstract`, else-`summary`, else the first prose paragraph, 256 bytes); the bytes left deepen+`summary`, else the leading prose read across paragraphs and lists, 256+bytes); the bytes left deepenpages to an L1 excerpt (`summary` first, 500 bytes, the same clip as A2compaction) and then to the whole body, pinned and `_slots/` pages before therest (`ai_memory_hooks::brief_tiers`). A body is included whole or not at all.diff --git a/docs/design-tiered-session-brief.md b/docs/design-tiered-session-brief.mdindex c3894246..1ae89e4c 100644--- a/docs/design-tiered-session-brief.md+++ b/docs/design-tiered-session-brief.md@@ -278,10 +278,10 @@ Restated from `AGENTS.md` because they bound the packing:## Key Decisions1. **L0/L1 extractive source and clips.** L0: frontmatter `abstract:` if- nonempty, else `summary:` if nonempty, else first prose paragraph,+ nonempty, else `summary:` if nonempty, else the leading prose,clipped to **256 UTF-8 bytes** with `truncate_utf8_bytes` (ellipsis- inside the cap). L1: `summary:` then `abstract:` then first prose- paragraph, clipped to **500 UTF-8 bytes**, matching A2+ inside the cap). L1: `summary:` then `abstract:` then the leading+ prose, clipped to **500 UTF-8 bytes**, matching A2`MAX_SUMMARY_LEN`. Do not raise `MAX_PAGE_ABSTRACT_LEN`. Brief-sideclip only. L2: current `pages.body` (already frontmatter-stripped).Rationale: OpenViking L0 is the abstract; the operator `summary:` is@@ -383,7 +383,7 @@ pub fn excerpt_from_page(body: &str,) -> PageExcerpt { /* … */ }-pub fn first_prose_paragraph(body: &str) -> Option<String> { /* … */ }+pub fn leading_prose(body: &str) -> Option<String> { /* … */ }pub fn frontmatter_nonempty<'a>(frontmatter: &'a serde_json::Value,@@ -392,19 +392,22 @@ pub fn frontmatter_nonempty<'a>(```**L0:** `abstract` if nonempty, else `summary` if nonempty, else-`first_prose_paragraph(body)`. Clip with `truncate_utf8_bytes(..., 256)`.+`leading_prose(body)`. Clip with `truncate_utf8_bytes(..., 256)`.**L1:** `summary` if nonempty, else `abstract` if nonempty, else-`first_prose_paragraph(body)`. Clip with `truncate_utf8_bytes(..., 500)`.--`first_prose_paragraph` walks every `\n\n` block, like A2 `summary_line`-(`compaction.rs` ~79-89). Inside a block it skips *leading* lines that-are `#` headings, a lone `---`, or `is_metadata_field` (already `pub` in-`profile.rs`; call it, do not relocate `ADR_METADATA_LABELS`). Collapse-the remainder the way A2 already does (`split_whitespace` joined by-spaces). If that remainder is empty, **continue to the next block**.-The first nonempty remainder is the excerpt: `# Title\n\nUse nextest.`-yields `Use nextest.`+`leading_prose(body)`. Clip with `truncate_utf8_bytes(..., 500)`.++`leading_prose` walks every `\n\n` block, like A2 `summary_line`+(`compaction.rs` ~79-89), and keeps reading across blocks until it has+more than the L1 clip can carry. It skips every line that is a `#`+heading, a lone `---`, or `is_metadata_field` (already `pub` in+`profile.rs`; call it, do not relocate `ADR_METADATA_LABELS`), wherever+it sits, and collapses the rest the way A2 already does+(`split_whitespace` joined by spaces). `# Title\n\nUse nextest.` yields+`Use nextest.`. An earlier draft stopped at the first paragraph; the+risk review found rules pages that open with a sentence about+themselves ("This page collects the security rules.") and lost every+rule after it, so the walk reads on into lists.Also skip a block whose trimmed text starts with`_Extractively compacted from a cold episodic page` (the A2 footer@@ -444,7 +447,8 @@ body, so a compacted page needs no flag for nonempty L0/L1. A2 left `abstract:`frontmatter and put the L1 line at the top of the body, thenkeep-tokens, then `COMPACTION_FOOTER`. Typical result: L0 from abstract(or summary, or the L1 line clipped to 256), L1 from-summary/abstract/first paragraph (the A2 line), L2 the whole compacted+summary/abstract/leading prose (the A2 line, then the retained facts),+L2 the whole compactedbody including keep-tokens. Promoting to L2 is how keep-tokens reachthe agent. Never treat a compacted page as "skip extraction" (that ishow a page becomes an empty section).@@ -997,7 +1001,7 @@ existing three):at least the count-only omitted line, and still fit the budget.- Extractive fallbacks: abstract present (L0 uses it even when summaryexists); summary present and abstract absent (L0 and L1 both use- summary; zero-delta if it is ≤256 bytes); neither (first paragraph);+ summary; zero-delta if it is ≤256 bytes); neither (leading prose);empty / whitespace abstract and summary do not inject blank sections.- Compacted A2 body (L1 line + keep-tokens + footer, `compacted: true`)still yields nonempty L0/L1 and, when promoted to L2, still contains@@ -1113,7 +1117,7 @@ Released CHANGELOG sections stay frozen.| Agents that relied on a full first `_rules/` page now see its L0/L1 | Medium | Pin that page (privileged L2). Raise `max_chars`. Footer names `memory_read_page`. Small wikis still L2-fit. || L0 of 256 × 24 plus headings still omits a tail at 4000 bytes | Medium | Expected as coverage math. After the L0 pass, reserve at least the count-only omitted line so those standing rules still appear as a count. Test at `BRIEF_BUDGET_DEFAULT` with 24 max-size L0s. Typical abstracts are <120 bytes (~15-20 pages). Raising the 24-row fetch limit is a follow-up. || Denser brief = more injection surface | Medium | Fence, notice, footer, escape, clamp unchanged. Abstracts are short. |-| Extractive first paragraph is a useless heading-like sentence | Low | Skip `#` headings and ADR metadata. Operators can set `abstract:`. |+| Extractive leading prose is a useless heading-like sentence | Low | Skip `#` headings and ADR metadata. Operators can set `abstract:`. || A2 compacted page double-summarized to empty | High if shipped | Explicit test; extraction never skips a compacted page, and L2 carries its keep-tokens. || Footer growth breaks `BRIEF_BUDGET_MIN` | Low | Scaffold is 816 bytes today, leftover 684; +22 for `memory_read_page` leaves 662, still ≥500. Re-measure from `brief_scaffold_len()` in commit 4. || `BriefPageBody` struct-literal tests fail to compile | Low | commit 3 updates every literal (hooks tests around 6465 and 16216+). |@@ -1219,7 +1223,7 @@ Base: `release/3.1`.- **Dependencies:** commit 1.- **Description:** Pure helper: L0 256 (`abstract` then `summary` thenparagraph) / L1 500 (`summary` then `abstract` then paragraph),- `first_prose_paragraph` skipping leading metadata / `#` / `---` lines+ `leading_prose` skipping metadata / `#` / `---` linesinside a block via `is_metadata_field` and continuing to the next`\n\n` block when the remainder is empty (A2's loop). Tests for`# Title\n\nUse nextest.` and the `profile.rs` ~1066 ADR template.diff --git a/docs/marker-file.md b/docs/marker-file.mdindex a5c106b9..8cb2e3ef 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -178,7 +178,7 @@ inject_on_session_start = "true"# Optional. Char budget for the WHOLE brief (~4 chars per token), headers# and footers included. Every core page first gets a short excerpt (its-# frontmatter `abstract:` or `summary:`, else its first paragraph); what is+# frontmatter `abstract:` or `summary:`, else the prose it opens with); what is# left deepens pages to longer excerpts and then whole bodies, pinned and# `_slots/` pages first. A body is shown whole or not at all.# Four or more unpinned excerpts from one folder (`_rules/`, `gotchas/`,diff --git a/docs/research-2026-landscape.md b/docs/research-2026-landscape.mdindex 47cd09b6..6f3bd624 100644--- a/docs/research-2026-landscape.md+++ b/docs/research-2026-landscape.md@@ -847,7 +847,7 @@ summary + L2 keep-token shape for cold episodic pagesbrief* landed after 3.0([`design-tiered-session-brief.md`](design-tiered-session-brief.md)): everycore page gets an extractive L0 excerpt (`abstract:`, else `summary:`, else-the first paragraph), and the leftover budget buys L1 excerpts and whole+the prose it opens with), and the leftover budget buys L1 excerpts and wholebodies, pinned and `_slots/` pages first, with crowded `_rules/` excerptsunder one heading (Letta-code MemFS's directory deferral, done at rendertime). It needs no LLM, no new tool and no migration. Directory-scoped retrieval