Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(mcp): add memory_restore_page to list a page's checkpoints and restore one through the write path
Gabriel Alencar2faa7dfa589f
diff --git a/AGENTS.md b/AGENTS.mdindex 2e5a24e2..cbce9903 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -580,7 +580,7 @@ Additional boundary rules:- **MCP tool surface changes** require updating `MEMORY_INSTRUCTIONS`,`ai_memory_core::SNIPPET_BODY`, README/docs tool references, and theregression tests asserting every tool appears in both prompt surfaces.- The tool count is currently 23 (see `docs/ARCHITECTURE.md`).+ The tool count is currently 24 (see `docs/ARCHITECTURE.md`).- **Semantic versioning:** patch = fixes; minor = additive (new CLIsubcommands, MCP tools, config keys, a new agent harness or LLMprovider); major = breaking (on-disk format without migration, removeddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex b43a8edc..8324f420 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Added the `memory_restore_page` MCP tool: without `rev` it lists the git+ checkpoints that changed a page, and with `rev` it writes that version back+ through `memory_write_page` (sanitizer, admission, slots and supersession+ apply), so an agent can undo a change or bring back a deleted page without+ root access to `/admin/restore-page`. The MCP surface is now 24 tools.+### Fixed- Fixed Cursor tool calls being stored with no title or content: Cursor's ownhooks, and the Claude Code hooks Cursor also runs, send Claude'sdiff --git a/crates/ai-memory-core/src/routing_skills.rs b/crates/ai-memory-core/src/routing_skills.rsindex 51113526..01cecd32 100644--- a/crates/ai-memory-core/src/routing_skills.rs+++ b/crates/ai-memory-core/src/routing_skills.rs@@ -114,6 +114,7 @@ mod tests {("memory_message_cancel", "ai-memory-messaging"),("memory_write_page", "ai-memory-durable-pages"),("memory_delete_page", "ai-memory-durable-pages"),+ ("memory_restore_page", "ai-memory-durable-pages"),("memory_consolidate", "ai-memory-learning-maintenance"),("memory_auto_improve", "ai-memory-learning-maintenance"),("memory_lint", "ai-memory-learning-maintenance"),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 7b4a8813..285b69c8 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@@ -12,6 +12,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.## Writing durable memorydiff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 203af3f6..5520295a 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -367,6 +367,10 @@ should be proposed from a completed session, or at explicit wrap-up \admission chain so mirrors/backups stay consistent. Follow the client-aware \project-scope rule above; missing explicit sibling scopes fail closed \instead of falling back.\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\- `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 \@@ -1587,6 +1591,27 @@ struct DeletePageArgs {scope: Option<String>,}+#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]+struct RestorePageArgs {+ /// Exact wiki path to restore or inspect (e.g. `notes/foo.md`).+ path: String,+ /// Checkpoint commit to restore from, as listed by a call without `rev`+ /// (the newest one is the change being undone). Omit it to+ /// list the checkpoints that changed this page.+ #[serde(default)]+ rev: Option<String>,+ /// Maximum checkpoints to list when `rev` is omitted (default 20, max 100).+ #[serde(default)]+ limit: Option<usize>,+ /// Project of the page. Static MCP clients must pass it together with+ /// `workspace` on every project-scoped call.+ #[serde(default)]+ project: Option<String>,+ /// Workspace of the page, together with `project`.+ #[serde(default)]+ workspace: Option<String>,+}+/// Write one durable wiki page. Optional metadata (`kind`, `entities`,/// `abstract`, `relations`) replaces the page's previous metadata; omitted/// fields are cleared, not inherited.@@ -4964,6 +4989,123 @@ impl AiMemoryServer {}))}+ /// List a page's checkpoints, or restore it from one through the+ /// normal write path.+ #[tool(+ annotations(+ title = "Restore memory page",+ read_only_hint = false,+ destructive_hint = false,+ idempotent_hint = true,+ open_world_hint = true+ ),+ 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."+ )]+ async fn memory_restore_page(+ &self,+ Parameters(args): Parameters<RestorePageArgs>,+ OptionalParts(parts): OptionalParts,+ ) -> Result<CallToolResult, McpError> {+ let aps_actor = Self::actor_key_from_parts(Some(&parts));+ let Some(wiki) = self.wiki.as_ref() else {+ return Err(McpError::internal_error(+ "memory_restore_page requires the server to be built with a wiki handle",+ None,+ ));+ };+ let path = PagePath::new(args.path.clone())+ .map_err(|e| McpError::invalid_params(format!("invalid path: {e}"), None))?;+ let (ws, proj) = self+ .effective_ids_for_read_args_with_actor(+ args.workspace.as_deref(),+ args.project.as_deref(),+ &aps_actor,+ Self::viewer_from_parts(Some(&parts)),+ )+ .await?;++ let Some(rev) = args.rev.as_deref().map(str::trim).filter(|r| !r.is_empty()) else {+ let limit = args.limit.unwrap_or(20).clamp(1, 100);+ let checkpoints = wiki+ .page_checkpoints(ws, proj, &path, limit)+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;+ let checkpoints: Vec<_> = checkpoints+ .into_iter()+ .map(|c| serde_json::json!({ "rev": c.oid, "summary": c.summary, "time": c.time }))+ .collect();+ return ok_json(&serde_json::json!({+ "path": path.to_string(),+ "checkpoints": checkpoints,+ }));+ };++ 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 fm = &md.frontmatter;+ let text = |key: &str| {+ fm.get(key)+ .and_then(serde_json::Value::as_str)+ .map(str::to_owned)+ };+ let tags = fm+ .get("tags")+ .and_then(serde_json::Value::as_array)+ .map(|tags| {+ tags.iter()+ .filter_map(serde_json::Value::as_str)+ .map(str::to_owned)+ .collect()+ })+ .unwrap_or_default();+ let write = WritePageArgs {+ metadata: Default::default(),+ path: path.to_string(),+ body: md.body,+ title: text("title"),+ tier: text("tier"),+ tags,+ pinned: fm+ .get("pinned")+ .and_then(serde_json::Value::as_bool)+ .unwrap_or(false),+ project: args.project,+ workspace: args.workspace,+ scope: None,+ expires_at: text("expires_at"),+ session_id: None,+ };+ let result = self+ .memory_write_page(Parameters(write), OptionalParts(parts))+ .await?;+ if result.is_error.unwrap_or(false) {+ return Ok(result);+ }+ let written = serde_json::to_value(&result.content)+ .ok()+ .and_then(|content| content.get(0)?.get("text")?.as_str().map(str::to_owned))+ .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok());+ match written {+ Some(serde_json::Value::Object(mut map)) => {+ map.insert(+ "restored_from".into(),+ serde_json::Value::String(rev.to_owned()),+ );+ ok_json(&map)+ }+ _ => Ok(result),+ }+ }+/// Delete a single wiki page by exact path.#[tool(annotations(@@ -7873,6 +8015,7 @@ mod tests {"memory_read_page","memory_read_session_observations","memory_delete_page",+ "memory_restore_page","memory_feedback","memory_lint","memory_forget_sweep",@@ -7899,6 +8042,7 @@ mod tests {"memory_read_page","memory_read_session_observations","memory_delete_page",+ "memory_restore_page","memory_feedback","memory_lint","memory_forget_sweep",@@ -16112,6 +16256,171 @@ mod tests {);}+ fn result_json(result: &CallToolResult) -> serde_json::Value {+ let text = result+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ serde_json::from_str(&text).unwrap()+ }++ fn restore_args(path: &str, rev: Option<&str>, project: Option<&str>) -> RestorePageArgs {+ RestorePageArgs {+ path: path.into(),+ rev: rev.map(str::to_owned),+ limit: None,+ project: project.map(str::to_owned),+ workspace: project.map(|_| "default".to_owned()),+ }+ }++ #[tokio::test]+ async fn memory_restore_page_lists_checkpoints_and_brings_back_a_deleted_page() {+ 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);++ server+ .memory_write_page(+ Parameters(WritePageArgs {+ metadata: Default::default(),+ path: "notes/retries.md".into(),+ body: "# Retries\n\nKeep the same event id.".into(),+ title: None,+ tier: Some("semantic".into()),+ tags: vec!["delivery".into()],+ pinned: false,+ project: None,+ workspace: None,+ scope: None,+ expires_at: None,+ session_id: None,+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap();+ server+ .memory_delete_page(+ Parameters(DeletePageArgs {+ scope: None,+ path: "notes/retries.md".into(),+ project: None,+ workspace: None,+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap();++ let listed = result_json(+ &server+ .memory_restore_page(+ Parameters(restore_args("notes/retries.md", None, None)),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap(),+ );+ let revs: Vec<String> = listed["checkpoints"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|c| c["rev"].as_str().map(str::to_owned))+ .collect();+ assert!(+ revs.len() >= 2,+ "the write and the delete both changed the page: {listed}"+ );+ let pre = revs[1].clone();++ let restored = result_json(+ &server+ .memory_restore_page(+ Parameters(restore_args("notes/retries.md", Some(&pre), None)),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap(),+ );+ assert_eq!(restored["restored_from"], pre.as_str());++ let read = result_json(+ &server+ .memory_read_page(+ Parameters(ReadPageArgs {+ query: None,+ path: Some("notes/retries.md".into()),+ project: None,+ workspace: None,+ include_related: false,+ related_depth: None,+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap(),+ );+ assert!(+ read["body"]+ .as_str()+ .unwrap()+ .contains("Keep the same event id.")+ );+ }++ #[tokio::test]+ async fn memory_restore_page_refuses_unknown_explicit_scope_and_bad_rev() {+ 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);++ let foreign = server+ .memory_restore_page(+ Parameters(restore_args("notes/x.md", None, Some("typo"))),+ OptionalParts(test_parts_default()),+ )+ .await;+ assert!(+ foreign.is_err(),+ "an unknown explicit project must fail closed"+ );++ let bad_rev = server+ .memory_restore_page(+ Parameters(restore_args("notes/x.md", Some("deadbeef"), None)),+ OptionalParts(test_parts_default()),+ )+ .await;+ assert!(bad_rev.is_err(), "an unknown rev must not write anything");+ }+#[tokio::test]async fn memory_delete_page_unknown_explicit_project_does_not_fallback() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-wiki/src/git.rs b/crates/ai-memory-wiki/src/git.rsindex b8032882..a96216c6 100644--- a/crates/ai-memory-wiki/src/git.rs+++ b/crates/ai-memory-wiki/src/git.rs@@ -678,6 +678,56 @@ impl GitAdapter {Ok(out)}+ /// Return up to `limit` commits, newest first, that changed the file at+ /// `path` (relative to the repo root), including the commit that deleted+ /// it.+ ///+ /// # Errors+ /// Propagates any underlying libgit2 error.+ pub fn path_checkpoints(&self, path: &Path, limit: 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,+ })?;+ if limit == 0 {+ return Ok(Vec::new());+ }+ let mut walk = repo.revwalk().map_err(map_git_err)?;+ if walk.push_head().is_err() {+ return Ok(Vec::new());+ }+ let blob_at = |commit: &git2::Commit<'_>| {+ commit+ .tree()+ .ok()+ .and_then(|tree| tree.get_path(path).ok())+ .map(|entry| entry.id())+ };+ let mut out = Vec::new();+ for oid in 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));+ if blob_at(&commit) == parent_blob {+ continue;+ }+ out.push(Checkpoint {+ oid: oid.to_string(),+ summary: commit+ .summary()+ .ok()+ .flatten()+ .unwrap_or("(no summary)")+ .to_string(),+ time: commit.time().seconds(),+ });+ if out.len() >= limit {+ break;+ }+ }+ Ok(out)+ }+/// Read `path` as it existed at `rev`.////// `path` is relative to the wiki repo root. The returned bytes are thediff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex 5ce3a2fe..9d42294d 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -382,6 +382,53 @@ impl Wiki {self.git.recent_checkpoints(limit)}+ /// Checkpoints, newest first, that changed one page (including the one+ /// that deleted it), so a caller can pick a `rev` to restore from.+ ///+ /// # Errors+ /// Returns [`WikiError`] when the path escapes the project tree or git+ /// cannot be read.+ pub fn page_checkpoints(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ path: &PagePath,+ limit: usize,+ ) -> WikiResult<Vec<Checkpoint>> {+ self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)?;+ let rel = PathBuf::from(workspace_id.to_string())+ .join(project_id.to_string())+ .join(path.as_str());+ self.git.path_checkpoints(&rel, limit)+ }++ /// Parse one page as stored at checkpoint `rev`, without touching the+ /// live tree or the index.+ ///+ /// # 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(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ path: &PagePath,+ rev: &str,+ ) -> WikiResult<Markdown> {+ self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)?;+ 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 raw = String::from_utf8(bytes).map_err(|e| {+ WikiError::Io(std::io::Error::other(format!(+ "{} at {rev} is not valid UTF-8 markdown: {e}",+ path.as_str()+ )))+ })?;+ parse(&raw)+ }+/// Create the one-time baseline checkpoint for an existing wiki tree that/// was created before git recovery checkpoints existed.///diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 65a664af..768e3ad1 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -547,7 +547,7 @@ Each crate has a single responsibility and exposes a typed API. Nocircular deps. Inter-crate boundaries enforce the cross-cuttinginvariants below.-## MCP tool surface (23 tools)+## MCP tool surface (24 tools)Every registered tool carries explicit MCP annotations for its human-readabletitle and read-only, destructive, idempotent, and open-world behavior. These@@ -593,6 +593,7 @@ long-lived entry appearing there is that policy working rather than 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. || `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. |+| `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_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 — 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/security-boundaries.md b/docs/security-boundaries.mdindex 5360eeb3..232dee58 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -49,6 +49,7 @@ boundary not yet built.| 6 | Active-project pointer (PerActor, no clobber) | `ai-memory-core/src/active_project.rs` `set_for`/`lookup_for` (fail-closed on `Mismatch`) | `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` | 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 || 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 d77a5fc2..2319740c 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -156,6 +156,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. A global query reports only its distinct FTS stream. || 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. || "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. |