Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): show a body shorter than its excerpt whole in the brief (#1360)
Victor Alencar09eeddd8583f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 59954396..d8e287ec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,16 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]+### Fixed+- Fixed the session-start brief hiding a page's body behind a longer+ frontmatter excerpt. When a pinned, `_rules/` or `_slots/` page had a+ `summary:` or `abstract:` longer than its body, the brief printed that+ excerpt instead of the body, however much of `[briefing] max_chars` was+ left, so a small wiki whose pages fit did not get every body whole. Such a+ body now shows whole: it is priced at its own size when the brief decides+ which pages fit, and the bytes it saves over the excerpt go to other pages.+ A page with an empty body keeps its excerpt. (#1360)+## [3.1.0] - 2026-10-16### Addeddiff --git a/crates/ai-memory-hooks/src/brief_tiers.rs b/crates/ai-memory-hooks/src/brief_tiers.rsindex 830ff1c3..c6ae755e 100644--- a/crates/ai-memory-hooks/src/brief_tiers.rs+++ b/crates/ai-memory-hooks/src/brief_tiers.rs@@ -119,10 +119,12 @@ pub(crate) fn assign_tiers(let mut spent = budget.prefix;let mut omitted_from = pages.len();for (idx, page) in pages.iter().enumerate() {- let tier = if page.tiers.is_some() {- BriefTier::L0- } else {- BriefTier::TitleOnly+ let tier = match page.tiers {+ // A body cheaper than its excerpt is covered whole, at its own+ // cost, instead of crowding later pages out at the excerpt's.+ Some([l0, _, l2]) if l2 < l0 => BriefTier::L2,+ Some(_) => BriefTier::L0,+ None => BriefTier::TitleOnly,};let cost = page.cost(tier);if spent + cost > coverage_ceiling {@@ -159,10 +161,31 @@ pub(crate) fn assign_tiers(_ => None,}};+ // A frontmatter excerpt can be longer than the body it describes+ // (#1360). Showing that body whole then costs less than the excerpt, so+ // the swap is free and returns the difference to the room.+ let saving = |tiers: &[BriefTier], idx: usize, target: BriefTier| {+ let page = &pages[idx];+ match (page.tiers, tiers[idx]) {+ (Some(_), current)+ if target == BriefTier::L2+ && current != BriefTier::TitleOnly+ && current < target =>+ {+ page.cost(current)+ .checked_sub(page.cost(target))+ .filter(|s| *s > 0)+ }+ _ => None,+ }+ };let mut promote =|tiers: &mut [BriefTier], order: &[usize], target: BriefTier, max_delta: usize| {for &idx in order {- if let Some(d) = delta(tiers, idx, target)+ if let Some(s) = saving(tiers, idx, target) {+ tiers[idx] = target;+ room += s;+ } else if let Some(d) = delta(tiers, idx, target)&& d <= room.min(max_delta){tiers[idx] = target;@@ -299,6 +322,45 @@ mod tests {assert_eq!(plan.omitted_from, 3);}+ #[test]+ fn a_body_cheaper_than_its_excerpt_shows_whole() {+ // A frontmatter `summary:` or `abstract:` can be longer than the body+ // it describes (#1360). The body then costs less than the excerpt the+ // page shows: less than its L0 (the first three), or only less than+ // the L1 a short `abstract:` makes way for (the last two).+ let pages = [+ page(true, 256, 500, 120),+ page(false, 256, 500, 120),+ page(false, 300, 300, 200),+ page(true, 100, 500, 200),+ page(false, 100, 500, 200),+ ];+ let plan = assign(&pages, 4_000, 0);+ assert_eq!(plan.tiers, vec![L2; 5]);+ }++ #[test]+ fn the_bytes_a_cheaper_body_saves_go_to_other_pages() {+ // After coverage, 400 bytes are left. The first page takes its+ // 500-byte L1 (all 400), then swaps it for its 150-byte body, which+ // frees 350. That pays for the second page's body (250 more than its+ // excerpt), which no longer fits without the refund.+ let pages = [page(true, 100, 500, 150), page(true, 100, 100, 350)];+ let plan = assign(&pages, 100 + 200 + 400, 0);+ assert_eq!(plan.tiers, vec![L2, L2]);+ assert!(100 + spent(&pages, &plan) <= 700, "{plan:?}");+ }++ #[test]+ fn a_body_cheaper_than_its_excerpt_is_covered_at_its_own_cost() {+ // Ten 300-byte excerpts do not fit; ten 50-byte bodies do. Priced at+ // the excerpt, most of these pages would be omitted.+ let pages = vec![page(false, 300, 300, 50); 10];+ let plan = assign(&pages, 100 + 1_000 + COUNT_ONLY, 0);+ assert_eq!(plan.omitted_from, 10, "{plan:?}");+ assert_eq!(plan.tiers, vec![L2; 10]);+ }+#[test]fn zero_delta_and_title_only_pages_do_not_block_bodies() {let pages = [@@ -396,11 +458,14 @@ mod tests {fn random_page(rng: &mut Rng) -> PageCosts {let l0 = 20 + rng.below(320);let l1 = l0 + [0, rng.below(300)][rng.below(2)];+ // The last choice is a body shorter than its excerpt, which a long+ // frontmatter `summary:` or `abstract:` produces (#1360).let l2 = [l1,l1 + rng.below(SHORT_BODY_SLACK * 2),l1 + rng.below(20_000),- ][rng.below(3)];+ 1 + rng.below(l1),+ ][rng.below(4)];PageCosts {privileged: rng.below(4) == 0,title_only: 10 + rng.below(60),@@ -469,6 +534,15 @@ mod tests {}}}+ // A covered page never shows an excerpt that costs more than+ // its whole body.+ for (page, tier) in pages.iter().zip(&p.tiers) {+ if let Some([_, _, l2]) = page.tiers+ && matches!(tier, L0 | L1)+ {+ assert!(page.cost(*tier) <= l2, "{ctx}");+ }+ }// More budget never covers fewer pages.let wider = plan(&pages, ceiling + 1 + rng.below(4_000), recent_full);assert!(diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex fd834892..b84a3095 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -2418,6 +2418,14 @@ impl<'a> BriefCandidate<'a> {fn costs(&self) -> brief_tiers::PageCosts {use brief_tiers::BriefTier::{L0, L1, TitleOnly};let with_heading = |text_len: usize| self.heading.len() + text_len + 1;+ // An empty body has nothing to show whole. Priced like a body too+ // long to keep, it can never replace the page's frontmatter excerpt+ // with an empty section.+ let l2 = if self.body_len == 0 {+ usize::MAX+ } else {+ with_heading(self.body_len)+ };brief_tiers::PageCosts {privileged: self.privileged(),title_only: self.section(TitleOnly).len(),@@ -2425,7 +2433,7 @@ impl<'a> BriefCandidate<'a> {[with_heading(self.text(L0).len()),with_heading(self.text(L1).len()),- with_heading(self.body_len),+ l2,]}),}@@ -16820,6 +16828,52 @@ pub(crate) mod tests {}}+ /// #1360: a frontmatter excerpt longer than the body it describes no+ /// longer stands in for that body. The body costs less, so it shows+ /// whole, pinned or not. A page with no body keeps its excerpt rather+ /// than an empty section.+ #[test]+ fn render_session_brief_shows_a_body_shorter_than_its_excerpt() {+ let summary = "Current focus of the team for this release cycle, kept as a \+ slot so every agent sees it at session start.";+ let abstract_ = "Style rules for runtime code, the error types to use at \+ each layer, and where panics are still acceptable.";+ let core = vec![+ brief_core_page(+ "_slots/focus.md",+ "# Focus\n\nShipping the release. Keep main green.",+ true,+ serde_json::json!({"summary": summary}),+ ),+ brief_core_page(+ "_rules/empty.md",+ "",+ false,+ serde_json::json!({"summary": "An empty body keeps this summary."}),+ ),+ brief_core_page(+ "_rules/style.md",+ "No unwrap in runtime code.",+ false,+ serde_json::json!({"abstract": abstract_}),+ ),+ ];+ let out = render_session_brief(&core, &[], BRIEF_BUDGET_DEFAULT).unwrap();+ for page in [&core[0], &core[2]] {+ assert!(+ out.contains(&format!("(`{}`)\n{}\n", page.path, page.body.trim())),+ "{} must render whole: {out}",+ page.path+ );+ }+ assert!(!out.contains(summary), "{out}");+ assert!(!out.contains(abstract_), "{out}");+ assert!(+ out.contains("(`_rules/empty.md`)\nAn empty body keeps this summary.\n"),+ "{out}"+ );+ }+/// A crowded family of unprivileged pages left at their excerpt is/// listed under one heading; pinned or deepened siblings keep their own,/// and a small family is not worth an index.@@ -16901,9 +16955,11 @@ pub(crate) mod tests {fn render_session_brief_reports_omitted_pages_under_max_size_excerpts() {let core: Vec<_> = (0..BRIEF_CORE_PAGES_LIMIT).map(|i| {+ // The body must outweigh the abstract: a cheaper body would+ // be covered whole instead of as this max-size excerpt.brief_core_page(&format!("_rules/standing-rule-{i:02}.md"),- "body",+ &"body ".repeat(200),false,serde_json::json!({"abstract": format!("{i:02} {}", "a".repeat(400))}),)@@ -16926,9 +16982,11 @@ pub(crate) mod tests {fn render_session_brief_keeps_the_omitted_count_under_escaped_excerpts() {let core: Vec<_> = (0..BRIEF_CORE_PAGES_LIMIT).map(|i| {+ // A body longer than the escaped excerpt, so the excerpt is+ // what renders and gets priced.brief_core_page(&format!("_rules/hostile-{i:02}.md"),- "body",+ &"body ".repeat(200),false,serde_json::json!({"abstract": UNTRUSTED_HISTORY_END.repeat(10)}),)diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex b5291550..c5e4235e 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -259,6 +259,8 @@ 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, other bodies cheapest first (`ai_memory_hooks::brief_tiers`). A body is included whole or not at all.+A body shorter than the frontmatter excerpt it would replace always shows+whole, priced at its own size.Four or more unpinned excerpts of one family share a heading. Pages that do notfit are listed by path for `memory_read_page`, and the count of them isreserved before any page is deepened. The security notice, thediff --git a/docs/design-tiered-session-brief.md b/docs/design-tiered-session-brief.mdindex 4159e243..13c89714 100644--- a/docs/design-tiered-session-brief.md+++ b/docs/design-tiered-session-brief.md@@ -562,7 +562,10 @@ first call" policy after coverage without eating the recent share.1. **L0 coverage.** Walk `core` in store order (`pinned DESC, path ASC`).For each page, compute L0 text. If `l0` is `None`, the candidate is- a TitleOnly path line. Greedy-fit against+ a TitleOnly path line. A non-empty body that costs less than its L0+ (a frontmatter `abstract:` or `summary:` can be longer than the body+ it describes) is covered at L2 instead, at its own cost (#1360).+ Greedy-fit against`l0_ceiling = content_ceiling - recent_cap - count_only_floor`(a candidate fits when `l0_spent + cost(candidate) <= l0_ceiling`).If the candidate does not fit, stop. Every later page is `Omitted`.@@ -584,7 +587,9 @@ first call" policy after coverage without eating the recent share.3. **Privileged L2.** For included privileged pages, in order: upgradeto full `body.trim()` only when the *entire* L2 fits. Do nottruncate an L2 in this pass. Truncation of one body is what starves- later pages today. If L2 does not fit, the page stays at L1.+ later pages today. If L2 does not fit, the page stays at L1. A body+ cheaper than the L1 the page shows always fits: the swap is free and+ its saving returns to the remainder. This holds in (5) and (6) too.4. **Unprivileged L1.** Same as (2) for the remaining included pages.5. **Short bodies.** In store order, complete any unprivileged page whosewhole body is at most `SHORT_BODY_SLACK` (128) bytes more than what itdiff --git a/docs/marker-file.md b/docs/marker-file.mdindex 3392ad6d..4d69a44a 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -181,7 +181,7 @@ inject_on_session_start = "true"# 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, then the cheapest bodies. A body is shown whole or-# not at all.+# not at all, and a body shorter than its excerpt is always shown whole.# Four or more unpinned excerpts from one folder (`_rules/`, `gotchas/`,# `decisions/`, `procedures/`) share a heading. Pages the budget cannot# cover are listed by path so the agent can `memory_read_page` them,