Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(web): apply the search kind and tier filter inside every stream
Peterson Salme0a9140257118
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex de9acff3..0e50da46 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,13 +14,13 @@ and [0.x](docs/changelog/0.x.md).### Added- Added kind and tier filters to the web search. The search page in `/web`has "Kind" and "Tier" selects, and `/web/search` accepts `kind` and `tier`- for both a project search and a cross-project one. A filtered search looks- through up to 500 candidates per stream rather than the first page of- results and says so when the ranker had more, so a rare kind is not crowded- out. A project search filters inside the ranker, before the reranker, so- the reranker scores only pages the filter keeps. The kind match ignores- case and a nonstandard kind is flagged on an empty result. An unknown- `tier` is a 400. (#1248)+ for both a project search and a cross-project one. Every retrieval stream+ applies the filter in its own query, so other kinds cannot crowd out a rare+ one, a filtered search asks the streams for no more candidates than an+ unfiltered one, and the+ reranker scores only pages the filter keeps. Kind and tier both ignore+ case, a nonstandard kind is flagged on an empty result, and "Search all+ projects" keeps the filters. An unknown `tier` is a 400. (#1248)- Added backlinks, outgoing links and an outline to the web page view. A pagein `/web` now has a side column (below the text on narrow screens) with "Onthis page", the h2 and h3 headings linked to their anchors (shown from twodiff --git a/crates/ai-memory-core/src/page.rs b/crates/ai-memory-core/src/page.rsindex f6f7b576..516318d7 100644--- a/crates/ai-memory-core/src/page.rs+++ b/crates/ai-memory-core/src/page.rs@@ -606,6 +606,14 @@ pub struct Page {}impl Tier {+ /// Every tier, in declaration order.+ pub const ALL: [Self; 4] = [+ Self::Working,+ Self::Episodic,+ Self::Semantic,+ Self::Procedural,+ ];+/// Canonical short string for storage and serialisation.#[must_use]pub const fn as_str(&self) -> &'static str {@@ -881,6 +889,21 @@ mod tests {}}+ #[test]+ fn tier_all_lists_every_variant() {+ // An exhaustive match: a new variant fails to compile here until it is+ // added to `ALL`, which the web search's tier filter offers.+ for (index, tier) in Tier::ALL.into_iter().enumerate() {+ let expected = match tier {+ Tier::Working => 0,+ Tier::Episodic => 1,+ Tier::Semantic => 2,+ Tier::Procedural => 3,+ };+ assert_eq!(index, expected);+ }+ }+#[test]fn tier_rejects_unknown() {assert!("nope".parse::<Tier>().is_err());diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 39c48e3b..4295e7ec 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -2426,8 +2426,7 @@ impl AiMemoryServer {// the `expires_at > cutoff` guard, i.e. expired pages stay// searchable when the caller opted in.let expiry_cutoff = options.include_expired.then_some(i64::MIN);- let found = self- .reader+ self.reader.hybrid_search_scopes(scopes,ai_memory_store::HybridSearch {@@ -2441,8 +2440,7 @@ impl AiMemoryServer {filter: ai_memory_store::PageFilter::default(),},)- .await?;- Ok((found.hits, found.timings))+ .await}fn rerank_fetch_limit(&self, limit: usize) -> usize {@@ -2680,6 +2678,7 @@ impl AiMemoryServer {limit,include_expired.then_some(i64::MIN),Self::viewer_from_parts(Some(&parts)),+ ai_memory_store::PageFilter::default(),).await.map_err(|e| McpError::internal_error(e.to_string(), None))?;diff --git a/crates/ai-memory-store/src/grants.rs b/crates/ai-memory-store/src/grants.rsindex 448bff17..59791e64 100644--- a/crates/ai-memory-store/src/grants.rs+++ b/crates/ai-memory-store/src/grants.rs@@ -693,9 +693,15 @@ mod tests {|h| h.path.as_str(),),paths(- &r.search_pages_with_meta("rate".into(), 10, None, viewer)- .await- .unwrap(),+ &r.search_pages_with_meta(+ "rate".into(),+ 10,+ None,+ viewer,+ crate::PageFilter::default(),+ )+ .await+ .unwrap(),|h| h.path.as_str(),),paths(&r.recent_pages_global(10, viewer).await.unwrap(), |h| {@@ -796,7 +802,13 @@ mod tests {assert!(hits.iter().all(|h| h.path.as_str().starts_with("visible/")));let hits = r- .search_pages_with_meta("needle".into(), 10, None, Some(f.bob))+ .search_pages_with_meta(+ "needle".into(),+ 10,+ None,+ Some(f.bob),+ crate::PageFilter::default(),+ ).await.unwrap();assert_eq!(hits.len(), 10);diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 91304d16..41f313e4 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -85,18 +85,18 @@ pub use reader::{ActivityWindow, AgentSessionCount, AuditEvent, AuditLogFilter, AutoImproveCandidateSession,AutoImproveParkedClaim, BriefPageBody, BriefingPage, BriefingSnapshot, ClientActivity,ContaminationFinding, ContaminationReport, ContaminationSummary, ContradictionEdge,- DecayCandidate, DecayTombstone, DerivedIndexStatus, EmbeddingTripleCount,- FILTER_CANDIDATE_POOL, FeedbackFinding, GraphVia, HealthDetail, HealthPage, HybridHits,- HybridSearch, InboxCount, InboxEntry, ObservationHit, ObservationOrder, ObservationPage,- ObservationPageResult, ObservationRecord, OpenSession, PAGE_KINDS, PAGE_VERSIONS_MAX_LIMIT,- PageAuthor, PageFilter, PageHit, PageHitWithMeta, PageLinks, PageLinksPreview, PageMeta,- PageSummary, PageVersion, PageVersionBody, PageVersions, ProjectCoordinateCollisionReason,- ProjectCoordinateDiagnostic, ProjectCoordinateStatus, ProjectSummary, RELATED_WALK_MAX_DEPTH,- RELATED_WALK_MAX_NODES, ReaderPool, ReindexTargetStatus, RelatedNode, RelatedPage,- RrfContributions, ScopeRow, SearchExplain, SessionConsolidationQueue,- SessionConsolidationSummary, SessionDependentRows, SessionEndDisposition, SessionSummary,- SettledPage, StatusCounts, StorageStatus, StoredEmbedding, StoredPageBody, StreamTimings,- VectorQuery, WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,+ DecayCandidate, DecayTombstone, DerivedIndexStatus, EmbeddingTripleCount, FeedbackFinding,+ GraphVia, HealthDetail, HealthPage, HybridSearch, InboxCount, InboxEntry, ObservationHit,+ ObservationOrder, ObservationPage, ObservationPageResult, ObservationRecord, OpenSession,+ PAGE_KINDS, PAGE_VERSIONS_MAX_LIMIT, PageAuthor, PageFilter, PageHit, PageHitWithMeta,+ PageLinks, PageLinksPreview, PageMeta, PageSummary, PageVersion, PageVersionBody, PageVersions,+ ProjectCoordinateCollisionReason, ProjectCoordinateDiagnostic, ProjectCoordinateStatus,+ ProjectSummary, RELATED_WALK_MAX_DEPTH, RELATED_WALK_MAX_NODES, ReaderPool,+ ReindexTargetStatus, RelatedNode, RelatedPage, RrfContributions, ScopeRow, SearchExplain,+ SessionConsolidationQueue, SessionConsolidationSummary, SessionDependentRows,+ SessionEndDisposition, SessionSummary, 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::{@@ -2449,7 +2449,7 @@ mod tests {let global = store.reader- .search_pages_with_meta(query.into(), 10, None, None)+ .search_pages_with_meta(query.into(), 10, None, None, crate::PageFilter::default()).await.unwrap();assert_eq!(global[0].path.as_str(), "decisions/embedding-policy.md");diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 795f8d38..11e64940 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -438,16 +438,12 @@ pub(crate) const OBSERVATION_ROWID_SPAN_SQL: &str = "SELECT \(SELECT MAX(rowid) FROM observations INDEXED BY idx_observations_project \WHERE project_id = ?1)";-#[derive(Debug, Clone)]+#[derive(Debug, Clone, Copy)]struct PageAuthority {factor: f64,/// Kind/tier penalty this page carries *because* it is a session page/// (`0.0` for every other kind). A `session_recall` query gives it back.session_penalty: f64,- /// Semantic kind and tier the factor was derived from, kept so a- /// [`PageFilter`] needs no second read of the same rows.- kind: String,- tier: String,}impl PageAuthority {@@ -520,8 +516,6 @@ impl PageAuthority {Self {factor: factor.clamp(0.55, 1.50),session_penalty,- kind: kind.to_owned(),- tier: tier.to_owned(),}}@@ -875,17 +869,12 @@ pub struct VectorQuery<'a> {pub dim: u32,}-/// Candidates each stream is asked for when a [`PageFilter`] is active.+/// Narrows a search to pages of one kind and/or tier.///-/// The streams have no kind or tier predicate, so a filter can only keep what-/// they return. A pool this much wider than an unfiltered search's keeps a-/// rare kind from being crowded out by pages of other kinds that outrank it.-pub const FILTER_CANDIDATE_POOL: usize = 500;--/// Narrows a [`HybridSearch`] to pages of one kind and/or tier.-///-/// Applied after fusion and authority, before the result is cut to-/// `limit`, so `limit` counts hits that passed it.+/// Every stream applies it in its own SQL, so each returns only pages the+/// filter keeps and a rare kind cannot be crowded out by other kinds. Entity+/// frequencies are still counted over every page, so the filter leaves an+/// entity's weight unchanged. Graph expansion seeds from the kept hits only.#[derive(Debug, Clone, Copy, Default)]pub struct PageFilter<'a> {/// Semantic kind to keep, compared ASCII case-insensitively; `None`@@ -896,28 +885,43 @@ pub struct PageFilter<'a> {}impl PageFilter<'_> {- fn is_active(&self) -> bool {- self.kind.is_some() || self.tier.is_some()+ /// An ` AND …` predicate over the pages row `alias`, taking each bound+ /// value's placeholder from `placeholder`, and those values in order.+ fn sql(&self, alias: &str, mut placeholder: impl FnMut() -> String) -> (String, Vec<Value>) {+ let mut clause = String::new();+ let mut values = Vec::new();+ if let Some(kind) = self.kind {+ let kind_expr = page_kind_expr(+ &format!("{alias}.path"),+ &format!("{alias}.frontmatter_json"),+ );+ clause.push_str(&format!(+ " AND {kind_expr} = {} COLLATE NOCASE",+ placeholder()+ ));+ values.push(Value::Text(kind.to_owned()));+ }+ if let Some(tier) = self.tier {+ clause.push_str(&format!(" AND {alias}.tier = {}", placeholder()));+ values.push(Value::Text(tier.to_owned()));+ }+ (clause, values)}+}- /// Whether a page of this kind and tier passes the filter.- #[must_use]- pub fn keeps(&self, kind: &str, tier: &str) -> bool {- self.kind.is_none_or(|k| k.eq_ignore_ascii_case(kind))- && self.tier.is_none_or(|t| t == tier)+/// Placeholders `?first`, `?first+1`, … for [`PageFilter::sql`] in a+/// statement that numbers its parameters.+fn numbered_placeholders(first: usize) -> impl FnMut() -> String {+ let mut next = first;+ move || {+ next += 1;+ format!("?{}", next - 1)}}-/// What [`ReaderPool::hybrid_search_scopes`] returns.-#[derive(Debug)]-pub struct HybridHits {- /// Hits best first, each with its explain details when asked for.- pub hits: Vec<(PageHit, Option<SearchExplain>)>,- /// Per-stream wall time; `explain` only.- pub timings: Option<StreamTimings>,- /// A [`PageFilter`] was active and a stream returned its whole- /// candidate pool, so matches ranked past it were never looked at.- pub filter_pool_full: bool,+/// Placeholder for [`PageFilter::sql`] in a statement of anonymous `?`s.+fn anonymous_placeholder() -> String {+ "?".to_owned()}/// One [`ReaderPool::hybrid_search_scopes`] request.@@ -1351,14 +1355,6 @@ pub struct PageHitWithMeta {pub snippet: String,/// Relevance rank after the bounded authority adjustment (lower is better).pub rank: f64,- /// Semantic kind, so the web search can filter without a second lookup.- /// Empty on a recency listing, which nothing filters. Not serialized: the- /// MCP `global_hits` shape stays as it was.- #[serde(skip)]- pub kind: String,- /// Memory tier; see `kind`.- #[serde(skip)]- pub tier: String,}/// One raw observation fallback hit returned when compiled wiki pages miss.@@ -2650,6 +2646,8 @@ impl ReaderPool {////// `viewer` restricts the hits to repositories that user may read — see/// [`readable_repository_filter`]. `None` searches every repository.+ /// `filter` keeps only pages of a kind and/or tier, before the cut to+ /// `limit`.////// # Errors/// Propagates any SQL or pool error.@@ -2659,16 +2657,18 @@ impl ReaderPool {limit: usize,expiry_cutoff_us: Option<i64>,viewer: Option<UserId>,+ filter: PageFilter<'_>,) -> StoreResult<Vec<PageHitWithMeta>> {let fts_query = normalize_fts_query(&query, &self.fts_stopwords);if fts_query.is_empty() || limit == 0 {return Ok(Vec::new());}let cutoff = expiry_cutoff_us.unwrap_or_else(now_us);+ let (visible, visible_params) = readable_repository_filter("pages.project_id", viewer, 4);+ let (kept, kept_params) =+ filter.sql("pages", numbered_placeholders(4 + visible_params.len()));self.with_conn(move |conn| {let kind_expr = page_kind_expr("pages.path", "pages.frontmatter_json");- let (visible, visible_params) =- readable_repository_filter("pages.project_id", viewer, 4);let sql = format!("SELECT workspaces.name, projects.name, pages.path, pages.title, \snippet(pages_fts, 1, '<mark>', '</mark>', '…', 24) AS snip, \@@ -2678,7 +2678,7 @@ impl ReaderPool {JOIN pages ON pages.rowid = pages_fts.rowid \JOIN projects ON projects.id = pages.project_id \JOIN workspaces ON workspaces.id = pages.workspace_id \- WHERE pages_fts MATCH ?1 AND pages.is_latest = 1{not_expired}{visible} \+ WHERE pages_fts MATCH ?1 AND pages.is_latest = 1{not_expired}{visible}{kept} \ORDER BY pages_fts.rank \LIMIT ?2",not_expired = not_expired("pages", "?3"),@@ -2691,6 +2691,7 @@ impl ReaderPool {Value::Integer(cutoff),];bound.extend(visible_params);+ bound.extend(kept_params);let rows = stmt.query_map(params_from_iter(bound.iter()), |row| {let workspace_name: String = row.get(0)?;let project_name: String = row.get(1)?;@@ -2740,8 +2741,6 @@ impl ReaderPool {title,snippet,rank,- kind,- tier,},authority,));@@ -2779,11 +2778,13 @@ impl ReaderPool {authority_candidate_limit(limit),expiry_cutoff_us,false,+ PageFilter::default(),).await?;Ok(rerank_page_hits(candidates, limit))}+ #[allow(clippy::too_many_arguments)]async fn search_page_candidates_for_project(&self,workspace_id: WorkspaceId,@@ -2792,12 +2793,14 @@ impl ReaderPool {candidate_limit: usize,expiry_cutoff_us: Option<i64>,include_superseded: bool,+ filter: PageFilter<'_>,) -> StoreResult<Vec<(PageHit, PageAuthority)>> {let fts_query = normalize_fts_query(&query, &self.fts_stopwords);if fts_query.is_empty() || candidate_limit == 0 {return Ok(Vec::new());}let cutoff = expiry_cutoff_us.unwrap_or_else(now_us);+ let (kept, kept_params) = filter.sql("pages", numbered_placeholders(6));self.with_conn(move |conn| {let kind_expr = page_kind_expr("pages.path", "pages.frontmatter_json");let sql = format!(@@ -2809,7 +2812,7 @@ impl ReaderPool {JOIN pages ON pages.rowid = pages_fts.rowid \WHERE pages_fts MATCH ?1 \AND pages.workspace_id = ?2 \- AND pages.project_id = ?3{latest}{not_expired} \+ AND pages.project_id = ?3{latest}{not_expired}{kept} \ORDER BY pages_fts.rank \LIMIT ?4",latest = latest_only("pages", include_superseded),@@ -2817,37 +2820,36 @@ impl ReaderPool {);let mut stmt = conn.prepare(&sql)?;#[allow(clippy::cast_possible_wrap)]- let rows = stmt.query_map(- params![- fts_query,- workspace_id.as_bytes(),- project_id.as_bytes(),- candidate_limit as i64,- cutoff- ],- |row| {- let id_bytes: Vec<u8> = row.get(0)?;- let path: String = row.get(1)?;- let title: String = row.get(2)?;- let snippet: String = row.get(3)?;- let rank: f64 = row.get(4)?;- let tier: String = row.get(5)?;- let pinned = row.get::<_, i64>(6)? != 0;- let frontmatter_json: String = row.get(7)?;- let kind: String = row.get(8)?;- Ok((- id_bytes,- path,- title,- snippet,- rank,- tier,- pinned,- frontmatter_json,- kind,- ))- },- )?;+ let mut bound = vec![+ Value::Text(fts_query),+ Value::Blob(workspace_id.as_bytes().to_vec()),+ Value::Blob(project_id.as_bytes().to_vec()),+ Value::Integer(candidate_limit as i64),+ Value::Integer(cutoff),+ ];+ bound.extend(kept_params);+ let rows = stmt.query_map(params_from_iter(bound.iter()), |row| {+ let id_bytes: Vec<u8> = row.get(0)?;+ let path: String = row.get(1)?;+ let title: String = row.get(2)?;+ let snippet: String = row.get(3)?;+ let rank: f64 = row.get(4)?;+ let tier: String = row.get(5)?;+ let pinned = row.get::<_, i64>(6)? != 0;+ let frontmatter_json: String = row.get(7)?;+ let kind: String = row.get(8)?;+ Ok((+ id_bytes,+ path,+ title,+ snippet,+ rank,+ tier,+ pinned,+ frontmatter_json,+ kind,+ ))+ })?;let mut candidates = Vec::new();for row in rows {@@ -3024,7 +3026,7 @@ impl ReaderPool {.await?;let mut authorities: std::collections::HashMap<PageId, PageAuthority> = fts_candidates.iter()- .map(|(hit, authority)| (hit.id, authority.clone()))+ .map(|(hit, authority)| (hit.id, *authority)).collect();// Entity-only hits never passed through an FTS candidate row;// read their authority off the version row itself (no latest@@ -3258,6 +3260,7 @@ impl ReaderPool {/// unexpired page in this scope contributes nothing; the raw-observation/// fallback still covers live sessions. The two reads share one read/// transaction so the mapping sees a single snapshot. Read-only.+ #[allow(clippy::too_many_arguments)]async fn observation_stream_votes(&self,workspace_id: WorkspaceId,@@ -3266,11 +3269,14 @@ impl ReaderPool {candidate_limit: usize,cutoff: i64,owner_filter: OwnerFilter,+ filter: PageFilter<'_>,) -> StoreResult<Vec<ObservationVote>> {let fts_query = normalize_fts_query(query, &self.fts_stopwords);if fts_query.is_empty() || candidate_limit == 0 {return Ok(Vec::new());}+ // The session pages' lookup takes anonymous `?`s after its IN list.+ let (kept, kept_params) = filter.sql("pages", anonymous_placeholder);let row_limit = candidate_limit.saturating_mul(OBSERVATION_STREAM_ROWS_PER_CANDIDATE).min(OBSERVATION_STREAM_MAX_ROWS);@@ -3367,13 +3373,14 @@ impl ReaderPool {placeholders.push('?');sql_params.push(Value::Text(format!("sessions/{session_id}.md")));}+ sql_params.extend(kept_params);let sql = format!("SELECT pages.id, pages.path, pages.title \FROM pages \WHERE pages.workspace_id = ?1 \AND pages.project_id = ?2 \AND pages.is_latest = 1{not_expired} \- AND pages.path IN ({placeholders})",+ AND pages.path IN ({placeholders}){kept}",not_expired = not_expired("pages", "?3"),);let mut pages: std::collections::HashMap<String, (PageId, String)> =@@ -3657,8 +3664,6 @@ impl ReaderPool {title,snippet,rank,- kind: String::new(),- tier: String::new(),});}Ok(hits)@@ -5113,6 +5118,7 @@ impl ReaderPool {limit: usize,expiry_cutoff_us: i64,include_superseded: bool,+ filter: PageFilter<'_>,) -> StoreResult<Vec<(PageId, PagePath, f32)>> {self.top_embedding_hits_in_table(EmbeddingTable::Body,@@ -5125,6 +5131,7 @@ impl ReaderPool {limit,expiry_cutoff_us,include_superseded,+ filter,).await}@@ -5145,18 +5152,20 @@ impl ReaderPool {limit: usize,expiry_cutoff_us: i64,include_superseded: bool,+ filter: PageFilter<'_>,) -> StoreResult<Vec<(PageId, PagePath, f32)>> {if limit == 0 {return Ok(Vec::new());}let table = table.name();+ let (kept, kept_params) = filter.sql("pages", numbered_placeholders(7));self.with_conn(move |conn| {let sql = format!("SELECT {table}.page_id, {table}.vector, pages.path \FROM {table} \JOIN pages ON pages.id = {table}.page_id \WHERE pages.workspace_id = ?1 \- AND pages.project_id = ?2{latest}{not_expired} \+ AND pages.project_id = ?2{latest}{not_expired}{kept} \AND {table}.provider = ?3 \AND {table}.model = ?4 \AND {table}.dim = ?5",@@ -5164,22 +5173,21 @@ impl ReaderPool {not_expired = not_expired("pages", "?6"),);let mut stmt = conn.prepare_cached(&sql)?;- let rows = stmt.query_map(- params![- workspace_id.as_bytes(),- project_id.as_bytes(),- provider,- model,- dim,- expiry_cutoff_us,- ],- |row| {- let id_bytes: Vec<u8> = row.get(0)?;- let vec_bytes: Vec<u8> = row.get(1)?;- let path: String = row.get(2)?;- Ok((id_bytes, vec_bytes, path))- },- )?;+ let mut bound = vec![+ Value::Blob(workspace_id.as_bytes().to_vec()),+ Value::Blob(project_id.as_bytes().to_vec()),+ Value::Text(provider),+ Value::Text(model),+ Value::Integer(i64::from(dim)),+ Value::Integer(expiry_cutoff_us),+ ];+ bound.extend(kept_params);+ let rows = stmt.query_map(params_from_iter(bound.iter()), |row| {+ let id_bytes: Vec<u8> = row.get(0)?;+ let vec_bytes: Vec<u8> = row.get(1)?;+ let path: String = row.get(2)?;+ Ok((id_bytes, vec_bytes, path))+ })?;let mut out = Vec::new();for row in rows {@@ -5549,6 +5557,7 @@ impl ReaderPool {////// # Errors/// Propagates any SQL or pool error.+ #[cfg(test)]pub(crate) async fn entity_hits_for_project(&self,workspace_id: WorkspaceId,@@ -5585,12 +5594,40 @@ impl ReaderPool {expiry_cutoff_us: Option<i64>,as_of_us: Option<i64>,include_superseded: bool,+ ) -> StoreResult<Vec<EntityHit>> {+ self.entity_hits_filtered(+ workspace_id,+ project_id,+ query,+ limit,+ expiry_cutoff_us,+ as_of_us,+ include_superseded,+ PageFilter::default(),+ )+ .await+ }++ /// [`Self::entity_hits_for_project_at`] returning only pages `filter`+ /// keeps. Entity frequencies still count every page.+ #[allow(clippy::too_many_arguments)]+ async fn entity_hits_filtered(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ query: &str,+ limit: usize,+ expiry_cutoff_us: Option<i64>,+ as_of_us: Option<i64>,+ include_superseded: bool,+ filter: PageFilter<'_>,) -> StoreResult<Vec<EntityHit>> {let tokens = entity_query_tokens(query);if tokens.is_empty() || limit == 0 {return Ok(Vec::new());}let cutoff = expiry_cutoff_us.unwrap_or_else(now_us);+ let (kept, kept_params) = filter.sql("pg", anonymous_placeholder);self.with_conn(move |conn| {let mut placeholders = String::with_capacity(tokens.len() * 96);let mut sql_params: Vec<Value> = Vec::with_capacity(tokens.len() * 5 + 7);@@ -5635,6 +5672,7 @@ impl ReaderPool {sql_params.push(Value::Integer(cutoff));}}+ sql_params.extend(kept_params);sql_params.push(Value::Integer(i64::try_from(limit).unwrap_or(i64::MAX)));let mut sql = String::with_capacity(placeholders.len() + 1_200);@@ -5663,7 +5701,7 @@ impl ReaderPool {FROM freq f \JOIN entity_page_links l ON l.entity_id = f.entity_id \JOIN pages pg ON pg.id = l.page_id \- WHERE pg.workspace_id = ? AND pg.project_id = ?{version_filter} \+ WHERE pg.workspace_id = ? AND pg.project_id = ?{version_filter}{kept} \GROUP BY pg.id, pg.path, pg.title \ORDER BY weight DESC, matches DESC, pg.path ASC \LIMIT ?",@@ -5809,6 +5847,7 @@ impl ReaderPool {limit,expiry_cutoff_us,false,+ PageFilter::default(),).await?.into_iter()@@ -5820,6 +5859,7 @@ impl ReaderPool {/// produced each neighbour (`seed_ord` indexes into the caller's/// `seed_ids`) and in which direction the link points. Feeds the/// `memory_query` explain surface.+ #[allow(clippy::too_many_arguments)]async fn graph_neighbors_for_project_explained(&self,workspace_id: WorkspaceId,@@ -5828,11 +5868,14 @@ impl ReaderPool {limit: usize,expiry_cutoff_us: Option<i64>,include_superseded: bool,+ filter: PageFilter<'_>,) -> StoreResult<Vec<GraphNeighbor>> {if seed_ids.is_empty() || limit == 0 {return Ok(Vec::new());}let cutoff = expiry_cutoff_us.unwrap_or_else(now_us);+ let (out_kept, out_kept_params) = filter.sql("tp", anonymous_placeholder);+ let (in_kept, in_kept_params) = filter.sql("fp", anonymous_placeholder);self.with_conn(move |conn| {let mut seen = std::collections::HashSet::new();let mut out = Vec::new();@@ -5851,9 +5894,11 @@ impl ReaderPool {sql_params.push(Value::Blob(workspace_id.as_bytes().to_vec()));sql_params.push(Value::Blob(project_id.as_bytes().to_vec()));sql_params.push(Value::Integer(now));+ sql_params.extend(out_kept_params);sql_params.push(Value::Blob(workspace_id.as_bytes().to_vec()));sql_params.push(Value::Blob(project_id.as_bytes().to_vec()));sql_params.push(Value::Integer(now));+ sql_params.extend(in_kept_params);let out_descriptor = page_descriptor_expr("tp.body", "tp.frontmatter_json");let in_descriptor = page_descriptor_expr("fp.body", "fp.frontmatter_json");@@ -5873,7 +5918,7 @@ impl ReaderPool {FROM seeds \JOIN links l ON l.from_page_id = seeds.seed_id \JOIN pages tp ON tp.id = l.to_page_id \- WHERE tp.workspace_id = ? AND tp.project_id = ?{out_latest}{out_not_expired} \+ WHERE tp.workspace_id = ? AND tp.project_id = ?{out_latest}{out_not_expired}{out_kept} \UNION ALL \SELECT fp.id AS id, fp.path AS path, fp.title AS title, \{in_descriptor} AS snippet, \@@ -5882,7 +5927,7 @@ impl ReaderPool {FROM seeds \JOIN links l ON l.to_page_id = seeds.seed_id \JOIN pages fp ON fp.id = l.from_page_id \- WHERE fp.workspace_id = ? AND fp.project_id = ?{in_latest}{in_not_expired} \+ WHERE fp.workspace_id = ? AND fp.project_id = ?{in_latest}{in_not_expired}{in_kept} \) \SELECT id, path, title, snippet, stream_ord, link_type \FROM neighbors \@@ -6262,7 +6307,7 @@ impl ReaderPool {expiry_cutoff_us: Option<i64>,include_superseded: bool,) -> StoreResult<(Vec<(PageHit, SearchExplain)>, StreamTimings)> {- let (hits, timings, _) = self+ let (hits, timings) = self.hybrid_search_inner(workspace_id,project_id,@@ -6311,7 +6356,7 @@ impl ReaderPool {&self,scopes: &[(WorkspaceId, ProjectId)],search: HybridSearch<'_>,- ) -> StoreResult<HybridHits> {+ ) -> StoreResult<(Vec<(PageHit, Option<SearchExplain>)>, Option<StreamTimings>)> {// Provider/model/dim only select which stored vectors are eligible;// with no query vector the vector stream never runs, so the empty// triple is inert rather than a fake identity.@@ -6325,10 +6370,9 @@ impl ReaderPool {None => (None, String::new(), String::new(), 0),};let mut timings: Option<StreamTimings> = None;- let mut filter_pool_full = false;let mut per_scope = Vec::with_capacity(scopes.len());for &(workspace_id, project_id) in scopes {- let (hits, scope_timings, pool_full) = self+ let (hits, scope_timings) = self.hybrid_search_inner(workspace_id,project_id,@@ -6345,7 +6389,6 @@ impl ReaderPool {search.filter,).await?;- filter_pool_full |= pool_full;if search.explain {timings.get_or_insert_with(Default::default)@@ -6391,11 +6434,7 @@ impl ReaderPool {} else {hits};- Ok(HybridHits {- hits,- timings,- filter_pool_full,- })+ Ok((hits, timings))}/// The streams [`Self::hybrid_search_scopes`] runs for a query, in the@@ -6432,7 +6471,7 @@ impl ReaderPool {include_superseded: bool,owner_filter: &OwnerFilter,filter: PageFilter<'_>,- ) -> StoreResult<(Vec<(PageHit, Option<SearchExplain>)>, StreamTimings, bool)> {+ ) -> StoreResult<(Vec<(PageHit, Option<SearchExplain>)>, StreamTimings)> {let cutoff = expiry_cutoff_us.unwrap_or_else(now_us);// Stream timings exist only for explain: `explain.then(Instant::now)`// reads no clock on the normal path.@@ -6445,39 +6484,24 @@ impl ReaderPool {// bounded candidate window used by FTS-only search. A `limit * 2`// window was too narrow at small limits for a canonical page to enter// the fused pool and receive its bounded promotion.- // A filter can only keep what the streams return, so they are asked- // for a wide pool and `limit` is applied to what survives.- let candidate_limit = authority_candidate_limit(if filter.is_active() {- limit.max(FILTER_CANDIDATE_POOL)- } else {- limit- });+ let candidate_limit = authority_candidate_limit(limit);// Tokenize the borrowed query before the FTS candidate call consumes// it. This avoids cloning a caller-controlled query on the hot path.// The default path uses the latest-only entry; the opt-in path reaches// superseded versions through the `_at` entry with no `as_of` instant.let started = explain.then(std::time::Instant::now);- let entity_hits = if include_superseded {- self.entity_hits_for_project_at(+ let entity_hits = self+ .entity_hits_filtered(workspace_id,project_id,&query,candidate_limit,Some(cutoff),None,- true,- )- .await?- } else {- self.entity_hits_for_project(- workspace_id,- project_id,- &query,- candidate_limit,- Some(cutoff),+ include_superseded,+ filter,)- .await?- };+ .await?;timings.entity_ms = elapsed_ms(started);// The stream-off hot path keeps moving the query without a clone.let observation_query = if tuning.observation_stream {@@ -6494,12 +6518,13 @@ impl ReaderPool {candidate_limit,Some(cutoff),include_superseded,+ filter,).await?;timings.fts_ms = elapsed_ms(started);let mut authorities: std::collections::HashMap<PageId, PageAuthority> = fts_candidates.iter()- .map(|(hit, authority)| (hit.id, authority.clone()))+ .map(|(hit, authority)| (hit.id, *authority)).collect();let fts_hits: Vec<PageHit> = fts_candidates.into_iter()@@ -6522,6 +6547,7 @@ impl ReaderPool {candidate_limit,cutoff,include_superseded,+ filter,).await?;}@@ -6536,6 +6562,7 @@ impl ReaderPool {candidate_limit,cutoff,include_superseded,+ filter,).await?;timings.vector_ms = elapsed_ms(started);@@ -6577,6 +6604,7 @@ impl ReaderPool {candidate_limit,Some(cutoff),include_superseded,+ filter,).await?;timings.graph_ms = elapsed_ms(started);@@ -6592,6 +6620,7 @@ impl ReaderPool {candidate_limit,cutoff,owner_filter.clone(),+ filter,).await?;timings.observation_ms = elapsed_ms(started);@@ -6600,11 +6629,6 @@ impl ReaderPool {Vec::new()};- let filter_pool_full = filter.is_active()- && [fts_hits.len(), vec_hits.len(), entity_hits.len()]- .into_iter()- .any(|returned| returned >= candidate_limit);-// RRF fuse: score(d) = Σ 1/(k + rank_i(d)) over rankers.let k = 60.0_f64;struct Fused {@@ -6914,13 +6938,6 @@ impl ReaderPool {// back to HashMap iteration order..then_with(|| a.0.path.as_str().cmp(b.0.path.as_str()))});- if filter.is_active() {- out.retain(|(hit, _)| {- authorities- .get(&hit.id)- .is_some_and(|a| filter.keeps(&a.kind, &a.tier))- });- }out.truncate(limit);// Label the superseded versions among the final hits so the caller can// tell historical versions from the current one. Only the opt-in path@@ -6935,7 +6952,7 @@ impl ReaderPool {hit.superseded = superseded.contains(&hit.id);}}- Ok((out, timings, filter_pool_full))+ Ok((out, timings))}/// The subset of `page_ids` that are superseded (non-latest) versions in@@ -12948,9 +12965,9 @@ mod tests {super::PageFilter::default(),)};- let (_, off, _) = search(false).await.unwrap();+ let (_, off) = search(false).await.unwrap();assert_eq!(off, super::StreamTimings::default());- let (_, on, _) = search(true).await.unwrap();+ let (_, on) = search(true).await.unwrap();assert!(on.fts_ms.is_some() && on.entity_ms.is_some() && on.graph_ms.is_some());assert!(on.observation_ms.is_some(), "the stream is on by default");assert!(on.vector_ms.is_none(), "no query vector, no vector scan");diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rsindex 44704e60..4dafc35d 100644--- a/crates/ai-memory-store/tests/suite/multi_session.rs+++ b/crates/ai-memory-store/tests/suite/multi_session.rs@@ -3555,7 +3555,7 @@ async fn explained_search_as().await.unwrap()- .hits+ .0.into_iter().map(|(hit, details)| (hit, details.unwrap())).collect()diff --git a/crates/ai-memory-web/src/recall.rs b/crates/ai-memory-web/src/recall.rsindex 1e3ca002..09d161bc 100644--- a/crates/ai-memory-web/src/recall.rs+++ b/crates/ai-memory-web/src/recall.rs@@ -43,15 +43,12 @@ pub(crate) struct RecallResult {pub timings: Option<StreamTimings>,/// The streams that ran, in `memory_query`'s `streams_active` order.pub streams_active: Vec<&'static str>,- /// A filter was set and a stream returned its whole candidate pool, so- /// matches ranked past it were not looked at.- pub filter_pool_full: bool,}/// Rank `query` over `scopes` as a `memory_query` project/scopes search does/// (latest versions only, expired pages hidden), keeping only pages that pass-/// `filter`. The filter runs in the ranker, before the reranker, so the-/// reranker scores only pages the caller can see. `owner` is the viewer's+/// `filter`. Every stream applies the filter, so the reranker scores only+/// pages the caller asked for. `owner` is the viewer's/// session-timeline filter: an observation excerpt is shown only from a/// session it admits, as in `memory_query`.pub(crate) async fn search_scopes(@@ -72,7 +69,7 @@ pub(crate) async fn search_scopes(.rerank.as_ref().map_or(limit, |stage| stage.fetch_limit(limit));- let found = state+ let (hits, mut timings) = state.reader.hybrid_search_scopes(scopes,@@ -93,7 +90,6 @@ pub(crate) async fn search_scopes(},).await?;- let (hits, mut timings) = (found.hits, found.timings);let hits = match &state.recall.rerank {Some(stage) => {let started = explain.then(std::time::Instant::now);@@ -130,6 +126,5 @@ pub(crate) async fn search_scopes(hits,timings,streams_active: state.reader.active_streams(query_vector.is_some()),- filter_pool_full: found.filter_pool_full,})}diff --git a/crates/ai-memory-web/src/routes/search.rs b/crates/ai-memory-web/src/routes/search.rsindex edd3c1bf..003ab7d2 100644--- a/crates/ai-memory-web/src/routes/search.rs+++ b/crates/ai-memory-web/src/routes/search.rs@@ -12,19 +12,16 @@//! viewer may read, as `memory_query(global=true)` does. Its trace is the//! FTS time alone; there are no per-hit streams to show.//!-//! `kind` and `tier` narrow either mode after fusion, inside the ranker. The-//! streams are asked for a wider candidate pool so a rare kind is not crowded-//! out, which means the order of the survivors can differ slightly from the-//! unfiltered top hits of the same query.+//! `kind` and `tier` narrow either mode inside each stream's SQL, so a rare+//! kind is never crowded out by other kinds. Survivors are ranked among+//! themselves, so their order can differ slightly from the unfiltered hits of+//! the same query, and graph expansion seeds only from pages the filter keeps.use std::collections::BTreeMap;-use std::str::FromStr;use std::sync::Arc;use ai_memory_core::Tier;-use ai_memory_store::{- FILTER_CANDIDATE_POOL, PAGE_KINDS, PageFilter, SearchExplain, StreamTimings,-};+use ai_memory_store::{PAGE_KINDS, PageFilter, SearchExplain, StreamTimings};use askama::Template;use axum::extract::{Query, State};use axum::http::StatusCode;@@ -44,8 +41,6 @@ const GLOBAL_DEFAULT_LIMIT: usize = 50;const SCOPED_DEFAULT_LIMIT: usize = 20;/// Upper bound on `limit`, the same clamp `memory_query` applies.const MAX_LIMIT: usize = 100;-/// Memory tiers the filter offers, in `Tier` declaration order.-const TIERS: [&str; 4] = ["working", "episodic", "semantic", "procedural"];/// Query-string parameters for the search endpoint.#[derive(Debug, Deserialize)]@@ -127,30 +122,28 @@ pub(crate) async fn handler(},};let kind = non_empty(params.kind.as_deref()).map(str::to_owned);+ // Matched like `kind`, ignoring ASCII case; the canonical name is what+ // the SQL compares.let tier = match non_empty(params.tier.as_deref()) {- Some(value) if Tier::from_str(value).is_ok() => Some(value.to_owned()),- Some(_) => {- return (- StatusCode::BAD_REQUEST,- "tier must be working, episodic, semantic or procedural",- )- .into_response();- }+ Some(value) => match Tier::ALL+ .iter()+ .find(|t| t.as_str().eq_ignore_ascii_case(value))+ {+ Some(t) => Some(t.as_str()),+ None => {+ return (+ StatusCode::BAD_REQUEST,+ "tier must be working, episodic, semantic or procedural",+ )+ .into_response();+ }+ },None => None,};let filtered = kind.is_some() || tier.is_some();let filter = PageFilter {kind: kind.as_deref(),- tier: tier.as_deref(),- };- // The global search has no ranker-side filter, so a filtered one is asked- // for a wide pool and the limit is applied to what survives.- let fetch_limit = |limit: usize| {- if filtered {- FILTER_CANDIDATE_POOL- } else {- limit + 1- }+ tier,};let internal = |error: ai_memory_store::StoreError| {tracing::error!(%error, "web search failed");@@ -162,8 +155,6 @@ pub(crate) async fn handler(// apart from one that has exactly `limit` matches.let mut limit_used = 0;let mut truncated = false;- // The filter saw a full pool, so matches ranked past it were not looked at.- let mut pool_capped = false;let mut timings = None;let mut streams_active: Vec<&'static str> = Vec::new();match &scope {@@ -195,7 +186,6 @@ pub(crate) async fn handler(};timings = result.timings;streams_active = result.streams_active;- pool_capped = result.filter_pool_full;truncated = result.hits.len() > limit;// The trace position is the rank among the hits shown.for (position, (hit, details)) in result.hits.into_iter().take(limit).enumerate() {@@ -223,7 +213,7 @@ pub(crate) async fn handler(let started = explain.then(std::time::Instant::now);let raw = match state.reader- .search_pages_with_meta(query.clone(), fetch_limit(limit), None, viewer)+ .search_pages_with_meta(query.clone(), limit + 1, None, viewer, filter).await{Ok(raw) => raw,@@ -236,11 +226,6 @@ pub(crate) async fn handler(});streams_active = vec!["fts"];}- pool_capped = filtered && raw.len() >= FILTER_CANDIDATE_POOL;- let raw: Vec<_> = raw- .into_iter()- .filter(|h| filter.keeps(&h.kind, &h.tier))- .collect();truncated = raw.len() > limit;for h in raw.into_iter().take(limit) {let path = h.path.as_str().to_owned();@@ -296,8 +281,16 @@ pub(crate) async fn handler(.unwrap_or_default().to_owned();let kind_options = filter_options(&PAGE_KINDS, kind.as_deref());- let tier_options = filter_options(&TIERS, tier.as_deref());- let global_href = format!("search?q={}", encode_segment(&query));+ let tiers = Tier::ALL.map(|t| t.as_str());+ let tier_options = filter_options(&tiers, tier);+ // Leaving the project keeps the filters, so an empty filtered result here+ // is compared with the same filters everywhere.+ let mut global_href = format!("search?q={}", encode_segment(&query));+ for (name, value) in [("kind", kind.as_deref()), ("tier", tier)] {+ if let Some(value) = value {+ global_href.push_str(&format!("&{name}={}", encode_segment(value)));+ }+ }let view = SearchView {global_href,project_href: project_href(&workspace, &project),@@ -306,8 +299,6 @@ pub(crate) async fn handler(hits,hit_count,filtered,- pool_capped,- filter_pool: FILTER_CANDIDATE_POOL,unknown_kind,kind_options,tier_options,diff --git a/crates/ai-memory-web/src/templates.rs b/crates/ai-memory-web/src/templates.rsindex ba723210..c296e72b 100644--- a/crates/ai-memory-web/src/templates.rs+++ b/crates/ai-memory-web/src/templates.rs@@ -688,11 +688,6 @@ pub(crate) struct SearchView {pub project_href: String,/// A kind or tier filter narrowed the hits.pub filtered: bool,- /// The filter looked only at the top `filter_pool` matches, and the- /// ranker had more.- pub pool_capped: bool,- /// Matches a filtered search ranks before it filters.- pub filter_pool: usize,/// The kind filter names no standard kind (empty when it does, or when/// there is none); a custom frontmatter kind or a typo.pub unknown_kind: String,diff --git a/crates/ai-memory-web/templates/search.html b/crates/ai-memory-web/templates/search.htmlindex 67c22792..500bd5b8 100644--- a/crates/ai-memory-web/templates/search.html+++ b/crates/ai-memory-web/templates/search.html@@ -113,7 +113,6 @@<p class="text-sm text-slate-500 dark:text-slate-400">Enter a search term above.</p>{% else if hits.is_empty() %}<p class="text-sm text-slate-500 dark:text-slate-400">No results for <strong>{{ query }}</strong>{% if filtered %} with these filters{% endif %}.- {% if pool_capped %}Only the top {{ filter_pool }} matches were searched.{% endif %}{% if unknown_kind != "" %}<code>{{ unknown_kind }}</code> is not a standard page kind; check the spelling.{% endif %}{% if self.scoped() %}<a href="{{ global_href }}" class="ml-2 inline-block rounded-md border border-slate-300 dark:border-slate-700 px-3 py-1 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-900">Search all projects</a>@@ -125,9 +124,6 @@{% else %}<p class="text-sm text-slate-500 dark:text-slate-400 mb-4">{{ hit_count }} result{% if hit_count != 1 %}s{% endif %}</p>{% endif %}-{% if pool_capped %}-<p class="text-sm text-slate-500 dark:text-slate-400 mb-4">The filters were applied to the top {{ filter_pool }} matches; refine the query to reach lower-ranked pages.</p>-{% endif %}<ul class="divide-y divide-slate-100 dark:divide-slate-800">{% for hit in hits %}<li class="py-4" data-hit-path="{{ hit.path }}">diff --git a/crates/ai-memory-web/tests/suite/recall_trace.rs b/crates/ai-memory-web/tests/suite/recall_trace.rsindex 05ddbbfb..2e991221 100644--- a/crates/ai-memory-web/tests/suite/recall_trace.rs+++ b/crates/ai-memory-web/tests/suite/recall_trace.rs@@ -578,9 +578,14 @@ async fn search_filters_a_project_by_kind_and_tier_keeping_rank_order() {assert_eq!(hit_paths(&body), ["procedures/rotate.md"], "{body}");let (_, body) = get(&app, &format!("{base}&tier=procedural"), None).await;assert_eq!(hit_paths(&body), ["procedures/rotate.md"], "{body}");+ // The tier ignores case, as the kind does.+ let (status, body) = get(&app, &format!("{base}&tier=Procedural"), None).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(hit_paths(&body), ["procedures/rotate.md"], "{body}");// The survivors of `kind=fact` are the unfiltered list minus the- // procedure, in the same order: the filter runs after ranking.+ // procedure, in the same order: dropping one page from every stream+ // leaves the others' relative ranks alone here.let expected: Vec<_> = all.iter().filter(|p| *p != "procedures/rotate.md")@@ -594,6 +599,12 @@ async fn search_filters_a_project_by_kind_and_tier_keeping_rank_order() {assert_eq!(status, StatusCode::OK, "{body}");assert!(hit_paths(&body).is_empty(), "{body}");assert!(body.contains("with these filters"), "{body}");+ // "Search all projects" keeps the filters, so it does not read as if+ // the filter matched elsewhere.+ assert!(+ body.contains(r#"href="search?q=token%20rotation&kind=procedure&tier=semantic""#),+ "{body}"+ );// The selects keep the current choice.let (_, body) = get(@@ -695,27 +706,6 @@ async fn kind_filter_is_case_insensitive_and_flags_a_nonstandard_kind() {assert!(body.contains("is not a standard page kind"), "{body}");}-#[test]-fn tier_filter_offers_every_tier() {- use ai_memory_core::Tier;- // An exhaustive match: a new `Tier` variant fails to compile here until- // the filter's list is revisited.- for tier in [- Tier::Working,- Tier::Episodic,- Tier::Semantic,- Tier::Procedural,- ] {- let name = match tier {- Tier::Working => "working",- Tier::Episodic => "episodic",- Tier::Semantic => "semantic",- Tier::Procedural => "procedural",- };- assert_eq!(name.parse::<Tier>().unwrap(), tier);- }-}-/// Scores every candidate equally and remembers which pages it was shown.#[derive(Default)]struct RecordingReranker {@@ -751,8 +741,8 @@ impl Reranker for RecordingReranker {}}-/// The filter runs in the ranker, before the reranker: pages the filter-/// drops are never sent to the (paid, slow) reranker.+/// The streams filter before the reranker: pages the filter drops are never+/// sent to the (paid, slow) reranker.#[tokio::test]async fn reranker_is_shown_only_the_pages_the_filter_keeps() {let f = fixture(false).await;@@ -805,7 +795,8 @@ async fn reranker_is_shown_only_the_pages_the_filter_keeps() {}/// A rare kind that the unfiltered result ranks out of view is still found:-/// the filter is applied to a candidate pool far wider than one page.+/// the FTS stream filters in SQL, so 60 better-ranked facts, more than its+/// candidate window, cannot push the gotcha out.#[tokio::test]async fn kind_filter_finds_a_rare_kind_the_unfiltered_page_ranks_out() {let f = fixture(false).await;@@ -850,3 +841,233 @@ async fn kind_filter_finds_a_rare_kind_the_unfiltered_page_ranks_out() {let (_, body) = get(&app, &format!("{base}&kind=gotcha"), None).await;assert_eq!(hit_paths(&body), ["gotchas/quiet.md"], "{body}");}++/// Every stream applies the filter itself. Each non-procedure page below is+/// reached by its own stream (page FTS, entity, vector, both directions of+/// graph from the procedure, observation votes), so dropping the predicate from any one of+/// them lets that page into a `kind=procedure` result. Control: unfiltered,+/// all of them are hits.+#[tokio::test]+async fn kind_and_tier_filters_hold_in_every_stream() {+ use ai_memory_core::{AgentKind, NewObservation, NewSession, ObservationKind, SessionId};++ let f = fixture(false).await;+ let ws = f+ .store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ // Written with the embedder, so the vector stream reaches every page.+ let wiki = f.wiki.clone().with_embedder(embedder());+ wiki.write_page(WritePageRequest {+ frontmatter: serde_json::json!({"kind": "procedure"}),+ tier: Tier::Procedural,+ ..req(+ ws,+ f.alpha,+ "procedures/quokka.md",+ "# Quokka care\n\nFeed the quokka at dawn. See [[notes/vault]].",+ )+ })+ .await+ .unwrap();+ wiki.write_page(req(+ ws,+ f.alpha,+ "notes/quokka-fact.md",+ "# Quokka fact\n\nA quokka is a small marsupial.",+ ))+ .await+ .unwrap();+ wiki.write_page(WritePageRequest {+ frontmatter: serde_json::json!({"kind": "fact", "entities": ["quokka"]}),+ ..req(+ ws,+ f.alpha,+ "notes/tagged.md",+ "# Tagged\n\nIsland wildlife.",+ )+ })+ .await+ .unwrap();+ // Links to the procedure without naming it in its text: the graph+ // stream's incoming side alone reaches it.+ f.store+ .writer+ .upsert_page(ai_memory_core::NewPage {+ workspace_id: ws,+ project_id: f.alpha,+ path: PagePath::new("notes/pointer.md").unwrap(),+ title: "Pointer".into(),+ body: "Island care handbook.".into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: vec![ai_memory_core::LinkTarget {+ workspace: None,+ project: None,+ path: PagePath::new("procedures/quokka.md").unwrap(),+ relation: None,+ }],+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ evidence: Vec::new(),+ })+ .await+ .unwrap();+ let session_id = SessionId::new();+ f.store+ .writer+ .begin_session(NewSession {+ occurred_at: None,+ id: session_id,+ workspace_id: ws,+ project_id: f.alpha,+ agent_kind: AgentKind::Codex,+ cwd: None,+ actor_user: None,+ })+ .await+ .unwrap();+ f.store+ .writer+ .insert_observation(ai_memory_core::Sanitized::new(+ NewObservation {+ occurred_at: None,+ session_id,+ workspace_id: ws,+ project_id: f.alpha,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "prompt".into(),+ body: "where does the quokka sleep".into(),+ importance: 5,+ },+ &ai_memory_core::Sanitizer::builtin(),+ ))+ .await+ .unwrap();+ let session_path = format!("sessions/{session_id}.md");+ f.store+ .writer+ .upsert_page(ai_memory_core::NewPage {+ workspace_id: ws,+ project_id: f.alpha,+ path: PagePath::new(session_path.clone()).unwrap(),+ title: "A session".into(),+ body: "Reviewed the release.".into(),+ tier: Tier::Episodic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ evidence: Vec::new(),+ })+ .await+ .unwrap();+ let app = web(+ &f,+ Recall {+ embedder: Some(embedder()),+ rerank: None,+ },+ );+ let base = "/web/search?q=quokka&workspace=default&project=alpha&limit=50";++ let (status, body) = get(&app, base, None).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ let all = hit_paths(&body);+ for path in [+ "procedures/quokka.md",+ "notes/quokka-fact.md",+ "notes/tagged.md",+ "notes/vault.md",+ "notes/pointer.md",+ "notes/deploy.md",+ session_path.as_str(),+ ] {+ assert!(+ all.contains(&path.to_owned()),+ "control lacks {path}: {all:?}"+ );+ }++ for filter in [+ "kind=procedure",+ "tier=procedural",+ "kind=PROCEDURE&tier=procedural",+ ] {+ let (status, body) = get(&app, &format!("{base}&{filter}"), None).await;+ assert_eq!(status, StatusCode::OK, "{filter}: {body}");+ assert_eq!(+ hit_paths(&body),+ ["procedures/quokka.md"],+ "{filter}: {body}"+ );+ }+ // The other way round: the session page alone is episodic.+ let (_, body) = get(&app, &format!("{base}&tier=episodic"), None).await;+ assert_eq!(hit_paths(&body), [session_path], "{body}");+}++/// The cross-project search filters in SQL too: 60 better-ranked facts, more+/// than its candidate window for `limit=5`, cannot push a matching gotcha out.+#[tokio::test]+async fn cross_project_kind_filter_sees_past_the_candidate_window() {+ let f = fixture(false).await;+ let ws = f+ .store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ for n in 0..60 {+ f.store+ .writer+ .upsert_page(ai_memory_core::NewPage {+ workspace_id: ws,+ project_id: f.alpha,+ path: PagePath::new(format!("notes/crowd-{n}.md")).unwrap(),+ title: "Crowd".into(),+ body: "crowdword crowdword crowdword crowdword crowdword.".into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ evidence: Vec::new(),+ })+ .await+ .unwrap();+ }+ f.wiki+ .write_page(WritePageRequest {+ frontmatter: serde_json::json!({"kind": "gotcha"}),+ ..req(+ ws,+ f.alpha,+ "gotchas/quiet.md",+ "# Quiet\n\nOne mention of crowdword among many other unrelated words \+ about cats, rivers, mountains, bridges and old maps.",+ )+ })+ .await+ .unwrap();+ let app = web(&f, Recall::default());+ let base = "/web/search?q=crowdword&limit=5";++ let (_, body) = get(&app, base, None).await;+ assert!(+ !hit_paths(&body).contains(&"gotchas/quiet.md".to_owned()),+ "control: the gotcha must be ranked out of the first page: {body}"+ );+ let (_, body) = get(&app, &format!("{base}&kind=gotcha"), None).await;+ assert_eq!(hit_paths(&body), ["gotchas/quiet.md"], "{body}");+}diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 5fa0c071..8d6b35e6 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -105,7 +105,7 @@ means the boundary is not built yet.| 14d | `include_related` and the web page's backlinks show and walk only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` and `page_links_preview` apply (the preview's visible totals are counted under it too), so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, `ai-memory-web/src/routes/page.rs` passes the request's viewer to `page_links_preview`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed; `ai-memory-web` `tests/suite/routes.rs` `page_backlink_from_an_unreadable_project_is_hidden` (the `/web` page's "Cited by" omits a page in an ungranted restricted project, with no title, path or project name; controls: a reader of both projects and an unrestricted viewer see it) — fails with the page handler passing no viewer to `page_links_preview`; `related_walk.rs` `page_links_preview_caps_in_sql_and_counts_only_readable_neighbours` (back-links from an ungranted restricted project are neither listed nor counted in the total behind "and N more"; control: no viewer counts them all) — fails with the predicate removed; `ai-memory-mcp` `server.rs` `bob_does_not_see_restricted_pages_through_the_related_walk` (an ungranted user's `memory_read_page{include_related}` omits the restricted page; control: no viewer still reaches it) — fails with `memory_read_page` passing `None` instead of `viewer_from_parts` | STRONG || 14e | `memory_write_page` session evidence cites only a session of the target project (#708) | `ai-memory-mcp/src/server.rs` `memory_write_page` — a `session_id` is accepted only when `require_session_in_scope` resolves the session (where its observations landed, else its session row, as `Consolidator::session_target` does) to the same `(workspace_id, project_id)` the write grant was checked against; unknown and foreign ids get one refusal, so the error is no existence oracle; `scope: "global"` with a `session_id` is refused; `refuse_pinned_page_overwrite` keeps a write that cites a session off a pinned page; only a write to `sessions/<id>.md` reconciles the session's queued SessionEnd job | `server.rs` `write_page_refuses_a_session_from_another_project` (a foreign and an unknown session refused, no evidence row written, the foreign job still queued; control: the project's own session accepted), `session_evidence_write_leaves_a_pinned_page_alone` (control: the same write without `session_id` edits the page), `session_evidence_on_another_path_leaves_the_job_queued`, `write_page_rejects_a_malformed_or_global_session_id` — each of the scope check, the pinned check and the session-page-only reconcile proven to fail its test when removed | STRONG || 14f | Consolidation apply path validates cross-scope wikilinks against the store (#1218) | `ai-memory-consolidate/src/link_guard.rs` `unresolved_cross_scope_links` — every `[[project:path]]` / `[[workspace/project:path]]` / `[[_global:path]]` target in a proposed body is resolved with the no-create `lookup_existing_scope` (never creates a scope) and batch-checked via `reader.rs` `existing_latest_paths`; a missing workspace/project, an ambiguous project name, or a missing target page de-links the wikilink, while a genuine store failure aborts the consolidation before any write. Typed `relations:` frontmatter targets go through the same check, and `prune_relations` drops an unresolved entry (an emptied relation and an emptied map with it). `delink_body` → `ai-memory-wiki/src/markdown.rs` `delink_wikilinks` drops the brackets and keeps the label, skipping code fences and inline code exactly as `extract_links` does. Wired into all three apply paths (`consolidator.rs` single-page and batch, `bootstrap.rs`) after the pinned/foreign-slot/portable guards and before the atomic `Wiki::apply_batch` / `write_page`, so an invented cross-project dependency can no longer be written and flagged by the lint pass later. Same-project `[[target]]` links stay untouched by design (the target may be written later). The probe runs with no viewer, so it reports nothing for a `restricted` project (the global preferences project excepted): a link into one is always de-linked, and whether a link survived says nothing about which paths exist there | `consolidator.rs` `batch_delinks_invented_cross_scope_wikilinks` (invented `[[_global:nope]]`, `[[otherproj:notes/missing.md]]`, `[[ghostproj:x.md]]` de-linked to plain text; controls: a cross-scope link to an existing page and a same-project pending link survive byte-identical; `dangling_cross_project_links` left empty), `single_page_delinks_invented_cross_scope_wikilinks`, `single_page_drops_unresolved_cross_scope_relations` (unresolved `relations:` entries dropped; controls: a live cross-scope and a same-project target stay), `link_guard.rs` `prune_relations_drops_only_unresolved_cross_scope_entries`, `bootstrap.rs` `bootstrap_delinks_invented_cross_scope_wikilinks` — each proven to fail with the guard neutralized; `markdown.rs` `delink_wikilinks_strips_only_listed_cross_scope_links`, `delink_wikilinks_without_label_keeps_the_target_text`, `delink_wikilinks_skips_code_and_leaves_empty_set_untouched`; store `multi_session.rs` `existing_latest_paths_reports_exactly_the_live_paths` (exact live-path set, superseded path still resolves, foreign scope sees nothing), `existing_latest_paths_reports_nothing_for_a_restricted_project` (real and absent paths answer alike while restricted; control: reopened, the page is seen) | STRONG |-| 14g | Web project search and its recall trace honour `memory_query`'s scope rules (#708) and never describe another project | `ai-memory-web/src/routes/search.rs` resolves `workspace`+`project` through `resolve_read_scope` (`lookup_existing_scope_guarded`, no-create, `ProjectAccess::Read`) before any ranking, and refuses partial scope; scoped `/api/v1/search` keeps `lookup_project` / `resolve_many_existing_scopes_guarded`; `ai-memory-web/src/recall.rs` ranks only the resolved scopes through `ReaderPool::hybrid_search_scopes`, whose streams and graph expansion are bound to each `(workspace_id, project_id)`; a search with no scope stays `search_pages_with_meta(.., viewer)` (readable repositories only) | `ai-memory-web` `tests/suite/recall_trace.rs` — `project_search_refuses_a_restricted_project_without_a_grant` (bob, with no grant, gets 403 from `/web/search` with and without `explain=1` and from scoped `/api/v1/search`, with no path, body text or trace in the response, and a `scopes` POST naming the restricted project next to an open one is refused; alice's grant and an unrestricted viewer are the controls), `project_search_fails_closed_on_unknown_and_partial_scope` (unknown project or workspace 404 with nothing created, partial scope 400), `explain_renders_stream_ranks_rrf_authority_and_timings` (a better-matching page in a sibling project never reaches the hits or the trace), `search_scope_selector_lists_only_readable_projects` (the search page's "Search in" selector lists only projects the viewer may read, and a hand-typed `scope=` for an ungranted project is a 403 that leaks nothing; controls: the granted reader and an unrestricted viewer; passing no viewer to `list_projects_with_stats` in the handler fails it), `routes.rs` `search_page_scope_selector_round_trips_and_rejects_malformed_values` (a malformed `scope` is a 400); `recall_trace.rs` `kind_filter_does_not_widen_what_a_viewer_can_read` (a `kind`/`tier` filter only narrows: bob gets no hits and a 403 on a scoped search; alice and an unrestricted viewer are the controls), `search_filters_a_project_by_kind_and_tier_keeping_rank_order` (survivors of a filter keep the unfiltered order), `reranker_is_shown_only_the_pages_the_filter_keeps` (a dropped page never reaches the reranker), `kind_filter_finds_a_rare_kind_the_unfiltered_page_ranks_out` (the filter sees past the first page of results); `ai-memory-mcp` `tests/suite/web_search_parity.rs` (same top-k order as `memory_query` from `/web` and `/api/v1`, with a deterministic embedder and with none, explain on and off, and merged `scopes`; controls show a web search without the embedder, or the old FTS-only scoped search, would fail it) | STRONG. Bite checks: passing no viewer to `resolve_read_scope` in the search handler, to `lookup_project` or to `resolve_scopes` in the API each fails the restricted-project test; dropping the query vector in `recall.rs` fails the embedder parity tests |+| 14g | Web project search and its recall trace honour `memory_query`'s scope rules (#708) and never describe another project | `ai-memory-web/src/routes/search.rs` resolves `workspace`+`project` through `resolve_read_scope` (`lookup_existing_scope_guarded`, no-create, `ProjectAccess::Read`) before any ranking, and refuses partial scope; scoped `/api/v1/search` keeps `lookup_project` / `resolve_many_existing_scopes_guarded`; `ai-memory-web/src/recall.rs` ranks only the resolved scopes through `ReaderPool::hybrid_search_scopes`, whose streams and graph expansion are bound to each `(workspace_id, project_id)`; a search with no scope stays `search_pages_with_meta(.., viewer)` (readable repositories only) | `ai-memory-web` `tests/suite/recall_trace.rs` — `project_search_refuses_a_restricted_project_without_a_grant` (bob, with no grant, gets 403 from `/web/search` with and without `explain=1` and from scoped `/api/v1/search`, with no path, body text or trace in the response, and a `scopes` POST naming the restricted project next to an open one is refused; alice's grant and an unrestricted viewer are the controls), `project_search_fails_closed_on_unknown_and_partial_scope` (unknown project or workspace 404 with nothing created, partial scope 400), `explain_renders_stream_ranks_rrf_authority_and_timings` (a better-matching page in a sibling project never reaches the hits or the trace), `search_scope_selector_lists_only_readable_projects` (the search page's "Search in" selector lists only projects the viewer may read, and a hand-typed `scope=` for an ungranted project is a 403 that leaks nothing; controls: the granted reader and an unrestricted viewer; passing no viewer to `list_projects_with_stats` in the handler fails it), `routes.rs` `search_page_scope_selector_round_trips_and_rejects_malformed_values` (a malformed `scope` is a 400); `recall_trace.rs` `kind_filter_does_not_widen_what_a_viewer_can_read` (a `kind`/`tier` filter only narrows: bob gets no hits and a 403 on a scoped search; alice and an unrestricted viewer are the controls), `search_filters_a_project_by_kind_and_tier_keeping_rank_order` (survivors of a filter keep the unfiltered order), `reranker_is_shown_only_the_pages_the_filter_keeps` (a dropped page never reaches the reranker), `kind_and_tier_filters_hold_in_every_stream` (FTS, entity, vector, observation and both graph directions each filter in SQL; dropping any one stream's predicate fails it), `kind_filter_finds_a_rare_kind_the_unfiltered_page_ranks_out` and `cross_project_kind_filter_sees_past_the_candidate_window` (the filter sees past the candidate window in both modes); `ai-memory-mcp` `tests/suite/web_search_parity.rs` (same top-k order as `memory_query` from `/web` and `/api/v1`, with a deterministic embedder and with none, explain on and off, and merged `scopes`; controls show a web search without the embedder, or the old FTS-only scoped search, would fail it) | STRONG. Bite checks: passing no viewer to `resolve_read_scope` in the search handler, to `lookup_project` or to `resolve_scopes` in the API each fails the restricted-project test; dropping the query vector in `recall.rs` fails the embedder parity tests || 15 | Agent-archive restore path confinement, resource bounds, and consistency | `ai-memory-cli/src/commands/restore_agents.rs` stages only bounded regular UTF-8 entries; requires a one-to-one manifest/body/checksum/target mapping; allowlists destinations by scope; rejects symlinked descendants; writes each file atomically and rolls back earlier writes after a later failure. `backup_agents.rs` skips direct and directory-root source symlinks, bounds individual assets, and atomically replaces a private archive only after gzip completion | `backup_agents.rs` `restore_agents_rejects_path_traversal`, `restore_agents_rejects_unauthorized_destination_path`, `restore_agents_verifies_sha256_integrity`, `restore_agents_requires_a_complete_one_to_one_manifest`, `restore_agents_rejects_oversized_entries_from_the_header`, `restore_agents_rejects_a_symlinked_destination_parent`, `backup_agents_does_not_follow_config_or_asset_root_symlinks`, and `failed_backup_leaves_the_previous_archive_intact`; `backup_and_restore_agents_round_trip` is the valid-path control; `restore_agents::tests::rollback_removes_new_files_and_restores_overwrites` covers recovery | STRONG || 16 | Relay queue identity, migration, and private filesystem state | `companions/ai-memory-relay/src/queue.rs` `Queue::open_inner` performs read-only identity preflight, rechecks under `IMMEDIATE`, commits schema and metadata together; `configure` checks the presence of user objects and rechecks `identity`/`schema_version` metadata on the same connection before every bounded BUSY/LOCKED retry; `fsguard.rs` checks existing paths and creates owner-only files before SQLite opens them | `tests/relay.rs` `a_foreign_database_is_refused_byte_for_byte`, `unknown_schemas_refuse_without_mutation`, `a_foreign_database_with_a_writer_is_refused_before_write_coordination`, `a_foreign_identity_after_preflight_is_refused_without_mutation`, `a_foreign_identity_during_journal_retry_is_refused_without_mutation`, `journal_retry_refuses_a_changed_version_or_empty_database_without_mutation`; controls: `journal_transition_retries_sqlite_lock_without_losing_v1_values`, `fresh_queue_init_and_v1_reopens_work_across_processes`; recovery: `interrupted_and_failed_migrations_roll_back_and_recover`, `journal_reclassification_busy_preserves_committed_migration_and_retries_same_queue`; diagnostics: `classification_read_failures_display_the_sqlite_cause_once_and_preserve_foreign_bytes`; Unix privacy: `the_queue_database_and_its_sidecars_are_owner_only` and the contended migration control | Guard-removal proof covers preflight, locked recheck, and journal retry identity/version checks; full table structure is outside this classification. Windows path rejection is preserved; Windows ACL hardening remains operator-owned |