Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(retrieval): report the observation stream through memory_query
AkitaOnRails849b53f5d975
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 888c7e65..56c57e3a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- Added an opt-in observation stream to `memory_query` ranking:+ `[retrieval] observation_stream = true` (env+ `AI_MEMORY_RETRIEVAL__OBSERVATION_STREAM=true`, default off). A zero-LLM+ session page keeps only a short excerpt of each turn, so the detail a+ question asks about often lives only in the session's observations. With the+ flag on, project and `scopes` searches also run full-text search over+ observations in the same project, and each matching session votes once,+ through its best-matching observation, for its own latest+ `sessions/<id>.md` page as one more RRF stream. The matching excerpt becomes+ the hit's snippet when it ranks ahead of the page's own match, and+ `explain=true` reports an `observation` stream with the matched observation+ ids. Hits are still pages and nothing is written; sessions without a page+ keep the `raw_hits` fallback, and `global=true` search is unchanged.+- Added the end reason to session-end observations. When a harness's`SessionEnd` payload carries a `reason` (Claude Code sends `clear`,`logout`, `prompt_input_exit` or `other`), its first line is stored,diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 219a50d3..9ed2b5b0 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -3101,6 +3101,9 @@ impl AiMemoryServer {}}streams.push("graph");+ if self.reader.retrieval_tuning().observation_stream {+ streams.push("observation");+ }streams});let hits: Vec<QueryHit> = hits@@ -16328,6 +16331,218 @@ mod tests {assert!(found_by_recent(bob, false).await);}+ /// R1 observation stream, per-project authorization (row 14) and pages+ /// shared (row 5a). The stream reads observation bodies, which hold more+ /// than the session page does, so it must sit behind the same resolver+ /// gate as page search: a non-grantee reaches neither the session page+ /// nor its evidence by naming the restricted project, listing it in+ /// `scopes`, or querying their own project. Controls: the writer and a+ /// second operator holding only a read grant both get the session page,+ /// lifted by the first operator's observation.+ #[tokio::test]+ async fn observation_stream_evidence_stays_inside_a_restricted_project() {+ let tmp = TempDir::new().unwrap();+ let mut store = Store::open(tmp.path()).unwrap();+ store+ .reader+ .set_retrieval_tuning(ai_memory_store::RetrievalTuning {+ observation_stream: true,+ ..ai_memory_store::RetrievalTuning::default()+ });+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let scratch = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ store+ .writer+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)+ .await+ .unwrap();+ let client = store+ .writer+ .get_or_create_project(ws, "alice-client-work", None)+ .await+ .unwrap();+ let human = |name: &'static str| {+ let writer = store.writer.clone();+ async move {+ writer+ .create_human_user(+ NewUser {+ username: name.into(),+ name: None,+ email: None,+ },+ ai_memory_core::UserRole::User,+ None,+ false,+ )+ .await+ .unwrap()+ }+ };+ let alice = human("alice").await;+ let bob = human("bob").await;+ let carol = human("carol").await;+ grant_writer(store.db_path(), alice, client);+ grant_role(store.db_path(), carol, client, "read");++ // Alice's finished session: the page keeps a short excerpt, the+ // observation keeps the confidential detail.+ let session_id = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ occurred_at: None,+ id: session_id,+ workspace_id: ws,+ project_id: client,+ agent_kind: AgentKind::ClaudeCode,+ cwd: None,+ actor_user: Some(ai_memory_core::IdentityKey::User("alice".into()).storage_key()),+ })+ .await+ .unwrap();+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ occurred_at: None,+ session_id,+ workspace_id: ws,+ project_id: client,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "prompt".into(),+ body: "the zircon day rate for this client is confidential".into(),+ importance: 5,+ },+ &Sanitizer::builtin(),+ ))+ .await+ .unwrap();+ let session_path = format!("sessions/{session_id}.md");+ store+ .writer+ .upsert_page(NewPage {+ workspace_id: ws,+ project_id: client,+ path: PagePath::new(session_path.clone()).unwrap(),+ title: "Session".into(),+ body: "User asked about pricing.".into(),+ tier: Tier::Episodic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: Some(alice),+ expires_at: None,+ entities: Vec::new(),+ evidence: Vec::new(),+ })+ .await+ .unwrap();+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, scratch);++ let as_user = |user: ai_memory_core::UserId| {+ let mut parts = test_parts_default();+ parts.extensions.insert(AuthLevel::User);+ parts.extensions.insert(user);+ parts+ .extensions+ .insert(ai_memory_core::AuthorizedViewer(user));+ parts+ };+ let ask =+ |user, workspace: Option<&str>, project: Option<&str>, scopes: Vec<MemoryScopeArg>| {+ let server = &server;+ let workspace = workspace.map(str::to_string);+ let project = project.map(str::to_string);+ async move {+ server+ .memory_query(+ Parameters(QueryArgs {+ reasoning: None,+ answer: None,+ include_superseded: None,+ pin_first: None,+ query: "zircon".into(),+ limit: Some(10),+ project,+ workspace,+ scopes,+ global: None,+ include_expired: None,+ explain: Some(true),+ as_of: None,+ }),+ OptionalParts(as_user(user)),+ )+ .await+ .ok()+ .and_then(|result| {+ result+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ })+ }+ };+ let client_scope = || {+ vec![MemoryScopeArg {+ workspace: "default".into(),+ project: "alice-client-work".into(),+ }]+ };+ let leaked = |text: &Option<String>| {+ text.as_deref()+ .is_some_and(|t| t.contains("zircon") || t.contains(&session_path))+ };++ // Bob holds nothing on the repository: naming it, scoping to it, or+ // searching his own project never surfaces the session or its+ // evidence.+ let named = ask(bob, Some("default"), Some("alice-client-work"), Vec::new()).await;+ assert!(!leaked(&named), "bob reached it by name: {named:?}");+ let scoped = ask(bob, None, None, client_scope()).await;+ assert!(+ !leaked(&scoped),+ "bob reached it through scopes: {scoped:?}"+ );+ let own = ask(bob, Some("default"), Some("scratch"), Vec::new()).await;+ assert!(own.is_some(), "bob's own project still answers");+ assert!(+ !leaked(&own),+ "bob reached it from his own project: {own:?}"+ );++ // Alice, and Carol with only a read grant, get the session page,+ // lifted by Alice's observation.+ for (who, user) in [("alice", alice), ("carol", carol)] {+ for text in [+ ask(user, Some("default"), Some("alice-client-work"), Vec::new()).await,+ ask(user, None, None, client_scope()).await,+ ] {+ let text = text.unwrap_or_else(|| panic!("{who}'s query failed"));+ let json: serde_json::Value = serde_json::from_str(&text).unwrap();+ let hit = json["hits"]+ .as_array()+ .unwrap()+ .iter()+ .find(|h| h["path"] == session_path.as_str())+ .unwrap_or_else(|| panic!("{who} missed the session page: {text}"));+ assert_eq!(hit["score_details"]["observation_rank"], 1, "{text}");+ }+ }+ }+fn parts_with_level(level: ai_memory_core::AuthLevel) -> axum::http::request::Parts {let mut parts = test_parts_default();parts.extensions.insert(level);diff --git a/crates/ai-memory-mcp/tests/suite/mod.rs b/crates/ai-memory-mcp/tests/suite/mod.rsindex 9c98f358..ac49e32d 100644--- a/crates/ai-memory-mcp/tests/suite/mod.rs+++ b/crates/ai-memory-mcp/tests/suite/mod.rs@@ -30,6 +30,7 @@ mod handoff_admission;mod handoff_identity;mod mcp_stateless_http;mod query_answer;+mod query_observation_stream;mod query_pin_first;mod query_reasoning;mod query_superseded;diff --git a/crates/ai-memory-mcp/tests/suite/query_observation_stream.rs b/crates/ai-memory-mcp/tests/suite/query_observation_stream.rsnew file mode 100644index 00000000..bbe0f260--- /dev/null+++ b/crates/ai-memory-mcp/tests/suite/query_observation_stream.rs@@ -0,0 +1,280 @@+//! `[retrieval] observation_stream` (R1), proven end to end through the real+//! `memory_query` tool over JSON-RPC.+//!+//! The use case: a finished session's zero-LLM page keeps only a short+//! excerpt of each turn, so the detail a later question asks about lives only+//! in the session's observations. With the stream on, `memory_query` returns+//! the session page (hits stay pages), explains the vote with an+//! `observation` stream entry, and shows the matching observation excerpt.+//! With it off, the same query finds no page and falls back to `raw_hits`.++use ai_memory_core::{+ AgentKind, NewObservation, NewPage, NewSession, ObservationKind, PagePath, ProjectId,+ Sanitized, Sanitizer, SessionId, Tier, WorkspaceId,+};+use ai_memory_mcp::AiMemoryServer;+use ai_memory_store::{RetrievalTuning, Store};+use axum::Router;+use axum::body::Body;+use axum::http::Request;+use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;+use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};+use serde_json::{Value, json};+use tempfile::TempDir;+use tower::ServiceExt;++const WS: &str = "default";+const PROJ: &str = "scratch";++struct Seeded {+ _tmp: TempDir,+ router: Router,+ session_id: SessionId,+ observation_id: String,+}++async fn seeded(observation_stream: bool) -> Seeded {+ seeded_with(observation_stream, true).await+}++async fn seeded_with(observation_stream: bool, session_page: bool) -> Seeded {+ let tmp = TempDir::new().expect("tempdir");+ let mut store = Store::open(tmp.path()).expect("store");+ // The server reads its tuning once at construction, as `serve` does from+ // `Config::load`.+ store.reader.set_retrieval_tuning(RetrievalTuning {+ observation_stream,+ ..RetrievalTuning::default()+ });+ let ws = store.writer.get_or_create_workspace(WS).await.expect("ws");+ let proj = store+ .writer+ .get_or_create_project(ws, PROJ, None)+ .await+ .expect("proj");+ let (session_id, observation_id) = seed_session(&store, ws, proj, session_page).await;+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj);+ let service = StreamableHttpService::new(+ move || Ok(server.clone()),+ LocalSessionManager::default().into(),+ StreamableHttpServerConfig::default()+ .with_stateful_mode(false)+ .with_json_response(true),+ );+ Seeded {+ _tmp: tmp,+ router: Router::new().nest_service("/mcp", service),+ session_id,+ observation_id,+ }+}++async fn seed_session(+ store: &Store,+ ws: WorkspaceId,+ proj: ProjectId,+ session_page: bool,+) -> (SessionId, String) {+ 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::ClaudeCode,+ cwd: Some("/repo".into()),+ actor_user: None,+ })+ .await+ .expect("session");+ let observation_id = store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ occurred_at: None,+ session_id,+ workspace_id: ws,+ project_id: proj,+ kind: ObservationKind::Stop,+ extension: None,+ source_event: None,+ title: "assistant".into(),+ body: "We pinned the flaky integration test to the zircon runner pool \+ because the default pool lacks the GPU driver."+ .into(),+ importance: 5,+ },+ &Sanitizer::builtin(),+ ))+ .await+ .expect("observation");+ // The session's compiled page, shaped like the zero-LLM synth page: a+ // short excerpt that does not carry the answer. A live session has none.+ if !session_page {+ return (session_id, observation_id.to_string());+ }+ store+ .writer+ .upsert_page(NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(format!("sessions/{session_id}.md")).unwrap(),+ title: "Session: CI fixes".into(),+ body: "User asked why CI was red.".into(),+ tier: Tier::Episodic,+ frontmatter_json: json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ evidence: Vec::new(),+ })+ .await+ .expect("session page");+ // A distractor page that shares one query word, so the stream has to+ // rank, not merely be the only source.+ store+ .writer+ .upsert_page(NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new("notes/runners.md").unwrap(),+ title: "Runners".into(),+ body: "The default runner pool is shared.".into(),+ tier: Tier::Semantic,+ frontmatter_json: json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ evidence: Vec::new(),+ })+ .await+ .expect("distractor");+ (session_id, observation_id.to_string())+}++async fn query(router: &Router, arguments: Value) -> Value {+ let body = json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/call",+ "params": { "name": "memory_query", "arguments": arguments },+ });+ let req = Request::builder()+ .method("POST")+ .uri("/mcp")+ .header("host", "localhost")+ .header("content-type", "application/json")+ .header("accept", "application/json, text/event-stream")+ .body(Body::from(body.to_string()))+ .expect("mcp req");+ let resp = router.clone().oneshot(req).await.expect("oneshot");+ let bytes = axum::body::to_bytes(resp.into_body(), 4_000_000)+ .await+ .expect("body");+ let v: Value = serde_json::from_slice(&bytes).expect("json-rpc");+ assert!(v.get("error").is_none(), "JSON-RPC error: {v}");+ let text = v+ .pointer("/result/content/0/text")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("missing tool text: {v}"));+ serde_json::from_str(text).expect("tool payload")+}++fn args() -> Value {+ json!({+ "query": "zircon runner",+ "workspace": WS,+ "project": PROJ,+ "explain": true,+ "limit": 5,+ })+}++#[tokio::test]+async fn memory_query_finds_a_session_page_by_its_observation_evidence() {+ let seeded = seeded(true).await;+ let payload = query(&seeded.router, args()).await;++ let hits = payload["hits"].as_array().expect("hits");+ let session_path = format!("sessions/{}.md", seeded.session_id);+ let hit = hits+ .iter()+ .find(|h| h["path"] == session_path.as_str())+ .unwrap_or_else(|| panic!("session page missing: {payload}"));+ // Hits are still pages; the excerpt shows the evidence that matched.+ assert_eq!(hit["title"], "Session: CI fixes");+ let snippet = hit["snippet"].as_str().unwrap();+ assert!(snippet.contains("<mark>zircon</mark>"), "{snippet}");+ let details = &hit["score_details"];+ assert_eq!(details["observation_rank"], 1, "{details}");+ assert_eq!(+ details["observation_ids"],+ json!([seeded.observation_id]),+ "{details}"+ );+ assert!(details["rrf"]["observation"].as_f64().unwrap() > 0.0);+ let streams = payload["streams_active"].as_array().expect("streams");+ assert!(streams.contains(&json!("observation")), "{streams:?}");+ // A page hit means the raw fallback stays quiet.+ assert!(+ payload+ .get("raw_hits")+ .and_then(Value::as_array)+ .is_none_or(Vec::is_empty),+ "{payload}"+ );+ // The distractor still competes on its own FTS match and carries no+ // observation vote.+ if let Some(distractor) = hits.iter().find(|h| h["path"] == "notes/runners.md") {+ assert!(+ distractor["score_details"]+ .get("observation_rank")+ .is_none()+ );+ }+}++#[tokio::test]+async fn memory_query_without_the_stream_never_reports_an_observation_vote() {+ let seeded = seeded(false).await;+ let payload = query(&seeded.router, args()).await;++ let session_path = format!("sessions/{}.md", seeded.session_id);+ let hits = payload["hits"].as_array().expect("hits");+ assert!(+ hits.iter().all(|h| h["path"] != session_path.as_str()),+ "{payload}"+ );+ assert!(+ hits.iter()+ .all(|h| h["score_details"].get("observation_rank").is_none()),+ "{payload}"+ );+ let streams = payload["streams_active"].as_array().expect("streams");+ assert!(!streams.contains(&json!("observation")), "{streams:?}");+}++#[tokio::test]+async fn a_live_session_without_a_page_still_reaches_the_raw_fallback() {+ let seeded = seeded_with(true, false).await;+ let payload = query(+ &seeded.router,+ json!({+ "query": "zircon",+ "workspace": WS,+ "project": PROJ,+ "explain": true,+ }),+ )+ .await;+ assert_eq!(payload["hits"], json!([]), "{payload}");+ let raw = payload["raw_hits"].as_array().expect("raw_hits");+ assert_eq!(raw.len(), 1, "{payload}");+ assert_eq!(raw[0]["id"], seeded.observation_id.as_str());+}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex f81c44ff..b407a5a0 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -156,7 +156,14 @@ from hook paths.bounded titles/snippets to the configured provider after project/scopefusion; it is limited to one call per query and four calls in flight, and anyinvalid, failed, timed-out, or saturated attempt preserves the local order.- Global and supplemental global-preference results do not take this path. If+ Global and supplemental global-preference results do not take this path.+ With the opt-in `[retrieval] observation_stream`, project and `scopes`+ searches add one more RRF stream: full-text search over `observations_fts`+ in the same `(workspace, project)`, where each matching session votes once,+ through its best-ranked observation, for its own latest unexpired+ `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. Ifcompiled wiki pages miss entirely in default, explicit project, or explicit`scopes` mode, bounded raw observation FTS returns fallback `raw_hits`;`global=true` searches compiled wiki pages across projects only. Page hits@@ -427,7 +434,7 @@ prunable rather than only after it ages in place.| `pages_fts` | FTS5 virtual table over `(title, body)`, auto-synced by triggers. || `sessions`, `observations` | Sanitized, bounded lifecycle-hook projections. `sessions.ended_observation_count` is the stable generation watermark for resumed-session re-end eligibility; wall clocks are not used for that decision. They are an operational audit trail, not a complete native transcript. || `session_consolidation_jobs` | Durable, observation-generation-idempotent queue for the *automatic* SessionEnd LLM consolidation worker. One bounded server worker leases jobs, retries provider failures with backoff, and recovers expired leases after restart. A manual `memory_consolidate` writes its page out-of-band and then reconciles this table (flipping a `failed`/`pending`/`superseded` row for the session to `completed`, never touching a live `running` lease), so the operator does not see a `failed` job for a session that is in fact consolidated. |-| `observations_fts` | FTS5 virtual table over raw observation `(title, body)`, used only as bounded fallback. |+| `observations_fts` | FTS5 virtual table over raw observation `(title, body)`. Feeds the bounded `raw_hits` fallback and, behind the opt-in `[retrieval] observation_stream`, the observation-evidence RRF stream that votes for session pages. || `workstreams`, `managed_runs`, `workstream_native_sessions` | Optional lease state plus per-harness native source and delivery cursors for `ai-memory run`. || `workstream_events`, `workstream_events_fts` | Append-only normalized visible transcript events and full-text search; immutable sanitized source batches also live under `raw/workstreams/`. || `links` | Wikilink / markdown cross-references. `to_page_id` (a global PageId) is nullable for unresolved forward links. `to_workspace` / `to_project` carry a cross-project scope (NULL = the source page's own project). |@@ -584,7 +591,7 @@ does not need to ride on the public protocol change.| Tool | Hint | Purpose ||---|---|---|-| `memory_query` | read-only | FTS5 + entity-match + graph RRF + optional vector RRF search, followed by bounded kind/tier/pinned/tag authority adjustment and raw fallback. Bumps access counters for page hits. Defaults to the current project; single-project calls (project implicit or named with `workspace`+`project`) also union the reserved `_global` preferences scope as `global_scope_hits`, and only an explicit multi-`scopes` set opts out (#930); `scopes` searches named sibling projects; `global=true` searches every project at once (each hit annotated with its workspace + project). With `AI_MEMORY_RERANKER=llm`, project/scopes candidate pools are fused before at most one final LLM relevance pass; query/title/snippet data is bounded and JSON-encoded, and any timeout, provider error, invalid/incomplete score set, or four-call concurrency saturation preserves the adjusted order. The distinct `global=true` FTS-only ranker and supplemental global-preference hits are not reranked. `explain=true` attaches per-hit `score_details` (per-stream ranks, matched entities, raw FTS/cosine/entity inverse-frequency scores, RRF contributions, graph provenance including the typed edge kind (`causes`/`fixes`/`contradicts`) a neighbour was reached by, the page's evidence count, authority multiplier, and optional rerank score) to project/scopes hits plus a top-level `streams_active` list. The global FTS-only ranker reports its active stream without per-hit details. `include_expired=true` also returns TTL-expired pages. `include_superseded=true` also returns superseded (non-latest) page versions across the FTS/entity/vector/graph streams, each hit labelled `superseded: true` (the current version is never marked); default-off is byte-identical to the latest-only behaviour, and `global=true` / `as_of` are unaffected. `pin_first=true` prepends the project's bounded pinned latest pages (`ReaderPool::list_pinned_pages`, cap 10) ahead of the fused hits, deduped by page id (a pinned page that also matches appears once, marked `pinned: true`) and re-truncated to the requested limit; it applies to single-project searches (default or `workspace`+`project`), is ignored on `scopes`/`global`/`as_of`, and default-off is byte-identical. `answer=true` (opt-in, off by default) additionally synthesizes a cited natural-language answer over the top hits via the configured LLM provider (`complete_structured`, JSON-schema `{ answer, citations }`), attached as `answer: { text, citations }`; with no provider configured it returns the hits plus an `answer_unavailable` note instead of erroring, and with `answer` unset/`false` no provider is accessed and the response is byte-identical (invariant #13). It applies to the normal single-project/`scopes` path; `global`/`as_of` ignore it. Answer quality is not yet eval-validated. An optional `reasoning` tier (`minimal` (default) / `low` / `medium` / `high` / `max`) tunes the synthesis effort: `ChatRequest` carries no per-request reasoning field (the provider-level `reasoning_effort` is fixed at construction from config), so the tier maps to a per-tier max-token budget scaled off the path's base (answer base 2 000; `minimal` = 1x = byte-identical, `low` 1.5x, `medium` 2x, `high` 3x, `max` 4x). The tier is inert unless the `answer` LLM path runs (invariant #13); an unknown value is rejected by the schema (invariant #7). |+| `memory_query` | read-only | FTS5 + entity-match + graph RRF + optional vector RRF search, followed by bounded kind/tier/pinned/tag authority adjustment and raw fallback. Bumps access counters for page hits. Defaults to the current project; single-project calls (project implicit or named with `workspace`+`project`) also union the reserved `_global` preferences scope as `global_scope_hits`, and only an explicit multi-`scopes` set opts out (#930); `scopes` searches named sibling projects; `global=true` searches every project at once (each hit annotated with its workspace + project). With `AI_MEMORY_RERANKER=llm`, project/scopes candidate pools are fused before at most one final LLM relevance pass; query/title/snippet data is bounded and JSON-encoded, and any timeout, provider error, invalid/incomplete score set, or four-call concurrency saturation preserves the adjusted order. The distinct `global=true` FTS-only ranker and supplemental global-preference hits are not reranked. `explain=true` attaches per-hit `score_details` (per-stream ranks, matched entities, raw FTS/cosine/entity inverse-frequency scores, the matched observation ids when the opt-in observation stream voted, RRF contributions, graph provenance including the typed edge kind (`causes`/`fixes`/`contradicts`) a neighbour was reached by, the page's evidence count, authority multiplier, and optional rerank score) to project/scopes hits plus a top-level `streams_active` list. The global FTS-only ranker reports its active stream without per-hit details. `include_expired=true` also returns TTL-expired pages. `include_superseded=true` also returns superseded (non-latest) page versions across the FTS/entity/vector/graph streams, each hit labelled `superseded: true` (the current version is never marked); default-off is byte-identical to the latest-only behaviour, and `global=true` / `as_of` are unaffected. `pin_first=true` prepends the project's bounded pinned latest pages (`ReaderPool::list_pinned_pages`, cap 10) ahead of the fused hits, deduped by page id (a pinned page that also matches appears once, marked `pinned: true`) and re-truncated to the requested limit; it applies to single-project searches (default or `workspace`+`project`), is ignored on `scopes`/`global`/`as_of`, and default-off is byte-identical. `answer=true` (opt-in, off by default) additionally synthesizes a cited natural-language answer over the top hits via the configured LLM provider (`complete_structured`, JSON-schema `{ answer, citations }`), attached as `answer: { text, citations }`; with no provider configured it returns the hits plus an `answer_unavailable` note instead of erroring, and with `answer` unset/`false` no provider is accessed and the response is byte-identical (invariant #13). It applies to the normal single-project/`scopes` path; `global`/`as_of` ignore it. Answer quality is not yet eval-validated. An optional `reasoning` tier (`minimal` (default) / `low` / `medium` / `high` / `max`) tunes the synthesis effort: `ChatRequest` carries no per-request reasoning field (the provider-level `reasoning_effort` is fixed at construction from config), so the tier maps to a per-tier max-token budget scaled off the path's base (answer base 2 000; `minimal` = 1x = byte-identical, `low` 1.5x, `medium` 2x, `high` 3x, `max` 4x). The tier is inert unless the `answer` LLM path runs (invariant #13); an unknown value is rejected by the schema (invariant #7). || `memory_recent` | read-only | Most-recently-updated `is_latest=1` pages. || `memory_read_page` | read-only | Fetch the FULL body of a single wiki page by `path` or by top FTS5 hit for a `query`; optional `workspace` + `project` targets a named sibling workspace/project. Use when an agent needs more than the 24-word snippets from `memory_query`. `include_related=true` also walks the link graph outward from the page (bounded BFS reusing the `page_links` primitive per node: default 1 hop, hard cap 3, global visited set for dedup/cycle-safety, total-node cap 50, cross-project aware) and returns a `related` array of reachable pages, each labelled with its `depth` (hop distance) and `direction` (`link`/`backlink`); default-off is byte-identical (no `related` field). || `memory_read_session_observations` | read-only | Page through ONE session's raw hook observations (`ObservationRecord` with full sanitized body, capped per row by `body_max_chars`), restricted to the rows that landed in the resolved scope and to sessions the caller may see; `total` and `elided_other_scope` report the in-scope count and the rows the session left in another project. `session_id` omitted reads the latest completed visible session. |@@ -986,6 +993,14 @@ belief_authority_weight = 0.0 # fold read-time belief-strength confidence (P# no belief query runs. confidence/evidence_count are still# exposed in explain regardless (inert). DEFAULT OFF,# R2-gated: do not default on without a positive R2 delta.+observation_stream = false # R1 observation-evidence stream: FTS over observations_fts+ # in the queried project; each matching session votes ONCE+ # (best observation) for its own latest sessions/<id>.md+ # page as one more RRF stream. Its excerpt may become the+ # snippet; explain reports `observation_rank` ++ # `observation_ids`. Read-only; sessions without a page keep+ # the raw_hits fallback; global=true unchanged. DEFAULT OFF.+ # Env: AI_MEMORY_RETRIEVAL__OBSERVATION_STREAM=true[search.fts] # FTS5 query-preparation tuning (contrast with [retrieval]:# this is not a ranking signal). Omit the whole section fordiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 73c02ef7..39093a8a 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 | `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) | 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` (opt-in `[retrieval] observation_stream`) filters both the matching observations and the `sessions/<id>.md` page they vote for to the queried workspace and project | `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 | 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 |@@ -43,7 +43,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 | `multi_session.rs` — a page with a **non-null** `author_id` (operator A) is readable by operator B in the same project | 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 || 5b | Page supersession (loser stays reachable) | `ai-memory-store/src/ops.rs` `upsert_page_in_tx` — demote `is_latest=0` (never delete) + `supersedes` chain | `multi_session.rs` `concurrent_writes_to_one_path_supersede_rather_than_destroy`; `retrieval_superseded.rs` | 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 |@@ -84,7 +84,7 @@ means the boundary is not built yet.| 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet || 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `interactive_launch_waits_out_a_lapsing_lease_then_proceeds`, and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users || 13c | A native store shared by every project yields only this checkout's records (Antigravity `history.jsonl`) | `ai-memory-workstream/src/transcript.rs` `export_antigravity` — the conversation must first pass `locate_session_file` (UUID file name + `.db` workspace == `cwd`); every `history.jsonl` line must match both that `conversationId` and, by `same_path`, this `cwd` (a conversation resumed in another directory keeps its id but records that directory, so the id alone is not enough); an id-less opening prompt is attributed only when exactly one same-workspace candidate falls within 5 s of the `.db` creation time and no other conversation of this checkout was created within 5 s of it; slash/shell entries and oversized lines are dropped, and only records naming this conversation are reported as its losses | `transcript.rs` `antigravity_history_exports_only_this_conversations_prompts_in_this_workspace` (other conversation in this and another workspace refused; own control passes), `antigravity_history_drops_prompts_from_a_resumed_conversation_in_another_workspace` (same id, foreign workspace refused), `antigravity_export_rejects_a_conversation_from_another_workspace`, `antigravity_export_rejects_unknown_or_traversal_ids`, `antigravity_opening_prompt_is_refused_when_another_conversation_started_with_it` (an opener another conversation of this checkout could own is refused), `antigravity_opening_prompt_covers_a_single_prompt_conversation` (control), `antigravity_history_reports_no_losses_for_foreign_records`; `backfill_e2e.rs` `backfill_imports_antigravity_prompts_from_history_and_nothing_foreign` (foreign prompts absent from wiki and db) | STRONG |-| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard; incremental `recent` resolves and authorizes the requested project before decoding its scope-bound cursor; batch outcomes do not bypass the capture grant or session owner check | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository` (foreign raw workstream id refuses populated provenance; granted reader receives the source record and tool correlation); `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized; `routes.rs` `api_recent_incremental_rechecks_restricted_scope_on_cursor` (a valid cursor cannot bypass a revoked grant; granted control passes), `api_recent_incremental_paginates_over_120_pages_and_binds_cursor`; `mcp_stateless_http.rs` `generic_machine_client_writes_queries_and_claims_a_handoff` (real machine key, foreign scope and partial scope refused); `router.rs` `an_unauthorized_batch_item_is_consumed_rather_than_retried`, `batch_acknowledges_foreign_collision_then_commits_next_item` (refused foreign item followed by a legitimate stored item) | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them |+| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard; incremental `recent` resolves and authorizes the requested project before decoding its scope-bound cursor; batch outcomes do not bypass the capture grant or session owner check | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `observation_stream_evidence_stays_inside_a_restricted_project` (with `[retrieval] observation_stream` on, a non-grantee naming the restricted project, listing it in `scopes`, or searching their own project never sees the session page or its observation excerpt; the writer and a read-grant holder do; fails with the read check in `ProjectAuthz::authorize` neutralized), `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository` (foreign raw workstream id refuses populated provenance; granted reader receives the source record and tool correlation); `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (19 tests) or the SQL filter (9 tests) neutralized; `routes.rs` `api_recent_incremental_rechecks_restricted_scope_on_cursor` (a valid cursor cannot bypass a revoked grant; granted control passes), `api_recent_incremental_paginates_over_120_pages_and_binds_cursor`; `mcp_stateless_http.rs` `generic_machine_client_writes_queries_and_claims_a_handoff` (real machine key, foreign scope and partial scope refused); `router.rs` `an_unauthorized_batch_item_is_consumed_rather_than_retried`, `batch_acknowledges_foreign_collision_then_commits_next_item` (refused foreign item followed by a legitimate stored item) | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them || 14aa | Companion capture privacy before persistence and delivery | `companions/ai-memory-client/src/lib.rs` `reject_sensitive`, `sanitize_external_value`, `check_body`; `src/scrub.rs` `sanitize_external_text`; relay `identity::validate`, `check_scope`, `relay::init` and `flush_locked`; importer `plan_external_conversation`, `planned_hook_event`, `truncate_utf8`, `ImportClient::post_hook_batch` | SDK secret-position, nested key, numeric metric (11 names plus numeric `*_tokens` counts; string values still redact), bounded schema and literal-marker tests; relay `sensitive_envelope_is_rejected_before_enqueue_with_clean_control`, `new_native_bodies_are_sanitized_before_hash_enqueue_and_exact_retry`, `unsafe_legacy_pending_is_dropped_locally_and_never_blocks_its_session`, `unsafe_legacy_native_identity_is_dropped_and_its_session_continues`, `legacy_binding_scope_spaces_are_preserved_on_delivery`; importer `sensitive_native_identity_is_refused_before_manifest_and_http_with_unicode_control`, `shared_key_sanitation_precedes_plan_manifest_transport_and_exact_retry`, `preview_and_manifest_use_scrubbed_bodies_and_digest`, `forged_body_authority_is_refused_before_transport`, `sanitized_redaction_markers_survive_utf8_byte_caps_in_bodies_and_titles`. Controls preserve opaque native Unicode IDs, metric representation and untrusted provenance. An unsafe item queued before these checks never reaches the wire (body or request line); it leaves the queue as a local `dropped_policy` receipt so the rest of its session ships. Guard-removal runtime probes target the final formatted sources and restore identical hashes. | Client-side privacy only; server scope, auth, admission and capture-policy guards remain authoritative || 14ap | Managed-run mutation owner and current project access (finish, cancel, heartbeat, native-session link, context acceptance) | `hooks/src/workstream.rs` `authorize_run_owner` derives `ManagedRunAuthority` only from authenticated middleware extensions and checks the real run before any mutation — for finish before status/payload/segment handling; cancel, heartbeat, link and context acceptance go through the same helper, so none is a side door around finish's rule; `ReaderPool::authorize_managed_run` and `store/src/workstream.rs` `authorize_run_mutation` use a read snapshot and the existing writer transaction, respectively. Strict resolution (`project_authz.rs` `resolve_project_authz_strict`, the canonical decision with a fail-closed resolution mode, so the reserved global-scope write gate applies here too) requires the actual workspace/project pair, current user existence and current Write decision for DB principals. The private trusted-proxy policy requires authenticated User capability, a canonical identity, no DB principal and server proxy configuration; it retains legacy project admission after strict scope validation, with ownership still enforced. Human-login disable does not revoke API keys. The legacy resolver and auth middleware remain unchanged. Both writer entry paths, including finished retries, require the same authority; no cross-owner bypass | MCP `auth.rs` `owner_finish_http_refuses_another_writer_before_payload_or_segment`, `owner_finish_http_trusted_proxy_preserves_restricted_lifecycle`, `owner_finish_http_active_api_key_survives_disabled_human_login`; store `multi_session.rs` `owner_finish_store_refuses_another_writer_including_finished_retry`, `owner_finish_store_rechecks_write_after_preflight`, `owner_finish_store_refuses_a_deleted_user_after_preflight`, `owner_finish_store_proxy_policy_requires_server_and_authenticated_identity`, `owner_finish_store_raw_ids_use_the_actual_project_and_workspace`, `owner_finish_store_topology_reload_and_phase_controls`, `owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure`, `owner_finish_store_keeps_qualified_identity_namespaces`; hooks `workstream.rs` `owner_finish_revocation_between_preflight_and_both_writer_paths`; MCP `auth.rs` `owner_finish_http_real_auth_rungs_shared_and_project_controls`, `owner_finish_http_preserves_late_active_terminal_and_missing_phases`; hooks `workstream.rs` `run_mutation_routes_refuse_another_operator` (another operator and root under another identity refused on heartbeat/link/accept/cancel, run left active; owner admitted); store `project_authz.rs` `strict_resolution_shares_the_global_gate_and_fails_closed_on_a_gap`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within finish's writer transaction; a revocation after preflight can leave an unindexed raw segment. Cancel, heartbeat, link and acceptance check one read snapshot immediately before a single-row update (a run's owner never changes). A later hook event carrying `AI_MEMORY_RUN_ID` links its native session only through `link_native_session_in_scope`, which applies the SessionStart boundary (`ManagedRunBoundaryRow::admits`: the run's own project and operator) and refuses a foreign run id while the event itself is still captured (`router.rs` `hook_event_links_a_managed_run_only_from_its_operator`, `hook_event_in_another_project_does_not_link_the_run`, control `hook_event_links_a_shared_run_on_a_single_operator_server`; #1082). Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional || 14au | Exact native managed identity and privacy (invariant #16) | `core/src/workstream.rs` `NativeSessionIdentity` validates original bytes and exact scrub equality; `workstream/src/harness.rs` and `transcript.rs` retain selector/path restrictions; CLI `run.rs` validates old-server prepare/status, planned selectors and finish transport; hooks `workstream.rs` checks payload and selected identity before raw segments, with the existing owner/current Write preflight first; `router.rs` validates both managed auto-links while preserving legacy shared capture; store `workstream.rs` carries validated identities into link/finish SQL after finish authority and before mutation. Store, HTTP search and CLI search project invalid historical identity to empty String without rewriting history | Core `native_identity_original_bytes_limits_privacy_and_collisions`; harness `native_identity_selector_rejects_original_before_resume_arguments`; transcript `native_identity_adapter_preserves_exact_and_rejects_privacy_changes`, `copilot_discovery_requires_uuid_directory_header_and_checkout` (another checkout's session, a `session.start` naming a different session than its directory, and non-UUID or `../` ids refused; exact-checkout control), `claude_transcript_is_located_by_the_real_folder_name` (a server-linked Claude id probed across project folders still resolves only to a transcript whose own header names this checkout; another checkout's transcript and a subagent sidechain with the same id are refused); store multi-session `native_identity_store_link_refuses_original_dirty_bytes`, `native_identity_store_adoption_refuses_before_link`, `native_identity_store_finish_refuses_without_sql_or_index_mutation`, `native_identity_store_history_projects_unknown_without_rewriting`; hooks `native_identity_http_link_refuses_before_status_or_sql`, `native_identity_http_finish_refuses_before_segment_or_sql`, `native_identity_http_event_guard_and_configured_history_projection`, `native_identity_http_stored_identity_refuses_before_raw_segment`, router `native_identity_managed_start_refuses_but_keeps_shared_legacy_capture`; CLI `native_identity_run_preflight_refuses_before_resume_or_private_path`, `native_identity_run_old_server_refusal_prevents_child_and_transport`, `native_identity_finish_transport_refuses_before_request_and_preserves_exact_control`, `native_identity_run_status_and_expected_refuse_before_discovery`, `native_identity_run_configured_selector_refuses_before_link_or_child`, `native_identity_run_configured_old_status_refuses_before_native_io_and_finish`, `native_identity_run_configured_discovery_refuses_before_export`, suite `native_identity_search_old_server_json_projects_unknown_and_keeps_history` | Representation/privacy only: no native authenticity, file-existence, run/event correlation or outcome proof. Original legacy rows and shared observation semantics remain intact; parent finish owner/current Write rules remain mandatory |