Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge pull request #55 from djalmajr/feature/admission-webhooks
AkitaOnRails556ce487a33f
diff --cc CHANGELOG.mdindex 370b873b,2da99b1e..cd9be2ac--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -6,50 -6,6 +6,57 @@@ The format is based on [Keep a Changeloand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).## [Unreleased]+### Added+- Page FTS now indexes normalized page paths, so searches can find pages by+ filename or slug even when the slug does not appear in the title/body ([#62]).++- Admission webhooks can now observe, mutate, or reject engine write/delete/++ purge operations, with authenticated actor context, loop-prevention skip++ lists for trusted re-entry, and non-blocking observer webhooks for mirrors++ and backups ([#55]).++- New `memory_delete_page` MCP tool deletes a single page by exact path,++ updates the SQLite index directly, and fires `op=delete` admission hooks++ before removal ([#55]).++### Fixed+- `memory_write_page` calls that specify `project` without `workspace` now+ default to the active workspace published by hooks, and project-only reads use+ the same active-workspace resolution so the write can be read back without an+ explicit workspace ([#61]).+- `memory_read_page` now accepts explicit `workspace` + `project` for sibling+ projects and falls back to the stored DB body only when the markdown file is+ missing, not when the disk source of truth is corrupt or unreadable ([#63]).++## [0.8.1] - 2026-05-30++### Fixed+- **Consolidation no longer fails on long sessions** (~5,000+ observations or+ multi-hour agent runs). Two bugs surfaced trying to consolidate a real+ 16-hour / 7,234-observation session:+ - **Prompt confusion (regression from the v0.8 `slot_kind` work):** the+ multi-page consolidator prompt listed `slot_kind` values+ (`state` / `invariant`) immediately above the `tier` values+ (`working` / `episodic` / `semantic` / `procedural`). The LLM read them+ as one list and emitted `tier: "state"` in structured responses, which+ deserialisation rejected. Prompt now leads with `tier` (with explicit+ "EXACTLY ONE OF FOUR strings" emphasis), then `kind`, then `slot_kind`+ under its own clearly-scoped section that states "completely unrelated+ to tier" and "only for `_slots/*` paths."+ - **No token budget on the observation dump:** `build_request` and+ `build_batch_request_with_slots` dumped every observation into the+ prompt buffer, which exceeded the provider's 200k-token context on long+ sessions (the sabadell run produced a 235k-token request → 400 from+ the provider). New `window_observations_to_budget` walks the slice+ from most-recent backward, keeping each entry whose render cost fits+ in a 400k-char budget (~100k tokens), leaving room for the system+ prompt + schema + LLM output. When entries are skipped, a prepended+ note tells the LLM the context is partial so its summary doesn't+ pretend to cover the early session. Both `PreCompact` and+ `memory_consolidate` triggers benefit from the fix — both were silently+ failing into the `warn!()` catchall on sessions this long.+ - 5 unit tests guard the windowing invariants (empty input, fits-under-+ budget passthrough, most-recent-preserved, single-too-large-obs drops+ everything, observation-boundary alignment). No schema change, no+ config knob, backward-compatible for sessions that already fit.## [0.8.0] - 2026-05-30diff --cc Cargo.lockindex c3f002f3,bed1f0ae..8b034a8d--- a/Cargo.lock+++ b/Cargo.lock@@@ -248,6 -248,7 +248,8 @@@ dependencies ="ai-memory-store","anyhow","async-trait",+ "axum",++ "futures-util","git2","jiff","notify",@@@ -2225,6 -2228,6 +2229,7 @@@ dependencies ="base64","bytes","futures-core",++ "futures-util","http","http-body","http-body-util",@@@ -2244,12 -2247,12 +2249,14 @@@"sync_wrapper","tokio","tokio-rustls",++ "tokio-util","tower","tower-http","tower-service","url","wasm-bindgen","wasm-bindgen-futures",++ "wasm-streams","web-sys","webpki-roots",]@@@ -3330,6 -3333,6 +3337,19 @@@ dependencies ="wasmparser",]++[[package]]++name = "wasm-streams"++version = "0.4.2"++source = "registry+https://github.com/rust-lang/crates.io-index"++checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"++dependencies = [++ "futures-util",++ "js-sys",++ "wasm-bindgen",++ "wasm-bindgen-futures",++ "web-sys",++]++[[package]]name = "wasmparser"version = "0.244.0"diff --cc Cargo.tomlindex ea235a73,97670813..287d118f--- a/Cargo.toml+++ b/Cargo.toml@@@ -111,7 -111,7 +111,8 @@@ regex = "1git2 = { version = "0.20", default-features = false, features = ["vendored-libgit2"] }# LLM provider HTTP.--reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }++reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] }++futures-util = "0.3"async-trait = "0.1"# Testing.diff --cc crates/ai-memory-cli/src/auth.rsindex c75d0e83,c75d0e83..ef0234d3--- a/crates/ai-memory-cli/src/auth.rs+++ b/crates/ai-memory-cli/src/auth.rs@@@ -241,6 -241,6 +241,7 @@@ pub async fn require_bearer..ActorContext::default()};req.extensions_mut().insert(actor);++ req.extensions_mut().insert(user.id);req.extensions_mut().insert(AuthLevel::User);// Fire-and-forget last_seen_at bump. Errors are loggeddiff --cc crates/ai-memory-core/src/routing_snippet.rsindex ebbefe21,b980f1ff..e604539b--- a/crates/ai-memory-core/src/routing_snippet.rs+++ b/crates/ai-memory-core/src/routing_snippet.rs@@@ -70,7 -70,8 +70,8 @@@ match the intent to the tool. They do n| "save context for the next session" / wrapping up | `memory_handoff_begin` (single-use handoff; terse summary; put detail in `open_questions` + `next_steps` bullets) || "consolidate this session" / "compile what we learned" (also runs on PreCompact; at session end only if `AI_MEMORY_CONSOLIDATE_ON_SESSION_END` is set) | `memory_consolidate` || "remember this permanently" / "save a note" / "add an annotation" / durable project knowledge | `memory_write_page` (write a wiki page; do **not** use handoff for permanent notes) |-| "read the page about X" / "show me the full content of Y" / "open the page on Z" | `memory_read_page` (full body; pass a query to search or `path` for a direct lookup) |+| "read the page about X" / "show me the full content of Y" / "open the page on Z" | `memory_read_page` (full body; pass a query to search or `path` for a direct lookup; pass `workspace` + `project` together only for a named sibling workspace/project) |+ | "delete the page X" / "remove that note" | `memory_delete_page` (by exact `path`; idempotent) || "audit the wiki" / "find contradictions" / "what rules should we add?" | `memory_lint` || "prune old pages" / "memory cleanup" | `memory_forget_sweep` |diff --cc crates/ai-memory-mcp/src/actor.rsindex 00000000,be9b27b5..c1e2124emode 000000,100644..100644--- a/crates/ai-memory-mcp/src/actor.rs+++ b/crates/ai-memory-mcp/src/actor.rs@@@ -1,0 -1,172 +1,221 @@@-//! Per-request actor context — pure helper mapping `X-Memory-Actor-*`-//! HTTP headers to a typed [`ActorContext`].++//! Per-request actor context helpers for MCP tool handlers.+ //!+ //! ## Why this exists+ //!-//! `mcp-auth` (Go sidecar) validates the Keycloak JWT and injects 5-//! request headers derived from claims. The `memory_write_page` tool-//! method receives the raw HTTP `Parts` via rmcp's `Extension<Parts>`-//! extractor (rmcp 1.7+) and calls [`actor_from_headers`] to build the-//! [`ActorContext`] that feeds into the admission webhook chain.++//! The auth middleware injects canonical [`ActorContext`] and [`AuthLevel`]++//! values into request extensions. Tool handlers receive raw HTTP `Parts` via++//! rmcp's `Extension<Parts>` extractor (rmcp 1.7+) and read those extensions;++//! raw actor headers are intentionally not trusted in handlers.+ //!+ //! ## Why not `tokio::task_local`+ //!+ //! We tried that first. `rmcp::transport::streamable_http_server::tower`+ //! dispatches each tool handler via `tokio::spawn` (see+ //! `tower.rs:569+619+1183`), which **does not** inherit task-locals from+ //! the outer axum middleware. The Extension extractor is the official+ //! supported path — see+ //! <https://docs.rs/rmcp/1.7/rmcp/transport/streamable_http_server/struct.StreamableHttpService.html#accessing-http-request-data-from-tool-handlers>.+ //!-//! ## Wire contract++//! ## Skip-list header+ //!-//! Headers expected (set by `mcp-auth` from validated JWT claims):-//!-//! | Header | JWT claim source |-//! |---|---|-//! | `X-Memory-Actor-Agent` | DCR `client_name` (fallback `azp`) |-//! | `X-Memory-Actor-User` | `preferred_username` |-//! | `X-Memory-Actor-Sub` | `sub` |-//! | `X-Memory-Actor-Client` | `azp` (authorized party / DCR client UUID) |-//! | `X-Memory-Actor-Session-Id` | optional |-//!-//! All headers are optional — missing ones fall back to `None`. Use-//! [`ActorContext::has_any`] to skip building an admission context when-//! the actor is completely anonymous (the chain still runs with a-//! default context — webhooks decide what to do with an empty actor).++//! `X-Memory-Skip-Admission-Chain` is a loop-prevention escape hatch for++//! trusted webhook re-entry. It is honored only for root/auth-disabled requests++//! (or test/stdio calls with no auth extension), so a regular DB user cannot++//! bypass a reject-policy admission webhook by setting a client-controlled++//! header.+-use ai_memory_core::ActorContext;++use ai_memory_core::{ActorContext, AuthLevel, UserId};+ use axum::http::HeaderMap;++use axum::http::request::Parts;++ fn header_str(headers: &HeaderMap, name: &str) -> Option<String> {+ headers+ .get(name)+ .and_then(|v| v.to_str().ok())+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty())+ }++ /// Build an [`ActorContext`] from `X-Memory-Actor-*` headers.+ ///+ /// Header names are matched case-insensitively (per HTTP spec).+ #[must_use]+ pub fn actor_from_headers(headers: &HeaderMap) -> ActorContext {+ ActorContext {+ agent: header_str(headers, "x-memory-actor-agent"),+ user: header_str(headers, "x-memory-actor-user"),+ sub: header_str(headers, "x-memory-actor-sub"),+ client: header_str(headers, "x-memory-actor-client"),+ session_id: header_str(headers, "x-memory-actor-session-id"),+ // `name`/`email` aren't carried by the `X-Memory-Actor-*` bridge;+ // the four-rung auth middleware fills those when it injects the+ // canonical `Extension<ActorContext>` directly.+ ..ActorContext::default()+ }+ }+++/// Return the authenticated actor injected by the auth middleware. Raw++/// `X-Memory-Actor-*` headers are deliberately ignored here; handlers should++/// only trust middleware-resolved identity.++#[must_use]++pub fn actor_from_parts(parts: &Parts) -> ActorContext {++ parts++ .extensions++ .get::<ActorContext>()++ .cloned()++ .unwrap_or_else(ActorContext::anonymous)++}++++/// Return the authenticated DB user's id when multi-user auth resolved one.++#[must_use]++pub fn author_id_from_parts(parts: &Parts) -> Option<UserId> {++ parts.extensions.get::<UserId>().copied()++}+++ /// Parse the admission-chain loop-prevention skip list from the+ /// `X-Memory-Skip-Admission-Chain` request header (comma-separated+ /// webhook names). A webhook that writes back into the engine (e.g. via+ /// `memory_write_page`) sets this so the chain doesn't re-invoke it on+ /// the recursive write — see [`ai_memory_wiki::AdmissionContext::skip_webhooks`].+ ///+ /// Returns an empty `Vec` when the header is absent. Entries are trimmed+ /// and empty tokens dropped, so `"a, ,b,"` → `["a", "b"]`.+ #[must_use]+ pub fn skip_webhooks_from_headers(headers: &HeaderMap) -> Vec<String> {+ headers+ .get("x-memory-skip-admission-chain")+ .and_then(|v| v.to_str().ok())+ .map(|s| {+ s.split(',')+ .map(str::trim)+ .filter(|t| !t.is_empty())+ .map(str::to_string)+ .collect()+ })+ .unwrap_or_default()+ }+++/// Parse the skip-list header only for trusted re-entry contexts.++#[must_use]++pub fn skip_webhooks_from_parts(parts: &Parts) -> Vec<String> {++ match parts.extensions.get::<AuthLevel>().copied() {++ Some(AuthLevel::User) => Vec::new(),++ Some(AuthLevel::Root | AuthLevel::Anonymous) | None => {++ skip_webhooks_from_headers(&parts.headers)++ }++ }++}+++ #[cfg(test)]+ mod tests {+ use super::*;+ use axum::http::HeaderValue;++ #[test]+ fn full_header_set_maps_correctly() {+ let mut h = HeaderMap::new();+ h.insert(+ "x-memory-actor-agent",+ HeaderValue::from_static("claude-code"),+ );+ h.insert("x-memory-actor-user", HeaderValue::from_static("djalmajr"));+ h.insert("x-memory-actor-sub", HeaderValue::from_static("8f3a-uuid"));+ h.insert(+ "x-memory-actor-client",+ HeaderValue::from_static("72836f52-uuid"),+ );+ h.insert(+ "x-memory-actor-session-id",+ HeaderValue::from_static("019e6d-session"),+ );+ let ctx = actor_from_headers(&h);+ assert_eq!(ctx.agent.as_deref(), Some("claude-code"));+ assert_eq!(ctx.user.as_deref(), Some("djalmajr"));+ assert_eq!(ctx.sub.as_deref(), Some("8f3a-uuid"));+ assert_eq!(ctx.client.as_deref(), Some("72836f52-uuid"));+ assert_eq!(ctx.session_id.as_deref(), Some("019e6d-session"));+ assert!(ctx.has_any());+ }++ #[test]+ fn missing_headers_leave_none() {+ let h = HeaderMap::new();+ let ctx = actor_from_headers(&h);+ assert!(ctx.agent.is_none());+ assert!(ctx.user.is_none());+ assert!(ctx.sub.is_none());+ assert!(ctx.client.is_none());+ assert!(ctx.session_id.is_none());+ assert!(!ctx.has_any());+ }++ #[test]+ fn empty_or_whitespace_header_treated_as_none() {+ let mut h = HeaderMap::new();+ h.insert("x-memory-actor-agent", HeaderValue::from_static(" "));+ h.insert("x-memory-actor-user", HeaderValue::from_static(""));+ let ctx = actor_from_headers(&h);+ assert!(ctx.agent.is_none(), "whitespace must trim to None");+ assert!(ctx.user.is_none(), "empty must be None");+ assert!(!ctx.has_any());+ }++ #[test]+ fn case_insensitive_header_lookup() {+ // HeaderMap normalises names to lowercase on insert; this verifies+ // that the canonical `X-Memory-Actor-Agent` form also resolves.+ let mut h = HeaderMap::new();+ h.insert("X-Memory-Actor-Agent", HeaderValue::from_static("codex"));+ let ctx = actor_from_headers(&h);+ assert_eq!(ctx.agent.as_deref(), Some("codex"));+ }++ #[test]+ fn skip_webhooks_parses_csv_trims_and_drops_empties() {+ let mut h = HeaderMap::new();+ h.insert(+ "x-memory-skip-admission-chain",+ HeaderValue::from_static("contributors, ,git-mirror,"),+ );+ assert_eq!(+ skip_webhooks_from_headers(&h),+ vec!["contributors".to_string(), "git-mirror".to_string()]+ );+ }++ #[test]+ fn skip_webhooks_absent_header_is_empty() {+ let h = HeaderMap::new();+ assert!(skip_webhooks_from_headers(&h).is_empty());+ }++++ #[test]++ fn actor_from_parts_prefers_authenticated_extension_over_headers() {++ let mut req = axum::http::Request::builder().uri("/mcp").body(()).unwrap();++ req.headers_mut().insert(++ "x-memory-actor-user",++ HeaderValue::from_static("spoofed-user"),++ );++ req.extensions_mut().insert(ActorContext {++ user: Some("real-user".into()),++ ..ActorContext::default()++ });++ let parts = req.into_parts().0;++++ let actor = actor_from_parts(&parts);++ assert_eq!(actor.user.as_deref(), Some("real-user"));++ }++++ #[test]++ fn skip_header_is_ignored_for_db_user_requests() {++ let mut req = axum::http::Request::builder().uri("/mcp").body(()).unwrap();++ req.headers_mut().insert(++ "x-memory-skip-admission-chain",++ HeaderValue::from_static("validator"),++ );++ req.extensions_mut().insert(AuthLevel::User);++ let parts = req.into_parts().0;++++ assert!(skip_webhooks_from_parts(&parts).is_empty());++ }+ }diff --cc crates/ai-memory-mcp/src/admin.rsindex 7a787676,3df3c76c..888391ab--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@@ -36,12 -36,12 +36,12 @@@ use ai_memory_llm::{Embedder, LlmProviduse ai_memory_store::{DecayParams, EmbeddingWrite, ReaderPool, StoreError, WriterHandle, f32_vec_to_bytes,};- use ai_memory_wiki::{Wiki, WikiError, WritePageRequest};-use ai_memory_wiki::{AdmissionContext, AdmissionOp, Wiki, WritePageRequest};++use ai_memory_wiki::{AdmissionContext, AdmissionOp, Wiki, WikiError, WritePageRequest};use axum::Json;use axum::Router;use axum::body::Body;use axum::extract::{Query, State};--use axum::http::{StatusCode, header};++use axum::http::{HeaderMap, StatusCode, header};use axum::response::{IntoResponse, Response};use axum::routing::{get, post};use flate2::Compression;@@@ -1420,23 -1381,43 +1420,42 @@@ async fn handle_purge_project};let label = format!("{}/{}", req.workspace, req.project);- let summary = match state.writer.purge_project(ws_id, proj_id, &label).await {- Ok(s) => s,- Err(e) => {- return (- StatusCode::INTERNAL_SERVER_ERROR,- Json(serde_json::json!({ "error": e.to_string() })),- );- }- };+- // Remove the entire per-project directory: <wiki_root>/<ws_uuid>/<proj_uuid>/.- // DB cascade already deleted all rows. Routed through Wiki::purge_project so- // the admission chain is notified (op=purge_project) before removal — a- // mirror can drop its copy of the project. Best-effort dir removal.- //- // The admission context MUST carry the workspace/project NAMES: the DB- // rows were already deleted above, so Wiki's name-resolution fallback- // would find nothing and a name-based mirror would purge the wrong- // ("_unscoped") path. We have the names from the request — pass them.++ // Admission must run before any destructive work. A reject-policy webhook++ // is allowed to abort the purge while DB rows and files are still intact.++ // Seed names from the request so mirrors do not depend on DB lookup after++ // the rows are purged below.+ let purge_ctx = AdmissionContext {+ workspace: req.workspace.clone(),+ project: req.project.clone(),+ op: AdmissionOp::PurgeProject,+ ..Default::default()+ };++ let resolved_purge_ctx = match state++ .wiki++ .admit_purge_project(ws_id, proj_id, Some(purge_ctx))++ .await++ {++ Ok(ctx) => ctx,++ Err(e) => return internal_err(e.to_string()),++ };+++ let summary = match state.writer.purge_project(ws_id, proj_id, &label).await {+ Ok(s) => s,- Err(e) => {- return (- StatusCode::INTERNAL_SERVER_ERROR,- Json(serde_json::json!({ "error": e.to_string() })),- );- }++ Err(e) => return internal_err(e.to_string()),+ };++ // Remove the entire per-project directory: <wiki_root>/<ws_uuid>/<proj_uuid>/.- // DB cascade already deleted all rows; the dir removal is best-effort.- let proj_root = state.wiki.project_root(ws_id, proj_id);- let proj_root_str = proj_root.display().to_string();++ // DB cascade already deleted all rows. Directory removal remains best-effort++ // and is reported separately, matching the pre-admission purge contract.+ let proj_root_str = state+ .wiki+ .project_root(ws_id, proj_id)+ .display()+ .to_string();let mut files_deleted: Vec<String> = Vec::new();let mut files_failed: Vec<String> = Vec::new();- match std::fs::remove_dir_all(&proj_root) {- match state- .wiki- .purge_project(ws_id, proj_id, Some(purge_ctx))- .await- {++ match state.wiki.remove_project_dir(ws_id, proj_id) {Ok(()) => {files_deleted.push(proj_root_str);}@@@ -1448,6 -1426,6 +1464,9 @@@files_failed.push(proj_root_str);}}++ state++ .wiki++ .dispatch_purge_project(resolved_purge_ctx.as_ref());let report = PurgeProjectReport {label: summary.label,@@@ -1608,6 -1586,6 +1627,10 @@@ struct WritePageResponseasync fn handle_write_page(State(state): State<Arc<AdminState>>,++ actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,++ author_ext: Option<axum::Extension<ai_memory_core::UserId>>,++ level_ext: Option<axum::Extension<ai_memory_core::AuthLevel>>,++ headers: HeaderMap,Json(req): Json<WritePageAdminRequest>,) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {let tier: Tier = req.tier.parse().map_err(|_| {@@@ -1658,6 -1636,6 +1681,26 @@@serde_json::Value::Object(fm)};++ let actor = actor_ext++ .map(|axum::Extension(actor)| actor)++ .unwrap_or_else(ai_memory_core::ActorContext::anonymous);++ let author_id = author_ext.map(|axum::Extension(author_id)| author_id);++ let skip_webhooks = match level_ext.map(|axum::Extension(level)| level) {++ Some(ai_memory_core::AuthLevel::User) => Vec::new(),++ Some(ai_memory_core::AuthLevel::Root | ai_memory_core::AuthLevel::Anonymous) | None => {++ crate::actor::skip_webhooks_from_headers(&headers)++ }++ };++ let admission_ctx = if actor.has_any() || !skip_webhooks.is_empty() {++ Some(AdmissionContext {++ op: AdmissionOp::WritePage,++ skip_webhooks,++ ..AdmissionContext::default()++ })++ } else {++ None++ };++let page_id = state.wiki.write_page(WritePageRequest {@@@ -1669,8 -1647,9 +1712,9 @@@tier,pinned: req.pinned,title: req.title,- admission_ctx: None,-- author_id: None,-- actor: ai_memory_core::ActorContext::anonymous(),++ admission_ctx,++ author_id,++ actor,}).await.map_err(|e| internal_err(e.to_string()))?;diff --cc crates/ai-memory-mcp/src/server.rsindex ff3a35ea,d2c264dd..78914b2b--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@@ -10,8 -10,9 +10,9 @@@ use ai_memory_core::};use ai_memory_llm::{Embedder, LlmProvider};use ai_memory_store::{DecayParams, PageHit, ReaderPool, WriterHandle};-use ai_memory_wiki::{Wiki, WritePageRequest};+use ai_memory_wiki::{Wiki, WikiError, WritePageRequest};use rmcp::handler::server::router::tool::ToolRouter;+ use rmcp::handler::server::tool::Extension;use rmcp::handler::server::wrapper::Parameters;use rmcp::model::{CallToolResult, Content, Implementation, ProtocolVersion, ServerCapabilities, ServerInfo,@@@ -80,11 -81,12 +81,14 @@@ the conversation calls for them:\ndo NOT use `memory_handoff_begin` for permanent annotations.\n\- `memory_read_page` — when the user asks to read, open, or show the \full content of a specific page. Accepts a `query` (searches FTS5 and \- returns the top hit's full body) or a `path` (direct lookup). Use \+ returns the top hit's full body) or a `path` (direct lookup). Pass \+ `workspace` + `project` together only when reading a page from a named \+ sibling workspace/project. Use \this instead of memory_query when the user wants the complete text, \not just snippets.\n\+ - `memory_delete_page` — when the user explicitly asks to delete or \+ remove a specific page (by exact path). Idempotent; fires the \+ admission chain so mirrors/backups stay consistent.\n\- `memory_lint` — when the user asks to audit the wiki for stale \pages, contradictions, or rule suggestions.\n\- `memory_forget_sweep` — when the user wants to prune old / cold \@@@ -382,14 -383,19 +386,25 @@@ struct ReadPageArgs/// working in (resolved from recent hook activity). **Omit unless the user explicitly names a *different* project.**#[serde(default)]project: Option<String>,+ /// Workspace to read together with `project`. Omit to use the+ /// current/default workspace resolution chain. Provide both to read a+ /// page that lives in a *different* workspace (e.g. a sibling project on+ /// a shared server).+ #[serde(default)]+ workspace: Option<String>,}+ #[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]+ struct DeletePageArgs {+ /// Exact wiki path to delete (e.g. `notes/foo.md`).+ path: String,+ /// Project to delete from. Omit to target the project you're currently+ /// working in (resolved from recent hook activity). **Omit unless the+ /// user explicitly names a *different* project.**+ #[serde(default)]+ project: Option<String>,+ }+#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]struct WritePageArgs {/// Relative wiki path to write, for example `notes/santander-2025.md`.@@@ -1014,6 -999,30 +1030,26 @@@ impl AiMemoryServerserde_json::Value::Object(fm)};- // Populate the admission context from the request's `X-Memory-Actor-*`- // headers (set by the `mcp-auth` sidecar after JWT validation). rmcp 1.7- // exposes the original HTTP `Parts` via the `Extension<Parts>` extractor —- // task-locals can't be used because StreamableHttpService dispatches the- // tool handler in a `tokio::spawn`-ed task that doesn't inherit them.- // See `crate::actor::actor_from_headers` for the JWT-claim → header map.- let actor = crate::actor::actor_from_headers(&parts.headers);++ // rmcp exposes the original HTTP `Parts`; trust the auth middleware's++ // extension, not raw client-controlled actor headers.++ let actor = crate::actor::actor_from_parts(&parts);++ let author_id = crate::actor::author_id_from_parts(&parts);+ // Loop prevention: a webhook that writes back into the engine sets+ // `X-Memory-Skip-Admission-Chain` so the chain doesn't re-invoke it- // on the recursive write. Build the ctx when either the actor OR the- // skip list is present (a skip-only write still needs to carry it).- let skip_webhooks = crate::actor::skip_webhooks_from_headers(&parts.headers);++ // on the recursive write. Only trusted/root re-entry can honor it.++ let skip_webhooks = crate::actor::skip_webhooks_from_parts(&parts);+ let admission_ctx = if actor.has_any() || !skip_webhooks.is_empty() {+ // Actor is NOT carried here — `write_page` fills the webhook+ // context from `req.actor` (single identity source).+ Some(ai_memory_wiki::AdmissionContext {+ op: ai_memory_wiki::AdmissionOp::WritePage,+ skip_webhooks,+ ..ai_memory_wiki::AdmissionContext::default()+ })+ } else {+ None+ };+let page_id = wiki.write_page(WritePageRequest {workspace_id: ws,@@@ -1024,8 -1033,9 +1060,9 @@@tier,pinned: args.pinned,title: args.title,- author_id: None,- actor: ai_memory_core::ActorContext::anonymous(),+ admission_ctx,- author_id: None,++ author_id,+ actor,}).await.map_err(|e| McpError::internal_error(e.to_string(), None))?;@@@ -1093,54 -1096,68 +1130,98 @@@));};- let md = wiki- .read_page(ws, proj, &page_path)- .map_err(|e| McpError::internal_error(e.to_string(), None))?;-- let title = md- .frontmatter- .get("title")- .and_then(|v| v.as_str())- .map(str::to_string);-- ok_json(&serde_json::json!({- "path": page_path.to_string(),- "title": title,- "body": md.body,- "frontmatter": md.frontmatter,- }))+ // Markdown on disk is the source of truth. Only a missing markdown file+ // uses the DB fallback; parse/permission/corruption errors must surface+ // so operators can fix the disk source of truth.+ match wiki.read_page(ws, proj, &page_path) {+ Ok(md) => {+ let title = md+ .frontmatter+ .get("title")+ .and_then(|v| v.as_str())+ .map(str::to_string);+ ok_json(&serde_json::json!({+ "path": page_path.to_string(),+ "title": title,+ "body": md.body,+ "frontmatter": md.frontmatter,+ }))+ }+ Err(disk_err) if is_missing_wiki_file(&disk_err) => {+ match self+ .reader+ .page_body_by_ids(ws, proj, page_path.as_str())+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?+ {+ Some(stored) => {+ let frontmatter: serde_json::Value =+ serde_json::from_str(&stored.frontmatter_json)+ .unwrap_or(serde_json::Value::Null);+ let title = frontmatter+ .get("title")+ .and_then(|v| v.as_str())+ .map(str::to_string)+ .or(Some(stored.title));+ ok_json(&serde_json::json!({+ "path": page_path.to_string(),+ "title": title,+ "body": stored.body,+ "frontmatter": frontmatter,+ "served_from": "db-fallback",+ }))+ }+ None => Err(McpError::internal_error(disk_err.to_string(), None)),+ }+ }+ Err(disk_err) => Err(McpError::internal_error(disk_err.to_string(), None)),+ }}+ /// Delete a single wiki page by exact path.+ #[tool(description = "Delete a single wiki page by its exact relative \+ path (e.g. `notes/foo.md`). Use when the user explicitly asks to \+ delete or remove a page. Fires the admission chain (op=delete) \+ before the file is removed so backups/mirrors stay consistent. \+ Idempotent — deleting a page that is already gone is a no-op. \+ Returns `{ path, deleted }`.")]+ async fn memory_delete_page(+ &self,+ Parameters(args): Parameters<DeletePageArgs>,+ Extension(parts): Extension<axum::http::request::Parts>,+ ) -> Result<CallToolResult, McpError> {+ let Some(wiki) = self.wiki.as_ref() else {+ return Err(McpError::internal_error(+ "memory_delete_page requires the server to be built with a wiki handle",+ None,+ ));+ };+ let path = PagePath::new(args.path.clone())+ .map_err(|e| McpError::internal_error(format!("invalid path: {e}"), None))?;+ let (ws, proj) = self.effective_ids(args.project.as_deref()).await;++ // Carry actor identity + loop-prevention skip list (same as write_page).+ // `Wiki::delete_page` stamps `op = Delete` regardless of what we pass.- let actor = crate::actor::actor_from_headers(&parts.headers);- let skip_webhooks = crate::actor::skip_webhooks_from_headers(&parts.headers);++ let actor = crate::actor::actor_from_parts(&parts);++ let skip_webhooks = crate::actor::skip_webhooks_from_parts(&parts);+ let admission_ctx = if actor.has_any() || !skip_webhooks.is_empty() {+ Some(ai_memory_wiki::AdmissionContext {+ actor,+ op: ai_memory_wiki::AdmissionOp::Delete,+ skip_webhooks,+ ..ai_memory_wiki::AdmissionContext::default()+ })+ } else {+ None+ };++ wiki.delete_page(ws, proj, &path, admission_ctx)+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;++ ok_json(&serde_json::json!({ "path": path.to_string(), "deleted": true }))+ }+/// Create a handoff snapshot for the next agent CLI.#[tool(description = "Record a cross-agent handoff snapshot for the \NEXT agent that opens this project (e.g. Codex picking up after \@@@ -1713,165 -1725,6 +1795,175 @@@ mod tests);}+ #[tokio::test]+ async fn write_target_ids_defaults_workspace_to_active_project() {+ let (_tmp, store, server, baked_ws, baked_proj) = setup_server().await;++ // A second workspace — the cwd's actual workspace (e.g. "djalmajr"),+ // distinct from the server's baked "default".+ let other_ws = store+ .writer+ .get_or_create_workspace("djalmajr")+ .await+ .unwrap();+ let other_proj = store+ .writer+ .get_or_create_project(other_ws, "ai-memory", None)+ .await+ .unwrap();+ // Hook publishes the cwd's project (in the OTHER workspace).+ server.active_project.set(other_ws, other_proj);++ // Explicit project, NO workspace → must land in the active project's+ // workspace (djalmajr) and REUSE the existing project, not recreate it+ // under the baked default.+ let (ws, proj) = server+ .write_target_ids(None, Some("ai-memory"))+ .await+ .unwrap();+ assert_eq!(+ ws, other_ws,+ "workspace must default to the active project's, not the baked default"+ );+ assert_eq!(+ proj, other_proj,+ "must reuse djalmajr/ai-memory, not recreate it"+ );++ // A different project name (no workspace) also lands in the cwd's workspace.+ let (ws2, _p2) = server+ .write_target_ids(None, Some("sibling"))+ .await+ .unwrap();+ assert_eq!(+ ws2, other_ws,+ "a sibling project lands in the cwd's workspace"+ );++ // Explicit workspace still overrides the active default.+ let (ws3, _p3) = server+ .write_target_ids(Some("default"), Some("ai-memory"))+ .await+ .unwrap();+ assert_eq!(+ ws3, baked_ws,+ "explicit workspace wins over the active pointer"+ );++ // No active project published → fall back to the baked workspace.+ let fresh = AiMemoryServer::new(+ store.reader.clone(),+ store.writer.clone(),+ baked_ws,+ baked_proj,+ );+ let (ws4, _p4) = fresh+ .write_target_ids(None, Some("ai-memory"))+ .await+ .unwrap();+ assert_eq!(+ ws4, baked_ws,+ "no active project → baked workspace is the fallback"+ );+ }++ #[tokio::test]+ async fn project_only_write_round_trips_with_project_only_read_in_active_workspace() {+ let (tmp, store, server, baked_ws, _baked_proj) = setup_server().await;+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let server = server.with_wiki(wiki);++ let active_ws = store+ .writer+ .get_or_create_workspace("djalmajr")+ .await+ .unwrap();+ let active_proj = store+ .writer+ .get_or_create_project(active_ws, "ai-memory", None)+ .await+ .unwrap();+ server.active_project.set(active_ws, active_proj);++ let parts = axum::http::Request::builder()++ .uri("/mcp")++ .method("POST")++ .body(())++ .unwrap()++ .into_parts()++ .0;++ server- .memory_write_page(Parameters(WritePageArgs {- path: "notes/sibling.md".to_string(),- body: "project-only write should use the active workspace".to_string(),- title: Some("Sibling Note".to_string()),- tier: None,- tags: Vec::new(),- pinned: false,- project: Some("sibling".to_string()),- workspace: None,- }))++ .memory_write_page(++ Parameters(WritePageArgs {++ path: "notes/sibling.md".to_string(),++ body: "project-only write should use the active workspace".to_string(),++ title: Some("Sibling Note".to_string()),++ tier: None,++ tags: Vec::new(),++ pinned: false,++ project: Some("sibling".to_string()),++ workspace: None,++ }),++ rmcp::handler::server::tool::Extension(parts),++ )+ .await+ .unwrap();++ assert!(+ store+ .reader+ .find_project(baked_ws, "sibling".to_string())+ .await+ .unwrap()+ .is_none(),+ "project-only write must not recreate default/sibling"+ );+ let sibling_proj = store+ .reader+ .find_project(active_ws, "sibling".to_string())+ .await+ .unwrap()+ .expect("project-only write should create active-workspace sibling");+ let direct_hits = store+ .reader+ .recent_pages_for_project(active_ws, sibling_proj, 5)+ .await+ .unwrap();+ assert_eq!(+ direct_hits.len(),+ 1,+ "direct read should see the written page"+ );+ assert_eq!(+ server.effective_ids(Some("sibling")).await,+ (active_ws, sibling_proj),+ "project-only read resolution should use the active workspace"+ );++ let result = server+ .memory_recent(Parameters(RecentArgs {+ limit: Some(5),+ project: Some("sibling".to_string()),+ workspace: None,+ }))+ .await+ .unwrap();+ let text = result+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.as_str())+ .unwrap_or_else(|| panic!("expected text content"));+ assert!(+ text.contains("notes/sibling.md"),+ "project-only read must find the active-workspace write:\n{text}"+ );+ assert!(+ text.contains("Sibling Note"),+ "project-only read must return the written page:\n{text}"+ );+ }+#[tokio::test]async fn memory_query_returns_hits_via_tool_method() {let (_tmp, _store, server, _ws, _pj) = setup_server().await;@@@ -2000,108 -1853,6 +2092,109 @@@assert!(text.contains("patterns.md"), "expected hit; got {text}");}+ #[tokio::test]+ async fn memory_read_page_can_target_explicit_workspace_project() {+ let (tmp, store, server, _ws, _pj) = setup_server().await;+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let practice_ws = store+ .writer+ .get_or_create_workspace("practice")+ .await+ .unwrap();+ let docs = store+ .writer+ .get_or_create_project(practice_ws, "docs", None)+ .await+ .unwrap();+ wiki.write_page(WritePageRequest {+ workspace_id: practice_ws,+ project_id: docs,+ path: PagePath::new("notes/sibling.md").unwrap(),+ frontmatter: serde_json::json!({"title": "Sibling Page"}),+ body: "workspace explicit read body".to_string(),+ tier: Tier::Semantic,+ pinned: false,+ title: Some("Sibling Page".into()),++ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),+ })+ .await+ .unwrap();++ let result = server+ .with_wiki(wiki)+ .memory_read_page(Parameters(ReadPageArgs {+ query: None,+ path: Some("notes/sibling.md".into()),+ project: Some("docs".into()),+ workspace: Some("practice".into()),+ }))+ .await+ .unwrap();+ let text = result+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ assert!(+ text.contains("workspace explicit read body"),+ "expected sibling workspace body; got {text}"+ );+ assert!(+ text.contains("notes/sibling.md"),+ "expected sibling workspace path; got {text}"+ );+ }++ #[tokio::test]+ async fn memory_read_page_marks_db_fallback_when_file_missing() {+ let (tmp, store, server, ws, proj) = setup_server().await;+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ store+ .writer+ .upsert_page(NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new("notes/db-only-tool.md").unwrap(),+ title: "DB Only Tool".into(),+ body: "tool fallback body".into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({"title": "DB Only Tool"}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ })+ .await+ .unwrap();++ let result = server+ .with_wiki(wiki)+ .memory_read_page(Parameters(ReadPageArgs {+ query: None,+ path: Some("notes/db-only-tool.md".into()),+ project: None,+ workspace: None,+ }))+ .await+ .unwrap();+ let text = result+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ assert!(+ text.contains("tool fallback body"),+ "expected DB body; got {text}"+ );+ assert!(+ text.contains("db-fallback"),+ "expected fallback diagnostic; got {text}"+ );+ }+#[tokio::test]async fn memory_query_can_search_multiple_scopes() {let (_tmp, store, server, ws, _pj) = setup_server().await;@@@ -2499,6 -2263,94 +2605,95 @@@);}+ #[tokio::test]+ async fn memory_delete_page_removes_the_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);+ let parts = || {+ axum::http::Request::builder()+ .uri("/mcp")+ .method("POST")+ .body(())+ .unwrap()+ .into_parts()+ .0+ };++ server+ .memory_write_page(+ Parameters(WritePageArgs {+ path: "notes/temp.md".into(),+ body: "# Temp\n\nthrowaway".into(),+ title: Some("Temp".into()),+ tier: Some("semantic".into()),+ tags: vec![],+ pinned: false,+ project: None,+ workspace: None,+ }),+ rmcp::handler::server::tool::Extension(parts()),+ )+ .await+ .unwrap();++ server+ .memory_delete_page(+ Parameters(DeletePageArgs {+ path: "notes/temp.md".into(),+ project: None,+ }),+ rmcp::handler::server::tool::Extension(parts()),+ )+ .await+ .unwrap();++ // The on-disk file is gone; reading it back errors (file not found).+ let read = server+ .memory_read_page(Parameters(ReadPageArgs {+ query: None,+ path: Some("notes/temp.md".into()),+ project: None,++ workspace: None,+ }))+ .await;+ assert!(read.is_err(), "deleted page must not be readable");++ // Regression: the derived index row must also be gone — the watcher+ // does not reconcile deletions, so a file-only delete would leave the+ // page surfacing in recent/search with stale content.+ let recent = server+ .memory_recent(Parameters(RecentArgs {+ limit: Some(10),+ project: None,+ workspace: None,+ }))+ .await+ .unwrap();+ let recent_text = recent+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ assert!(+ !recent_text.contains("notes/temp.md"),+ "deleted page must not linger in the index; got {recent_text}"+ );+ }+#[tokio::test]async fn memory_write_page_creates_explicit_project() {// Bug B regression: an explicit `project` that doesn't exist yet mustdiff --cc crates/ai-memory-mcp/tests/admin_purge.rsindex 9bcdced5,b459277a..c3dc5634--- a/crates/ai-memory-mcp/tests/admin_purge.rs+++ b/crates/ai-memory-mcp/tests/admin_purge.rs@@@ -10,9 -10,9 +10,13 @@@ use ai_memory_core::};use ai_memory_mcp::{AdminState, admin_router};use ai_memory_store::{DecayParams, Store};--use ai_memory_wiki::{Wiki, WritePageRequest};++use ai_memory_wiki::{++ AdmissionChain, AdmissionOp, FailurePolicy, WebhookConfig, Wiki, WritePageRequest,++};++use axum::Router;use axum::body::Body;use axum::http::{Request, StatusCode};++use axum::routing::post as route_post;use serde_json::json;use tempfile::TempDir;use tower::ServiceExt;@@@ -295,6 -297,6 +301,86 @@@ async fn purge_project_deletes_data_and);}++/// A reject-policy purge webhook must be able to abort before DB rows or files++/// are deleted. This guards the destructive-operation ordering.++#[tokio::test]++async fn purge_project_rejecting_admission_leaves_source_intact() {++ let tmp = TempDir::new().unwrap();++ let store = Store::open(tmp.path()).unwrap();++++ let app = Router::new().route(++ "/guard",++ route_post(|| async { (StatusCode::FORBIDDEN, "blocked") }),++ );++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();++ let addr = listener.local_addr().unwrap();++ tokio::spawn(async move {++ axum::serve(listener, app).await.unwrap();++ });++++ let chain = AdmissionChain::new(vec![WebhookConfig {++ name: "purge-guard".into(),++ url: format!("http://{addr}/guard"),++ timeout_ms: 1_000,++ failure_policy: FailurePolicy::Reject,++ events: vec![AdmissionOp::PurgeProject],++ blocking: true,++ }])++ .unwrap();++ let wiki = Wiki::new(tmp.path(), store.writer.clone())++ .unwrap()++ .with_admission_chain(chain)++ .with_store_reader(store.reader.clone());++ let state = AdminState {++ writer: store.writer.clone(),++ reader: store.reader.clone(),++ wiki,++ llm: None,++ embedder: None,++ provider_health: ai_memory_llm::ProviderHealth::default(),++ decay_params: DecayParams::default(),++ data_dir: tmp.path().to_path_buf(),++ db_path: store.db_path().to_path_buf(),++ bind: "127.0.0.1:0".to_string(),++ bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),++ token_pepper: None,++ };++++ let (ws, _keep, doomed) = seed_two_projects(&store, &state.wiki).await;++ let doomed_dir = state.wiki.project_root(ws, doomed);++++ let resp = post(++ state,++ "/admin/purge-project",++ json!({ "workspace": "default", "project": "doomed", "confirm": true }),++ )++ .await;++ assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);++++ assert!(++ store++ .reader++ .find_project(ws, "doomed".to_string())++ .await++ .unwrap()++ .is_some(),++ "rejecting admission must leave project row intact"++ );++ assert!(++ doomed_dir.exists(),++ "rejecting admission must leave files intact"++ );++ assert_eq!(++ store++ .reader++ .list_pages("default", "doomed")++ .await++ .unwrap()++ .len(),++ 1++ );++}++/// After purging `doomed`, `keep` must still have all its data and files intact.#[tokio::test]async fn purge_project_preserves_sibling_project() {diff --cc crates/ai-memory-mcp/tests/admin_read_page.rsindex 866f633f,00000000..79f7f845mode 100644,000000..100644--- a/crates/ai-memory-mcp/tests/admin_read_page.rs+++ b/crates/ai-memory-mcp/tests/admin_read_page.rs@@@ -1,235 -1,0 +1,237 @@@+//! Integration tests for `GET /admin/read-page`, focused on the DB-backed+//! fallback: when the on-disk markdown file is missing (index ahead of disk),+//! the handler serves the store's faithful copy instead of 404ing+//! (gotchas/read-page-by-query-misses), while real parse errors still surface.++use ai_memory_core::{NewPage, PagePath, Tier};+use ai_memory_mcp::{AdminState, admin_router};+use ai_memory_store::{DecayParams, Store};+use ai_memory_wiki::{Wiki, WritePageRequest};+use axum::body::Body;+use axum::http::{Request, StatusCode};+use tempfile::TempDir;+use tower::ServiceExt;++async fn make_state(tmp: &TempDir) -> (AdminState, Store) {+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let db_path = store.db_path().to_path_buf();+ let state = AdminState {+ writer: store.writer.clone(),+ reader: store.reader.clone(),+ wiki,+ llm: None,+ embedder: None,+ provider_health: ai_memory_llm::ProviderHealth::default(),+ decay_params: DecayParams::default(),+ data_dir: tmp.path().to_path_buf(),+ db_path,+ bind: "127.0.0.1:49374".to_string(),+ bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,+ };+ (state, store)+}++async fn body_json(resp: axum::response::Response) -> serde_json::Value {+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap();+ serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null)+}++async fn get(state: AdminState, uri: &str) -> axum::response::Response {+ let router = admin_router(state);+ let req = Request::builder()+ .method("GET")+ .uri(uri)+ .body(Body::empty())+ .unwrap();+ router.oneshot(req).await.unwrap()+}++/// A page present in the store but NOT on disk (the index is ahead of the+/// filesystem) is still served — from the DB copy — rather than 404ing.+#[tokio::test]+async fn read_page_falls_back_to_db_when_file_missing() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;++ // Seed straight through the store writer: this writes the DB row + FTS+ // index but NEVER touches disk, so the on-disk read will fail.+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch".to_string(), None)+ .await+ .unwrap();+ store+ .writer+ .upsert_page(NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new("notes/db-only.md").unwrap(),+ title: "DB Only".to_string(),+ body: "this body lives only in the database".to_string(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({"title": "DB Only"}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ })+ .await+ .unwrap();++ let resp = get(+ state,+ "/admin/read-page?workspace=default&project=scratch&path=notes%2Fdb-only.md",+ )+ .await;+ assert_eq!(resp.status(), StatusCode::OK, "must serve from DB fallback");+ let body = body_json(resp).await;+ assert_eq!(+ body["body"].as_str().unwrap_or(""),+ "this body lives only in the database",+ "{body}"+ );+ assert_eq!(body["title"], "DB Only", "{body}");+ assert_eq!(body["served_from"], "db-fallback", "{body}");+}++/// Sanity: a page written through the wiki (disk + index) is served from disk+/// and reads back its body. Guards the happy path the fallback wraps.+#[tokio::test]+async fn read_page_serves_on_disk_page() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch".to_string(), None)+ .await+ .unwrap();+ state+ .wiki+ .write_page(WritePageRequest {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new("notes/on-disk.md").unwrap(),+ frontmatter: serde_json::json!({"title": "On Disk"}),+ body: "written to disk via the wiki".to_string(),+ tier: Tier::Semantic,+ pinned: false,+ title: Some("On Disk".into()),++ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),+ })+ .await+ .unwrap();++ let resp = get(+ state,+ "/admin/read-page?workspace=default&project=scratch&path=notes%2Fon-disk.md",+ )+ .await;+ assert_eq!(resp.status(), StatusCode::OK);+ let body = body_json(resp).await;+ assert_eq!(+ body["body"].as_str().unwrap_or(""),+ "written to disk via the wiki",+ "{body}"+ );+ assert!(body.get("served_from").is_none(), "{body}");+}++/// A malformed markdown source must not be hidden by the DB fallback. The disk+/// file is the source of truth; parse errors need to be visible to operators.+#[tokio::test]+async fn read_page_does_not_fall_back_when_disk_frontmatter_is_malformed() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch".to_string(), None)+ .await+ .unwrap();+ let path = PagePath::new("notes/malformed.md").unwrap();+ state+ .wiki+ .write_page(WritePageRequest {+ workspace_id: ws,+ project_id: proj,+ path: path.clone(),+ frontmatter: serde_json::json!({"title": "Stored Copy"}),+ body: "stored copy must not mask a malformed disk file".to_string(),+ tier: Tier::Semantic,+ pinned: false,+ title: Some("Stored Copy".into()),++ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),+ })+ .await+ .unwrap();++ let abs = state.wiki.abs_path(ws, proj, &path);+ std::fs::write(+ &abs,+ "---\ntitle: [unterminated\n---\nmalformed disk body\n",+ )+ .unwrap();++ let resp = get(+ state,+ "/admin/read-page?workspace=default&project=scratch&path=notes%2Fmalformed.md",+ )+ .await;+ assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);+ let body = body_json(resp).await;+ assert!(+ body["error"]+ .as_str()+ .unwrap_or("")+ .contains("frontmatter yaml"),+ "{body}"+ );+ assert!(body.get("served_from").is_none(), "{body}");+}++/// A genuinely-absent page (no DB row, no file) still 404s — the fallback+/// must not mask a real miss.+#[tokio::test]+async fn read_page_404_when_truly_absent() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ // Create the workspace/project so resolution succeeds but the page does not.+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .unwrap();+ store+ .writer+ .get_or_create_project(ws, "scratch".to_string(), None)+ .await+ .unwrap();++ let resp = get(+ state,+ "/admin/read-page?workspace=default&project=scratch&path=notes%2Fnope.md",+ )+ .await;+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);+}diff --cc crates/ai-memory-wiki/Cargo.tomlindex 47d5f75a,67d3a91c..b3aa61f7--- a/crates/ai-memory-wiki/Cargo.toml+++ b/crates/ai-memory-wiki/Cargo.toml@@@ -25,6 -25,8 +25,9 @@@ notify.workspace = trunotify-debouncer-full.workspace = truegit2.workspace = trueasync-trait.workspace = true+ # Admission webhook chain (sync HTTP calls before page persistence).+ reqwest.workspace = true++futures-util.workspace = true[target.'cfg(windows)'.dependencies]winapi-util = { workspace = true }diff --cc crates/ai-memory-wiki/src/admission.rsindex 00000000,33fd8a49..facf6457mode 000000,100644..100644--- a/crates/ai-memory-wiki/src/admission.rs+++ b/crates/ai-memory-wiki/src/admission.rs@@@ -1,0 -1,539 +1,557 @@@+ //! HTTP admission webhook chain — engine's *only* extension point for+ //! enriching/validating pages just before persistence.+ //!+ //! ## Design (OCP)+ //!+ //! The engine ships ONE generic primitive: a chain of HTTP webhooks invoked+ //! synchronously inside [`Wiki::write_page`](crate::Wiki::write_page) AFTER+ //! the [`Markdown`](crate::Markdown) is built but BEFORE [`crate::emit`] ++ //! atomic write. Each webhook receives the page (path + frontmatter + body)+ //! and an [`AdmissionContext`] (actor identity + workspace/project scope),+ //! and may:+ //!+ //! - Return `200 OK` with a mutated `{ page }` → engine substitutes+ //! `frontmatter` and/or `body` before persistence.+ //! - Return `204 No Content` → no mutation, chain continues.+ //! - Return `4xx/5xx` → behaviour governed by the webhook's+ //! [`FailurePolicy`] (`Ignore` = log+skip; `Reject` = abort the write).+ //!+ //! Each new domain extension (`contributors`, `cost-tracker`, `git-mirror`,+ //! `review-marker`, …) becomes a NEW external HTTP service — engine never+ //! grows for new fields/behaviours.+ //!+ //! ## Loop prevention+ //!+ //! Callers may set [`AdmissionContext::skip_webhooks`] from the+ //! `X-Memory-Skip-Admission-Chain` request header — that lets a webhook+ //! that calls back into the engine (e.g. to write a derived page) opt out+ //! of being re-invoked on the recursive write.++ use std::sync::Arc;+ use std::time::Duration;++ use ai_memory_core::PagePath;++use futures_util::StreamExt;+ use serde::{Deserialize, Serialize};++ use crate::error::WikiError;+ use crate::{Markdown, WikiResult};++ /// Lifecycle operation that triggered the chain. Webhooks subscribe via+ /// [`WebhookConfig::events`].+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+ #[serde(rename_all = "snake_case")]+ pub enum AdmissionOp {+ /// A `Wiki::write_page` call (most writes — MCP `memory_write_page`,+ /// CLI `write-page`, admin endpoint).+ #[default]+ WritePage,+ /// An LLM consolidation write (consolidator/lint compile observations+ /// into a durable page).+ Consolidate,+ /// A single page is being deleted (`Wiki::delete_page`). Carries the+ /// page path; no body. Lets a mirror `git rm` the file.+ Delete,+ /// A whole project is being purged (`Wiki::purge_project` →+ /// `remove_dir_all`). Carries the project (ctx), no page path. Lets a+ /// mirror remove the project's directory.+ PurgeProject,+ }++ impl AdmissionOp {+ /// String value for the `X-Memory-Op` request header sent to webhooks.+ #[must_use]+ pub fn as_header_value(&self) -> &'static str {+ match self {+ AdmissionOp::WritePage => "write_page",+ AdmissionOp::Consolidate => "consolidate",+ AdmissionOp::Delete => "delete",+ AdmissionOp::PurgeProject => "purge_project",+ }+ }+ }++ /// What the engine does when a webhook returns 4xx/5xx or fails to respond.+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+ #[serde(rename_all = "snake_case")]+ pub enum FailurePolicy {+ /// Log a warning and continue with the unmutated page. Safer default —+ /// page writes never blocked by buggy/down webhooks.+ #[default]+ Ignore,+ /// Abort the write with an error. Use for safety-critical webhooks+ /// (e.g. a `validate-no-secrets` enforcer).+ Reject,+ }++ fn default_timeout_ms() -> u64 {+ 2_000+ }++ fn default_blocking() -> bool {+ true+ }++ /// One webhook entry in the chain. Loaded from operator config+ /// (`[[admission_webhooks]]`).+ #[derive(Debug, Clone, Serialize, Deserialize)]+ pub struct WebhookConfig {+ /// Stable identifier (used by loop-prevention skip lists + log fields).+ pub name: String,+ /// HTTP endpoint to POST the payload to.+ pub url: String,+ /// Per-request timeout in milliseconds. Default 2000.+ #[serde(default = "default_timeout_ms")]+ pub timeout_ms: u64,+ /// What to do on webhook failure. Default [`FailurePolicy::Ignore`].+ #[serde(default)]+ pub failure_policy: FailurePolicy,+ /// Subset of [`AdmissionOp`] this webhook subscribes to. If empty,+ /// the webhook is effectively disabled (it'll never fire).+ pub events: Vec<AdmissionOp>,+ /// When `true` (default), the webhook runs **synchronously** inside the+ /// write path — it can mutate the page (`run`) and a `Reject` failure+ /// aborts the write. When `false`, it's dispatched **fire-and-forget**+ /// AFTER the page has landed: the engine doesn't wait for it and ignores+ /// its response (so it can't mutate or reject). Use `false` for pure+ /// observers/mirrors (e.g. `git-mirror`) so a slow/down backup never adds+ /// latency to writes.+ #[serde(default = "default_blocking")]+ pub blocking: bool,+ }++ /// Per-write context passed to each webhook. Cheap to construct+ /// (mostly references at the request layer, owned here for serialisation).+ #[derive(Debug, Clone, Default, Serialize)]+ pub struct AdmissionContext {+ /// Workspace name the write belongs to. Resolved automatically by+ /// [`crate::Wiki::write_page`] from `workspace_id` when the wiki has+ /// been built with [`crate::Wiki::with_store_reader`]; left empty+ /// otherwise. Webhooks rely on this to address pages by the same+ /// human-readable name the engine and UI use, instead of+ /// re-implementing UUID→name lookup or falling back to a placeholder.+ #[serde(default)]+ pub workspace: String,+ /// Project name the write belongs to. Resolution mirrors `workspace`+ /// (auto-filled from `project_id` when the wiki has a store reader).+ #[serde(default)]+ pub project: String,+ /// Identity of the actor that triggered the write. The canonical+ /// multi-user [`ai_memory_core::ActorContext`] (since the v0.8 merge);+ /// `Wiki::write_page` fills it from `WritePageRequest::actor` so the+ /// webhook payload and the on-disk `last_modified_by` block share one+ /// identity source.+ pub actor: ai_memory_core::ActorContext,+ /// Which lifecycle op fired the chain.+ pub op: AdmissionOp,+ /// Names from `X-Memory-Skip-Admission-Chain` (CSV at the request layer);+ /// matched against [`WebhookConfig::name`] to short-circuit re-entrant writes.+ #[serde(default, skip_serializing)]+ pub skip_webhooks: Vec<String>,+ }++ /// Wire format sent to each webhook (one POST per webhook per write).+ #[derive(Serialize)]+ struct WebhookRequestBody<'a> {+ page: WebhookPagePayload<'a>,+ ctx: &'a AdmissionContext,+ }++ #[derive(Serialize)]+ struct WebhookPagePayload<'a> {+ path: &'a str,+ frontmatter: &'a serde_json::Value,+ body: &'a str,+ }++ /// Wire format expected back from each webhook on `200 OK`. Both inner+ /// fields are optional: the webhook may mutate only frontmatter, only body,+ /// or both. Anything missing means "leave that field unchanged".+ #[derive(Deserialize, Debug, Default)]+ struct WebhookResponseBody {+ #[serde(default)]+ page: Option<WebhookResponsePage>,+ }++ #[derive(Deserialize, Debug, Default)]+ struct WebhookResponsePage {+ #[serde(default)]+ frontmatter: Option<serde_json::Value>,+ #[serde(default)]+ body: Option<String>,+ }++ /// Sanity cap on the number of webhooks per chain. The chain runs+ /// sequentially inside `Wiki::write_page`, so each entry adds+ /// `timeout_ms` to worst-case write latency — beyond this many entries+ /// the operator almost certainly mis-templated the config (e.g. helm+ /// loop) and would be better served by an out-of-band fan-out service.+ pub const MAX_ADMISSION_WEBHOOKS: usize = 16;++ /// Maximum bytes read from a single webhook response body. Webhooks+ /// only need to return the mutated `page` envelope; multi-megabyte+ /// responses are pathological (faulty webhook or hostile peer) and+ /// would force the engine to buffer them mid-write. Anything beyond+ /// this is treated as malformed and the response is ignored — same+ /// safety profile as a 4xx under `FailurePolicy::Ignore`.+ pub const MAX_RESPONSE_BYTES: usize = 1024 * 1024;++ /// The chain. Cloneable (cheap — `Arc<Vec<…>>` + `reqwest::Client`).+ #[derive(Clone, Debug)]+ pub struct AdmissionChain {+ webhooks: Arc<Vec<WebhookConfig>>,+ client: reqwest::Client,+ }++ impl AdmissionChain {+ /// Build a chain from operator-provided webhook configs. Constructs a+ /// shared `reqwest::Client` for connection reuse.+ ///+ /// # Errors+ /// - [`WikiError::Io`] if the HTTP client cannot be built.+ /// - [`WikiError::Io`] if `webhooks.len()` exceeds+ /// [`MAX_ADMISSION_WEBHOOKS`] (see the constant docs).+ pub fn new(webhooks: Vec<WebhookConfig>) -> WikiResult<Self> {+ if webhooks.len() > MAX_ADMISSION_WEBHOOKS {+ return Err(WikiError::Io(std::io::Error::other(format!(+ "admission chain capped at {MAX_ADMISSION_WEBHOOKS} webhooks, got {}",+ webhooks.len()+ ))));+ }+ let client = reqwest::Client::builder().build().map_err(|e| {+ WikiError::Io(std::io::Error::other(format!("admission http client: {e}")))+ })?;+ Ok(Self {+ webhooks: Arc::new(webhooks),+ client,+ })+ }++ /// `true` if no webhooks are configured (caller can skip the round-trip).+ #[must_use]+ pub fn is_empty(&self) -> bool {+ self.webhooks.is_empty()+ }++ /// Run the chain against `markdown` (mutating `frontmatter`/`body` in+ /// place). Webhooks are invoked sequentially in config order; each sees+ /// the output of the previous one.+ ///+ /// # Errors+ /// Returns [`WikiError`] only when a webhook with+ /// [`FailurePolicy::Reject`] fails — otherwise errors are logged and+ /// skipped (`FailurePolicy::Ignore`).+ pub async fn run(+ &self,+ page_path: &PagePath,+ markdown: &mut Markdown,+ ctx: &AdmissionContext,+ ) -> WikiResult<()> {+ for hook in self.webhooks.iter() {+ // Caller-driven skip list (loop prevention via X-Memory-Skip-Admission-Chain).+ if ctx.skip_webhooks.iter().any(|n| n == &hook.name) {+ tracing::debug!(webhook = %hook.name, "admission skip (caller opt-out)");+ continue;+ }+ // Webhook doesn't subscribe to this op.+ if !hook.events.contains(&ctx.op) {+ continue;+ }+ // Non-blocking webhooks are fired fire-and-forget after the write+ // (see `dispatch_async`); they never run in the synchronous,+ // mutation-capable path.+ if !hook.blocking {+ continue;+ }++ let payload = WebhookRequestBody {+ page: WebhookPagePayload {+ path: page_path.as_str(),+ frontmatter: &markdown.frontmatter,+ body: &markdown.body,+ },+ ctx,+ };++ let result = self+ .client+ .post(&hook.url)+ .header("X-Memory-Op", ctx.op.as_header_value())+ .timeout(Duration::from_millis(hook.timeout_ms))+ .json(&payload)+ .send()+ .await;++ match result {+ Ok(resp) if resp.status().is_success() => {+ if resp.status().as_u16() == 204 {+ tracing::debug!(webhook = %hook.name, "admission no-op (204)");+ continue;+ }- // Bound the response read at MAX_RESPONSE_BYTES — a- // pathological/hostile webhook can't force the engine- // to buffer arbitrary bytes mid-write.- let bytes = match resp.bytes().await {- Ok(b) => b,++ let bytes = match read_response_limited(resp).await {++ Ok(Some(b)) => b,++ Ok(None) => {++ tracing::warn!(++ webhook = %hook.name,++ cap = MAX_RESPONSE_BYTES,++ "admission response exceeds cap; treating as no-op",++ );++ continue;++ }+ Err(e) => {+ tracing::warn!(+ webhook = %hook.name,+ error = %e,+ "admission response read failed; treating as no-op",+ );+ continue;+ }+ };- if bytes.len() > MAX_RESPONSE_BYTES {- tracing::warn!(- webhook = %hook.name,- bytes = bytes.len(),- cap = MAX_RESPONSE_BYTES,- "admission response exceeds cap; treating as no-op",- );- continue;- }+ match serde_json::from_slice::<WebhookResponseBody>(&bytes) {+ Ok(parsed) => {+ if let Some(page) = parsed.page {+ if let Some(new_fm) = page.frontmatter {+ markdown.frontmatter = new_fm;+ }+ if let Some(new_body) = page.body {+ markdown.body = new_body;+ }+ tracing::debug!(webhook = %hook.name, "admission mutation applied");+ }+ }+ Err(e) => {+ tracing::warn!(+ webhook = %hook.name,+ error = %e,+ "admission response not JSON; treating as no-op",+ );+ }+ }+ }+ Ok(resp) => {+ let status = resp.status();- let body_txt = resp.text().await.unwrap_or_default();++ let body_txt = response_text_limited(resp).await;+ let err_msg = format!(+ "admission webhook {} status {}: {}",+ hook.name, status, body_txt+ );+ tracing::warn!(webhook = %hook.name, status = %status, body = %body_txt, "admission error response");+ if matches!(hook.failure_policy, FailurePolicy::Reject) {+ return Err(WikiError::Io(std::io::Error::other(err_msg)));+ }+ }+ Err(e) => {+ tracing::warn!(webhook = %hook.name, error = %e, "admission request failed");+ if matches!(hook.failure_policy, FailurePolicy::Reject) {+ return Err(WikiError::Io(std::io::Error::other(format!(+ "admission webhook {} request failed: {}",+ hook.name, e+ ))));+ }+ }+ }+ }+ Ok(())+ }++ /// Notify webhooks of a delete / purge (`ctx.op` = `Delete` /+ /// `PurgeProject`). Unlike [`Self::run`], there is no body to send or+ /// mutate — the webhook acts on `ctx.op` + the (optional) page path, e.g.+ /// a mirror `git rm`s the file or removes the project directory. Honours+ /// the same skip-list, op-subscription, timeout, and failure policy.+ ///+ /// # Errors+ /// Returns an error only when a `Reject`-policy webhook fails.+ pub async fn notify(&self, page_path: Option<&str>, ctx: &AdmissionContext) -> WikiResult<()> {+ let empty_frontmatter = serde_json::Value::Object(serde_json::Map::new());+ for hook in self.webhooks.iter() {+ if ctx.skip_webhooks.iter().any(|n| n == &hook.name) {+ tracing::debug!(webhook = %hook.name, "admission skip (caller opt-out)");+ continue;+ }+ if !hook.events.contains(&ctx.op) {+ continue;+ }+ if !hook.blocking {+ continue;+ }+ let payload = WebhookRequestBody {+ page: WebhookPagePayload {+ path: page_path.unwrap_or(""),+ frontmatter: &empty_frontmatter,+ body: "",+ },+ ctx,+ };+ let result = self+ .client+ .post(&hook.url)+ .header("X-Memory-Op", ctx.op.as_header_value())+ .timeout(Duration::from_millis(hook.timeout_ms))+ .json(&payload)+ .send()+ .await;+ match result {+ Ok(resp) if resp.status().is_success() => {+ tracing::debug!(webhook = %hook.name, op = ctx.op.as_header_value(), "admission notify ok");+ }+ Ok(resp) => {+ let status = resp.status();- let body_txt = resp.text().await.unwrap_or_default();++ let body_txt = response_text_limited(resp).await;+ tracing::warn!(webhook = %hook.name, status = %status, body = %body_txt, "admission notify error response");+ if matches!(hook.failure_policy, FailurePolicy::Reject) {+ return Err(WikiError::Io(std::io::Error::other(format!(+ "admission webhook {} status {}: {}",+ hook.name, status, body_txt+ ))));+ }+ }+ Err(e) => {+ tracing::warn!(webhook = %hook.name, error = %e, "admission notify request failed");+ if matches!(hook.failure_policy, FailurePolicy::Reject) {+ return Err(WikiError::Io(std::io::Error::other(format!(+ "admission webhook {} request failed: {}",+ hook.name, e+ ))));+ }+ }+ }+ }+ Ok(())+ }++ /// Fire the chain's **non-blocking** webhooks for this op WITHOUT awaiting+ /// them. Called AFTER the page has landed on disk + in the index, so these+ /// are pure observers/mirrors: each is spawned fire-and-forget and its+ /// response is ignored (a non-blocking webhook can't mutate or reject).+ /// Honours the skip-list and op-subscription. For a write the caller passes+ /// the FINAL (post-mutation) page; for a delete/purge, an empty body.+ pub fn dispatch_async(+ &self,+ page_path: Option<&str>,+ frontmatter: &serde_json::Value,+ body: &str,+ ctx: &AdmissionContext,+ ) {+ for hook in self.webhooks.iter() {+ if hook.blocking {+ continue;+ }+ if ctx.skip_webhooks.iter().any(|n| n == &hook.name) {+ continue;+ }+ if !hook.events.contains(&ctx.op) {+ continue;+ }+ let client = self.client.clone();+ let url = hook.url.clone();+ let name = hook.name.clone();+ let timeout = hook.timeout_ms;+ let op = ctx.op;+ let owned_ctx = ctx.clone();+ let path = page_path.map(str::to_string);+ let frontmatter = frontmatter.clone();+ let body = body.to_string();+ tokio::spawn(async move {+ let payload = WebhookRequestBody {+ page: WebhookPagePayload {+ path: path.as_deref().unwrap_or(""),+ frontmatter: &frontmatter,+ body: &body,+ },+ ctx: &owned_ctx,+ };+ match client+ .post(&url)+ .header("X-Memory-Op", op.as_header_value())+ .timeout(Duration::from_millis(timeout))+ .json(&payload)+ .send()+ .await+ {+ Ok(resp) if resp.status().is_success() => {+ tracing::debug!(webhook = %name, op = op.as_header_value(), "admission async ok");+ }+ Ok(resp) => {+ tracing::warn!(webhook = %name, status = %resp.status(), "admission async error response");+ }+ Err(e) => {+ tracing::warn!(webhook = %name, error = %e, "admission async request failed");+ }+ }+ });+ }+ }+ }+++async fn read_response_limited(resp: reqwest::Response) -> Result<Option<Vec<u8>>, reqwest::Error> {++ let mut stream = resp.bytes_stream();++ let mut bytes = Vec::new();++ while let Some(chunk) = stream.next().await {++ let chunk = chunk?;++ if bytes.len().saturating_add(chunk.len()) > MAX_RESPONSE_BYTES {++ return Ok(None);++ }++ bytes.extend_from_slice(&chunk);++ }++ Ok(Some(bytes))++}++++async fn response_text_limited(resp: reqwest::Response) -> String {++ match read_response_limited(resp).await {++ Ok(Some(bytes)) => String::from_utf8_lossy(&bytes).into_owned(),++ Ok(None) => format!("<response body exceeds {MAX_RESPONSE_BYTES} bytes>"),++ Err(e) => format!("<failed to read response body: {e}>"),++ }++}+++ #[cfg(test)]+ mod tests {+ use super::*;++ #[test]+ fn defaults_are_safe() {+ let pol = FailurePolicy::default();+ assert!(matches!(pol, FailurePolicy::Ignore));+ let op = AdmissionOp::default();+ assert!(matches!(op, AdmissionOp::WritePage));+ }++ #[test]+ fn webhook_config_deserialises_with_defaults() {+ // Using JSON keeps the test free of an extra TOML dep — the+ // serde derives are format-agnostic so the same `#[serde(default)]`+ // handling exercised here covers TOML/YAML/etc.+ let json_src = serde_json::json!({+ "name": "contributors",+ "url": "http://contributors-webhook/enrich",+ "events": ["write_page", "consolidate"],+ });+ let cfg: WebhookConfig = serde_json::from_value(json_src).expect("parses");+ assert_eq!(cfg.name, "contributors");+ assert_eq!(cfg.timeout_ms, 2_000);+ assert!(matches!(cfg.failure_policy, FailurePolicy::Ignore));+ assert_eq!(cfg.events.len(), 2);+ }++ #[test]+ fn op_header_values() {+ assert_eq!(AdmissionOp::WritePage.as_header_value(), "write_page");+ assert_eq!(AdmissionOp::Consolidate.as_header_value(), "consolidate");+ }++ #[tokio::test]+ async fn empty_chain_is_noop() {+ let chain = AdmissionChain::new(vec![]).expect("builds");+ assert!(chain.is_empty());+ let mut md = Markdown {+ frontmatter: serde_json::Value::Null,+ body: "hello".to_string(),+ };+ let path = PagePath::new("foo.md").expect("valid path");+ let ctx = AdmissionContext::default();+ chain.run(&path, &mut md, &ctx).await.expect("noop");+ assert_eq!(md.body, "hello");+ assert!(md.frontmatter.is_null());+ }+ }diff --cc crates/ai-memory-wiki/src/wiki.rsindex 609f738e,efd42bbf..fddaa7ce--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@@ -158,15 -230,61 +230,123 @@@ impl Wikiworkspace_id: WorkspaceId,project_id: ProjectId,path: &PagePath,+ admission_ctx: Option<AdmissionContext>,) -> WikiResult<()> {++ let mut resolved_ctx = None;+ if let Some(chain) = &self.admission_chain {+ let mut ctx = admission_ctx.unwrap_or_default();+ ctx.op = AdmissionOp::Delete;+ self.resolve_admission_names(workspace_id, project_id, &mut ctx)+ .await;+ chain.notify(Some(path.as_str()), &ctx).await?;- chain.dispatch_async(Some(path.as_str()), &serde_json::Value::Null, "", &ctx);++ resolved_ctx = Some(ctx);+ }let abs = self.abs_path(workspace_id, project_id, path);-- match std::fs::remove_file(&abs) {- Ok(()) => {}- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}++ let quarantined = match quarantine_file(&abs) {++ Ok(path) => path,++ Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,+ Err(e) => return Err(crate::WikiError::Io(e)),- }- // The watcher only reconciles create/modify events, not deletions, so- // drop the derived index rows here — otherwise the page lingers in- // search/recent with stale content after its file is gone.- self.writer++ };++++ let delete_result = self++ .writer+ .delete_page(workspace_id, project_id, path.clone())- .await?;++ .await;++ if let Err(e) = delete_result {++ if let Some(quarantine) = &quarantined++ && let Err(restore_err) = std::fs::rename(quarantine, &abs)++ {++ tracing::error!(++ path = %path.as_str(),++ quarantine = %quarantine.display(),++ error = %restore_err,++ "delete_page: DB delete failed and restoring quarantined file also failed"++ );++ }++ return Err(e.into());++ }++++ if let Some(quarantine) = quarantined {++ std::fs::remove_file(&quarantine)?;++ }++++ if let (Some(chain), Some(ctx)) = (&self.admission_chain, &resolved_ctx) {++ chain.dispatch_async(Some(path.as_str()), &serde_json::Value::Null, "", ctx);++ }+ Ok(())+ }++ /// Purge a whole project's wiki directory. When an admission chain is+ /// attached, it is notified (`op=purge_project`, no page path) BEFORE the+ /// directory is removed, so a mirror can drop the project. A `Reject`+ /// webhook aborts the purge. Routes the on-disk removal through the+ /// namespaced [`Self::project_root`] (invariant: never hand-roll paths).+ ///+ /// # Errors+ /// Returns [`WikiError`] on a filesystem error or a rejecting webhook.+ pub async fn purge_project(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ admission_ctx: Option<AdmissionContext>,+ ) -> WikiResult<()> {++ let ctx = self++ .admit_purge_project(workspace_id, project_id, admission_ctx)++ .await?;++ self.remove_project_dir(workspace_id, project_id)?;++ self.dispatch_purge_project(ctx.as_ref());++ Ok(())++ }++++ /// Run the blocking admission notification for a project purge without++ /// removing files. Admin callers use this before the DB purge so a++ /// `failure_policy = reject` webhook can still abort all destructive work.++ ///++ /// # Errors++ /// Returns [`WikiError`] when a reject-policy webhook fails.++ pub async fn admit_purge_project(++ &self,++ workspace_id: WorkspaceId,++ project_id: ProjectId,++ admission_ctx: Option<AdmissionContext>,++ ) -> WikiResult<Option<AdmissionContext>> {+ if let Some(chain) = &self.admission_chain {+ let mut ctx = admission_ctx.unwrap_or_default();+ ctx.op = AdmissionOp::PurgeProject;+ self.resolve_admission_names(workspace_id, project_id, &mut ctx)+ .await;+ chain.notify(None, &ctx).await?;- chain.dispatch_async(None, &serde_json::Value::Null, "", &ctx);++ Ok(Some(ctx))++ } else {++ Ok(None)+ }++ }++++ /// Remove the project's on-disk directory without running admission.++ ///++ /// # Errors++ /// Returns [`WikiError::Io`] on filesystem errors other than NotFound.++ pub fn remove_project_dir(++ &self,++ workspace_id: WorkspaceId,++ project_id: ProjectId,++ ) -> WikiResult<()> {+ let root = self.project_root(workspace_id, project_id);+ match std::fs::remove_dir_all(&root) {Ok(()) => Ok(()),Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),Err(e) => Err(crate::WikiError::Io(e)),}}++ /// Dispatch non-blocking purge webhooks after the caller's purge has++ /// completed its durable DB/filesystem work.++ pub fn dispatch_purge_project(&self, admission_ctx: Option<&AdmissionContext>) {++ if let (Some(chain), Some(ctx)) = (&self.admission_chain, admission_ctx) {++ chain.dispatch_async(None, &serde_json::Value::Null, "", ctx);++ }++ }++/// Cloneable handle to the underlying store writer.#[must_use]pub fn writer(&self) -> &WriterHandle {@@@ -228,6 -346,6 +408,7 @@@WritePageRequest,tempfile::NamedTempFile,std::path::PathBuf,++ Option<AdmissionContext>,)> = Vec::with_capacity(requests.len());for mut req in requests {// Defence-in-depth scrub at the batch boundary too.@@@ -235,11 -353,11 +416,31 @@@if let Some(t) = req.title.take() {req.title = Some(self.sanitizer.scrub(&t));}-- let title = derive_title(&req.frontmatter, &req.body, &req.path);-- let markdown = Markdown {-- frontmatter: req.frontmatter.clone(),-- body: req.body.clone(),++++ req.frontmatter = stamp_last_modified_by(req.frontmatter, &req.actor);++ let mut markdown = Markdown {++ frontmatter: req.frontmatter,++ body: req.body,+ };++++ let resolved_ctx = if let Some(chain) = &self.admission_chain {++ let mut ctx = req.admission_ctx.take().unwrap_or_default();++ ctx.actor = req.actor.clone();++ self.resolve_admission_names(req.workspace_id, req.project_id, &mut ctx)++ .await;++ chain.run(&req.path, &mut markdown, &ctx).await?;++ Some(ctx)++ } else {++ None+ };++++ markdown.body = self.sanitizer.scrub(&markdown.body);++ scrub_frontmatter_strings(&mut markdown.frontmatter, &self.sanitizer);++++ let title = req++ .title++ .take()++ .unwrap_or_else(|| derive_title(&markdown.frontmatter, &markdown.body, &req.path));let emitted = emit(&markdown)?;let abs = self.abs_path(req.workspace_id, req.project_id, &req.path);let parent = abs.parent().ok_or_else(|| {@@@ -252,17 -370,17 +453,19 @@@use std::io::Write as _;tmp.write_all(emitted.as_bytes())?;tmp.as_file().sync_data()?;++ req.frontmatter = markdown.frontmatter;++ req.body = markdown.body;let req_with_title = WritePageRequest {title: Some(title),..req};-- staged.push((req_with_title, tmp, abs));++ staged.push((req_with_title, tmp, abs, resolved_ctx));}// Build NewPage batch with the precomputed titles.let pages: Vec<ai_memory_core::NewPage> = staged.iter()-- .map(|(req, _, _)| ai_memory_core::NewPage {++ .map(|(req, _, _, _)| ai_memory_core::NewPage {workspace_id: req.workspace_id,project_id: req.project_id,path: req.path.clone(),@@@ -272,16 -390,16 +475,26 @@@frontmatter_json: req.frontmatter.clone(),pinned: req.pinned || is_slot_path(&req.path),links: extract_links(&req.body, &req.path),-- author_id: None,++ author_id: req.author_id,}).collect();let ids = self.writer.upsert_pages_batch(pages).await?;// SQL succeeded; rename tempfiles into place.-- for (_, tmp, abs) in staged {++ let mut dispatches = Vec::with_capacity(staged.len());++ for (req, tmp, abs, ctx) in staged {let persisted = tmp.persist(&abs)?;persisted.sync_data()?;++ dispatches.push((req.path, req.frontmatter, req.body, ctx));++ }++++ if let Some(chain) = &self.admission_chain {++ for (path, frontmatter, body, ctx) in &dispatches {++ if let Some(ctx) = ctx {++ chain.dispatch_async(Some(path.as_str()), frontmatter, body, ctx);++ }++ }}Ok(ids)@@@ -317,21 -436,60 +531,49 @@@// tool slips through.let body = self.sanitizer.scrub(&body);- let title = explicit_title- .clone()- .map(|t| self.sanitizer.scrub(&t))- .unwrap_or_else(|| derive_title(&frontmatter, &body, &path));- let links = extract_links(&body, &path);let pinned = pinned || is_slot_path(&path);- // Multi-user attribution: when the auth middleware resolved a- // non-anonymous identity, stamp a `last_modified_by` block into- // the on-disk frontmatter. Rung 0 (anonymous) → no block, no- // disk-shape change for existing single-user installs.+ // Multi-user attribution (P1.6): stamp `last_modified_by` into the+ // frontmatter BEFORE building the markdown, so both the admission+ // chain and the on-disk file see the resolved author. Rung 0+ // (anonymous) → no block, no disk-shape change for single-user.let frontmatter = stamp_last_modified_by(frontmatter, &actor);- let markdown = Markdown {- frontmatter: frontmatter.clone(),- body: body.clone(),+ let mut markdown = Markdown { frontmatter, body };+- // Admission webhook chain — runs AFTER the markdown is built and- // sanitised, BEFORE emit + atomic write. Mutations to++ // Admission webhook chain runs after the initial scrub, before emit +++ // atomic write. Mutations to+ // frontmatter/body here propagate to both the on-disk markdown+ // (via emit below) and the store's `frontmatter_json` / `body`+ // (via the upsert below) atomically. See `crate::admission`.+ let resolved_ctx = if let Some(chain) = &self.admission_chain {+ let mut ctx = admission_ctx.unwrap_or_default();+ // Single identity source: the webhook actor is the same+ // `ActorContext` used for on-disk attribution (req.actor),+ // populated by the auth layer — not a separate header bridge.+ ctx.actor = actor.clone();- // Resolve workspace + project names from the store reader (if- // attached) so webhooks address pages by the human-readable- // names the engine uses on disk and in the UI. Best-effort —- // lookup failures fall through with empty names (webhooks- // tolerate that and fall back to header introspection).- if let Some(reader) = &self.store_reader {- if ctx.workspace.is_empty()- && let Ok(Some(name)) = reader.workspace_name_by_id(workspace_id).await- {- ctx.workspace = name;- }- if ctx.project.is_empty()- && let Ok(Some(name)) =- reader.project_name_by_id(workspace_id, project_id).await- {- ctx.project = name;- }- }++ self.resolve_admission_names(workspace_id, project_id, &mut ctx)++ .await;+ // Blocking webhooks run synchronously (they may mutate / reject).+ chain.run(&path, &mut markdown, &ctx).await?;+ Some(ctx)+ } else {+ None};+++ // Webhook mutations are external input too. Scrub again so a webhook++ // cannot reintroduce secrets after the caller body was sanitized.++ markdown.body = self.sanitizer.scrub(&markdown.body);++ scrub_frontmatter_strings(&mut markdown.frontmatter, &self.sanitizer);+++ // Re-derive title + links from the (possibly mutated) markdown.+ // We do this after the chain so explicit title overrides survive+ // mutations and webhooks that rename or restructure the body+ // still get the right title/links extracted.+ let title = explicit_title+ .clone()+ .map(|t| self.sanitizer.scrub(&t))+ .unwrap_or_else(|| derive_title(&markdown.frontmatter, &markdown.body, &path));+ let links = extract_links(&markdown.body, &path);+let emitted = emit(&markdown)?;let abs = self.abs_path(workspace_id, project_id, &path);if let Some(parent) = abs.parent() {@@@ -339,6 -497,22 +581,12 @@@}atomic::write_atomic(&abs, emitted.as_bytes())?;- // Non-blocking webhooks fire-and-forget AFTER the page has landed on- // disk (the markdown-in-git source of truth). They only observe/mirror- // the final page — never block the write or mutate it.- if let (Some(chain), Some(ctx)) = (&self.admission_chain, &resolved_ctx) {- chain.dispatch_async(- Some(path.as_str()),- &markdown.frontmatter,- &markdown.body,- ctx,- );- }-+ let Markdown {+ frontmatter: final_frontmatter,+ body: final_body,+ } = markdown;++ let path_for_dispatch = path.clone();++ let frontmatter_for_dispatch = final_frontmatter.clone();let page_id = self.writer.upsert_page(NewPage {@@@ -377,6 -551,6 +625,18 @@@}}}++++ // Non-blocking webhooks fire-and-forget only after the page has landed++ // on disk and the DB/index write has succeeded. They observe the final++ // persisted page and cannot mutate or reject it.++ if let (Some(chain), Some(ctx)) = (&self.admission_chain, &resolved_ctx) {++ chain.dispatch_async(++ Some(path_for_dispatch.as_str()),++ &frontmatter_for_dispatch,++ &final_body,++ ctx,++ );++ }Ok(page_id)}}@@@ -426,6 -609,6 +695,45 @@@ fn ai_memory_wiki_error(msg: &str) -> ccrate::WikiError::Io(std::io::Error::other(msg.to_string()))}++fn quarantine_file(path: &Path) -> std::io::Result<Option<PathBuf>> {++ let Some(parent) = path.parent() else {++ return Err(std::io::Error::other(++ "page path has no parent (cannot quarantine delete)",++ ));++ };++ let tmp = tempfile::Builder::new()++ .prefix(".ai-memory-delete.")++ .tempfile_in(parent)?;++ let (_file, quarantine) = tmp.keep().map_err(|e| e.error)?;++ std::fs::remove_file(&quarantine)?;++ match std::fs::rename(path, &quarantine) {++ Ok(()) => Ok(Some(quarantine)),++ Err(e) => {++ let _ = std::fs::remove_file(&quarantine);++ Err(e)++ }++ }++}++++fn scrub_frontmatter_strings(value: &mut serde_json::Value, sanitizer: &Sanitizer) {++ match value {++ serde_json::Value::String(s) => {++ *s = sanitizer.scrub(s);++ }++ serde_json::Value::Array(items) => {++ for item in items {++ scrub_frontmatter_strings(item, sanitizer);++ }++ }++ serde_json::Value::Object(map) => {++ for item in map.values_mut() {++ scrub_frontmatter_strings(item, sanitizer);++ }++ }++ serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) => {}++ }++}++/// Append a `last_modified_by` block to the page's frontmatter when the/// auth middleware resolved a non-anonymous actor. The block carries the/// stable `username` plus optional `name` + `email`. Designed to be@@@ -713,6 -898,6 +1023,100 @@@ mod testsassert_eq!(hits.len(), 5);}++ #[tokio::test]++ async fn apply_batch_runs_admission_and_scrubs_webhook_mutations() {++ use crate::admission::{++ AdmissionChain, AdmissionContext, AdmissionOp, FailurePolicy, WebhookConfig,++ };++ use axum::http::StatusCode;++ use axum::routing::post;++ use axum::{Json, Router};++ use tokio::net::TcpListener;++++ let app = Router::new().route(++ "/mutate",++ post(|Json(_payload): Json<serde_json::Value>| async move {++ (++ StatusCode::OK,++ Json(serde_json::json!({++ "page": {++ "frontmatter": { "title": "leaked sk-1234567890abcdef" },++ "body": "webhook returned sk-1234567890abcdef"++ }++ })),++ )++ }),++ );++ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();++ let addr = listener.local_addr().unwrap();++ tokio::spawn(async move {++ axum::serve(listener, app).await.unwrap();++ });++++ 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 chain = AdmissionChain::new(vec![WebhookConfig {++ name: "mutator".into(),++ url: format!("http://{addr}/mutate"),++ timeout_ms: 1_000,++ failure_policy: FailurePolicy::Reject,++ events: vec![AdmissionOp::Consolidate],++ blocking: true,++ }])++ .unwrap();++ let wiki = Wiki::new(tmp.path(), store.writer.clone())++ .unwrap()++ .with_admission_chain(chain)++ .with_store_reader(store.reader.clone());++++ let ids = wiki++ .apply_batch(vec![WritePageRequest {++ workspace_id: ws,++ project_id: proj,++ path: PagePath::new("batch/admitted.md").unwrap(),++ frontmatter: serde_json::json!({"title": "before"}),++ body: "before".into(),++ tier: Tier::Semantic,++ pinned: false,++ title: None,++ admission_ctx: Some(AdmissionContext {++ op: AdmissionOp::Consolidate,++ ..AdmissionContext::default()++ }),++ author_id: None,++ actor: ai_memory_core::ActorContext::anonymous(),++ }])++ .await++ .unwrap();++ assert_eq!(ids.len(), 1);++++ let on_disk = std::fs::read_to_string(wiki.abs_path(++ ws,++ proj,++ &PagePath::new("batch/admitted.md").unwrap(),++ ))++ .unwrap();++ assert!(on_disk.contains("[REDACTED]"), "{on_disk}");++ assert!(!on_disk.contains("sk-1234567890abcdef"), "{on_disk}");++++ let hits = store++ .reader++ .search_pages("REDACTED".into(), 5)++ .await++ .unwrap();++ assert_eq!(hits.len(), 1);++ }++/// Two projects writing the same relative path must produce two distinct/// files under their respective UUID-namespaced directories.#[tokio::test]diff --cc docs/ARCHITECTURE.mdindex bf1c3406,36adde0c..fb7ee576--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@@ -229,7 -229,7 +229,7 @@@ Each crate has a single responsibilitycircular deps. Inter-crate boundaries enforce the cross-cuttinginvariants below.--## MCP tool surface (13 tools)++## MCP tool surface (14 tools)| Tool | Hint | Purpose ||---|---|---|@@@ -248,17 -249,17 +249,18 @@@| `memory_install_self_routing` | read-only | Return the canonical routing snippet for CLAUDE.md / AGENTS.md. |`memory_briefing`, `memory_explore`, `memory_write_page`,--`memory_install_self_routing`, and `memory_read_page`++`memory_install_self_routing`, `memory_read_page`, and `memory_delete_page`post-date the original "narrow on purpose" cut (§10 of`design-decisions.md`): briefing/explore separate the structured vs.prose halves of "what's going on", `memory_write_page` covers explicitdurable annotations without abusing single-use handoffs,`memory_install_self_routing` exists for the meta case where the agentmust re-write its own routing rules into a project's `CLAUDE.md` /--`AGENTS.md`, and `memory_read_page` complements `memory_query` for the++`AGENTS.md`, `memory_read_page` complements `memory_query` for the"I need the full page, not a snippet" case (e.g. opening a decision page--end-to-end). The narrow-surface discipline still holds — every new tool--has to earn its slot — but the v1 count is 13, not 10.++end-to-end), and `memory_delete_page` is the exact-path destructive pair++needed by admission-aware mirrors. The narrow-surface discipline still holds++— every new tool has to earn its slot — but the v1 count is 14, not 10.MCP parameter aliases are intentionally sparse: `memory_query.query` accepts`q|search`, and limit fields accept `n` / `top_k` where shipped. Project anddiff --cc docs/admission-webhooks.mdindex 00000000,1ee37e38..d8b70b39mode 000000,100644..100644--- a/docs/admission-webhooks.md+++ b/docs/admission-webhooks.md@@@ -1,0 -1,318 +1,325 @@@+ # Admission webhooks: pre-persistence HTTP hooks++ > Operator-configured HTTP hooks invoked on the engine's write path+ > (`Wiki::write_page`, `delete_page`, `purge_project`)+ > just before the page hits disk. Each hook can mutate the+ > page (return a new frontmatter / body) or just observe and side-effect+ > (return `204 No Content`). Sourced from+ > `crates/ai-memory-wiki/src/admission.rs` and the wiring in+ > `crates/ai-memory-cli/src/commands/serve.rs` — keep both as the+ > canonical reference if anything here drifts.++ ## 1. What this is (and isn't)++ | | What you can do | What you can't do |+ |---|---|---|+ | Chain | Add canonical frontmatter fields (e.g. `contributors`); mirror the write into an external system (git, search index, audit log); reject writes that fail policy (e.g. `validate-no-secrets`). | Talk back to the engine's writer or store directly — the chain only sees one page at a time and mutates it in place. |+ | Engine | Stays closed for modification: every new behaviour ships as an independent HTTP service in any language. | The engine doesn't discover or auto-register webhooks — operators name them in config. |++ If your idea doesn't fit "mutate the page or observe the write", it's+ probably a different extension point (`/hook` ingress, `/admin/*` admin+ surface, or out-of-band scheduled job).++ ## 2. Lifecycle+-The chain fires inside `Wiki::write_page`, **after** the markdown is-parsed and sanitised but **before** the atomic write and store upsert.-A mutation applied by a webhook propagates to both the on-disk markdown-file and the SQLite row in a single atomic step (see++The blocking chain fires inside `Wiki::write_page`, **after** the markdown is++parsed and initially sanitised but **before** the atomic write and store upsert.++Webhook mutations are sanitised again before persistence. A mutation applied++by a webhook propagates to both the on-disk markdown file and the SQLite row++in a single atomic step (see+ [ARCHITECTURE.md](ARCHITECTURE.md) on the writer actor / atomic write+ invariants).++ Webhooks run **sequentially**, in the order declared in config. Each one+ sees the (possibly mutated) page from the previous webhook — so a+ `contributors` hook that adds frontmatter is followed by a `git-mirror`+ hook that mirrors the enriched page.++ Webhooks fire on these `op` values today (extensible enum):++ - `write_page` — direct writes via MCP `memory_write_page`, the CLI+ `write-page`, `/admin/write-page`, the lint rewriter, hook synthesis.+ - `consolidate` — LLM consolidation writes from the consolidator+ (SessionEnd opt-in + PreCompact + manual `memory_consolidate`).+ - `delete` — a single page is removed (`Wiki::delete_page`, triggered by the+ `memory_delete_page` MCP tool). Carries the page path, no body; fired+ **before** the file is removed so a mirror can `git rm` the same path. The- SQLite index is reconciled by the watcher on the file-removal event.++ SQLite index is deleted directly by the writer actor; the watcher does not++ reconcile delete events.+ - `purge_project` — a whole project is purged (`Wiki::purge_project` →+ `remove_dir_all`, routed from `/admin/purge-project`). Carries the+ project in `ctx`, **no** page path; fired before the directory is+ removed so a mirror can drop the project.++ `delete` / `purge_project` are notifications — there is no body to mutate;+ a `Reject`-policy webhook still aborts the operation. Each webhook opts+ into the ops it cares about via `events`; the chain checks the op against+ `WebhookConfig::events` before dispatching.++ ### What does NOT fire the chain (by design)++ - **`log.md` / `log-YYYY-MM.md` appends** — written on every hook event+ (per prompt/tool-call). Routing each through the chain would mean an+ HTTP POST per observation, violating the fire-and-forget hook budget. The+ per-event log is a local audit artifact; back it up out-of-band (batched+ rsync), not per-line.+ - **Handoffs** — SQLite rows, transient cross-agent state, not wiki pages.+ - **Forget-sweep soft/hard-delete** — DB-only (`is_latest=0` / row delete);+ the markdown file stays on disk, so there is nothing for a file mirror to+ do. (Only `purge_project` removes files in bulk.)+ - **`rename-project`** — a `projects.name` column update; the on-disk path+ is the stable UUID, so no file moves and nothing to propagate.+ - **External / manual edits on disk** — reconciled by the watcher, not the+ admission chain (the chain is for the engine's own write path).++ ## 3. Wire contract++ ### Request (engine → webhook)++ ```http+ POST <webhook.url>+ Content-Type: application/json+ X-Memory-Op: write_page | consolidate | delete | purge_project+ ```++ ```jsonc+ {+ "page": {+ "path": "gotchas/example.md", // relative wiki path (PagePath)+ "frontmatter": { "title": "...", ... }, // arbitrary JSON, may be null+ "body": "..." // markdown body, no frontmatter block+ },+ "ctx": {+ "workspace": "default", // resolved name (see §5)+ "project": "ai-memory-ops", // resolved name+ "actor": { // request-layer identity+ "agent": "claude-code", // claude-code | codex | opencode | hook | cli | …+ "user": "djalmajr", // null when unauthenticated+ "sub": "8f3a-...", // JWT sub+ "client": "72836f52-...", // DCR client UUID+ "session_id": "019e6d-..."+ },+ "op": "write_page" // write_page | consolidate | delete | purge_project+ }+ }+ ```++ The `WebhookRequestBody` / `WebhookPagePayload` / `ActorContext` /+ `AdmissionContext` types in+ `crates/ai-memory-wiki/src/admission.rs` are the authoritative+ serialisation source.++ ### Response (webhook → engine)++ | Status | Body | Behaviour |+ |---|---|---|+ | `200 OK` | `{ "page": { "frontmatter": ..., "body": ... } }` — both inner fields optional. Anything missing means "leave that field unchanged". | The engine swaps in the returned values before the next webhook (or the final atomic write). |+ | `204 No Content` | (empty) | The engine treats the webhook as a pure observer / side-effect — no mutation, no parse. |+ | `4xx` / `5xx` | (optional textual body, logged) | See **§4 Failure policy**. |++ The engine bounds the response read at `MAX_RESPONSE_BYTES` (1 MiB).+ Anything beyond that is treated as a no-op with a `warn` log — webhooks+ have no legitimate reason to return more than the page envelope.++ ## 4. Failure policy++ Each webhook picks one when the engine can't reach it or it returns+ non-2xx:++ - **`ignore` (default, recommended)** — Engine logs a `warn` and+ continues with the unmutated page. The page write still succeeds.+ This is the right choice for everything except safety-critical+ enforcers.+ - **`reject`** — Engine aborts the write, propagating the error up to+ the caller. Use this **only** when the webhook is a hard precondition+ for persistence (e.g. a future `validate-no-secrets` enforcer).++ A webhook that subscribes to multiple ops uses the same policy across+ all of them.++ ## 5. Workspace / project names++ The engine resolves `workspace_id` and `project_id` into the same+ human-readable names the UI and on-disk wiki use, so webhooks can+ address pages by name without re-implementing UUID lookup. Resolution+ happens just before the chain fires; both fields are empty when the+ wiki was built without [`Wiki::with_store_reader`] (e.g. legacy+ embedders, tests that wire a chain without a reader).++ External webhooks should treat the names as opaque strings (workspace /+ project values use the same validation as `--workspace` / `--project`+ CLI flags). They are stable for the lifetime of the workspace / project+ — the engine doesn't rename them silently. `rename-project` is a manual+ op that an operator runs and that will eventually trigger a fresh+ webhook fan-out if you wire one.++ ## 6. Loop prevention++ A webhook that turns around and writes back to the engine (e.g. via+ `/admin/write-page` or `memory_write_page`) must include the header++ ```+ X-Memory-Skip-Admission-Chain: <name>[,<name>...]+ ```++ on its re-entrant call. The engine matches the CSV against-`WebhookConfig::name` and short-circuits those hooks for that write.-Without this, you get infinite recursion (engine → webhook → engine →-webhook → ...). The header propagates only for the single re-entrant++`WebhookConfig::name` and short-circuits those hooks for that write, but only++for trusted re-entry (root/auth-disabled requests). Regular DB-user writes++cannot set this header to bypass a reject-policy webhook. Without the skip++header on trusted re-entry, you get infinite recursion (engine → webhook →++engine → webhook → ...). The header propagates only for the single re-entrant+ write; the next external write picks the chain back up normally.++ ## 7. Limits++ Constants are exported from the `ai-memory-wiki` crate root:++ | Constant | Value | What it caps |+ |---|---|---|+ | `MAX_ADMISSION_WEBHOOKS` | `16` | Chain length. `AdmissionChain::new` errors out beyond this — a misconfigured template (helm loop, duplicated block) can't push N hooks into the write-path. |+ | `MAX_RESPONSE_BYTES` | `1 MiB` | Webhook response body. Beyond this the response is dropped (treated as no-op + `warn`). |+ | Per-webhook `timeout_ms` | operator-set (default `2000`) | Single request. The chain is sequential, so total worst case ≈ `Σ timeout_ms`. |++ ## 8. Configuration++ `config.toml`:++ ```toml+ [[admission_webhooks]]+ name = "contributors" # stable identifier (used by skip list + logs)+ url = "http://contributors.memory.svc.cluster.local:8080/enrich"+ timeout_ms = 2000 # per request+ failure_policy = "ignore" # ignore | reject+ events = ["write_page", "consolidate"]+ blocking = true # runs synchronously; may mutate / reject++ [[admission_webhooks]]+ name = "git-mirror"+ url = "http://git-mirror.memory.svc.cluster.local:8080/sync"+ timeout_ms = 2000+ failure_policy = "ignore"+ events = ["write_page", "consolidate", "delete", "purge_project"]+ blocking = false # fire-and-forget after the write; never blocks it+ ```++ ### `blocking` (default `true`)++ A webhook is either **blocking** or **non-blocking**:++ - **`blocking = true`** (default) — runs *synchronously* inside the write path.+ It can mutate the page (`write_page`/`consolidate`), and a `reject` failure+ aborts the write. The write waits for it (up to `timeout_ms`). Use for+ enrichers/validators (e.g. `contributors`, `validate-no-secrets`).-- **`blocking = false`** — dispatched *fire-and-forget* **after** the page has- landed on disk. The engine does not wait for it and ignores its response, so- it **cannot mutate or reject** — it only observes/mirrors the final page. Use- for pure backups/mirrors (e.g. `git-mirror`) so a slow or down sink never adds- latency to writes. Still honours `events` and the skip list.++- **`blocking = false`** — dispatched *fire-and-forget* **after** the durable++ operation has completed. For writes that means the final page is on disk and++ indexed in SQLite; for deletes that means the file and index row are gone;++ for project purges that means the DB purge has completed and filesystem++ removal has been attempted. The engine does not wait for it and ignores its++ response, so it **cannot mutate or reject** — it only observes/mirrors the++ final state. Use for pure backups/mirrors (e.g. `git-mirror`) so a slow or++ down sink never adds latency to writes. Still honours `events` and the skip++ list.++ Since the blocking chain is sequential, total worst-case write latency is+ `Σ timeout_ms` over the **blocking** webhooks only; non-blocking ones add none.+-Env override (figment env layer):++Env override:++ ```bash-AI_MEMORY_ADMISSION_WEBHOOKS__0__NAME=contributors-AI_MEMORY_ADMISSION_WEBHOOKS__0__URL=http://contributors.memory.svc.cluster.local:8080/enrich-AI_MEMORY_ADMISSION_WEBHOOKS__0__TIMEOUT_MS=2000-AI_MEMORY_ADMISSION_WEBHOOKS__0__FAILURE_POLICY=ignore-AI_MEMORY_ADMISSION_WEBHOOKS__0__EVENTS=write_page,consolidate++AI_MEMORY_ADMISSION_WEBHOOKS_JSON='[{"name":"contributors","url":"http://contributors.memory.svc.cluster.local:8080/enrich","timeout_ms":2000,"failure_policy":"ignore","events":["write_page","consolidate"],"blocking":true}]'+ ```+++The JSON env var is canonical for webhook lists because the figment env layer++does not reliably reconstruct `Vec<Struct>` from indexed nested variables.+++ Empty config = no chain attached → zero overhead per write (no client+ built, no per-write branch).++ ## 9. Worked examples++ ### Mutating: append the writer to `frontmatter.contributors`++ ```jsonc+ // POST /enrich+ {+ "page": { "path": "gotchas/x.md", "frontmatter": { "title": "X" }, "body": "..." },+ "ctx": { "workspace": "default", "project": "ai-memory-ops",+ "actor": { "agent": "claude-code", "user": "djalmajr", "client": "72836f52-..." }, ... }+ }++ // → 200 OK+ {+ "page": {+ "frontmatter": {+ "title": "X",+ "contributors": [+ { "agent": "claude-code", "user": "djalmajr", "client": "72836f52-...",+ "first_seen": "...", "last_seen": "...", "writes": 1 }+ ]+ }+ }+ }+ ```++ The engine replaces `frontmatter` with the returned object before+ persisting. `body` is left untouched (not in the response).++ ### Side-effect: mirror the write into an external git repo++ ```jsonc+ // POST /sync (same request body)+ // → 204 No Content+ ```++ The webhook materialises the page into a local clone of an external+ repo, batches commits, and pushes asynchronously. The engine doesn't+ wait for the push — only the local enqueue runs inside the write path+ under the webhook's `timeout_ms`.++ ## 10. Tests++ `crates/ai-memory-wiki/tests/admission.rs` covers the wire contract end+ to end against an axum loopback server. Categories:++ - Mutating frontmatter and body propagates correctly.+ - `204` is a no-op (frontmatter / body unchanged).+ - `failure_policy=ignore` swallows errors; `failure_policy=reject`+ aborts.+ - Multi-webhook chain runs in declared order; each sees the previous+ mutation.+ - `X-Memory-Skip-Admission-Chain` short-circuits named hooks.+ - `X-Memory-Op` header is set correctly per op.+ - `op`-filtering: webhooks only fire on subscribed events.+ - `MAX_ADMISSION_WEBHOOKS` rejection at construct time.+ - `MAX_RESPONSE_BYTES` cap drops oversized responses.+ - `workspace` / `project` resolution propagates into the payload.++ `crates/ai-memory-wiki/src/wiki.rs::tests::write_page_resolves_workspace_and_project_names_for_chain`+ covers the integrated path (`Wiki::write_page` → store reader resolution+ → chain → recorded payload).++ ## 11. Where to look in source (the canonical spec)++ | Concept | File:line |+ |---|---|+ | `AdmissionContext` / `ActorContext` / wire structs | `crates/ai-memory-wiki/src/admission.rs` |+ | `AdmissionChain::run` (the hot loop) | `crates/ai-memory-wiki/src/admission.rs` |+ | Invocation inside `write_page` (resolution + chain call) | `crates/ai-memory-wiki/src/wiki.rs::Wiki::write_page` |+ | Config schema (`[[admission_webhooks]]`) | `crates/ai-memory-cli/src/config.rs::Config::admission_webhooks` |+ | Server wiring (`with_admission_chain` + `with_store_reader`) | `crates/ai-memory-cli/src/commands/serve.rs` |+ | Header → `ActorContext` mapping (mcp-auth → engine) | `crates/ai-memory-mcp/src/actor.rs` |++ ## 12. Non-goals (planned iterations, not blockers)++ - **Parallel fan-out.** The chain is sequential by design today —+ mutation composition is well-defined that way. A future+ `parallel = true` for side-effect-only webhooks (no body mutation+ expected) is possible but not in scope.+ - **Webhook discovery / dynamic registration.** Hooks are operator-named+ in config. A future `/admin/admission-webhooks` POST surface is+ conceivable but explicitly out of scope here — single-tenant config+ is simpler and matches how the engine treats every other extension+ point (`[[etl_sources]]`, etc.).+ - **Per-webhook metrics surface.** The chain logs via `tracing` today.+ Surfacing per-webhook counters via `/admin/status` is a natural+ follow-up but lives outside this contract.diff --cc docs/users.mdindex 28e59a41,28e59a41..82a9ce53--- a/docs/users.md+++ b/docs/users.md@@@ -24,7 -24,7 +24,7 @@@ You probably want multi-user mode when- You want the audit log to record *who* made each write (e.g. totrace `Codex` writes vs `Claude Code` writes vs hand-rolled CLIcalls).--- You're planning to use the (deferred) admission webhook chain —++- You're planning to use the admission webhook chain —webhooks receive the actor identity in their payload.You probably **don't** need it when: