Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(retrieval): trim the observation excerpt a hit carries
AkitaOnRails101268bdd870
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 56c57e3a..2a10be86 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,8 +16,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0flag on, project and `scopes` searches also run full-text search overobservations in the same project, and each matching session votes once,through its best-matching observation, for its own latest- `sessions/<id>.md` page as one more RRF stream. The matching excerpt becomes- the hit's snippet when it ranks ahead of the page's own match, and+ `sessions/<id>.md` page as one more RRF stream. When page search did not+ match the page itself, the matching excerpt becomes the hit's snippet, and`explain=true` reports an `observation` stream with the matched observationids. Hits are still pages and nothing is written; sessions without a pagekeep the `raw_hits` fallback, and `global=true` search is unchanged.diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 0847e5df..19be1259 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -338,6 +338,11 @@ const OBSERVATION_STREAM_ROWS_PER_CANDIDATE: usize = 4;const OBSERVATION_STREAM_MAX_ROWS: usize = 1_000;/// Matched observation ids reported per page in `explain`.const OBSERVATION_STREAM_IDS_PER_PAGE: usize = 3;+/// Token window of the observation excerpt shown as a hit's snippet. Session+/// pages are short, so their own FTS snippets rarely fill the 24-token page+/// window; an observation body usually does, and a full window made each+/// excerpt-backed hit cost more context than the page hit it stands in for.+const OBSERVATION_SNIPPET_TOKENS: usize = 16;#[derive(Debug, Clone, Copy)]struct PageAuthority {@@ -2859,9 +2864,10 @@ impl ReaderPool {// CROSS JOIN pins the FTS table as the outer loop: left to// itself the planner drives from the observations scope index// and re-enters FTS once per row, which is far slower.- let mut stmt = tx.prepare(+ let mut stmt = tx.prepare(&format!("SELECT observations.id, observations.session_id, \- snippet(observations_fts, 1, '<mark>', '</mark>', '…', 24) \+ snippet(observations_fts, 1, '<mark>', '</mark>', '…', \+ {OBSERVATION_SNIPPET_TOKENS}) \FROM observations_fts \CROSS JOIN observations ON observations.rowid = observations_fts.rowid \WHERE observations_fts MATCH ?1 \@@ -2871,7 +2877,7 @@ impl ReaderPool {AND observations.project_id = ?3 \ORDER BY observations_fts.rank \LIMIT ?4",- )?;+ ))?;#[allow(clippy::cast_possible_wrap)]let rows = stmt.query_map(params![@@ -5945,10 +5951,11 @@ impl ReaderPool {snippet: String,score: f64,explain: Option<SearchExplain>,- /// 1-based FTS rank, kept to decide whose snippet explains the hit.- fts_rank: Option<usize>,- /// Observation-stream rank and the matching observation's snippet.- observation: Option<(usize, String)>,+ /// Whether page FTS matched this page, which decides whose+ /// snippet explains the hit.+ fts_matched: bool,+ /// The best matching observation's excerpt (observation stream).+ observation_snippet: Option<String>,}let mut fused: std::collections::HashMap<PageId, Fused> = std::collections::HashMap::new();@@ -5960,11 +5967,11 @@ impl ReaderPool {snippet: h.snippet.clone(),score: 0.0,explain: explain.then(SearchExplain::default),- fts_rank: None,- observation: None,+ fts_matched: false,+ observation_snippet: None,});entry.score += contrib;- entry.fts_rank = Some(rank + 1);+ entry.fts_matched = true;if let Some(details) = &mut entry.explain {details.fts_rank = Some(rank + 1);details.fts_score = Some(h.rank);@@ -5980,8 +5987,8 @@ impl ReaderPool {snippet: String::new(),score: 0.0,explain: explain.then(SearchExplain::default),- fts_rank: None,- observation: None,+ fts_matched: false,+ observation_snippet: None,});entry.score += contrib;if let Some(details) = &mut entry.explain {@@ -5999,8 +6006,8 @@ impl ReaderPool {snippet: String::new(),score: 0.0,explain: explain.then(SearchExplain::default),- fts_rank: None,- observation: None,+ fts_matched: false,+ observation_snippet: None,});entry.score += contrib;if let Some(details) = &mut entry.explain {@@ -6018,8 +6025,8 @@ impl ReaderPool {snippet: e.hit.snippet.clone(),score: 0.0,explain: explain.then(SearchExplain::default),- fts_rank: None,- observation: None,+ fts_matched: false,+ observation_snippet: None,});entry.score += contrib;if let Some(details) = &mut entry.explain {@@ -6038,8 +6045,8 @@ impl ReaderPool {snippet: n.hit.snippet.clone(),score: 0.0,explain: explain.then(SearchExplain::default),- fts_rank: None,- observation: None,+ fts_matched: false,+ observation_snippet: None,});entry.score += contrib;if let Some(details) = &mut entry.explain {@@ -6066,14 +6073,14 @@ impl ReaderPool {snippet: String::new(),score: 0.0,explain: explain.then(SearchExplain::default),- fts_rank: None,- observation: None,+ fts_matched: false,+ observation_snippet: None,});entry.score += contrib;if entry.title.is_empty() {entry.title = vote.title;}- entry.observation = Some((rank + 1, vote.snippet));+ entry.observation_snippet = Some(vote.snippet);if let Some(details) = &mut entry.explain {details.observation_rank = Some(rank + 1);details.observation_ids = vote.observation_ids;@@ -6082,17 +6089,20 @@ impl ReaderPool {}}+ // Pages whose snippet is the observation excerpt; the descriptor fill+ // below must not overwrite it.+ let mut observation_excerpts: std::collections::HashSet<PageId> =+ std::collections::HashSet::new();let mut out: Vec<(PageHit, Option<SearchExplain>)> = fused.into_iter().map(|(id, entry)| {- // The matching observation's excerpt explains the hit when- // the observation stream ranked the page ahead of FTS (or FTS- // missed it); otherwise the page keeps its own snippet.- let snippet = match entry.observation {- Some((observation_rank, observation_snippet))- if entry.fts_rank.is_none_or(|fts| observation_rank < fts) =>- {- observation_snippet+ // A page FTS matched keeps its own snippet. The observation+ // excerpt stands in only when FTS missed the page, so the+ // hit still shows the text that matched.+ let snippet = match entry.observation_snippet {+ Some(excerpt) if !entry.fts_matched => {+ observation_excerpts.insert(id);+ excerpt}_ => entry.snippet,};@@ -6125,7 +6135,9 @@ impl ReaderPool {for (hit, _) in &mut out {if let Some((title, descriptor)) = descriptors.get(&hit.id) {hit.title = title.clone();- hit.snippet = descriptor.clone();+ if !observation_excerpts.contains(&hit.id) {+ hit.snippet = descriptor.clone();+ }}}}diff --git a/crates/ai-memory-store/tests/suite/retrieval_observation_stream.rs b/crates/ai-memory-store/tests/suite/retrieval_observation_stream.rsindex 3f66cdda..5931e6be 100644--- a/crates/ai-memory-store/tests/suite/retrieval_observation_stream.rs+++ b/crates/ai-memory-store/tests/suite/retrieval_observation_stream.rs@@ -381,3 +381,65 @@ async fn stream_off_ranks_byte_identically_to_a_store_without_observations() {}}}++/// A session page with an empty title is still described by the page+/// descriptor fill, but that fill must not replace the observation excerpt+/// that explains why the page surfaced.+#[tokio::test]+async fn an_untitled_session_page_keeps_the_observation_excerpt() {+ let tmp = tempfile::tempdir().unwrap();+ let mut store = Store::open(tmp.path()).unwrap();+ store.reader.set_retrieval_tuning(stream_on());+ let (ws, proj) = scope(&store, "default", "app").await;+ let sid = session(&store, ws, proj).await;+ let mut untitled = page(ws, proj, &format!("sessions/{sid}.md"), "short excerpt");+ untitled.title = String::new();+ store.writer.upsert_page(untitled).await.unwrap();+ observe(&store, ws, proj, sid, "the heron nested by the old mill").await;++ let hits = search(&store, ws, proj, "heron").await;+ assert_eq!(hits.len(), 1);+ assert!(+ hits[0].0.snippet.contains("<mark>heron</mark>"),+ "{}",+ hits[0].0.snippet+ );+}++/// When page FTS matched the session page itself, the page keeps its own+/// snippet; the observation excerpt stands in only for a page FTS missed.+#[tokio::test]+async fn a_page_fts_matched_keeps_its_own_snippet() {+ let tmp = tempfile::tempdir().unwrap();+ let mut store = Store::open(tmp.path()).unwrap();+ store.reader.set_retrieval_tuning(stream_on());+ let (ws, proj) = scope(&store, "default", "app").await;+ let sid = session(&store, ws, proj).await;+ session_page(&store, ws, proj, sid, "User mentioned the puffin colony.").await;+ // A denser page takes FTS rank 1, so the session page's observation vote+ // (stream rank 1) outranks its own FTS match (rank 2).+ store+ .writer+ .upsert_page(page(ws, proj, "notes/puffins.md", "puffin puffin puffin"))+ .await+ .unwrap();+ observe(+ &store,+ ws,+ proj,+ sid,+ "a long assistant reply about the puffin colony and its nesting season",+ )+ .await;++ let hits = search(&store, ws, proj, "puffin").await;+ let session_path = format!("sessions/{sid}.md");+ let (hit, details) = hits+ .iter()+ .find(|(h, _)| h.path.as_str() == session_path)+ .unwrap();+ assert_eq!(details.fts_rank, Some(2));+ assert_eq!(details.observation_rank, Some(1));+ assert!(hit.snippet.contains("colony"), "{}", hit.snippet);+ assert!(!hit.snippet.contains("assistant"), "{}", hit.snippet);+}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex b407a5a0..17f47322 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -996,9 +996,10 @@ belief_authority_weight = 0.0 # fold read-time belief-strength confidence (Pobservation_stream = false # R1 observation-evidence stream: FTS over observations_fts# in the queried project; each matching session votes ONCE# (best observation) for its own latest sessions/<id>.md- # page as one more RRF stream. Its excerpt may become the- # snippet; explain reports `observation_rank` +- # `observation_ids`. Read-only; sessions without a page keep+ # page as one more RRF stream. Its excerpt is the snippet+ # only when page FTS missed that page; explain reports+ # `observation_rank` + `observation_ids`. Read-only;+ # sessions without a page keep# the raw_hits fallback; global=true unchanged. DEFAULT OFF.# Env: AI_MEMORY_RETRIEVAL__OBSERVATION_STREAM=true