Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(retrieval): show observation text only to a session's readers

AkitaOnRails0a8742e822fa
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 9de6f39f..9c9f93ef 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -796,6 +796,9 @@ struct ProjectSearchOptions<'a> {
include_expired: bool,
explain: bool,
include_superseded: bool,
+ /// The caller's session-timeline owner filter: observation excerpts come
+ /// only from sessions it admits.
+ owner: &'a ai_memory_core::OwnerFilter,
}
/// Borrow an embedded query as the store's vector-stream input.
@@ -2433,6 +2436,7 @@ impl AiMemoryServer {
expiry_cutoff_us: expiry_cutoff,
include_superseded: options.include_superseded,
explain: options.explain,
+ owner: options.owner,
},
)
.await
@@ -2780,6 +2784,12 @@ impl AiMemoryServer {
// Explain-only: per-stream timings of the primary search, summed over
// `scopes`. `None` on the normal path, which reads no clocks for it.
let mut timings: Option<ai_memory_store::StreamTimings> = None;
+ // Session pages are shared and every operator's observations may vote
+ // for them, but observation text (a hit's excerpt, explain's
+ // observation ids, the raw fallback) follows the session timeline's
+ // owner rule.
+ let owner_filter =
+ ai_memory_core::OwnerFilter::for_actor_context(&crate::actor::actor_from_parts(&parts));
let options = ProjectSearchOptions {
query: &args.query,
query_vec: query_vec.as_ref(),
@@ -2787,6 +2797,7 @@ impl AiMemoryServer {
include_expired,
explain,
include_superseded,
+ owner: &owner_filter,
};
let hits = if let Some(scopes) = &resolved_scopes {
self.search_scopes(scopes, options).await
@@ -2828,7 +2839,13 @@ impl AiMemoryServer {
for &(ws, proj) in scopes {
let mut scope_obs = self
.reader
- .search_observations_for_project(ws, proj, query.clone(), limit)
+ .search_observations_for_project_as(
+ ws,
+ proj,
+ query.clone(),
+ limit,
+ owner_filter.clone(),
+ )
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
obs.append(&mut scope_obs);
@@ -2850,7 +2867,7 @@ impl AiMemoryServer {
)
.await?;
self.reader
- .search_observations_for_project(ws, proj, query, limit)
+ .search_observations_for_project_as(ws, proj, query, limit, owner_filter.clone())
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?
};
@@ -2899,6 +2916,7 @@ impl AiMemoryServer {
include_expired,
explain,
include_superseded,
+ owner: &owner_filter,
},
)
.await
@@ -2968,6 +2986,7 @@ impl AiMemoryServer {
include_expired,
explain,
include_superseded,
+ owner: &owner_filter,
},
)
.await
@@ -10935,6 +10954,154 @@ mod tests {
assert!(text.contains("quokka"), "expected raw snippet; got {text}");
}
+ /// `memory_query` hands the store the caller's session-timeline owner
+ /// filter. Operator B searching words only operator A's owned session
+ /// holds gets A's shared session page (the vote stays), but no excerpt of
+ /// A's observation, no observation id in `explain`, and no raw fallback
+ /// hit. Control: A gets all three.
+ #[tokio::test]
+ async fn memory_query_shows_observation_text_only_to_its_sessions_owner() {
+ let (_tmp, store, server, ws, proj) = setup_server().await;
+ let owner = ai_memory_core::IdentityKey::User("alice".into()).storage_key();
+ let mut observation_ids = Vec::new();
+ let mut sessions = Vec::new();
+ for (body, with_page) in [
+ ("alice private quokka rollout detail", true),
+ ("alice private wombat rollout detail", false),
+ ] {
+ let session_id = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ occurred_at: None,
+ id: session_id,
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: AgentKind::Codex,
+ cwd: None,
+ actor_user: Some(owner.clone()),
+ })
+ .await
+ .unwrap();
+ observation_ids.push(
+ store
+ .writer
+ .insert_observation(Sanitized::new(
+ NewObservation {
+ occurred_at: None,
+ session_id,
+ workspace_id: ws,
+ project_id: proj,
+ kind: ObservationKind::UserPrompt,
+ extension: None,
+ source_event: None,
+ title: "prompt".into(),
+ body: body.into(),
+ importance: 5,
+ },
+ &Sanitizer::builtin(),
+ ))
+ .await
+ .unwrap(),
+ );
+ if with_page {
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new(format!("sessions/{session_id}.md")).unwrap(),
+ title: "Alice session".into(),
+ body: "Alice worked on 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();
+ }
+ sessions.push(session_id);
+ }
+ let parts_for = |user: &str| {
+ let mut parts = test_parts_default();
+ parts.extensions.insert(ai_memory_core::AuthLevel::User);
+ parts.extensions.insert(ai_memory_core::ActorContext {
+ user: Some(user.to_string()),
+ ..ai_memory_core::ActorContext::default()
+ });
+ parts
+ };
+ let query = |user: &str, term: &str| {
+ let server = server.clone();
+ let parts = parts_for(user);
+ let term = term.to_string();
+ async move {
+ let result = server
+ .memory_query(
+ Parameters(QueryArgs {
+ query: term,
+ limit: Some(5),
+ project: Some("scratch".into()),
+ scopes: Vec::new(),
+ workspace: Some("default".into()),
+ global: None,
+ include_expired: None,
+ include_superseded: None,
+ pin_first: None,
+ explain: Some(true),
+ as_of: None,
+ answer: None,
+ reasoning: None,
+ }),
+ OptionalParts(parts),
+ )
+ .await
+ .unwrap();
+ let text = result.content[0].as_text().unwrap().text.clone();
+ serde_json::from_str::<serde_json::Value>(&text).unwrap()
+ }
+ };
+ let session_path = format!("sessions/{}.md", sessions[0]);
+
+ let bob = query("bob", "quokka").await;
+ let hit = bob["hits"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|hit| hit["path"] == session_path.as_str())
+ .unwrap_or_else(|| panic!("the shared session page still ranks for bob: {bob}"));
+ let rendered = bob.to_string();
+ assert!(!rendered.contains("quokka"), "no excerpt for bob: {bob}");
+ assert!(
+ !rendered.contains(&observation_ids[0].to_string()),
+ "no observation id for bob: {bob}"
+ );
+ assert_eq!(hit["score_details"]["observation_rank"], 1, "{bob}");
+ let bob_raw = query("bob", "wombat").await;
+ assert!(
+ bob_raw["raw_hits"].as_array().is_none_or(Vec::is_empty),
+ "no raw hit from alice's session for bob: {bob_raw}"
+ );
+
+ let alice = query("alice", "quokka").await;
+ assert!(alice.to_string().contains("quokka"), "{alice}");
+ assert!(
+ alice.to_string().contains(&observation_ids[0].to_string()),
+ "{alice}"
+ );
+ let alice_raw = query("alice", "wombat").await;
+ assert_eq!(
+ alice_raw["raw_hits"].as_array().map(Vec::len),
+ Some(1),
+ "{alice_raw}"
+ );
+ }
+
#[tokio::test]
async fn memory_query_returns_raw_hits_via_explicit_scopes() {
// The raw-observation fallback must also fire on the explicit
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 3f97560d..33932fd5 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -695,12 +695,61 @@ struct ObservationVote {
title: String,
/// FTS5 snippet of the session's best-ranked matching observation.
/// Observations are sanitized and bounded on the way in, and the snippet
- /// is a bounded window over that stored text.
- snippet: String,
- /// Best-ranked first, at most [`OBSERVATION_STREAM_IDS_PER_PAGE`].
+ /// is a bounded window over that stored text. `None` when the caller's
+ /// owner filter may not read the session: the vote still counts, since
+ /// session pages are shared, but the observation text stays with its
+ /// owner.
+ snippet: Option<String>,
+ /// Best-ranked first, at most [`OBSERVATION_STREAM_IDS_PER_PAGE`]; empty
+ /// under the same rule as `snippet`.
observation_ids: Vec<ObservationId>,
}
+/// The voting sessions whose observations `owner_filter` may not read, by
+/// the session-timeline rule ([`OwnerFilter::admits`] on `sessions.actor_user`).
+///
+/// `OwnerFilter::Any` hides nothing and reads nothing, so the single-user and
+/// evaluation paths run exactly the query they ran before. One batched read
+/// over at most the stream's candidate sessions otherwise.
+fn sessions_hidden_from(
+ conn: &rusqlite::Connection,
+ owner_filter: &OwnerFilter,
+ sessions: &[(SessionId, String, Vec<ObservationId>)],
+) -> StoreResult<std::collections::HashSet<SessionId>> {
+ let mut hidden = std::collections::HashSet::new();
+ if matches!(owner_filter, OwnerFilter::Any) || sessions.is_empty() {
+ return Ok(hidden);
+ }
+ let placeholders = vec!["?"; sessions.len()].join(", ");
+ let mut stmt = conn.prepare(&format!(
+ "SELECT id, actor_user FROM sessions WHERE id IN ({placeholders})"
+ ))?;
+ let ids: Vec<Value> = sessions
+ .iter()
+ .map(|(session_id, _, _)| Value::Blob(session_id.as_bytes().to_vec()))
+ .collect();
+ let rows = stmt.query_map(params_from_iter(ids.iter()), |row| {
+ Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, Option<String>>(1)?))
+ })?;
+ let mut known = std::collections::HashSet::new();
+ for row in rows {
+ let (id_bytes, actor_user) = row?;
+ let session_id = SessionId::from_slice(&id_bytes)?;
+ known.insert(session_id);
+ if !owner_filter.admits(actor_user.as_deref()) {
+ hidden.insert(session_id);
+ }
+ }
+ // An observation whose session row is gone has no owner to check
+ // against; keep its text back rather than guess.
+ for (session_id, _, _) in sessions {
+ if !known.contains(session_id) {
+ hidden.insert(*session_id);
+ }
+ }
+ Ok(hidden)
+}
+
/// Which seed page pulled a hit in via graph expansion, and the link
/// direction. Part of [`SearchExplain`].
#[derive(Debug, Clone, Serialize)]
@@ -774,6 +823,9 @@ pub struct HybridSearch<'a> {
pub include_superseded: bool,
/// Attach per-hit [`SearchExplain`] and per-stream [`StreamTimings`].
pub explain: bool,
+ /// Who is asking, as the session timeline sees them: an observation
+ /// excerpt is attached only from a session this filter admits.
+ pub owner: &'a OwnerFilter,
}
/// Per-query wall time of each retrieval stream, in milliseconds, for an
@@ -2946,6 +2998,10 @@ impl ReaderPool {
out.truncate(limit);
Ok(out)
}
+ /// Raw-observation FTS over one project, with no owner filter: every
+ /// session's observations. Internal callers and tests use this; a
+ /// caller answering on someone's behalf uses
+ /// [`Self::search_observations_for_project_as`].
///
/// # Errors
/// Propagates any SQL or pool error.
@@ -2955,13 +3011,50 @@ impl ReaderPool {
project_id: ProjectId,
query: String,
limit: usize,
+ ) -> StoreResult<Vec<ObservationHit>> {
+ self.search_observations_for_project_as(
+ workspace_id,
+ project_id,
+ query,
+ limit,
+ OwnerFilter::Any,
+ )
+ .await
+ }
+
+ /// Raw-observation FTS over one project, limited to sessions
+ /// `owner_filter` admits: the rule `memory_read_session_observations`
+ /// and the web session timeline apply (the caller's own sessions plus
+ /// unattributed ones). Another operator's owned session contributes no
+ /// hit.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn search_observations_for_project_as(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ query: String,
+ limit: usize,
+ owner_filter: OwnerFilter,
) -> StoreResult<Vec<ObservationHit>> {
let fts_query = normalize_fts_query(&query, &self.fts_stopwords);
if fts_query.is_empty() {
return Ok(Vec::new());
}
self.with_conn(move |conn| {
- let mut stmt = conn.prepare(
+ let owner_clause = match &owner_filter {
+ OwnerFilter::Any => "",
+ OwnerFilter::User(_) => {
+ " AND EXISTS (SELECT 1 FROM sessions s WHERE s.id = observations.session_id \
+ AND (s.actor_user IS NULL OR s.actor_user = ?5))"
+ }
+ OwnerFilter::Unattributed => {
+ " AND EXISTS (SELECT 1 FROM sessions s WHERE s.id = observations.session_id \
+ AND s.actor_user IS NULL)"
+ }
+ };
+ let mut stmt = conn.prepare(&format!(
"SELECT observations.id, observations.session_id, observations.kind, \
observations.title, \
snippet(observations_fts, 1, '<mark>', '</mark>', '…', 24) AS snip, \
@@ -2970,37 +3063,44 @@ impl ReaderPool {
JOIN observations ON observations.rowid = observations_fts.rowid \
WHERE observations_fts MATCH ?1 \
AND observations.workspace_id = ?2 \
- AND observations.project_id = ?3 \
+ AND observations.project_id = ?3{owner_clause} \
ORDER BY observations_fts.rank \
LIMIT ?4",
- )?;
+ ))?;
+ let actor = match &owner_filter {
+ OwnerFilter::User(user) => Some(user.as_str()),
+ OwnerFilter::Any | OwnerFilter::Unattributed => None,
+ };
+ let mut sql_params: Vec<&dyn rusqlite::ToSql> = Vec::with_capacity(5);
+ let ws_bytes = workspace_id.as_bytes();
+ let proj_bytes = project_id.as_bytes();
#[allow(clippy::cast_possible_wrap)]
- let rows = stmt.query_map(
- params![
- fts_query,
- workspace_id.as_bytes(),
- project_id.as_bytes(),
- limit as i64,
- ],
- |row| {
- let id_bytes: Vec<u8> = row.get(0)?;
- let session_bytes: Vec<u8> = row.get(1)?;
- let kind: String = row.get(2)?;
- let title: String = row.get(3)?;
- let snippet: String = row.get(4)?;
- let rank: f64 = row.get(5)?;
- let created_us: i64 = row.get(6)?;
- Ok((
- id_bytes,
- session_bytes,
- kind,
- title,
- snippet,
- rank,
- created_us,
- ))
- },
- )?;
+ let limit = limit as i64;
+ sql_params.push(&fts_query);
+ sql_params.push(&ws_bytes);
+ sql_params.push(&proj_bytes);
+ sql_params.push(&limit);
+ if let Some(actor) = &actor {
+ sql_params.push(actor);
+ }
+ let rows = stmt.query_map(sql_params.as_slice(), |row| {
+ let id_bytes: Vec<u8> = row.get(0)?;
+ let session_bytes: Vec<u8> = row.get(1)?;
+ let kind: String = row.get(2)?;
+ let title: String = row.get(3)?;
+ let snippet: String = row.get(4)?;
+ let rank: f64 = row.get(5)?;
+ let created_us: i64 = row.get(6)?;
+ Ok((
+ id_bytes,
+ session_bytes,
+ kind,
+ title,
+ snippet,
+ rank,
+ created_us,
+ ))
+ })?;
let mut hits = Vec::new();
for row in rows {
@@ -3041,6 +3141,7 @@ impl ReaderPool {
query: &str,
candidate_limit: usize,
cutoff: i64,
+ owner_filter: OwnerFilter,
) -> StoreResult<Vec<ObservationVote>> {
let fts_query = normalize_fts_query(query, &self.fts_stopwords);
if fts_query.is_empty() || candidate_limit == 0 {
@@ -3128,6 +3229,7 @@ impl ReaderPool {
if sessions.is_empty() {
return Ok(Vec::new());
}
+ let hidden = sessions_hidden_from(&tx, &owner_filter, &sessions)?;
let mut sql_params: Vec<Value> = Vec::with_capacity(sessions.len() + 3);
sql_params.push(Value::Blob(workspace_id.as_bytes().to_vec()));
@@ -3174,12 +3276,17 @@ impl ReaderPool {
let Some((page_id, title)) = pages.remove(&path) else {
continue;
};
+ let readable = !hidden.contains(&session_id);
votes.push(ObservationVote {
page_id,
path: PagePath::new(path)?,
title,
- snippet,
- observation_ids,
+ snippet: readable.then_some(snippet),
+ observation_ids: if readable {
+ observation_ids
+ } else {
+ Vec::new()
+ },
});
if votes.len() == candidate_limit {
break;
@@ -5963,6 +6070,7 @@ impl ReaderPool {
expiry_cutoff_us,
false,
include_superseded,
+ &OwnerFilter::Any,
)
.await?
.0
@@ -6040,6 +6148,7 @@ impl ReaderPool {
expiry_cutoff_us,
true,
include_superseded,
+ &OwnerFilter::Any,
)
.await?;
// Belief-strength fields (`evidence_count`, `confidence`,
@@ -6103,6 +6212,7 @@ impl ReaderPool {
search.expiry_cutoff_us,
search.explain,
search.include_superseded,
+ search.owner,
)
.await?;
if search.explain {
@@ -6185,6 +6295,7 @@ impl ReaderPool {
expiry_cutoff_us: Option<i64>,
explain: bool,
include_superseded: bool,
+ owner_filter: &OwnerFilter,
) -> 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)`
@@ -6338,6 +6449,7 @@ impl ReaderPool {
&observation_query,
candidate_limit,
cutoff,
+ owner_filter.clone(),
)
.await?;
timings.observation_ms = elapsed_ms(started);
@@ -6493,10 +6605,15 @@ impl ReaderPool {
observation_snippet: None,
});
entry.score += contrib;
- if entry.title.is_empty() {
- entry.title = vote.title;
+ // A vote from a session the caller may not read still ranks the
+ // shared page, but leaves its title empty so the descriptor fill
+ // below gives the hit the page's own title and snippet.
+ if vote.snippet.is_some() {
+ if entry.title.is_empty() {
+ entry.title = vote.title;
+ }
+ entry.observation_snippet = 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;
@@ -12673,6 +12790,7 @@ mod tests {
None,
explain,
false,
+ &OwnerFilter::Any,
)
};
let (_, off) = search(false).await.unwrap();
diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rs
index ca221c1f..5a5d3816 100644
--- a/crates/ai-memory-store/tests/suite/multi_session.rs
+++ b/crates/ai-memory-store/tests/suite/multi_session.rs
@@ -3505,3 +3505,163 @@ async fn another_operators_observations_lift_their_session_page_in_a_shared_proj
assert_eq!(hits[0].0.path.as_str(), format!("sessions/{sid}.md"));
assert_eq!(hits[0].1.observation_ids, vec![evidence]);
}
+
+/// Begin a session owned by `owner` (`None`: unattributed, as a single-user
+/// server or a legacy row stores it).
+async fn owned_session(
+ store: &Store,
+ ws: WorkspaceId,
+ proj: ProjectId,
+ owner: Option<String>,
+) -> SessionId {
+ let id = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ occurred_at: None,
+ id,
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: AgentKind::Codex,
+ cwd: Some("/repo".into()),
+ actor_user: owner,
+ })
+ .await
+ .unwrap();
+ id
+}
+
+async fn explained_search_as(
+ store: &Store,
+ ws: WorkspaceId,
+ proj: ProjectId,
+ query: &str,
+ owner: &OwnerFilter,
+) -> Vec<(ai_memory_store::PageHit, ai_memory_store::SearchExplain)> {
+ store
+ .reader
+ .hybrid_search_scopes(
+ &[(ws, proj)],
+ ai_memory_store::HybridSearch {
+ query,
+ vector: None,
+ limit: 10,
+ expiry_cutoff_us: None,
+ include_superseded: false,
+ explain: true,
+ owner,
+ },
+ )
+ .await
+ .unwrap()
+ .0
+ .into_iter()
+ .map(|(hit, details)| (hit, details.unwrap()))
+ .collect()
+}
+
+/// Session pages are shared (invariant #16), so another operator's
+/// observations may still vote for one. The observation text is not: the
+/// excerpt a vote attaches, the observation ids in `explain`, and the
+/// raw-observation fallback follow the session timeline's owner rule, so
+/// operator B searching A's words learns that A's session page matches but
+/// never reads A's observation. Controls: A sees their own excerpt, and an
+/// unattributed session's excerpt reaches everyone, as does the unfiltered
+/// single-user path.
+#[tokio::test]
+async fn observation_excerpts_follow_the_session_owner_while_the_vote_stays_shared() {
+ use super::retrieval_observation_stream::{observe, session_page};
+
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+ let alice = OwnerFilter::User(operator("alice"));
+ let bob = OwnerFilter::User(operator("bob"));
+
+ let a_session = owned_session(&store, ws, proj, Some(operator("alice"))).await;
+ session_page(&store, ws, proj, a_session, "Alice worked on the build.").await;
+ let a_obs = observe(
+ &store,
+ ws,
+ proj,
+ a_session,
+ "alice private quasar credentials discussion",
+ )
+ .await;
+ let shared_session = owned_session(&store, ws, proj, None).await;
+ session_page(&store, ws, proj, shared_session, "A legacy session.").await;
+ let shared_obs = observe(&store, ws, proj, shared_session, "the zebra migration plan").await;
+
+ let a_path = format!("sessions/{a_session}.md");
+
+ // B: the vote still lifts A's shared session page, but nothing of A's
+ // observation comes with it.
+ let hits = explained_search_as(&store, ws, proj, "quasar", &bob).await;
+ let (hit, details) = hits
+ .iter()
+ .find(|(hit, _)| hit.path.as_str() == a_path)
+ .expect("the shared session page still ranks for B");
+ assert_eq!(details.observation_rank, Some(1));
+ assert!(details.observation_ids.is_empty(), "{details:?}");
+ assert!(!hit.snippet.contains("quasar"), "{}", hit.snippet);
+ assert!(!hit.snippet.contains("credentials"), "{}", hit.snippet);
+ assert!(
+ hit.snippet.contains("Alice worked"),
+ "page's own snippet: {}",
+ hit.snippet
+ );
+ assert!(!hit.title.is_empty());
+ for filter in [&bob, &OwnerFilter::Unattributed] {
+ let raw = store
+ .reader
+ .search_observations_for_project_as(ws, proj, "quasar".into(), 10, filter.clone())
+ .await
+ .unwrap();
+ assert!(
+ raw.is_empty(),
+ "{filter:?} must get no raw hit from A: {raw:?}"
+ );
+ }
+
+ // Control: A reads their own excerpt and raw hit.
+ let hits = explained_search_as(&store, ws, proj, "quasar", &alice).await;
+ let (hit, details) = hits
+ .iter()
+ .find(|(hit, _)| hit.path.as_str() == a_path)
+ .unwrap();
+ assert_eq!(details.observation_ids, vec![a_obs]);
+ assert!(hit.snippet.contains("quasar"), "{}", hit.snippet);
+ let raw = store
+ .reader
+ .search_observations_for_project_as(ws, proj, "quasar".into(), 10, alice.clone())
+ .await
+ .unwrap();
+ assert_eq!(raw.len(), 1);
+ assert_eq!(raw[0].session_id, a_session);
+
+ // Control: an unattributed session's excerpt reaches every viewer.
+ let shared_path = format!("sessions/{shared_session}.md");
+ for filter in [&alice, &bob, &OwnerFilter::Unattributed, &OwnerFilter::Any] {
+ let hits = explained_search_as(&store, ws, proj, "zebra", filter).await;
+ let (hit, details) = hits
+ .iter()
+ .find(|(hit, _)| hit.path.as_str() == shared_path)
+ .unwrap();
+ assert_eq!(details.observation_ids, vec![shared_obs], "{filter:?}");
+ assert!(hit.snippet.contains("zebra"), "{filter:?}: {}", hit.snippet);
+ let raw = store
+ .reader
+ .search_observations_for_project_as(ws, proj, "zebra".into(), 10, filter.clone())
+ .await
+ .unwrap();
+ assert_eq!(raw.len(), 1, "{filter:?}");
+ }
+
+ // Control: the unfiltered single-user path is unchanged.
+ let hits = explained_search_as(&store, ws, proj, "quasar", &OwnerFilter::Any).await;
+ let (hit, _) = hits
+ .iter()
+ .find(|(hit, _)| hit.path.as_str() == a_path)
+ .unwrap();
+ assert!(hit.snippet.contains("quasar"), "{}", hit.snippet);
+}
diff --git a/crates/ai-memory-web/src/recall.rs b/crates/ai-memory-web/src/recall.rs
index 520304af..e84e34a4 100644
--- a/crates/ai-memory-web/src/recall.rs
+++ b/crates/ai-memory-web/src/recall.rs
@@ -16,7 +16,7 @@
use std::sync::Arc;
-use ai_memory_core::{ProjectId, WorkspaceId};
+use ai_memory_core::{OwnerFilter, ProjectId, WorkspaceId};
use ai_memory_llm::{Embedder, QueryVector, RerankCandidate, RerankStage};
use ai_memory_store::{
HybridSearch, PageHit, SearchExplain, StoreResult, StreamTimings, VectorQuery,
@@ -46,13 +46,16 @@ pub(crate) struct RecallResult {
}
/// Rank `query` over `scopes` exactly as a `memory_query` project/scopes
-/// search does (latest versions only, expired pages hidden).
+/// search does (latest versions only, expired pages hidden). `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(
state: &WebState,
scopes: &[(WorkspaceId, ProjectId)],
query: &str,
limit: usize,
explain: bool,
+ owner: &OwnerFilter,
) -> StoreResult<RecallResult> {
let query_vector: Option<QueryVector> = match &state.recall.embedder {
Some(embedder) => ai_memory_llm::embed_search_query(embedder.as_ref(), query).await,
@@ -79,6 +82,7 @@ pub(crate) async fn search_scopes(
expiry_cutoff_us: None,
include_superseded: false,
explain,
+ owner,
},
)
.await?;
diff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rs
index aa5ecb5f..ffed748f 100644
--- a/crates/ai-memory-web/src/routes/api.rs
+++ b/crates/ai-memory-web/src/routes/api.rs
@@ -349,21 +349,23 @@ async fn history_handler(
async fn search_handler(
State(state): State<Arc<WebState>>,
viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ actor: Option<axum::Extension<ai_memory_core::ActorContext>>,
RawQuery(raw_query): RawQuery,
) -> Result<Response, Response> {
let query = SearchQuery::from_raw(raw_query.as_deref()).map_err(ApiFailure::into_response)?;
let request = query
.try_into_request()
.map_err(ApiFailure::into_response)?;
- search_with_request(&state, request, viewer_of(viewer)).await
+ search_with_request(&state, request, viewer_of(viewer), &owner_filter_for(actor)).await
}
async fn search_post_handler(
State(state): State<Arc<WebState>>,
viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ actor: Option<axum::Extension<ai_memory_core::ActorContext>>,
Json(request): Json<SearchRequest>,
) -> Result<Response, Response> {
- search_with_request(&state, request, viewer_of(viewer)).await
+ search_with_request(&state, request, viewer_of(viewer), &owner_filter_for(actor)).await
}
// A global search is FTS5 over every readable repository, as
@@ -374,6 +376,7 @@ async fn search_with_request(
state: &WebState,
request: SearchRequest,
viewer: Option<ai_memory_core::UserId>,
+ owner: &ai_memory_core::OwnerFilter,
) -> Result<Response, Response> {
let term = request.q.trim().to_owned();
if term.is_empty() {
@@ -403,7 +406,7 @@ async fn search_with_request(
.iter()
.map(|scope| (scope.workspace_id, scope.project_id))
.collect();
- crate::recall::search_scopes(state, &scopes, &term, limit, false)
+ crate::recall::search_scopes(state, &scopes, &term, limit, false, owner)
.await
.map(|result| result.hits.into_iter().map(|(hit, _)| hit).collect())
}
diff --git a/crates/ai-memory-web/src/routes/search.rs b/crates/ai-memory-web/src/routes/search.rs
index 4a3bde48..669c7c86 100644
--- a/crates/ai-memory-web/src/routes/search.rs
+++ b/crates/ai-memory-web/src/routes/search.rs
@@ -75,6 +75,7 @@ fn non_empty(value: Option<&str>) -> Option<&str> {
pub(crate) async fn handler(
State(state): State<Arc<WebState>>,
viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ actor: Option<axum::Extension<ai_memory_core::ActorContext>>,
Query(params): Query<SearchParams>,
) -> Response {
let query = params.q.trim().to_owned();
@@ -139,6 +140,7 @@ pub(crate) async fn handler(
&query,
limit + 1,
explain,
+ &super::api::owner_filter_for(actor),
)
.await
{
diff --git a/crates/ai-memory-web/tests/suite/recall_trace.rs b/crates/ai-memory-web/tests/suite/recall_trace.rs
index 7f3e07dc..e008ebce 100644
--- a/crates/ai-memory-web/tests/suite/recall_trace.rs
+++ b/crates/ai-memory-web/tests/suite/recall_trace.rs
@@ -419,3 +419,110 @@ async fn search_scope_selector_lists_only_readable_projects() {
assert!(body.contains(r#"<option value="default/alpha">"#), "{body}");
assert!(body.contains(r#"<option value="default/beta">"#), "{body}");
}
+
+/// Web and `/api/v1` project search apply `memory_query`'s owner rule to
+/// observation text: another operator's owned session still lifts its shared
+/// session page, but the hit shows the page's own snippet and the trace no
+/// observation id. Control: the session's owner sees the excerpt.
+#[tokio::test]
+async fn project_search_shows_observation_excerpts_only_to_the_sessions_owner() {
+ 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();
+ 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: Some(ai_memory_core::IdentityKey::User("alice".into()).storage_key()),
+ })
+ .await
+ .unwrap();
+ let observation_id = 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: "quokka plutonium shipment notes".into(),
+ importance: 5,
+ },
+ &ai_memory_core::Sanitizer::builtin(),
+ ))
+ .await
+ .unwrap();
+ f.store
+ .writer
+ .upsert_page(ai_memory_core::NewPage {
+ workspace_id: ws,
+ project_id: f.alpha,
+ path: PagePath::new(format!("sessions/{session_id}.md")).unwrap(),
+ title: "Alice session".into(),
+ body: "Alice 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::default());
+ let as_operator = |user: &'static str, uri: &'static str| {
+ let app = app.clone();
+ async move {
+ let request = Request::builder()
+ .uri(uri)
+ .extension(ActorContext {
+ user: Some(user.into()),
+ ..ActorContext::default()
+ })
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(request).await.unwrap();
+ let status = resp.status();
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ (status, String::from_utf8_lossy(&body).into_owned())
+ }
+ };
+ let session_path = format!("sessions/{session_id}.md");
+ for uri in [
+ "/web/search?q=quokka&workspace=default&project=alpha&explain=1",
+ "/api/v1/search?q=quokka&workspace=default&project=alpha",
+ ] {
+ let (status, body) = as_operator("bob", uri).await;
+ assert_eq!(status, StatusCode::OK, "{uri}: {body}");
+ assert!(body.contains(&session_path), "{uri}: vote kept: {body}");
+ assert!(!body.contains("plutonium"), "{uri}: excerpt leaked: {body}");
+ assert!(
+ !body.contains(&observation_id.to_string()),
+ "{uri}: observation id leaked: {body}"
+ );
+ let (status, body) = as_operator("alice", uri).await;
+ assert_eq!(status, StatusCode::OK, "{uri}: {body}");
+ assert!(body.contains("plutonium"), "{uri}: owner's excerpt: {body}");
+ }
+}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index e30e8924..e97bc1ab 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -164,9 +164,14 @@ from hook paths.
`sessions/<id>.md` page in that scope. The vote never crosses projects (both
the observation and the page are scope-filtered), a session without a page
contributes nothing, and nothing is written. Setting it to `false` restores
- the earlier ranking byte for byte. If
+ the earlier ranking byte for byte. Every operator's observations vote, since
+ session pages are shared, but a vote's excerpt and observation ids are
+ attached only when the caller may read that session under the session
+ timeline's owner rule (their own sessions and unattributed ones); otherwise
+ the hit shows the page's own snippet. If
compiled wiki pages miss entirely in default, explicit project, or explicit
- `scopes` mode, bounded raw observation FTS returns fallback `raw_hits`;
+ `scopes` mode, bounded raw observation FTS returns fallback `raw_hits`, from
+ sessions the caller may read under that same rule;
`global=true` searches compiled wiki pages across projects only. Page hits
bump `access_count` + `last_accessed_at`, the M8 reinforcement term, which
`memory_feedback` complements with explicit per-page salience. Identified
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 9e6be216..4a60127c 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -22,7 +22,7 @@ means the boundary is not built yet.
| # | Boundary | Enforcing code | Adversarial test(s) | Coverage |
|---|----------|----------------|---------------------|----------|
-| 1 | Per-project isolation (3-tuple) | `ai-memory-store/src/scope.rs` `ScopeResolver::resolve_read_args`/`resolve_write_args`, no-create `lookup_existing_scope`; reader queries filter by `(workspace_id, project_id)`; `reader.rs` `sessions_for_scope_filtered` joins only consolidation jobs in the requested workspace and project; `reader.rs` `incremental_pages` filters workspace and project before its keyset and limit; `reader.rs` `session_counts_by_agent` filters mixed-source observations by the requested workspace and project; `reader.rs` `observation_stream_votes` (`[retrieval] observation_stream`, on by default) filters both the matching observations and the `sessions/<id>.md` page they vote for to the queried workspace and project; `reader.rs` `page_versions` / `page_version_body` (web page history) read by `(workspace_id, project_id, path)` and take a caller's version id only inside that triple; `ai-memory-web` `routes/session.rs` takes a raw session id only through `session_summary_scoped` (row or observation in the project, owner filter) and `session_observations_scoped` | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs`; `session_observations.rs` `consolidation_summary_latest_generation_is_scope_and_owner_bound` (a foreign-scope job is absent; the own latest generation and owner controls pass), `incremental_pages_equal_timestamps_cutoff_expiry_and_foreign_scope` (foreign scope absent with a same-scope control), `mixed_capture_count_scopes_observations_and_preserves_owner_and_window` (foreign-scope observations cannot turn an own session into a mixed one; same-scope control can); handoff receiver-session scope: see row 4, `multi_session.rs` `handoff_accept_rejects_foreign_or_missing_receiver_session` (cross-project and cross-workspace receivers refused); `multi_session.rs` `observation_stream_never_crosses_a_project_or_workspace` (a home observation cannot vote for a same-path session page in another project or workspace, and a foreign project's observation cannot lift a home page; control: home's own page receives the vote), fails with either the observation or the page scope filter removed; `multi_session.rs` `page_history_keeps_the_overwritten_version_and_stays_in_scope` (a sibling project's or another workspace's version id, or a home id under another path, reads as `None`; control: both home versions); `ai-memory-web` `history_replay.rs` `history_refuses_foreign_project_workspace_and_version_ids` (another project's or workspace's path, and a foreign version id as `from` or `to`, answer 404 on `/web/w/…/h/*path` and `/api/v1/…/history/*path` without the foreign text; control: the home history lists only home's rows at a path a sibling also uses, and an explicit home pair diffs) and `session_timeline_refuses_foreign_session_ids` (a sibling project's or another workspace's session id and an unknown id → 404, another operator's owned session → 404; controls: the home session, and the owner reading theirs); bite: dropping the scope filter from `page_version_body` or the project filter from `page_versions`, or replacing the `session_summary_scoped` check or its owner filter, fails them | STRONG |
+| 1 | Per-project isolation (3-tuple) | `ai-memory-store/src/scope.rs` `ScopeResolver::resolve_read_args`/`resolve_write_args`, no-create `lookup_existing_scope`; reader queries filter by `(workspace_id, project_id)`; `reader.rs` `sessions_for_scope_filtered` joins only consolidation jobs in the requested workspace and project; `reader.rs` `incremental_pages` filters workspace and project before its keyset and limit; `reader.rs` `session_counts_by_agent` filters mixed-source observations by the requested workspace and project; `reader.rs` `observation_stream_votes` (`[retrieval] observation_stream`, on by default) filters both the matching observations and the `sessions/<id>.md` page they vote for to the queried workspace and project, and attaches a vote's observation excerpt and ids only when the caller's session-timeline owner filter admits the session (`sessions_hidden_from`; `HybridSearch::owner`, threaded from `memory_query`, `/web/search` and `/api/v1/search` through `OwnerFilter::for_actor_context`); the raw-observation fallback `search_observations_for_project_as` drops sessions that filter does not admit; `reader.rs` `page_versions` / `page_version_body` (web page history) read by `(workspace_id, project_id, path)` and take a caller's version id only inside that triple; `ai-memory-web` `routes/session.rs` takes a raw session id only through `session_summary_scoped` (row or observation in the project, owner filter) and `session_observations_scoped` | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs`; `session_observations.rs` `consolidation_summary_latest_generation_is_scope_and_owner_bound` (a foreign-scope job is absent; the own latest generation and owner controls pass), `incremental_pages_equal_timestamps_cutoff_expiry_and_foreign_scope` (foreign scope absent with a same-scope control), `mixed_capture_count_scopes_observations_and_preserves_owner_and_window` (foreign-scope observations cannot turn an own session into a mixed one; same-scope control can); handoff receiver-session scope: see row 4, `multi_session.rs` `handoff_accept_rejects_foreign_or_missing_receiver_session` (cross-project and cross-workspace receivers refused); `multi_session.rs` `observation_stream_never_crosses_a_project_or_workspace` (a home observation cannot vote for a same-path session page in another project or workspace, and a foreign project's observation cannot lift a home page; control: home's own page receives the vote), fails with either the observation or the page scope filter removed; `multi_session.rs` `observation_excerpts_follow_the_session_owner_while_the_vote_stays_shared` (operator B, and an unattributed caller, querying words only A's owned session holds get A's shared session page with its own snippet, no excerpt, no observation ids and no raw hit; controls: A gets the excerpt, ids and raw hit, an unattributed session's excerpt reaches every viewer, and the unfiltered single-user path is unchanged), bite-checked against both the vote guard and the raw-fallback clause; `ai-memory-mcp` `server.rs` `memory_query_shows_observation_text_only_to_its_sessions_owner` and `ai-memory-web` `recall_trace.rs` `project_search_shows_observation_excerpts_only_to_the_sessions_owner` (the same through `memory_query`, `/web/search` and `/api/v1/search`; each fails when its surface passes `OwnerFilter::Any`); `multi_session.rs` `page_history_keeps_the_overwritten_version_and_stays_in_scope` (a sibling project's or another workspace's version id, or a home id under another path, reads as `None`; control: both home versions); `ai-memory-web` `history_replay.rs` `history_refuses_foreign_project_workspace_and_version_ids` (another project's or workspace's path, and a foreign version id as `from` or `to`, answer 404 on `/web/w/…/h/*path` and `/api/v1/…/history/*path` without the foreign text; control: the home history lists only home's rows at a path a sibling also uses, and an explicit home pair diffs) and `session_timeline_refuses_foreign_session_ids` (a sibling project's or another workspace's session id and an unknown id → 404, another operator's owned session → 404; controls: the home session, and the owner reading theirs); bite: dropping the scope filter from `page_version_body` or the project filter from `page_versions`, or replacing the `session_summary_scoped` check or its owner filter, fails them | STRONG |
| 1b | Reserved `_global` scope union never leaks a foreign project (#930) | `ai-memory-mcp/src/server.rs` `memory_query` — the union runs for single-project queries (`scopes` empty) and searches **only** `lookup_global_scope`'s reserved `(workspace_id, project_id)`, never an arbitrary project; the double-search guard resolves the *queried* project (named or active) so it can't be tricked into skipping | `server.rs` `global_union_never_leaks_a_foreign_projects_pages` (a third real project's page must not surface via the union; reserved page must), `single_project_query_unions_global_scope_and_multi_scope_skips_it` | STRONG |
| 1c | Reserved `_global` scope is read-open, write-gated (GHSA-7qj3-7wqw-m5w6) | `ai-memory-store/src/project_authz.rs` `ProjectAuthz::authorize` (a write to `default/_global` needs root or a `write` grant in either access mode; creator ignored) fed by `resolve_project_authz`/`read_project_row` (`reserved_global`, grant read for the global scope regardless of mode); `ai-memory-mcp/src/server.rs` `memory_write_page` resolves `scope: "global"` through `write_target_ids_with_actor` like an explicit `default/_global` | `project_authz.rs` `the_global_scope_admits_writes_only_from_root_or_a_write_grant`; `server.rs` `a_user_without_a_global_grant_cannot_change_the_global_scope` (both spellings and delete refused for an ungranted user and for `_global`'s creator; page survives; reads stay open), `a_global_write_grant_admits_writes_and_the_union_stays_readable` (legitimate control: write grant admits both spellings, another user's restricted-project query still unions the page); bite-checked with the authz rule removed and with the raw `create_global_scope` path restored | STRONG |
| 1d | A private cross-project profile is readable and writable by its operator alone (`[profile] share = "user"`) | `ai-memory-store/src/ops.rs` `initial_access_mode` (a `_profile.<user id>` project is always created `restricted`, creator recorded in the same transaction); `ai-memory-store/src/scope.rs` `lookup_profile_scope` / `create_profile_scope` (the project name derives from the authenticated viewer's id; no database user, no private profile); `ai-memory-mcp/src/server.rs` `profile_target_ids` and the `memory_query` profile union (resolved per viewer through the per-project choke point); `scope.rs` `refuse_foreign_profile_name` (called by `ScopeResolver` explicit writes and `create_explicit_scope_guarded`: a database user may name only their own `default/_profile.<id>`, so nobody can create another operator's private profile first and lock its owner out); `ops.rs` `rename_project` (no rename onto or away from a profile name); `admin.rs` `handle_project_access` (a profile project's mode is fixed) and `move_project_core` (a private profile cannot leave `default`) | store `integration::profile` `a_private_profile_refuses_every_other_operator` (another operator's read and write by name refused; owner control admitted), `reserved_profile_projects_get_their_fixed_access_modes`; `server.rs` `a_private_profile_is_private_to_its_operator` (no union leak; read, write and delete by name refused; owner and own-profile controls); `multi_session.rs` `two_harnesses_of_one_operator_share_one_private_profile`; both fail with the restricted-mode guard removed; `server.rs` `a_user_cannot_squat_another_operators_private_profile` (another user's explicit write naming the owner's private profile refused and creates nothing; owner's profile and explicit own-name controls; fails with the name guard removed); `ops.rs` `rename_project_refuses_profile_names_both_ways`; `admin.rs` `project_access_sets_the_mode_and_refuses_what_it_must`; `admin_move.rs` `move_project_refuses_a_private_profile` | STRONG |
@@ -47,7 +47,7 @@ means the boundary is not built yet.
| 4f | Finalize-on-exit closes only a session the run provably owns (invariant #16) | `ai-memory-cli/src/commands/run.rs` `finalize_hookless_session` runs only for `harness.lacks_session_end_hook()` harnesses (Command Code, Kiro v2/v3, Antigravity); `own_native_session` returns a session only when it is named, chosen before the spawn, or linked under this run's own id in this checkout — a merely *discovered* native session (possibly a concurrent launch's) is never finalized | `run.rs` `a_session_linked_during_the_run_wins_over_discovery` — `own_native_session` returns `None` for the unlinked and other-checkout (`nested`) cases, so a foreign/concurrent session is refused; the named/linked control is finalized (#944) | STRONG |
| 4g | `memory_handoff_accept` `status` never points a caller at another session's baton | `ai-memory-store/src/reader.rs` `handoff_claimed_by_live_session` — the caller-supplied session id (header or native `_meta`, routing-only per row 6b) selects which claim to check, but the answer is bounded by the resolved `(workspace_id, project_id)`, the authenticated `handoff_owner_sql` owner filter, `state='accepted'`, and a still-open receiving session; `ai-memory-mcp/src/server.rs` `unclaimed_handoff` reports `consumed_by_hook` only on that match (and, for a requested `handoff_id`, only when it is the matched row), `none_pending` otherwise | `handoff_ownership.rs` `a_session_start_claim_is_confirmed_only_to_its_own_live_session` (forged session id under another operator, unattributed reader, foreign project, sibling session and ended session all empty; owner and root controls see the claim); `ai-memory-mcp` `tests/suite/handoff_identity.rs` `consumed_by_hook_is_reported_only_to_the_session_that_claimed_it` (over the production transport: a colleague forwarding the session id, the owner from another session, and a request with no session id all get `none_pending`; the claiming session gets `consumed_by_hook`) | STRONG |
| 4h | Offer-mode SessionStart never consumes or injects handoff-controlled text | `ai-memory-hooks/src/router.rs` `fetch_and_accept_handoff_at` branches on the startup configuration before admission/claim and `render_handoff_notice` emits only typed metadata (`HandoffId`, `AgentKind`, computed age); the normal writer CAS remains the only later claim path | `router.rs` `handoff_notice_is_metadata_only_and_never_carries_the_summary` plants hostile summary/questions/steps/files; `offer_mode_leaves_the_baton_open_and_notice_omits_the_summary` exercises the production hook route, asserts the row remains open, then proves the legitimate exact-id writer claim still consumes it (#1030) | STRONG |
-| 5a | Pages shared: `author_id` is never a read filter (invariant #16) | `ai-memory-store/src/reader.rs` `search_pages`/`page_body_by_ids` — `author_id` is an attribution JOIN only, never a WHERE term; `observation_stream_votes` takes no owner or author coordinate | `multi_session.rs` — a page with a **non-null** `author_id` (operator A) is readable by operator B in the same project; `multi_session.rs` `another_operators_observations_lift_their_session_page_in_a_shared_project` (operator B's owned session, authored page and observations lift that page for operator A's query); `ai-memory-mcp` `server.rs` `observation_stream_evidence_stays_inside_a_restricted_project` (a second operator with only a read grant gets the session page lifted by the first operator's observation) | STRONG |
+| 5a | Pages shared: `author_id` is never a read filter (invariant #16) | `ai-memory-store/src/reader.rs` `search_pages`/`page_body_by_ids` — `author_id` is an attribution JOIN only, never a WHERE term; `observation_stream_votes` lets every session vote whatever its owner (the owner filter only withholds the observation excerpt and ids, never the vote or the page) | `multi_session.rs` — a page with a **non-null** `author_id` (operator A) is readable by operator B in the same project; `multi_session.rs` `another_operators_observations_lift_their_session_page_in_a_shared_project` (operator B's owned session, authored page and observations lift that page for operator A's query); `ai-memory-mcp` `server.rs` `observation_stream_evidence_stays_inside_a_restricted_project` (a second operator with only a read grant gets the session page lifted by the first operator's observation); `multi_session.rs` `observation_excerpts_follow_the_session_owner_while_the_vote_stays_shared` (B still gets A's session page ranked by A's observation, with the page's own snippet) | STRONG |
| 5b | Page supersession (loser stays reachable) | `ai-memory-store/src/ops.rs` `upsert_page_in_tx` — demote `is_latest=0` (never delete) + `supersedes` chain; read side: `reader.rs` `page_versions` lists every row at the path, with no `is_latest` filter, for `/web/w/…/h/*path` and `/api/v1/…/history/*path`. It does apply TTL expiry (`reader.rs` `history_visible`): a version whose own `expires_at` passed is neither listed nor readable by id, a path whose live version expired shows no history at all (the forget sweep hard-deletes every row there), and a `supersedes` link to a hidden version reads as `null`. Expiry is the only thing that hides a superseded version; a concurrent write never does | `multi_session.rs` `concurrent_writes_to_one_path_supersede_rather_than_destroy`; `retrieval_superseded.rs`; `multi_session.rs` `page_history_keeps_the_overwritten_version_and_stays_in_scope`; `ai-memory-web` `history_replay.rs` `history_keeps_both_sides_of_a_concurrent_divergent_write` (two attributed writers on one base: all three versions and both authors listed, one `is_latest`, the two writers' versions diff by id) and `history_lists_k_plus_one_versions_newest_first_and_diffs_the_latest`; bite: an `is_latest = 1` filter in `page_versions` fails both; `history_hides_expired_versions_and_expired_pages` (an expired superseded version and every version of a page whose live version expired answer 404 by path and by id on HTML and JSON, and the live successor's `supersedes` is `null`; control: a TTL in the future is listed and diffable; bites with the per-row predicate removed, with the live-version clause disabled, and with the `supersedes` hiding removed) | STRONG |
| 5c | Watcher reindex and Wiki writes share per-page serialization (invariant #16) | `ai-memory-wiki/src/wiki.rs` `reindex_page` takes `mutation_lock.read` before `reindex_page_locked` takes `lock_page`, covering disk read through the single-writer upsert; callers already holding the exclusive global guard do not reacquire it. `write_page` uses the same page mutex and `apply_batch` retains sorted, deduplicated locks; embedding runs after both guards are released | `wiki.rs` `reindex_page_lock_waits_before_reading_and_allows_another_path` (transient snapshot refused while locked, another path progresses, release indexes the committed bytes without rewriting disk), `reindex_page_lock_serializes_write_through_the_upsert` and `reindex_page_lock_and_reversed_duplicate_batches_do_not_deadlock` (real concurrent operations, final disk/SQL winner and supersession ancestry preserved); all three fail with the reindex page guard removed. `reindex_page_lock_releases_both_guards_before_embedding` checks both body and abstract embedding; `decay_cleanup_reindex_does_not_embed_under_the_exclusive_lock` covers the exclusive caller | STRONG for a shared Wiki handle and its clones. External editors and independently constructed Wiki handles do not participate in these locks |
| 5d | Wiki project-tree filesystem confinement | `ai-memory-wiki/src/confinement.rs` checks the wiki root, workspace/project roots, every existing ancestor, the final component, and the in-root ordinary `.git` directory with link-aware metadata; repository workdir/gitdir/commondir are containment-checked after opening, and write parents are created one component at a time and rechecked. `Wiki` checks before admission and again under mutation/page locks, while `GitAdapter` rechecks immediately before writes, appends, renames, and removals. Direct reindex, checkpoint restore, manifests, auto-improvement artifacts, ledger append, startup repair, purge/session moves, rollback, migrations, and git tree staging use the same boundary. Confinement is a distinct `WikiError` and therefore cannot trigger missing-file DB fallback | `wiki.rs` `page_reads_refuse_leaf_and_ancestor_symlinks_without_fallback_classification`, `ai-memory-mcp` `admin_read_page.rs` `read_page_does_not_db_fallback_through_a_symlink`, `page_mutations_refuse_ancestor_symlink_and_leave_outside_and_store_unchanged`, `confinement_refusal_happens_before_blocking_and_observer_admission`, `restore_and_reindex_refuse_ancestor_symlink_without_touching_canary_or_db`; `git.rs` `git_metadata_link_is_refused_without_touching_external_repository`, `gitfile_redirect_outside_is_refused_without_touching_target`, `git_metadata_redirect_files_are_refused_before_repository_open`, `configured_worktree_outside_the_wiki_root_is_refused`, `linked_git_metadata_never_reaches_commit_fallback`, `gitfile_metadata_never_reaches_commit_fallback`, `out_of_root_worktree_never_reaches_commit_fallback`, `fallback_preflight_refuses_invalid_git_metadata`, `windows_commit_fallback_accepts_established_eligible_errors`, `eligible_windows_open_error_dispatches_the_fallback_after_validation`, `windows_init_error_dispatches_fallback_after_root_preflight`, `invalid_root_never_reaches_init_fallback`, `checkpoint_and_revision_reads_refuse_a_replaced_git_directory`, and ordinary-repository/API controls `init_is_idempotent_and_creates_dotgit`; `linked_wiki_root_is_refused_during_construction`, `linked_or_dangling_scope_roots_are_refused_but_real_roots_work`, existing `decay_cleanup_refuses_to_reindex_a_symlinked_recreation` and `reindex_rejects_symlinked_scope_manifest`; `ai-memory-mcp` `admin_move.rs` `true_move_refuses_an_invalid_destination_namespace_without_db_changes` and `delete_workspace_refuses_invalid_namespace_before_db_or_notification`; `admin_backup.rs` `backup_refuses_redirected_git_metadata_before_returning_an_archive`, `backup_refuses_wiki_leaf_links_before_returning_an_archive`, `backup_refuses_linked_wiki_directories_before_returning_an_archive`, and ordinary archive controls; `watcher.rs` `direct_file_event_skips_symlink`, `walk_markdown_skips_linked_directories_and_their_ledgers`, and `shared_link_like_helper_accepts_regular_files_and_directories` (Windows directory-link coverage exercises reparse metadata when privilege is available); `backup.rs` `a_pre_migration_backup_refuses_a_linked_wiki_tree_without_an_archive`; `confinement.rs` metadata-helper controls run on every platform | STRONG for imported/static links and same-process mutations. Component checks do not claim descriptor-relative protection against a concurrently malicious same-user process; Windows reparse behavior requires the `windows` PR label/full CI |