Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(mcp): gate memory_restore_page behind admin and keep restored metadata
AkitaOnRails3e5fcd15604f
diff --git a/companions/ai-memory-ts/README.md b/companions/ai-memory-ts/README.mdindex 5b921d64..ada5d75d 100644--- a/companions/ai-memory-ts/README.md+++ b/companions/ai-memory-ts/README.md@@ -158,7 +158,7 @@ Not wrapped (call them with `callTool`):- `memory_auto_improve`: maintenance job that needs the server's LLM; use callTool- `memory_forget_sweep`: changes retention for a whole project; use callTool- `memory_install_self_routing`: writes coding-agent instruction files; specific to harnesses-- `memory_restore_page`: restores one page from a git checkpoint; use callTool+- `memory_restore_page`: admin-only restore of one page from a git checkpoint; use callTool<!-- generated:methods:end -->`callTool(name, args)` calls any tool with wire-format arguments and returnsdiff --git a/companions/ai-memory-ts/src/coverage.ts b/companions/ai-memory-ts/src/coverage.tsindex 849f0e27..8d82f58a 100644--- a/companions/ai-memory-ts/src/coverage.ts+++ b/companions/ai-memory-ts/src/coverage.ts@@ -193,7 +193,7 @@ export const TOOL_COVERAGE: Readonly<Record<string, ToolClassification>> = {},memory_restore_page: {status: "not_exposed",- reason: "restores one page from a git checkpoint; use callTool",+ reason: "admin-only restore of one page from a git checkpoint; use callTool",},};diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.mdindex de00ac5d..a5c2c460 100644--- a/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md@@ -13,7 +13,8 @@ Use this skill only for deliberate durable wiki mutations. Routine session captu- `memory_write_page` writes a durable wiki page for permanent project knowledge.- `memory_delete_page` removes a durable wiki page by exact path.- `memory_restore_page` lists a page's checkpoints (no `rev`) or writes an- earlier version back (with `rev`), including a deleted page.+ earlier version back (with `rev`), including a deleted page. It is admin+ only on a multi-user server and does not reach `scope: "profile"` pages.## Writing durable memorydiff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex c25536b3..d60db446 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -391,9 +391,11 @@ should be proposed from a completed session, or at explicit wrap-up \instead of falling back. Pass `expected_page_id` to delete only the \version you read.\n\- `memory_restore_page` — when the user asks to undo a page change or \- bring back a deleted page. Without `rev` it lists the page's checkpoints; \- with `rev` it writes that version back through `memory_write_page`. \- Follow the client-aware project-scope rule above.\n\+ bring back a deleted page. Admin only (implicit on a single-operator \+ server); project pages only, not `scope: \"profile\"` pages. Without \+ `rev` it lists the page's checkpoints; with `rev` it writes that version, \+ frontmatter included, back through the `memory_write_page` path. Follow \+ the client-aware project-scope rule above.\n\- `memory_feedback` — right after a `memory_query` / `memory_read_page` \hit proves useful or misleading, and whenever the user says a recalled \page is out of date or wrong. Pass the exact `path` from the hit plus \@@ -1693,6 +1695,38 @@ struct RestorePageArgs {workspace: Option<String>,}+/// The page metadata a checkpoint's frontmatter carries, in the shape+/// `memory_write_page` takes, so a restore keeps `kind`, `entities`,+/// `abstract`, `relations` and the profile fields instead of clearing them.+/// The write path validates them again with the same bounds as any write.+fn checkpoint_write_metadata(+ frontmatter: &serde_json::Value,+) -> Result<ai_memory_core::page::PageWriteMetadata, McpError> {+ const KEYS: [&str; 6] = [+ "kind",+ "entities",+ "abstract",+ "relations",+ "applies_to",+ "enforced_by",+ ];+ let picked: serde_json::Map<String, serde_json::Value> = KEYS+ .iter()+ .filter_map(|key| {+ frontmatter+ .get(*key)+ .filter(|value| !value.is_null())+ .map(|value| ((*key).to_owned(), value.clone()))+ })+ .collect();+ serde_json::from_value(serde_json::Value::Object(picked)).map_err(|e| {+ McpError::invalid_params(+ format!("the checkpoint's page metadata cannot be restored as written: {e}"),+ None,+ )+ })+}+/// Write one durable wiki page. Optional metadata (`kind`, `entities`,/// `abstract`, `relations`) replaces the page's previous metadata; omitted/// fields are cleared, not inherited.@@ -4310,6 +4344,18 @@ impl AiMemoryServer {&self,Parameters(args): Parameters<WritePageArgs>,OptionalParts(parts): OptionalParts,+ ) -> Result<CallToolResult, McpError> {+ self.write_page_in_scope(args, parts, None).await+ }++ /// The body of [`Self::memory_write_page`]. `resolved` is a scope the+ /// caller already resolved and authorized (`memory_restore_page` resolves+ /// once and must write where it read); `None` resolves from `args`.+ async fn write_page_in_scope(+ &self,+ args: WritePageArgs,+ parts: axum::http::request::Parts,+ resolved: Option<ai_memory_store::ResolvedWriteScope>,) -> Result<CallToolResult, McpError> {let metadata = args.metadata@@ -4386,74 +4432,77 @@ impl AiMemoryServer {None,));}- let resolved_scope = match args.scope.as_deref().map(str::trim) {- None | Some("") => {- self.resolve_write_target_with_actor(- args.workspace.as_deref(),- args.project.as_deref(),- &aps_actor,- Self::viewer_from_parts(Some(&parts)),- )- .await?- }- Some("global") => {- if args- .workspace- .as_deref()- .is_some_and(|s| !s.trim().is_empty())- || args- .project+ let resolved_scope = match resolved {+ Some(resolved) => resolved,+ None => match args.scope.as_deref().map(str::trim) {+ None | Some("") => {+ self.resolve_write_target_with_actor(+ args.workspace.as_deref(),+ args.project.as_deref(),+ &aps_actor,+ Self::viewer_from_parts(Some(&parts)),+ )+ .await?+ }+ Some("global") => {+ if args+ .workspace.as_deref().is_some_and(|s| !s.trim().is_empty())- {- return Err(McpError::internal_error(- "scope: \"global\" cannot be combined with workspace/project",- None,- ));+ || args+ .project+ .as_deref()+ .is_some_and(|s| !s.trim().is_empty())+ {+ return Err(McpError::internal_error(+ "scope: \"global\" cannot be combined with workspace/project",+ None,+ ));+ }+ // The same resolver and choke point as an explicit+ // `default/_global` write, so both spellings are gated alike.+ self.resolve_write_target_with_actor(+ Some(ai_memory_core::DEFAULT_WORKSPACE_NAME),+ Some(ai_memory_core::GLOBAL_SCOPE_PROJECT),+ &aps_actor,+ Self::viewer_from_parts(Some(&parts)),+ )+ .await?}- // The same resolver and choke point as an explicit- // `default/_global` write, so both spellings are gated alike.- self.resolve_write_target_with_actor(- Some(ai_memory_core::DEFAULT_WORKSPACE_NAME),- Some(ai_memory_core::GLOBAL_SCOPE_PROJECT),- &aps_actor,- Self::viewer_from_parts(Some(&parts)),- )- .await?- }- Some("profile") => {- if args- .workspace- .as_deref()- .is_some_and(|s| !s.trim().is_empty())- || args- .project+ Some("profile") => {+ if args+ .workspace.as_deref().is_some_and(|s| !s.trim().is_empty())- {+ || args+ .project+ .as_deref()+ .is_some_and(|s| !s.trim().is_empty())+ {+ return Err(McpError::internal_error(+ "scope: \"profile\" cannot be combined with workspace/project",+ None,+ ));+ }+ let (workspace_id, project_id) =+ self.profile_target_ids(&parts, &aps_actor, true).await?;+ ai_memory_store::ResolvedWriteScope {+ scope: ai_memory_store::ResolvedScope {+ workspace_id,+ project_id,+ },+ promoted_from: None,+ }+ }+ Some(other) => {return Err(McpError::internal_error(- "scope: \"profile\" cannot be combined with workspace/project",+ format!(+ "unknown scope '{other}': the supported values are \"global\" and \"profile\""+ ),None,));}- let (workspace_id, project_id) =- self.profile_target_ids(&parts, &aps_actor, true).await?;- ai_memory_store::ResolvedWriteScope {- scope: ai_memory_store::ResolvedScope {- workspace_id,- project_id,- },- promoted_from: None,- }- }- Some(other) => {- return Err(McpError::internal_error(- format!(- "unknown scope '{other}': the supported values are \"global\" and \"profile\""- ),- None,- ));- }+ },};let (ws, proj) = resolved_scope.scope.as_tuple();let manifest_warning = self.refresh_promoted_scope(&resolved_scope).await;@@ -5019,26 +5068,35 @@ impl AiMemoryServer {annotations(title = "Restore memory page",read_only_hint = false,- destructive_hint = false,+ destructive_hint = true,idempotent_hint = true,- open_world_hint = true+ open_world_hint = false),description = "Bring back an earlier version of a wiki page, \- including a deleted one. Without `rev`, lists the checkpoints that \- changed `path` (newest first): `{ path, checkpoints: [{ rev, summary, \- time }] }` — read-only. With `rev` (a listed checkpoint, or the \- checkpoint before a `memory_delete_page`), writes that \- version back as a new current version through `memory_write_page`, \- so sanitization, admission, attribution and supersession apply; the \- version it replaces stays reachable. Pass `workspace` + `project` \- together on static clients. Use only when the user asks to restore \- or undo a page change."+ including a deleted one. Admin only: the same authority as \+ `/admin/restore-page`, because a checkpoint can hold text a root \+ deleted, purged or let expire (implicit on a single-operator \+ server). Without `rev`, lists the checkpoints that changed `path` \+ (newest first): `{ path, checkpoints: [{ rev, summary, time }] }`. \+ With `rev` (a listed checkpoint, or the checkpoint before a \+ `memory_delete_page`), writes that version back, frontmatter \+ included, as a new current version through the `memory_write_page` \+ path, so sanitization, admission, attribution and supersession \+ apply; the version it replaces stays reachable. Project pages only: \+ `scope: \"profile\"` pages cannot be restored here. Pass \+ `workspace` + `project` together on static clients. Use only when \+ the user asks to restore or undo a page change.")]async fn memory_restore_page(&self,Parameters(args): Parameters<RestorePageArgs>,OptionalParts(parts): OptionalParts,) -> Result<CallToolResult, McpError> {+ // Git history keeps every version the live wiki dropped: pages a root+ // deleted, purge-session removed or the forget sweep expired. Listing+ // names those versions and restoring resurrects them, so both need+ // `/admin/restore-page`'s authority, not a reader's or writer's grant.+ self.require_admin_capability(&parts).await?;let aps_actor = Self::actor_key_from_parts(Some(&parts));let Some(wiki) = self.wiki.as_ref() else {return Err(McpError::internal_error(@@ -5047,9 +5105,14 @@ impl AiMemoryServer {));};let path = PagePath::new(args.path.clone())+ .and_then(|p| p.ensure_portable().map(|()| p)).map_err(|e| McpError::invalid_params(format!("invalid path: {e}"), None))?;+ // Resolved once, no-create, for writing: the listing, the checkpoint+ // read and the write all address this one project, so a moving+ // active-project pointer cannot read from one project and write into+ // another.let (ws, proj) = self- .effective_ids_for_read_args_with_actor(+ .effective_ids_for_mutation_args_with_actor(args.workspace.as_deref(),args.project.as_deref(),&aps_actor,@@ -5061,6 +5124,7 @@ impl AiMemoryServer {let limit = args.limit.unwrap_or(20).clamp(1, 100);let checkpoints = wiki.page_checkpoints(ws, proj, &path, limit)+ .await.map_err(|e| McpError::internal_error(e.to_string(), None))?;let checkpoints: Vec<_> = checkpoints.into_iter()@@ -5072,10 +5136,14 @@ impl AiMemoryServer {}));};- let md = wiki.page_at_checkpoint(ws, proj, &path, rev).map_err(|e| {- McpError::invalid_params(format!("cannot read {path} at {rev}: {e}"), None)- })?;+ let md = wiki+ .page_at_checkpoint(ws, proj, &path, rev)+ .await+ .map_err(|e| {+ McpError::invalid_params(format!("cannot read {path} at {rev}: {e}"), None)+ })?;let fm = &md.frontmatter;+ let metadata = checkpoint_write_metadata(fm)?;let text = |key: &str| {fm.get(key).and_then(serde_json::Value::as_str)@@ -5092,7 +5160,7 @@ impl AiMemoryServer {}).unwrap_or_default();let write = WritePageArgs {- metadata: Default::default(),+ metadata,path: path.to_string(),body: md.body,title: text("title"),@@ -5110,8 +5178,15 @@ impl AiMemoryServer {expected_page_id: None,create_only: false,};+ let resolved = ai_memory_store::ResolvedWriteScope {+ scope: ai_memory_store::ResolvedScope {+ workspace_id: ws,+ project_id: proj,+ },+ promoted_from: None,+ };let result = self- .memory_write_page(Parameters(write), OptionalParts(parts))+ .write_page_in_scope(write, parts, Some(resolved)).await?;if result.is_error.unwrap_or(false) {return Ok(result);@@ -17391,6 +17466,117 @@ mod tests {);}+ /// A restore must bring back the page's metadata, not only its body:+ /// the write path clears omitted metadata, so a restore that dropped it+ /// would silently strip `kind`, `entities`, `abstract` and `relations`.+ #[tokio::test]+ async fn memory_restore_page_round_trips_frontmatter_metadata() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)+ .with_wiki(wiki.clone());+ let payload = serde_json::json!({+ "path": "notes/metadata.md", "body": "# Metadata\n\nDurable content.",+ "kind": "rule", "entities": ["sqlite", "writer actor"],+ "abstract": "One-line summary.",+ "relations": {"fixes": ["gotchas/build"], "contradicts": ["decisions/old.md"]},+ "tags": ["storage"], "pinned": true, "tier": "procedural"+ });+ server+ .memory_write_page(+ Parameters(serde_json::from_value(payload.clone()).unwrap()),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap();+ let path = PagePath::new("notes/metadata.md").unwrap();+ let before = wiki.read_page(ws, proj, &path).unwrap();+ server+ .memory_delete_page(+ Parameters(DeletePageArgs {+ scope: None,+ path: path.to_string(),+ project: None,+ workspace: None,+ expected_page_id: None,+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap();++ let listed = result_json(+ &server+ .memory_restore_page(+ Parameters(restore_args(path.as_str(), None, None)),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap(),+ );+ let pre_delete = listed["checkpoints"][1]["rev"].as_str().unwrap().to_owned();+ server+ .memory_restore_page(+ Parameters(restore_args(path.as_str(), Some(&pre_delete), None)),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap();++ let after = wiki.read_page(ws, proj, &path).unwrap();+ for key in [+ "kind",+ "entities",+ "abstract",+ "relations",+ "tags",+ "pinned",+ "tier",+ ] {+ assert_eq!(+ after.frontmatter.get(key),+ before.frontmatter.get(key),+ "restore must keep `{key}`: {}",+ after.frontmatter+ );+ }+ assert_eq!(after.frontmatter["kind"], "rule");+ assert_eq!(after.frontmatter["relations"], payload["relations"]);+ assert_eq!(after.body, before.body);+ }++ /// Metadata that the write path would refuse is refused from a+ /// checkpoint too, before anything is written.+ #[test]+ fn checkpoint_write_metadata_keeps_only_page_metadata_and_rejects_bad_shapes() {+ let meta = checkpoint_write_metadata(&serde_json::json!({+ "title": "ignored here", "kind": "rule", "entities": ["a"],+ "abstract": null, "session_id": "x"+ }))+ .unwrap();+ assert_eq!(meta.kind.as_deref(), Some("rule"));+ assert_eq!(meta.entities, ["a"]);+ assert!(meta.abstract_text.is_none());+ assert!(+ checkpoint_write_metadata(&serde_json::json!({ "entities": "not-a-list" })).is_err()+ );+ assert!(+ checkpoint_write_metadata(&serde_json::json!({ "relations": { "blocks": ["x"] } }))+ .is_err()+ );+ }+#[tokio::test]async fn memory_restore_page_refuses_unknown_explicit_scope_and_bad_rev() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-mcp/tests/suite/mod.rs b/crates/ai-memory-mcp/tests/suite/mod.rsindex 814cb24c..d6848f9d 100644--- a/crates/ai-memory-mcp/tests/suite/mod.rs+++ b/crates/ai-memory-mcp/tests/suite/mod.rs@@ -37,6 +37,7 @@ mod query_reasoning;mod query_superseded;mod read_page_related;mod recap_identity;+mod restore_page_authz;mod retrieval_via_tools;mod self_service_keys;mod session_management;diff --git a/crates/ai-memory-mcp/tests/suite/restore_page_authz.rs b/crates/ai-memory-mcp/tests/suite/restore_page_authz.rsnew file mode 100644index 00000000..ff16ade6--- /dev/null+++ b/crates/ai-memory-mcp/tests/suite/restore_page_authz.rs@@ -0,0 +1,461 @@+//! `memory_restore_page` through the production auth stack.+//!+//! Git keeps every version the live wiki dropped: a page a root deleted, a+//! session purge removed, an expired page the forget sweep hard-deleted. The+//! tool's listing names those versions and a restore brings their text back,+//! so both carry the authority of root-only `/admin/restore-page`. These tests+//! drive the real `require_bearer` middleware with real `aim_` DB-user tokens+//! and the trusted-proxy rung, attempt each bypass, and keep a root control+//! beside every refusal so a blanket deny cannot pass for the guard.++use ai_memory_core::{ActorContext, ApiCredentialId, NewUser, ProjectId, UserRole};+use ai_memory_mcp::AiMemoryServer;+use ai_memory_mcp::auth::{AuthState, require_bearer};+use ai_memory_store::{AccessMode, GrantLevel, Store, TokenPepper, generate_api_key, hash_token};+use ai_memory_wiki::Wiki;+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 std::sync::Arc;+use tempfile::TempDir;+use tower::ServiceExt;++const ROOT_TOKEN: &str = "the-root-token";+const PROXY_TOKEN: &str = "the-proxy-token";+const PEPPER: &str = "test-pepper-restore-page-authz-123456789";+const ISSUER: &str = "https://idp.example";+const ALICE_SUB: &str = "oidc-subject-alice";++struct Harness {+ http: Router,+ store: Store,+ shared: ProjectId,+ _tmp: TempDir,+}++/// A multi-user server: root bearer, `aim_` DB users, a trusted proxy, and+/// per-user slots on. `shared` is open to every user, `secret` is restricted.+async fn harness() -> Harness {+ let tmp = TempDir::new().expect("tempdir");+ let store = Store::open(tmp.path()).expect("store");+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .expect("ws");+ let baked = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .expect("baked");+ let shared = store+ .writer+ .get_or_create_project(ws, "shared", None)+ .await+ .expect("shared");+ let secret = store+ .writer+ .get_or_create_project(ws, "secret", None)+ .await+ .expect("secret");+ store+ .writer+ .set_access_mode(secret, AccessMode::Restricted)+ .await+ .expect("restrict secret");+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).expect("wiki");+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, baked)+ .with_wiki(wiki)+ .with_per_user_slots(true)+ .with_trusted_proxy_identity(true);+ let service = StreamableHttpService::new(+ move || Ok(server.clone()),+ LocalSessionManager::default().into(),+ StreamableHttpServerConfig::default()+ .with_stateful_mode(false)+ .with_json_response(true),+ );+ let auth = AuthState::new(Some(ROOT_TOKEN.to_string()))+ .with_root_actor(ActorContext {+ user: Some("dj".to_string()),+ ..ActorContext::default()+ })+ .with_trusted_proxy_bearer(PROXY_TOKEN)+ .with_multiuser(+ TokenPepper::new(PEPPER),+ store.reader.clone(),+ store.writer.clone(),+ );+ let http =+ Router::new()+ .nest_service("/mcp", service)+ .layer(axum::middleware::from_fn_with_state(+ Arc::new(auth),+ require_bearer,+ ));+ Harness {+ http,+ store,+ shared,+ _tmp: tmp,+ }+}++/// Mint a DB user with an `aim_` token; `write_on` grants write on a project.+async fn db_user(h: &Harness, username: &str, write_on: Option<ProjectId>) -> String {+ let token = generate_api_key().expect("token");+ let id = h+ .store+ .writer+ .create_human_user(+ NewUser {+ username: username.into(),+ name: None,+ email: None,+ },+ UserRole::User,+ None,+ false,+ )+ .await+ .expect("user");+ h.store+ .writer+ .create_api_credential(+ ApiCredentialId::new(),+ id,+ "test".into(),+ hash_token(&token, &TokenPepper::new(PEPPER)),+ None,+ )+ .await+ .expect("credential");+ if let Some(project) = write_on {+ h.store+ .writer+ .grant_memory(id, project, GrantLevel::Write, None)+ .await+ .expect("grant");+ }+ token+}++/// The raw JSON-RPC outcome: `Ok` is the tool's JSON payload, `Err` the+/// refusal message (JSON-RPC error or an `isError` tool result).+async fn call(+ router: &Router,+ bearer: &str,+ name: &str,+ arguments: Value,+) -> Result<Value, String> {+ call_with(+ router,+ &[("authorization", &format!("Bearer {bearer}"))],+ name,+ arguments,+ )+ .await+}++async fn call_with(+ router: &Router,+ headers: &[(&str, &str)],+ name: &str,+ arguments: Value,+) -> Result<Value, String> {+ let body = json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/call",+ "params": { "name": name, "arguments": arguments },+ });+ let mut req = Request::builder()+ .method("POST")+ .uri("/mcp")+ .header("host", "localhost")+ .header("content-type", "application/json")+ .header("accept", "application/json, text/event-stream");+ for (k, v) in headers {+ req = req.header(*k, *v);+ }+ let resp = router+ .clone()+ .oneshot(req.body(Body::from(body.to_string())).expect("mcp req"))+ .await+ .expect("oneshot");+ let status = resp.status();+ let bytes = axum::body::to_bytes(resp.into_body(), 4_000_000)+ .await+ .expect("body");+ let text = String::from_utf8(bytes.to_vec()).expect("utf8");+ if !status.is_success() {+ return Err(format!("HTTP {status}: {text}"));+ }+ let v: Value = serde_json::from_str(&text).unwrap_or_else(|e| panic!("non-JSON: {text}: {e}"));+ if let Some(err) = v.get("error") {+ return Err(err.to_string());+ }+ let joined = v+ .pointer("/result/content")+ .and_then(|c| c.as_array())+ .unwrap_or_else(|| panic!("missing result.content: {text}"))+ .iter()+ .filter_map(|i| i.get("text").and_then(|t| t.as_str()))+ .collect::<Vec<_>>()+ .join("\n");+ if v.pointer("/result/isError").and_then(Value::as_bool) == Some(true) {+ return Err(joined);+ }+ Ok(serde_json::from_str(&joined)+ .unwrap_or_else(|e| panic!("tool text not JSON: {joined}: {e}")))+}++fn scoped(project: &str, extra: Value) -> Value {+ let mut args = json!({ "workspace": "default", "project": project });+ if let (Some(map), Value::Object(extra)) = (args.as_object_mut(), extra) {+ map.extend(extra);+ }+ args+}++/// Root writes then deletes `path` in `project`; returns the pre-delete rev+/// root's own listing names, so a refused caller is handed a valid rev.+async fn written_then_deleted(h: &Harness, project: &str, path: &str, body: &str) -> String {+ call(+ &h.http,+ ROOT_TOKEN,+ "memory_write_page",+ scoped(project, json!({ "path": path, "body": body })),+ )+ .await+ .expect("root write");+ call(+ &h.http,+ ROOT_TOKEN,+ "memory_delete_page",+ scoped(project, json!({ "path": path })),+ )+ .await+ .expect("root delete");+ pre_delete_rev(h, project, path).await+}++async fn pre_delete_rev(h: &Harness, project: &str, path: &str) -> String {+ let listed = call(+ &h.http,+ ROOT_TOKEN,+ "memory_restore_page",+ scoped(project, json!({ "path": path })),+ )+ .await+ .expect("root lists checkpoints");+ listed["checkpoints"][1]["rev"]+ .as_str()+ .unwrap_or_else(|| panic!("write and delete checkpoints: {listed}"))+ .to_owned()+}++async fn root_reads(h: &Harness, project: &str, path: &str) -> Option<String> {+ call(+ &h.http,+ ROOT_TOKEN,+ "memory_read_page",+ scoped(project, json!({ "path": path })),+ )+ .await+ .ok()+ .and_then(|page| page["body"].as_str().map(str::to_owned))+}++/// A DB user who may WRITE the project still cannot list its checkpoints or+/// restore a version a root deleted. Root, the control, can do both.+#[tokio::test]+async fn a_db_user_with_a_write_grant_cannot_list_or_restore() {+ let h = harness().await;+ let alice = db_user(&h, "alice", Some(h.shared)).await;+ let rev = written_then_deleted(+ &h,+ "shared",+ "notes/removed.md",+ "# Removed\n\nroot-deleted text",+ )+ .await;++ // Alice's grant is real: an ordinary write in the project succeeds.+ call(+ &h.http,+ &alice,+ "memory_write_page",+ scoped(+ "shared",+ json!({ "path": "notes/alice.md", "body": "# Alice\n\nmine" }),+ ),+ )+ .await+ .expect("a write grant lets alice write");++ let listed = call(+ &h.http,+ &alice,+ "memory_restore_page",+ scoped("shared", json!({ "path": "notes/removed.md" })),+ )+ .await;+ assert!(+ listed.is_err(),+ "a DB user must not list checkpoints: {listed:?}"+ );+ let restored = call(+ &h.http,+ &alice,+ "memory_restore_page",+ scoped("shared", json!({ "path": "notes/removed.md", "rev": rev })),+ )+ .await;+ assert!(+ restored.is_err(),+ "a DB user must not restore: {restored:?}"+ );+ assert_eq!(+ root_reads(&h, "shared", "notes/removed.md").await,+ None,+ "the refused restore must not have written anything"+ );++ // Control: root restores the same rev.+ let restored = call(+ &h.http,+ ROOT_TOKEN,+ "memory_restore_page",+ scoped("shared", json!({ "path": "notes/removed.md", "rev": rev })),+ )+ .await+ .expect("root restores");+ assert_eq!(restored["restored_from"], rev.as_str());+ assert!(+ root_reads(&h, "shared", "notes/removed.md")+ .await+ .is_some_and(|body| body.contains("root-deleted text"))+ );+}++/// A restricted project the caller holds no grant on: neither listing nor+/// restoring reaches it, while root's control succeeds. An unknown bearer is+/// refused at the door.+#[tokio::test]+async fn a_foreign_restricted_project_is_refused_without_a_grant() {+ let h = harness().await;+ let mallory = db_user(&h, "mallory", Some(h.shared)).await;+ let rev = written_then_deleted(&h, "secret", "notes/plan.md", "# Plan\n\nsecret text").await;++ for args in [+ scoped("secret", json!({ "path": "notes/plan.md" })),+ scoped("secret", json!({ "path": "notes/plan.md", "rev": rev })),+ ] {+ let out = call(&h.http, &mallory, "memory_restore_page", args.clone()).await;+ let refused = out.expect_err("a foreign restricted project must be refused");+ assert!(+ !refused.contains("secret text") && !refused.contains("Plan"),+ "the refusal must not leak the version: {refused}"+ );+ let out = call(&h.http, "aim_not-a-real-token", "memory_restore_page", args).await;+ assert!(out.is_err(), "an unknown bearer must be refused: {out:?}");+ }+ assert_eq!(root_reads(&h, "secret", "notes/plan.md").await, None);++ call(+ &h.http,+ ROOT_TOKEN,+ "memory_restore_page",+ scoped("secret", json!({ "path": "notes/plan.md", "rev": rev })),+ )+ .await+ .expect("root restores in the restricted project");+ assert!(+ root_reads(&h, "secret", "notes/plan.md")+ .await+ .is_some_and(|body| body.contains("secret text"))+ );+}++/// Per-user slots: an operator's slot write lands in their own namespace.+/// The operator cannot restore it through this tool (restore is admin-only,+/// even for their own slot). Root restores the exact namespaced path, and+/// it is not re-homed into root's namespace or onto the shared slot that+/// reaches every operator's brief.+#[tokio::test]+async fn a_personal_slot_restores_to_its_exact_path_and_only_for_root() {+ let h = harness().await;+ let alice = [+ ("authorization", "Bearer the-proxy-token"),+ ("x-memory-actor-issuer", ISSUER),+ ("x-memory-actor-sub", ALICE_SUB),+ ];+ let written = call_with(+ &h.http,+ &alice,+ "memory_write_page",+ scoped(+ "scratch",+ json!({ "path": "_slots/current-focus.md", "body": "alice focus" }),+ ),+ )+ .await+ .expect("alice writes her slot");+ let personal = written["path"].as_str().expect("written path").to_owned();+ assert_ne!(+ personal, "_slots/current-focus.md",+ "per-user slots re-home the write"+ );+ call_with(+ &h.http,+ &alice,+ "memory_delete_page",+ scoped("scratch", json!({ "path": "_slots/current-focus.md" })),+ )+ .await+ .expect("alice deletes her slot");+ let rev = pre_delete_rev(&h, "scratch", &personal).await;++ for path in ["_slots/current-focus.md", personal.as_str()] {+ let out = call_with(+ &h.http,+ &alice,+ "memory_restore_page",+ scoped("scratch", json!({ "path": path, "rev": rev })),+ )+ .await;+ assert!(+ out.is_err(),+ "a non-admin operator must not restore {path}: {out:?}"+ );+ }+ assert_eq!(root_reads(&h, "scratch", &personal).await, None);++ let restored = call(+ &h.http,+ ROOT_TOKEN,+ "memory_restore_page",+ scoped("scratch", json!({ "path": personal, "rev": rev })),+ )+ .await+ .expect("root restores the personal slot");+ assert_eq!(+ restored["path"],+ personal.as_str(),+ "restored to the exact path"+ );+ assert!(+ root_reads(&h, "scratch", &personal)+ .await+ .is_some_and(|body| body.contains("alice focus"))+ );+ assert_eq!(+ root_reads(&h, "scratch", "_slots/current-focus.md").await,+ None,+ "a restore must never land on the shared slot"+ );+}diff --git a/crates/ai-memory-wiki/src/git.rs b/crates/ai-memory-wiki/src/git.rsindex a96216c6..fd122d10 100644--- a/crates/ai-memory-wiki/src/git.rs+++ b/crates/ai-memory-wiki/src/git.rs@@ -680,11 +680,17 @@ impl GitAdapter {/// Return up to `limit` commits, newest first, that changed the file at/// `path` (relative to the repo root), including the commit that deleted- /// it.+ /// it. At most `max_walk` commits are inspected, so a page untouched for a+ /// long history costs a bounded walk rather than the whole repository.////// # Errors/// Propagates any underlying libgit2 error.- pub fn path_checkpoints(&self, path: &Path, limit: usize) -> WikiResult<Vec<Checkpoint>> {+ pub fn path_checkpoints(+ &self,+ path: &Path,+ limit: usize,+ max_walk: usize,+ ) -> WikiResult<Vec<Checkpoint>> {let repo = open_validated_repository(&self.root).map_err(|error| match error {OpenRepositoryError::Git(error) => map_git_err(error),OpenRepositoryError::Wiki(error) => error,@@ -704,7 +710,7 @@ impl GitAdapter {.map(|entry| entry.id())};let mut out = Vec::new();- for oid in walk {+ for oid in walk.take(max_walk) {let oid = oid.map_err(map_git_err)?;let commit = repo.find_commit(oid).map_err(map_git_err)?;let parent_blob = commit.parent(0).ok().and_then(|p| blob_at(&p));@@ -1611,6 +1617,47 @@ mod tests {assert_eq!(std::fs::read(external.join("HEAD")).unwrap(), before);}+ #[test]+ fn path_checkpoints_lists_changes_and_deletion_and_stops_at_the_walk_cap() {+ let tmp = tempdir();+ let root = tmp.path().join("wiki");+ let adapter = GitAdapter::open_or_init(&root).unwrap();+ std::fs::write(root.join("page.md"), "v1").unwrap();+ adapter.commit_all("write v1").unwrap();+ std::fs::write(root.join("page.md"), "v2").unwrap();+ adapter.commit_all("write v2").unwrap();+ std::fs::remove_file(root.join("page.md")).unwrap();+ adapter.commit_all("delete").unwrap();+ for i in 0..3 {+ std::fs::write(root.join("other.md"), format!("o{i}")).unwrap();+ adapter.commit_all("unrelated").unwrap();+ }+ let summaries = |hits: Vec<Checkpoint>| -> Vec<String> {+ hits.into_iter().map(|c| c.summary).collect()+ };++ let all = adapter+ .path_checkpoints(Path::new("page.md"), 10, 100)+ .unwrap();+ assert_eq!(summaries(all), ["delete", "write v2", "write v1"]);+ let limited = adapter+ .path_checkpoints(Path::new("page.md"), 1, 100)+ .unwrap();+ assert_eq!(summaries(limited), ["delete"]);+ // Three unrelated commits sit on top: a walk of four sees only the+ // delete, a walk of three sees nothing.+ let capped = adapter+ .path_checkpoints(Path::new("page.md"), 10, 4)+ .unwrap();+ assert_eq!(summaries(capped), ["delete"]);+ assert!(+ adapter+ .path_checkpoints(Path::new("page.md"), 10, 3)+ .unwrap()+ .is_empty()+ );+ }+#[test]fn commit_all_returns_none_when_clean_some_when_dirty() {let tmp = tempdir();diff --git a/crates/ai-memory-wiki/src/lib.rs b/crates/ai-memory-wiki/src/lib.rsindex 4126fb29..ea535bc3 100644--- a/crates/ai-memory-wiki/src/lib.rs+++ b/crates/ai-memory-wiki/src/lib.rs@@ -34,8 +34,8 @@ pub use markdown::{pub use migrations::run_pending as run_wiki_migrations;pub use watcher::{DEBOUNCE_WINDOW, RECONCILE_INTERVAL, WatcherHandle};pub use wiki::{- ConditionalWrite, MoveSessionOutcome, PurgeSessionOutcome, SessionPageFile, Wiki,- WritePageRequest,+ ConditionalWrite, MoveSessionOutcome, PAGE_CHECKPOINT_WALK_LIMIT, PurgeSessionOutcome,+ SessionPageFile, Wiki, WritePageRequest,};// Integration tests compile into this crate's test harness instead of adiff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex 78912835..48b2eed8 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -97,6 +97,11 @@ enum PageStoreRemoval {},}+/// Most commits [`Wiki::page_checkpoints`] inspects for one page. A+/// checkpoint is one commit per write or consolidation pass, so this covers a+/// long history while keeping a lookup on a page nobody touched lately bounded.+pub const PAGE_CHECKPOINT_WALK_LIMIT: usize = 5_000;+/// Body + optional L0 abstract text a caller of `reindex_page_locked` should/// embed once it is safe to do so (i.e. after releasing whatever lock it/// took to call in). Captured before `upsert_page` moves `md.body` /@@ -388,10 +393,13 @@ impl Wiki {/// Checkpoints, newest first, that changed one page (including the one/// that deleted it), so a caller can pick a `rev` to restore from.///+ /// The history walk runs on the blocking pool and inspects at most+ /// [`PAGE_CHECKPOINT_WALK_LIMIT`] commits.+ ////// # Errors/// Returns [`WikiError`] when the path escapes the project tree or git/// cannot be read.- pub fn page_checkpoints(+ pub async fn page_checkpoints(&self,workspace_id: WorkspaceId,project_id: ProjectId,@@ -402,7 +410,12 @@ impl Wiki {let rel = PathBuf::from(workspace_id.to_string()).join(project_id.to_string()).join(path.as_str());- self.git.path_checkpoints(&rel, limit)+ let git = self.git.clone();+ tokio::task::spawn_blocking(move || {+ git.path_checkpoints(&rel, limit, PAGE_CHECKPOINT_WALK_LIMIT)+ })+ .await+ .map_err(|e| WikiError::Io(std::io::Error::other(e.to_string())))?}/// Parse one page as stored at checkpoint `rev`, without touching the@@ -411,7 +424,7 @@ impl Wiki {/// # Errors/// Returns [`WikiError`] when the revision/path does not exist or the/// stored bytes are not parseable UTF-8 markdown.- pub fn page_at_checkpoint(+ pub async fn page_at_checkpoint(&self,workspace_id: WorkspaceId,project_id: ProjectId,@@ -422,7 +435,11 @@ impl Wiki {let rel = PathBuf::from(workspace_id.to_string()).join(project_id.to_string()).join(path.as_str());- let bytes = self.git.file_at_rev(rev, &rel)?;+ let git = self.git.clone();+ let rev_owned = rev.to_owned();+ let bytes = tokio::task::spawn_blocking(move || git.file_at_rev(&rev_owned, &rel))+ .await+ .map_err(|e| WikiError::Io(std::io::Error::other(e.to_string())))??;let raw = String::from_utf8(bytes).map_err(|e| {WikiError::Io(std::io::Error::other(format!("{} at {rev} is not valid UTF-8 markdown: {e}",diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 6f7e65dd..52fe2062 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -649,7 +649,7 @@ long-lived entry there is expected policy behavior, not a fault.| `memory_auto_improve` | write | Manually review a completed session and apply or stage validated wiki edits through the auto-improvement approval path. Without a session ID, selects the newest completed session with no persisted auto-improvement run so repeated calls advance through preflight skips; an explicit ID remains rerunnable. The server also schedules review for new sessions; `[auto_improve] require_approval = true` leaves proposals pending for manual review. || `memory_write_page` | destructive | Write durable wiki knowledge when the user explicitly asks to remember/annotate it. `scope: "global"` writes into the reserved `_global` preferences scope and `scope: "profile"` into the caller's cross-project profile (path placed under `profile/`); optional `expires_at` sets an RFC3339 or date-only TTL; optional `session_id` cites a session of the same project as evidence, and on `sessions/<id>.md` stamps the session-page frontmatter and settles the queued consolidation job. Optional `expected_page_id` (the `page_id` a read returned) writes only if that is still the latest version, and `create_only: true` refuses to overwrite an existing page; a failed precondition writes nothing and returns `reason: "precondition_failed"` with the current version (see `docs/programmatic-memory.md`). || `memory_delete_page` | destructive | Delete a single page by exact `path`; `scope: "profile"` deletes from the caller's cross-project profile. Fires the admission chain (op=delete); idempotent. Optional `expected_page_id` deletes only if that is still the latest version; otherwise nothing is deleted and the call returns `reason: "precondition_failed"`. |-| `memory_restore_page` | write | Without `rev`, list the git checkpoints that changed `path` (read-only). With `rev`, write that version back through `memory_write_page` (sanitizer, admission, slots, supersession), including a deleted page. |+| `memory_restore_page` | destructive | Admin only, like `/admin/restore-page`. Without `rev`, list the git checkpoints that changed `path`. With `rev`, write that version (body and frontmatter metadata) back through the `memory_write_page` path (sanitizer, admission, slots, supersession), including a deleted page. Project pages only, not `scope: "profile"`. || `memory_forget_sweep` | destructive | Retention pass: evict cold pages through the wiki layer, purge aged tombstone ancestry, and hard-delete TTL-expired pages. `dry_run=true` for preview. || `memory_lint` | destructive | Rule-based + LLM contradiction findings → `wiki/_lint/`. Also runs a **zero-LLM contradiction detector** (design-memory-aging.md A5): cold semantic/procedural pages whose already-stored embeddings sit in the `contradiction_band_min`–`contradiction_band_max` cosine-similarity band (default 0.4–0.75; "same topic, not a near-duplicate"; at/above the max is A3 dedup, below the min unrelated) get an advisory `contradiction` finding with newer-wins timestamp advice. Bounded (one embeddings load over the capped cold set, capped findings, deterministic); a clean no-op with no embedder configured; advisory-only (never deletes/edits/supersedes a page and persists no edge, invariants #13, #16, #2), so no migration. On a single-language or single-domain store, background similarity between unrelated pages already sits well above the default floor, so the band measures domain proximity more than conflict and produces noisy findings, so raise `contradiction_band_min` (`config.toml` or `AI_MEMORY_CONTRADICTION_BAND_MIN`) for such a store. || `memory_install_self_routing` | read-only | Return the canonical slim routing snippet plus managed Agent Skill payloads and target hints for CLAUDE.md / AGENTS.md installs. |diff --git a/docs/competitive-parity.md b/docs/competitive-parity.mdindex f97eca22..46721c4c 100644--- a/docs/competitive-parity.md+++ b/docs/competitive-parity.md@@ -283,7 +283,7 @@ invariants), **ALREADY** (we have it and should say so).| Auth on by default | SHIPPED (3.0) for new installs; requiring auth on existing loopback installs DECLINED for 2.x | Flipping existing installs would break every env-less hook and MCP config, a major change under our semver. Existing installs opt in with `ai-memory auth enable` || One-command installer / onboarding | SHIPPED (3.0) for Linux and macOS (`install.sh` + `ai-memory setup`); the agent-driven install doc is folded in | No npm package; no Windows service step || Many-language README | DECLINE | Translations go stale on every release, and stale docs are defects under our quality bar |-| Large speculative tool surfaces (leases, task graphs, routines, sentinels, sketches, crystals, facets; 50+ tools visible by default) | DECLINE | No evidence of real use; each tool adds prompt-surface cost; we keep 23 tools and have run leases where needed |+| Large speculative tool surfaces (leases, task graphs, routines, sentinels, sketches, crystals, facets; 50+ tools visible by default) | DECLINE | No evidence of real use; each tool adds prompt-surface cost; we keep 24 tools and have run leases where needed || Signals between agents | ALREADY | Typed cross-project messaging with exactly-once pop || Mesh / P2P sync | ALREADY (3.0) via `ai-memory-wikisync` | Two-way, conflict-aware git sync over the file truth using `expected_page_id` compare-and-swap || Durable capture inbox / offline spool | ALREADY | Hook spool, `ai-memory-relay`, `ai-memory recover`, 202/429 backpressure |diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.mdindex 17a7bb45..9412ae0e 100644--- a/docs/lifecycle-ops.md+++ b/docs/lifecycle-ops.md@@ -21,6 +21,7 @@ on a homelab box where mistakes are harder to undo.| `reclaim-ledger-versions` | ✅ yes | superseded pre-#660 ledger page *versions* only | no (the latest page version stays) | Dry-run by default; needs `--confirm` to delete. Online through the writer actor, safe alongside the live writer. Content-gated: only non-latest, non-decay `log.md`/`log-YYYY-MM.md` versions whose body opens with a ledger hook entry are removed; a real page that merely shares the name is untouched. `--compact` additionally rebuilds FTS and `VACUUM`s to reclaim the freed bytes. || `checkpoints` | ✅ yes | no | n/a | Lists recent wiki git checkpoints. Read-only. || `restore-page --path --from` | ✅ yes | overwrites one markdown page version | yes (restore another checkpoint) | Restores one page from wiki git history, reindexes it into SQLite, and writes a post-restore checkpoint. Does not restore DB-only state. |+| MCP `memory_restore_page` | ✅ yes | no (writes a new current version; the replaced one stays reachable) | yes (restore another checkpoint) | Lists a page's checkpoints, or writes one back through the `memory_write_page` path. Admin only, like `restore-page`. See [below](#mcp-memory_restore_page). || `backup-agents --to` / `restore-agents --from <tarball>` | ✅ yes (client-side; never touches the server or its data dir) | no | yes (`restore-agents --apply` keeps timestamped copies of overwritten files) | Agent-config assets, not wiki/db: MCP configs (redacted unless `--include-secrets`), hook configs, instructions, skills, plugins. `restore-agents` is a dry run by default; `--apply` writes to disk and `--force` overwrites existing or differing targets. Non-MCP assets are restored verbatim and may contain secrets, so only `--apply` an archive whose source you trust. || `restore --from <tarball>` | ❌ **stop the server first** | overwrites the data dir | no (without prior backup) | Refuses if any sibling `ai-memory` process is alive (sysinfo guard). Stages and verifies the archive before swapping it in, so a failed restore leaves `wiki/` and `db/` as they were. || `reset --confirm` | ❌ **stop the server first** | yes, all data | no | Refuses if any sibling `ai-memory` process is alive (sysinfo guard). |@@ -944,6 +945,45 @@ What it does not recover:embeddings. Those live only in SQLite and require a full `backup` / `restore`if you need to roll them back.+### MCP `memory_restore_page`++The agent-facing counterpart of `restore-page`. Without `rev` it lists the git+checkpoints that changed one page, newest first, including the one that+deleted it; with `rev` it writes that version back as the page's new current+version.++It differs from `restore-page` in how the text gets back in. The checkpoint's+body and frontmatter (`title`, `tier`, `tags`, `pinned`, `expires_at`, `kind`,+`entities`, `abstract`, `relations`, `applies_to`, `enforced_by`) go through the+same path as `memory_write_page`: the sanitizer, the admission chain, write+attribution and supersession all apply, and the version it replaces stays+reachable. Metadata that `memory_write_page` would refuse is refused here too,+before anything is written. Other frontmatter keys are not carried over.+Scope is resolved once, without creating anything, and the listing, the read+and the write all use that one project.++Who may call it: an admin, the same authority as `/admin/restore-page`. Git+history keeps every version the live wiki dropped, including pages a root+deleted, pages a session purge removed and expired pages the forget sweep+hard-deleted, so listing names them and restoring brings their text back. A DB+user or proxied operator is refused for both, even on a project they can write+and even for their own per-user slot. On a server that tells no operators+apart (anonymous loopback, or a root bearer with no users) the caller is root+and nothing changes. Over stdio there is no auth layer, and the caller already+holds the data directory.++Limits:++- Project pages only. Pages written with `scope: "profile"` live in the+ operator's profile and are not addressable here; restore them with+ `restore-page` on the profile's project.+- Listing walks at most 5,000 commits back from `HEAD`, off the async runtime,+ so a page untouched for longer than that lists no checkpoints. Use+ `ai-memory checkpoints` and `restore-page --from` for older history.+- A restored `expires_at` is kept as written. If it is already past, the page+ is hidden again at once and removed by the next forget sweep; restore an+ expired page with `memory_write_page` and a new expiry instead.+### `backup````bashdiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 9a7a0c5c..c5de93de 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -57,7 +57,7 @@ means the boundary is not built yet.| 6 | Active-project pointer (PerActor, no clobber) | `ai-memory-core/src/active_project.rs` `set_for`/`lookup_for` (fail-closed on `Mismatch`); `ai-memory-cli/src/commands/mcp_bridge.rs` `bridge_session_id`: the session-less bridge (`--no-session-id`, every non-Claude stdio client on a token-file install) never forwards an inherited `CLAUDE_CODE_SESSION_ID`, so a client launched from a Claude Code terminal cannot steer that session's per-session pointer; the session-aware bridge reads only the variable its `--agent` names (`CLAUDE_CODE_SESSION_ID`, or `MUSE_SESSION_ID` for Meta Muse Code), so neither harness's id stands in for the other's | `active_project.rs` `parallel_harnesses_of_one_user_keep_separate_pointers`, `two_operators_never_read_each_others_pointer`, `a_session_mismatch_fails_closed_once_anything_has_been_keyed`; `mcp_bridge.rs` `only_the_session_aware_mode_forwards_and_requires_a_session_id` (an inherited id is dropped in session-less mode; the session-aware control forwards it and still fails closed without one), `each_harness_forwards_only_its_own_session_id` (a Muse bridge never forwards an inherited Claude id and fails closed without its own, a Claude bridge never forwards an inherited Muse id; controls forward each harness's own id) and `a_session_less_upstream_config_carries_no_session_header`; `auth_default_e2e.rs` `a_session_less_bridge_serves_any_client_without_holding_the_token` (the built `mcp-bridge --agent muse` refuses to start with only `CLAUDE_CODE_SESSION_ID` set) | STRONG || 6b | Native `_meta` routing coordinate is routing-only (never grants identity) | `ai-memory-mcp/src/server.rs` `attach_native_session` reads only `_meta["ai.opencode/sessionID"]` into `ActorKey.session_id` (trimmed, non-empty-string-validated); `user` still comes from the authenticated `ActorContext`, so a forged `_meta` cannot cross a user/scope boundary — it only selects a session slot behind the existing `active_project` guard | `server.rs` `native_session_metadata_is_routing_only_and_preserves_precedence`, `native_session_metadata_validates_strings_without_granting_identity`; `autoscope_multiuser.rs` `native_metadata_routes_concurrent_reads_and_writes_to_hook_workspaces` (#864) | STRONG || 6c | Per-user slot namespaces stay per operator (`[slots] per_user`) | `ai-memory-mcp/src/server.rs` `place_slot_mutation`, shared by `place_slot_write` (`memory_write_page`) and `place_slot_delete` (`memory_delete_page`): a non-admin's generic `_slots/<name>.md` is redirected to their own `_slots/u-<operator>/` namespace, a path inside another operator's namespace is refused, admins bypass, and nothing changes with the flag off (#1083) | `slot_identity.rs` `oidc_operator_cannot_delete_another_operators_personal_slot`, `oidc_operator_deleting_shared_slot_path_deletes_their_personal_slot` (shared slot survives), legitimate controls `oidc_operator_can_delete_their_own_personal_slot_explicitly`, `admin_can_delete_shared_and_personal_slots` | STRONG |-| 6d | MCP page restore cannot bypass the write boundary | `ai-memory-mcp/src/server.rs` `memory_restore_page`: listing resolves scope with the fail-closed read resolver; a restore reads the checkpoint and calls `memory_write_page`, so the sanitizer, admission chain, slot namespaces, write authorization and supersession all apply (unlike root-only `/admin/restore-page`) | `server.rs` `memory_restore_page_refuses_unknown_explicit_scope_and_bad_rev` (foreign scope and unknown rev refused), legitimate control `memory_restore_page_lists_checkpoints_and_brings_back_a_deleted_page` | MEDIUM |+| 6d | MCP page restore is admin-only and cannot bypass the write boundary | `ai-memory-mcp/src/server.rs` `memory_restore_page`: `require_admin_capability` gates listing and restoring alike (git keeps text a root deleted, purged or let expire), the same rung as `/admin/restore-page`; scope resolves once with the no-create mutation resolver (`effective_ids_for_mutation_args_with_actor`), so a restricted project needs a write grant even past the gate; a restore writes through `write_page_in_scope` (the `memory_write_page` body) into that resolved scope, so the sanitizer, admission chain, slot placement, attribution and supersession apply, and `checkpoint_write_metadata` re-validates the checkpoint's metadata | `tests/suite/restore_page_authz.rs`: `a_db_user_with_a_write_grant_cannot_list_or_restore` (an `aim_` user who can write the project is refused for both; root control restores), `a_foreign_restricted_project_is_refused_without_a_grant` (no grant on a restricted project, plus an unknown bearer, refused without leaking the version; root control), `a_personal_slot_restores_to_its_exact_path_and_only_for_root` (the slot owner is refused; root restores the exact `_slots/u-…` path, never the shared slot); `server.rs` `memory_restore_page_refuses_unknown_explicit_scope_and_bad_rev`, `memory_restore_page_round_trips_frontmatter_metadata`, legitimate control `memory_restore_page_lists_checkpoints_and_brings_back_a_deleted_page` | STRONG. Bite checks: removing the admin gate fails the write-grant and slot tests; removing it and also resolving without the viewer fails the restricted-project test; dropping the checkpoint metadata fails the round-trip test || 7 | Sanitizer trust boundary (invariant #6) | `ai-memory-core/src/sanitize.rs` `Sanitized<T>` (private field, only `sanitize()` ctor); `Sanitized::new` scrubs the title *before* the 80-char display cap; `ai-memory-mcp/src/server.rs` `sanitize_feedback_reason` scrubs the reason *before* the 500-char cap; `ai-memory-hooks/src/router.rs` `durable_body` scrubs the full excerpt *before* the per-event body caps (`payload::durable_body_cap`), which no longer run at excerpt extraction; `ai-memory-hooks/src/payload.rs` `cap_object_fields` scrubs with the built-in sanitizer *before* the client spool cap; `WriterHandle::insert_observation` requires `Sanitized`; `ops` crate-private | Structural (compile-time) + `store/src/lib.rs` `insert_observation_boundary_scrubs_before_disk` + sanitizer scrub unit tests + `ai-memory-core::sanitize` `title_is_scrubbed_before_the_80_char_cap_runs` + `ai-memory-hooks::router` `issue_980_user_prompt_title_is_sanitized_before_truncated` (a secret straddling the 80-char boundary is redacted, not stored truncated; #980) + `ai-memory-mcp::server` `feedback_reason_is_scrubbed_before_the_500_char_cap` (#1109) + `ai-memory-hooks::router` `issue_1114_user_prompt_body_is_sanitized_before_the_16kib_cap`, `issue_1114_post_compaction_body_is_sanitized_before_the_16kib_cap`, `issue_1114_tool_body_is_sanitized_before_the_2kb_cap`, `tool_body_cap_keeps_the_utf8_boundary` + `ai-memory-hooks::payload` `client_body_cap_scrubs_before_truncating` (each places a secret straddling the cap and asserts a `[REDACTED:…]` marker survives with no raw fragment; #1114) | STRONG (structural) || 7a | Eval observations: server provenance and reason privacy | `ai-memory-consolidate/src/auto_improve.rs` constructs private results from the existing execution, ignores extra model/scorer result fields and all eval results on report deserialization, hashes the evaluated request/bodies, and scrubs reasons before the 2,048-character cap and pending persistence; changed bodies cannot receive the earlier result | `auto_improve::tests::structured_eval_records_server_observation`; `tests/suite/eval_results.rs` `eval_reason_is_sanitized_before_pending_storage_with_legitimate_control` attempts forged deserialized reports and IDs/digests and malicious reasons with secrets/control characters, checks report and stored evidence before sidecar rendering, and preserves a legitimate reason and external evidence without independent results; fails with reason scrubbing or the report deserialization guard removed | STRONG || 7b | New public page metadata is bounded and cannot supply scope, author or admission controls; admin kind retains its legacy adapter | `ai-memory-core/src/page.rs` `PageWriteMetadata::into_frontmatter`; MCP validates all four fields; admin consumes legacy kind explicitly and shares entities/abstract/relations validation before scope creation; both use `Wiki::write_page` for sanitization/admission/authenticated attribution | `admin_write_page.rs` `write_page_metadata_rejects_invalid_payload_before_scope_creation` (invalid shapes, unknown relation kinds, raw-input over-limit values, untrimmed relation scopes and escaping paths refused; legitimate control admitted), `write_page_metadata_preserves_admin_auth_and_sanitization` (anonymous/DB-user refused, root control admitted with scrubbed metadata and authenticated attribution); `server.rs` `memory_write_page_metadata_rejects_invalid_before_scope_creation`, `memory_write_page_metadata_preserves_scope_author_and_sanitization` (foreign user denied; writer control admitted, forged frontmatter/author ignored, secrets scrubbed, invalid rewrite leaves disk and SQL latest unchanged); core `page_write_metadata_scope_components_refuse_surrounding_whitespace` and `page_write_metadata_limits_apply_before_trimming_and_normalization`; admin `write_page_metadata_admin_legacy_kind_matches_base` compares long/control-character kind behavior with the base adapter; entity-bound refusal bite-checked with its validation removed | STRONG |diff --git a/docs/usage.md b/docs/usage.mdindex 66edd634..3f751e1b 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -224,7 +224,7 @@ at the managed ai-memory Agent Skills that carry detailed tool routing.| "Search expired notes for X" | `memory_query` with `include_expired: true` | Opts an explicit project, sibling-scope, or global search into expired historical pages; ordinary searches exclude them. || "Why did this page rank here?" | `memory_query` with `explain: true` | Adds bounded per-stream ranks, matched entities, scores, RRF contributions, graph provenance, and authority factors to project/scopes hits, plus a top-level `timings` object with each stream's wall time in milliseconds (`fts_ms`, `entity_ms`, `vector_ms`, `graph_ms`, `observation_ms`, `rerank_ms`; streams that did not run are left out). A global query reports only its distinct FTS stream and `fts_ms`. || Improve top project/scopes search relevance | Set `AI_MEMORY_RERANKER=llm` on a server with an LLM provider | Sends the bounded query plus up to 30 bounded titles/snippets to the provider for at most one final relevance pass. Invalid, partial, failed, timed-out, or concurrency-saturated requests preserve the normal order; `global=true` and supplemental global-preference hits are unchanged. |-| "Undo that change" / "bring back the page I deleted" | `memory_restore_page` | Call it without `rev` to list the page's checkpoints, then with the chosen `rev` to write that version back as the current one. The replaced version stays reachable. |+| "Undo that change" / "bring back the page I deleted" | `memory_restore_page` | Call it without `rev` to list the page's checkpoints, then with the chosen `rev` to write that version back as the current one. The replaced version stays reachable. Admin only on a multi-user server; see [lifecycle-ops](lifecycle-ops.md#mcp-memory_restore_page). || "Delete this page" / "remove the note about X" | `memory_delete_page` | Removes a page by exact path. Pass `workspace` + `project` together when the page lives in a sibling workspace, so a project name shared between workspaces never silently routes the delete to the wrong slot. || "That recalled page helped" / "this page is stale" | `memory_feedback` | Records `helpful`, `not_helpful`, `stale`, or `wrong` for the exact path. Retention weight affects sweep-eligible episodic pages; stale/wrong also flag any current page for lint review. Retrieved content never authorizes feedback by itself. || "Audit the wiki" / "any contradictions?" | `memory_lint` | Runs stale-page, contradiction, and rule-suggestion checks. |diff --git a/plugins/claude-code/skills/ai-memory-durable-pages/SKILL.md b/plugins/claude-code/skills/ai-memory-durable-pages/SKILL.mdindex de00ac5d..a5c2c460 100644--- a/plugins/claude-code/skills/ai-memory-durable-pages/SKILL.md+++ b/plugins/claude-code/skills/ai-memory-durable-pages/SKILL.md@@ -13,7 +13,8 @@ Use this skill only for deliberate durable wiki mutations. Routine session captu- `memory_write_page` writes a durable wiki page for permanent project knowledge.- `memory_delete_page` removes a durable wiki page by exact path.- `memory_restore_page` lists a page's checkpoints (no `rev`) or writes an- earlier version back (with `rev`), including a deleted page.+ earlier version back (with `rev`), including a deleted page. It is admin+ only on a multi-user server and does not reach `scope: "profile"` pages.## Writing durable memorydiff --git a/plugins/codex/skills/ai-memory-durable-pages/SKILL.md b/plugins/codex/skills/ai-memory-durable-pages/SKILL.mdindex de00ac5d..a5c2c460 100644--- a/plugins/codex/skills/ai-memory-durable-pages/SKILL.md+++ b/plugins/codex/skills/ai-memory-durable-pages/SKILL.md@@ -13,7 +13,8 @@ Use this skill only for deliberate durable wiki mutations. Routine session captu- `memory_write_page` writes a durable wiki page for permanent project knowledge.- `memory_delete_page` removes a durable wiki page by exact path.- `memory_restore_page` lists a page's checkpoints (no `rev`) or writes an- earlier version back (with `rev`), including a deleted page.+ earlier version back (with `rev`), including a deleted page. It is admin+ only on a multi-user server and does not reach `scope: "profile"` pages.## Writing durable memory