Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): scope bounded session reads
AkitaOnRails3bd4d333507c
diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rsindex 984f1875..cf7fe0db 100644--- a/crates/ai-memory-hooks/src/lib.rs+++ b/crates/ai-memory-hooks/src/lib.rs@@ -62,7 +62,7 @@ pub use router::{DEFAULT_PROJECT_CACHE_MAX_ENTRIES, HookState, IngestGates, IngestRateLimiter, ProjectCache,ProjectCacheStore, SubagentSessionSet, SubagentSessions, hook_router,};-pub use synth::{DigestLoadStats, SessionDigest, synthesize_session_page};+pub use synth::{SessionDigest, synthesize_session_page};pub use workstream::{WorkstreamState, workstream_router};/// Request header every first-party client (native hook and CLI, the shell anddiff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 4498d270..f5e14479 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -3801,7 +3801,11 @@ async fn process_authorized(}if state.reader- .session_has_substantive_observation(session_id)+ .session_has_substantive_observation(+ session.workspace_id(),+ session.project_id(),+ session_id,+ ).await?{recovered |= enqueue_session_end_consolidation(@@ -3976,19 +3980,10 @@ async fn process_authorized(&& !managed&& !body_is_subagent(&env.raw);if matches!(env.event, HookEvent::SessionEnd) || turn_checkpoint {- // A session can hold hundreds of thousands of rows, so nothing on this- // path loads them all: the lifecycle-only decision is one existence- // query (the writer re-checks it in the ending transaction with the- // same predicate), and the page and handoff are rendered from a- // digest read with bounded queries.- let substantive = state- .reader- .session_has_substantive_observation(session_id)- .await?;// A checkpoint writes where the session's end will: the session row's// scope, not wherever this Stop resolved (a marker may have appeared// mid-session). One that lost the race with the end writes nothing.- let checkpoint_scope = if turn_checkpoint && substantive {+ let checkpoint_scope = if turn_checkpoint {state.reader.open_session_scope(session_id).await?} else {None@@ -4000,6 +3995,16 @@ async fn process_authorized(return Ok(outcome);}let (page_ws, page_proj) = checkpoint_scope.unwrap_or((ws, proj));+ // A session can hold hundreds of thousands of rows, so nothing on this+ // path loads them all: the lifecycle-only decision is one existence+ // query (the writer re-checks it in the ending transaction with the+ // same predicate), and the page and handoff are rendered from a+ // digest read with bounded queries. Bind it to the session/page scope,+ // not the provisional scope of a mid-session marker.+ let substantive = state+ .reader+ .session_has_substantive_observation(page_ws, page_proj, session_id)+ .await?;if !substantive {let lifecycle_outcome = state.writer@@ -4037,7 +4042,7 @@ async fn process_authorized(}// Read after the decision above, so a substantive write that raced the// lifecycle-only end is in it.- let digest = SessionDigest::load(&state.reader, session_id).await?;+ let digest = SessionDigest::load(&state.reader, page_ws, page_proj, session_id).await?;// The writer observed substantive work when it answered `Substantive`,// so the digest cannot still satisfy the lifecycle-only predicate.debug_assert!(substantive || digest.is_substantive());@@ -4612,7 +4617,7 @@ async fn write_checkpoint_page({return Ok(false);}- let digest = SessionDigest::load(&state.reader, session_id).await?;+ let digest = SessionDigest::load(&state.reader, workspace_id, project_id, session_id).await?;if !digest.is_substantive() {return Ok(false);}@@ -14961,17 +14966,9 @@ mod tests {}tx.commit().unwrap();- let before = state.reader.session_observation_rows_loaded();process(&state, fire("session-end"), None, Vec::new()).await.unwrap();- let loaded = state.reader.session_observation_rows_loaded() - before;-- // Head and tail lines plus one row per early-exit scan.- assert!(- loaded <= 500 + 16,- "SessionEnd of a {FILLER}-row session loaded {loaded} rows"- );let page = state.wiki.read_page(diff --git a/crates/ai-memory-hooks/src/session_end_equivalence.rs b/crates/ai-memory-hooks/src/session_end_equivalence.rsindex 4f5f095e..52e8c702 100644--- a/crates/ai-memory-hooks/src/session_end_equivalence.rs+++ b/crates/ai-memory-hooks/src/session_end_equivalence.rs@@ -861,7 +861,9 @@ impl Fixture {let agent = AgentKind::ClaudeCode;let old_page = full_load::synthesize_session_page(self.ws, self.proj, sid, agent, &rows);- let digest = SessionDigest::load(reader, sid).await.unwrap();+ let digest = SessionDigest::load(reader, self.ws, self.proj, sid)+ .await+ .unwrap();let new_page = super::synthesize_session_page(self.ws, self.proj, sid, agent, &digest);assert_eq!(new_page.path, old_page.path, "{name}: page path");assert_eq!(new_page.title, old_page.title, "{name}: page title");@@ -922,7 +924,7 @@ impl Fixture {let ephemeral = is_ephemeral_session(&rows);assert_eq!(!reader- .session_has_substantive_observation(sid)+ .session_has_substantive_observation(self.ws, self.proj, sid).await.unwrap(),ephemeral,@@ -1252,11 +1254,9 @@ async fn a_huge_session_reads_a_bounded_number_of_rows() {"the fixture must dwarf the bound");- let before = fx.store.reader.session_observation_rows_loaded();- let (digest, stats) = SessionDigest::load_with_stats(&fx.store.reader, sid)+ let (digest, stats) = SessionDigest::load_with_stats(&fx.store.reader, fx.ws, fx.proj, sid).await.unwrap();- let loaded = fx.store.reader.session_observation_rows_loaded() - before;assert_eq!(digest.observation_count(), rows.len());assert!(@@ -1265,19 +1265,11 @@ async fn a_huge_session_reads_a_bounded_number_of_rows() {rows.len(),stats.rows_read);- assert_eq!(- loaded, stats.rows_read as u64,- "the pool's counter and the snapshot's agree"- );assert_eq!(stats.prompt_titles, prompts);// Control: the load this replaced materializes every row.let full = fx.store.reader.observations_for_session(sid).await.unwrap();assert_eq!(full.len(), rows.len());- assert_eq!(- fx.store.reader.session_observation_rows_loaded() - before - loaded,- rows.len() as u64- );// And the output did not change for being cheap.fx.assert_equivalent("12k rows", sid).await;}@@ -1310,7 +1302,7 @@ async fn subagent_preamble_bodies_stop_at_the_first_usable_one() {rows.push(end(1 + preambles as i64));let sid = fx.seed(&rows).await;- let (_, stats) = SessionDigest::load_with_stats(&fx.store.reader, sid)+ let (_, stats) = SessionDigest::load_with_stats(&fx.store.reader, fx.ws, fx.proj, sid).await.unwrap();assert_eq!(@@ -1370,10 +1362,12 @@ async fn the_ephemeral_predicate_agrees_for_every_observation_kind() {let sql = fx.store.reader- .session_has_substantive_observation(sid)+ .session_has_substantive_observation(fx.ws, fx.proj, sid)+ .await+ .unwrap();+ let digest = SessionDigest::load(&fx.store.reader, fx.ws, fx.proj, sid).await.unwrap();- let digest = SessionDigest::load(&fx.store.reader, sid).await.unwrap();assert_eq!(sql, rust, "{kind:?}: existence query vs row predicate");assert_eq!(digest.is_substantive(),diff --git a/crates/ai-memory-hooks/src/synth.rs b/crates/ai-memory-hooks/src/synth.rsindex 4a0eeb2d..75f62750 100644--- a/crates/ai-memory-hooks/src/synth.rs+++ b/crates/ai-memory-hooks/src/synth.rs@@ -169,7 +169,7 @@ pub struct SessionDigest {/// What loading a [`SessionDigest`] cost, for a bound test and for debugging.#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub struct DigestLoadStats {+pub(crate) struct DigestLoadStats {/// Rows deserialized: the raw-observation lines plus every row an/// early-exit scan visited (one resident at a time).pub rows_read: usize,@@ -184,20 +184,31 @@ impl SessionDigest {////// # Errors/// Propagates any store error.- pub async fn load(reader: &ReaderPool, session_id: SessionId) -> StoreResult<Self> {- Ok(Self::load_with_stats(reader, session_id).await?.0)+ pub async fn load(+ reader: &ReaderPool,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ session_id: SessionId,+ ) -> StoreResult<Self> {+ Ok(+ Self::load_with_stats(reader, workspace_id, project_id, session_id)+ .await?+ .0,+ )}/// [`Self::load`], also reporting what the load read.////// # Errors/// Propagates any store error.- pub async fn load_with_stats(+ pub(crate) async fn load_with_stats(reader: &ReaderPool,+ workspace_id: WorkspaceId,+ project_id: ProjectId,session_id: SessionId,) -> StoreResult<(Self, DigestLoadStats)> {reader- .read_session_observations(session_id, move |snapshot| {+ .read_session_observations(workspace_id, project_id, session_id, move |snapshot| {build_digest(snapshot, session_id)}).awaitdiff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 9680a40c..b0ffcce3 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -12424,7 +12424,7 @@ pub(crate) mod tests {// Asked before the writer ends the session: the question is the// same one, put to the rows as they are.let reader_says_substantive = runtime- .block_on(reader.session_has_substantive_observation(session))+ .block_on(reader.session_has_substantive_observation(ws, proj, session)).unwrap();let writer_says_substantive = matches!(end_lifecycle_only_session(&mut conn, &session).unwrap(),diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 8ed59deb..3439f248 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -2181,11 +2181,6 @@ struct Inner {db_path: PathBuf,pool: Mutex<Pool>,soft_cap: usize,- /// Observation rows deserialized by the whole-session reads- /// ([`ReaderPool::observations_for_session`] and- /// [`ReaderPool::read_session_observations`]); see- /// [`ReaderPool::session_observation_rows_loaded`].- session_rows_loaded: std::sync::atomic::AtomicU64,}/// The idle connections and whether the pool still hands out new ones. One@@ -2211,7 +2206,6 @@ impl ReaderPool {closed: false,}),soft_cap: soft_cap.max(1),- session_rows_loaded: std::sync::atomic::AtomicU64::new(0),}),tuning: RetrievalTuning::default(),fts_stopwords: FtsStopwords::default(),@@ -2234,19 +2228,6 @@ impl ReaderPool {pool.idle.clear();}- /// Observation rows the whole-session reads have deserialized since this- /// pool (or any clone of it) was created: every row- /// [`Self::observations_for_session`] returned, plus the rows- /// [`Self::read_session_observations`] snapshots read. A SessionEnd on a- /// session far larger than its raw-observation window must move this by no- /// more than that window, which is what the bound tests assert.- #[must_use]- pub fn session_observation_rows_loaded(&self) -> u64 {- self.inner- .session_rows_loaded- .load(std::sync::atomic::Ordering::Relaxed)- }-/// Configure the opt-in ranking signals used by [`Self::hybrid_search`]./// Only handles cloned from this one afterwards observe the change.pub fn set_retrieval_tuning(&mut self, tuning: RetrievalTuning) {@@ -3595,7 +3576,6 @@ impl ReaderPool {&self,session_id: SessionId,) -> StoreResult<Vec<Observation>> {- let inner = self.inner.clone();self.with_conn(move |conn| {let mut stmt = conn.prepare_cached("SELECT id, session_id, workspace_id, project_id, kind, extension, source_event, \@@ -3609,37 +3589,54 @@ impl ReaderPool {for r in rows {out.push(r??);}- inner- .session_rows_loaded- .fetch_add(out.len() as u64, std::sync::atomic::Ordering::Relaxed);Ok(out)}).await}- /// Whether the session holds at least one prompt or tool use: the positive- /// "real work" predicate ([`SUBSTANTIVE_OBSERVATION_KIND_SQL`]) the writer's- /// lifecycle-only end applies in its own transaction, asked as one- /// short-circuiting existence query instead of loading the rows.+ /// Whether the session in the given scope holds at least one prompt or+ /// tool use: the positive "real work" predicate+ /// ([`SUBSTANTIVE_OBSERVATION_KIND_SQL`]) the writer's lifecycle-only end+ /// applies in its own transaction, asked as one short-circuiting existence+ /// query instead of loading the rows. A missing or foreign session returns+ /// `false` without revealing which condition applied.////// # Errors/// Propagates any SQL or pool error.pub async fn session_has_substantive_observation(&self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,session_id: SessionId,) -> StoreResult<bool> {self.with_conn(move |conn| {let sql = format!(- "SELECT EXISTS(SELECT 1 FROM observations WHERE session_id = ?1 AND {})",+ "SELECT EXISTS(\+ SELECT 1 FROM observations AS o \+ JOIN sessions AS s ON s.id = o.session_id \+ WHERE o.session_id = ?1 \+ AND s.workspace_id = ?2 AND s.project_id = ?3 \+ AND {}\+ )",SUBSTANTIVE_OBSERVATION_KIND_SQL);- Ok(conn.query_row(&sql, params![session_id.as_bytes()], |row| row.get(0))?)+ Ok(conn.query_row(+ &sql,+ params![+ session_id.as_bytes(),+ workspace_id.as_bytes(),+ project_id.as_bytes()+ ],+ |row| row.get(0),+ )?)}).await}/// Read one session's observations through bounded queries, all inside one- /// read transaction so every answer describes the same set of rows.+ /// read transaction so every answer describes the same set of rows. The+ /// session must belong to the given workspace and project; a foreign or+ /// missing id is refused as [`StoreError::SessionCollision`].////// This is the SessionEnd path's alternative to/// [`Self::observations_for_session`]: that call deserializes every row@@ -3652,6 +3649,8 @@ impl ReaderPool {/// Propagates any SQL or pool error, and whatever `read` returns.pub async fn read_session_observations<F, T>(&self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,session_id: SessionId,read: F,) -> StoreResult<T>@@ -3659,20 +3658,29 @@ impl ReaderPool {F: FnOnce(&SessionObservationSnapshot<'_>) -> StoreResult<T> + Send + 'static,T: Send + 'static,{- let inner = self.inner.clone();self.with_conn(move |conn| {let tx = conn.unchecked_transaction()?;+ let in_scope = tx.query_row(+ "SELECT EXISTS(\+ SELECT 1 FROM sessions \+ WHERE id = ?1 AND workspace_id = ?2 AND project_id = ?3\+ )",+ params![+ session_id.as_bytes(),+ workspace_id.as_bytes(),+ project_id.as_bytes()+ ],+ |row| row.get::<_, bool>(0),+ )?;+ if !in_scope {+ return Err(StoreError::SessionCollision);+ }let snapshot = SessionObservationSnapshot {conn: &tx,session_id: session_id.as_bytes().to_vec(),rows_read: std::cell::Cell::new(0),};- let result = read(&snapshot);- inner.session_rows_loaded.fetch_add(- snapshot.rows_read() as u64,- std::sync::atomic::Ordering::Relaxed,- );- result+ read(&snapshot)}).await}diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rsindex 5a5d3816..d7d0e309 100644--- a/crates/ai-memory-store/tests/suite/multi_session.rs+++ b/crates/ai-memory-store/tests/suite/multi_session.rs@@ -69,6 +69,102 @@ async fn open_session(id}+/// A SessionEnd digest takes a raw session id internally, but the reader must+/// still require the admitted scope. Otherwise a future caller could render a+/// foreign project's prompts merely by learning its id.+#[tokio::test]+async fn session_end_readers_refuse_foreign_session_ids() {+ use ai_memory_core::{NewObservation, ObservationKind, Sanitized, Sanitizer};++ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let home = store+ .writer+ .get_or_create_project(ws, "home", None)+ .await+ .unwrap();+ let sibling = store+ .writer+ .get_or_create_project(ws, "sibling", None)+ .await+ .unwrap();+ let other_ws = store.writer.get_or_create_workspace("other").await.unwrap();+ let session = open_session(&store, ws, home, AgentKind::Codex).await;+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ occurred_at: None,+ session_id: session,+ workspace_id: ws,+ project_id: home,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "private prompt".into(),+ body: "foreign scopes must not read this".into(),+ importance: 5,+ },+ &Sanitizer::builtin(),+ ))+ .await+ .unwrap();++ assert!(+ store+ .reader+ .session_has_substantive_observation(ws, home, session)+ .await+ .unwrap(),+ "the owning scope is the legitimate control"+ );+ let total = store+ .reader+ .read_session_observations(ws, home, session, |snapshot| {+ Ok(snapshot.kind_summary()?.total)+ })+ .await+ .unwrap();+ assert_eq!(total, 1);++ for (attempt_ws, attempt_project) in [(ws, sibling), (other_ws, home)] {+ assert!(+ !store+ .reader+ .session_has_substantive_observation(attempt_ws, attempt_project, session)+ .await+ .unwrap(),+ "a foreign scope must not learn the session's substantive state"+ );+ let error = store+ .reader+ .read_session_observations(attempt_ws, attempt_project, session, |snapshot| {+ Ok(snapshot.kind_summary()?.total)+ })+ .await+ .unwrap_err();+ assert!(matches!(error, StoreError::SessionCollision));+ }++ let missing = SessionId::new();+ let error = store+ .reader+ .read_session_observations(ws, home, missing, |snapshot| {+ Ok(snapshot.kind_summary()?.total)+ })+ .await+ .unwrap_err();+ assert!(+ matches!(error, StoreError::SessionCollision),+ "missing and foreign ids deliberately expose the same refusal"+ );+}+fn page(ws: WorkspaceId, proj: ProjectId, path: &str, title: &str, body: &str) -> NewPage {NewPage {workspace_id: ws,diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex d5fad577..f944d8b1 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -30,6 +30,7 @@ means the boundary is not built yet.| 1f | Event capture never lands in a profile project, and the sweep keeps them | `ai-memory-hooks/src/router.rs` project resolution refuses `ai_memory_core::profile::is_reserved_scope_project` (`_global`, `_profile`, `_profile.*`) from a directory or a marker override, falling back to the server default; `ops.rs` `sweep_hollow_projects` exempts `_profile` and `_profile.%` | `router.rs` `capture_is_never_attributed_to_a_profile_project` (override and directory spellings refused; ordinary `my_profile` control resolves), fails with the check narrowed to `_global`; store `integration::profile` `the_hollow_project_sweep_keeps_empty_profile_projects` | STRONG || 1g | The profile reaches only the sessions it is meant for: off by default on a multi-user server, suppressed by `[profile] consume = false`, and an opt-out is sticky | `ai_memory_core::profile::ProfileSettings::effective_share` (`enabled = auto` is off once operators are distinguished); `router.rs` `persist_profile_flags` (flags are tri-state: an absent forwarded value keeps the stored one, so a client that sends nothing never undoes an opt-out; every front door sends explicit `0`/`1` once a marker resolved) and `render_requested_profile_digest` (a team profile is headed "team defaults"); `server.rs` `memory_query` drops `profile/` hits for a project whose stored `profile_consume` is off; `admin_profile.rs` `handle_apply` (`ai-memory profile apply`) returns no lines for such a project and sits behind the root-only `/admin/*` gate on a multi-user server | `router.rs` `a_multi_user_server_has_no_profile_digest_by_default`, `profile_digest_honours_consume_once_per_session_and_the_server_switch`, `session_start_records_the_marker_profile_flags` (a session start with no flags after an opt-out keeps the project out of the harvest and the digest; fails when an absent flag defaults to on); `server.rs` `the_single_user_profile_lives_in_global_and_honours_consume` (fails with the consume filter removed); `admin_profile_routes.rs` `apply_lists_the_lines_for_a_project_and_honours_consume`, `apply_is_root_only_on_a_multi_user_server` (database user refused, root control admitted); core `profile::tests::effective_share_matrix` | STRONG || 1h | The profile learns only from what it may: the user's own prompts and curated pages, from contributing projects, never another operator's words in a private profile and never a restricted project in a shared one; stored text stays data | `ai-memory-store/src/profile.rs` `profile_prompts_since` (only `user-prompt` observations), `auto_improve_decided_by` (the decider agent a page's `auto_improve_proposal_id` resolves to), `profile_harvest_projects` / `profile_candidates` (`profile_contribute = 0` excluded, including candidates recorded before the opt-out); `ai-memory-store/src/ops.rs` `move_session` (a moved session's `session:<id>` prompt candidates are re-stamped into the target project in the same transaction, so they answer to its contribute flag and access mode, #1265); `ai-memory-consolidate/src/profile.rs` `user_written` (a harness turn or Codex's injected instructions stored as a prompt is skipped whole, and ai-memory's routing and untrusted-history blocks, fenced by markers on their own lines, are cut out before any sentence is read), the auto-approved-proposal skip in `harvest_project` (a page the auto-improve scheduler auto-approved is model output nobody reviewed and never becomes a candidate; a human-approved page, or one whose proposal id has no row, stays curated, #1211), `convergence_targets` (a `user` target keeps only candidates whose `contributor` is that operator, from projects the per-project choke point lets them read; a `global`/`workspace` target on an operator-distinguishing server drops restricted projects), `min_contributors` / `converge` (a team profile admits a statement only on evidence from at least two distinct operators, so one operator cannot plant a default in everyone's session start) (never rewrites a page without its `generated_by` stamp or whose body changed; `profile_entry_ledger` keeps a forgotten entry out), `classify_batch` / `merge_entry` (sanitized, JSON-encoded input; the evidence quote is always the user's sentence) | consolidate `integration::profile_harvest` `tool_output_is_never_a_candidate`, `an_opted_out_project_is_never_harvested`, `a_private_profile_never_harvests_another_operator`, `a_team_profile_never_harvests_a_restricted_project`, `a_team_profile_needs_more_than_one_operator` (one operator in two open projects not admitted; a second operator admits it; fails with the threshold at one), `a_personal_profile_admits_one_operators_habit` (control), `a_hand_edited_entry_is_never_clobbered`, `a_forgotten_entry_is_not_recreated_until_said_again`, `injected_instructions_stay_data`, `injected_instructions_and_ai_memory_blocks_are_never_candidates`, `page_metadata_fields_are_never_candidates`, `auto_approved_auto_improve_pages_are_never_candidates` (an auto-approved page refused; human-approved and hand-written controls admitted; fails with the decider check removed), consolidate `profile::tests::a_stored_page_metadata_field_is_not_a_waiting_habit` (each with a legitimate control; each fails with its guard removed); mcp `integration::admin_profile_routes` `review_and_rebuild_are_root_only_on_a_multi_user_server`; store `integration::session_move` `a_moved_sessions_profile_candidate_follows_the_target_projects_governance` (a session moved into an opted-out project stops counting and one moved into a restricted project is marked restricted; an open-target control still counts, from the target; fails with the `move_session` re-stamp removed) | STRONG |+| 1i | SessionEnd's bounded digest cannot read a foreign session by raw id | `ai-memory-store/src/reader.rs` `session_has_substantive_observation` joins the session row to the caller's `(workspace_id, project_id)`; `read_session_observations` validates that same tuple inside the read transaction before exposing its bounded snapshot, returning the same `SessionCollision` refusal for foreign and missing ids; `ai-memory-hooks/src/router.rs` supplies only the scope pinned by hook admission | `multi_session.rs` `session_end_readers_refuse_foreign_session_ids` (sibling-project and cross-workspace tuples cannot learn the substantive bit or open the snapshot; a missing id gets the same refusal; the owning tuple reads the one-row summary as the legitimate control). Removing either scope predicate fails its corresponding assertion | STRONG || 2 | Workspace isolation | same as #1; same-named project → distinct ids per workspace | `scope.rs` cross-workspace resolution rows; `multi_scope` dedup/validate; `ai-memory-web` `history_replay.rs` (another workspace's page path, version id and session id answer 404, same tests and bites as row 1) | STRONG || 2b | Managed-workstream discovery stays checkout-local, including pagination | `ai-memory-workstream/src/repository.rs` `inspect_repository_fingerprints` shares the launch identity derivation without checkpoint scans; `ai-memory-cli/src/commands/resume.rs` `candidates_for_checkout` queries only the cwd, never registry links; the explicit `--all` walk (`candidates_across_checkouts`) lists each linked checkout through its own fingerprint-scoped request and applies `--workspace` before any request; `ai-memory-hooks/src/workstream.rs` `list_recent_workstreams` resolves an authorized explicit scope on every page; `ai-memory-store/src/workstream.rs` `list_recent` applies workspace/project/repository/worktree predicates before `LIMIT`/`OFFSET` | `resume.rs` `resume_lists_all_current_checkout_rows_not_registered_foreign_checkouts` (same scope/remote foreign checkout refused, 125 local rows visible), `empty_current_checkout_does_not_fall_back_to_the_registry`, `resume_all_walks_every_linked_checkout_and_honours_the_workspace_filter` (a foreign workspace filter sends no request; the default picker still ignores the registry); `workstream.rs` `recent_workstream_pages_reach_older_rows_without_crossing_checkout_or_scope` (foreign repo, worktree, project and workspace excluded on every page; 105 legitimate rows reach the client, huge offsets return nothing); store `recent_workstreams_are_checkout_local_and_include_linked_harnesses` (page two keeps native harness links); `repository.rs` `reports_origin_push_url_and_linked_worktree` verifies lightweight/full fingerprint parity and distinct worktree keys; CLI `resume_yolo_displays_picker_without_scanning_git_status` verifies listing skips status scans | STRONG || 3 | Multi-user auth ladder | `ai-memory-core/src/actor.rs` `AuthLevel::authorize`; `ai-memory-mcp/src/auth.rs` middleware; `admin.rs` `require_root_for_multiuser_admin` / `require_root`; `identity.rs` authorizes `NormalRead` behind the same machine bearer middleware as MCP; `serve.rs` mounts API-only and web+API protected routers behind `require_dual_auth` | `admin.rs` `multiuser_admin_routes_reject_db_user_tier` / `…reject_anonymous` / `create_user_as_user_tier_returns_403`; `auth.rs` unknown-bearer 401; `actor.rs` `skip_admission_chain_rejects_db_users`; `identity.rs` `identity_real_auth_isolates_users_root_and_revoked_keys`, `identity_anonymous_ignores_forged_headers_and_proxy_qualifies_oidc` (distinct users and root, invalid/revoked keys, forged headers, anonymous control); `serve.rs` `api_only_mode_keeps_data_authenticated_and_web_absent` (anonymous API read refused, authenticated control admitted, browser route absent; #986) | STRONG |