Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(wiki): admission webhook chain as engine extension point

Djalma Júnior2e8842eb9cb9
diff --git a/Cargo.lock b/Cargo.lock
index 411ca367..b8a17ee2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -245,16 +245,19 @@ dependencies = [
"ai-memory-store",
"anyhow",
"async-trait",
+ "axum",
"git2",
"jiff",
"notify",
"notify-debouncer-full",
+ "reqwest",
"serde",
"serde_json",
"serde_yaml",
"tempfile",
"thiserror 2.0.18",
"tokio",
+ "tower",
"tracing",
"winapi-util",
]
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 02fa688e..927212a2 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -506,6 +506,7 @@ async fn process(state: &HookState, env: HookEnvelope) -> anyhow::Result<()> {
tier: new_page.tier,
pinned: new_page.pinned,
title: None,
+ admission_ctx: None,
})
.await?;
state.writer.end_session(session_id, Some(page_id)).await?;
@@ -702,6 +703,7 @@ async fn consolidate_or_synth(
tier: new_page.tier,
pinned: new_page.pinned,
title: None,
+ admission_ctx: None,
})
.await?;
let _ = state.wiki.commit_all(&format!(
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index b2f8fbf6..29e27978 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1583,6 +1583,32 @@ impl ReaderPool {
.await
}
+ /// Look up a workspace name by id.
+ ///
+ /// Returns `None` when no matching workspace exists. Used by the
+ /// admission webhook chain to populate `AdmissionContext.workspace`
+ /// so external webhooks can address the page by human name without
+ /// re-implementing UUID→name lookup against the engine's store.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn workspace_name_by_id(
+ &self,
+ workspace_id: WorkspaceId,
+ ) -> StoreResult<Option<String>> {
+ self.with_conn(move |conn| {
+ let row_opt = conn
+ .query_row(
+ "SELECT name FROM workspaces WHERE id = ?1",
+ params![workspace_id.as_bytes()],
+ |row| row.get::<_, String>(0),
+ )
+ .optional()?;
+ Ok(row_opt)
+ })
+ .await
+ }
+
/// Look up a project name by id within a workspace.
///
/// Returns `None` when no matching project exists.
diff --git a/crates/ai-memory-web/tests/routes.rs b/crates/ai-memory-web/tests/routes.rs
index cd02d477..104b360c 100644
--- a/crates/ai-memory-web/tests/routes.rs
+++ b/crates/ai-memory-web/tests/routes.rs
@@ -55,6 +55,7 @@ fn wiki_req(
tier: Tier::Semantic,
pinned: false,
title: None,
+ admission_ctx: None,
}
}
@@ -1518,6 +1519,7 @@ async fn api_page_handler_emits_etag_and_supports_if_none_match() {
tier: Tier::Semantic,
pinned: false,
title: None,
+ admission_ctx: None,
})
.await
.unwrap();
@@ -1596,6 +1598,7 @@ async fn api_page_handler_etag_differs_per_page() {
tier: Tier::Semantic,
pinned: false,
title: None,
+ admission_ctx: None,
})
.await
.unwrap();
@@ -1608,6 +1611,7 @@ async fn api_page_handler_etag_differs_per_page() {
tier: Tier::Semantic,
pinned: false,
title: None,
+ admission_ctx: None,
})
.await
.unwrap();
diff --git a/crates/ai-memory-wiki/Cargo.toml b/crates/ai-memory-wiki/Cargo.toml
index 47d5f75a..67d3a91c 100644
--- a/crates/ai-memory-wiki/Cargo.toml
+++ b/crates/ai-memory-wiki/Cargo.toml
@@ -25,11 +25,16 @@ notify.workspace = true
notify-debouncer-full.workspace = true
git2.workspace = true
async-trait.workspace = true
+# Admission webhook chain (sync HTTP calls before page persistence).
+reqwest.workspace = true
[target.'cfg(windows)'.dependencies]
winapi-util = { workspace = true }
[dev-dependencies]
+# Mock HTTP server for admission chain integration tests.
+axum.workspace = true
+tower.workspace = true
[lints]
workspace = true
diff --git a/crates/ai-memory-wiki/src/admission.rs b/crates/ai-memory-wiki/src/admission.rs
new file mode 100644
index 00000000..4517280a
--- /dev/null
+++ b/crates/ai-memory-wiki/src/admission.rs
@@ -0,0 +1,412 @@
+//! 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 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,
+}
+
+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",
+ }
+ }
+}
+
+/// 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
+}
+
+/// 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>,
+}
+
+/// Identity of the actor that triggered a write. Populated by the caller
+/// (MCP tool, admin endpoint, hook router) from validated JWT claims +
+/// injected headers (typically `X-Memory-Actor-*` from `mcp-auth`).
+///
+/// All fields are optional: internal callers (CLI bootstrap, tests) may
+/// leave them blank; webhooks must handle that gracefully.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct ActorContext {
+ /// `claude-code` | `codex` | `opencode` | `hook` | `cli` | …
+ pub agent: Option<String>,
+ /// Keycloak `preferred_username` (e.g. `djalmajr`).
+ pub user: Option<String>,
+ /// JWT `sub` claim (stable user UUID).
+ pub sub: Option<String>,
+ /// DCR client UUID (identifies the agent install).
+ pub client: Option<String>,
+ /// Session id from the agent (if known).
+ pub session_id: Option<String>,
+}
+
+impl ActorContext {
+ /// `true` if at least one identity field is set. Useful for callers
+ /// that want to skip building an [`AdmissionContext`] entirely when
+ /// the actor is completely anonymous.
+ #[must_use]
+ pub fn has_any(&self) -> bool {
+ self.agent.is_some()
+ || self.user.is_some()
+ || self.sub.is_some()
+ || self.client.is_some()
+ || self.session_id.is_some()
+ }
+}
+
+/// 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.
+ pub actor: 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;
+ }
+
+ 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,
+ 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 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(())
+ }
+}
+
+#[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 --git a/crates/ai-memory-wiki/src/lib.rs b/crates/ai-memory-wiki/src/lib.rs
index 1f1481f2..36285bc9 100644
--- a/crates/ai-memory-wiki/src/lib.rs
+++ b/crates/ai-memory-wiki/src/lib.rs
@@ -5,6 +5,7 @@
//! actor so the SQLite index never diverges from the file. The watcher +
//! git layer arrive in M1-D and M5.
+pub mod admission;
mod atomic;
mod error;
mod git;
@@ -13,6 +14,10 @@ pub mod migrations;
mod watcher;
mod wiki;
+pub use admission::{
+ ActorContext, AdmissionChain, AdmissionContext, AdmissionOp, FailurePolicy,
+ MAX_ADMISSION_WEBHOOKS, MAX_RESPONSE_BYTES, WebhookConfig,
+};
pub use error::{WikiError, WikiResult};
pub use git::{COMMIT_AUTHOR_EMAIL, COMMIT_AUTHOR_NAME, GitAdapter};
pub use markdown::{Markdown, derive_title, emit, parse};
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index eabd7d2b..f27b4f67 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -5,8 +5,9 @@ use std::sync::Arc;
use ai_memory_core::{NewPage, PageId, PagePath, ProjectId, Sanitizer, Tier, WorkspaceId};
use ai_memory_llm::Embedder;
-use ai_memory_store::{WriterHandle, f32_vec_to_bytes};
+use ai_memory_store::{ReaderPool, WriterHandle, f32_vec_to_bytes};
+use crate::admission::{AdmissionChain, AdmissionContext};
use crate::atomic;
use crate::error::WikiResult;
use crate::git::GitAdapter;
@@ -37,6 +38,18 @@ pub struct Wiki {
/// write-page CLI, agent-supplied tool input) still gets scrubbed
/// at the wiki boundary even if upstream forgot.
sanitizer: Sanitizer,
+ /// Optional HTTP webhook chain invoked just before page persistence.
+ /// When configured, each `write_page` call POSTs the (path, frontmatter,
+ /// body, ctx) tuple to every webhook subscribing to the op; webhooks
+ /// may mutate frontmatter/body before the atomic write hits disk.
+ /// Set via [`Wiki::with_admission_chain`]; see [`crate::admission`].
+ admission_chain: Option<AdmissionChain>,
+ /// Optional store reader used to resolve `workspace_id`/`project_id`
+ /// into human names for the [`AdmissionContext`] passed to webhooks.
+ /// Set via [`Wiki::with_store_reader`]; when unset, webhooks receive
+ /// empty `workspace`/`project` strings and must fall back to
+ /// IDs/headers/`_unscoped` paths.
+ store_reader: Option<ReaderPool>,
}
impl Wiki {
@@ -56,9 +69,39 @@ impl Wiki {
git,
embedder: None,
sanitizer: Sanitizer::builtin(),
+ admission_chain: None,
+ store_reader: None,
})
}
+ /// Attach an admission webhook chain. When set, every `write_page` call
+ /// invokes the chain after the [`Markdown`] is built but before the
+ /// atomic write — webhooks may mutate frontmatter/body. An empty chain
+ /// is a no-op (skipped without HTTP overhead).
+ #[must_use]
+ pub fn with_admission_chain(mut self, chain: AdmissionChain) -> Self {
+ if !chain.is_empty() {
+ self.admission_chain = Some(chain);
+ }
+ self
+ }
+
+ /// Attach a store reader so the admission chain receives
+ /// human-readable `workspace`/`project` names in its context, resolved
+ /// from the `workspace_id`/`project_id` carried on the
+ /// [`WritePageRequest`]. Without this, those fields stay empty and
+ /// external webhooks must fall back to header introspection or use
+ /// `_unscoped` placeholders.
+ ///
+ /// The reader is only invoked when the chain is configured AND would
+ /// actually fire; tests and CLI paths that don't wire a chain pay
+ /// nothing for setting (or omitting) this.
+ #[must_use]
+ pub fn with_store_reader(mut self, reader: ReaderPool) -> Self {
+ self.store_reader = Some(reader);
+ self
+ }
+
/// Replace the default built-in-only sanitizer with one carrying
/// the operator's `[sanitize].extra_patterns` + `allowlist`.
#[must_use]
@@ -303,6 +346,7 @@ impl Wiki {
tier,
pinned,
title: explicit_title,
+ admission_ctx,
} = req;
// Defence-in-depth: scrub the body before we touch disk or the
@@ -312,16 +356,47 @@ impl Wiki {
// tool slips through.
let body = self.sanitizer.scrub(&body);
+ let pinned = pinned || is_slot_path(&path);
+ let mut markdown = Markdown { frontmatter, body };
+
+ // Admission webhook chain — runs AFTER the markdown is built and
+ // sanitised, 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`.
+ if let Some(chain) = &self.admission_chain {
+ let mut ctx = admission_ctx.unwrap_or_default();
+ // 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;
+ }
+ }
+ chain.run(&path, &mut markdown, &ctx).await?;
+ }
+
+ // 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(&frontmatter, &body, &path));
- let links = extract_links(&body, &path);
- let pinned = pinned || is_slot_path(&path);
- let markdown = Markdown {
- frontmatter: frontmatter.clone(),
- body: body.clone(),
- };
+ .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() {
@@ -329,6 +404,10 @@ impl Wiki {
}
atomic::write_atomic(&abs, emitted.as_bytes())?;
+ let Markdown {
+ frontmatter: final_frontmatter,
+ body: final_body,
+ } = markdown;
let page_id = self
.writer
.upsert_page(NewPage {
@@ -336,9 +415,9 @@ impl Wiki {
project_id,
path,
title,
- body: body.clone(),
+ body: final_body.clone(),
tier,
- frontmatter_json: frontmatter,
+ frontmatter_json: final_frontmatter,
pinned,
links,
})
@@ -348,7 +427,7 @@ impl Wiki {
// transaction" (basic-memory #763 lesson): no fire-and-forget
// background embedding.
if let Some(embedder) = &self.embedder {
- match embedder.embed_document(&body).await {
+ match embedder.embed_document(&final_body).await {
Ok(vec) => {
let bytes = f32_vec_to_bytes(&vec);
self.writer
@@ -392,6 +471,14 @@ pub struct WritePageRequest {
/// title between the staged markdown file + the store row).
#[doc(hidden)]
pub title: Option<String>,
+ /// Optional admission webhook context (actor identity + JWT claims +
+ /// request headers + loop-prevention skip list). Populated by
+ /// authenticated callers (MCP tool, admin endpoint) from the JWT +
+ /// `X-Memory-Actor-*` / `X-Memory-Skip-Admission-Chain` headers; left
+ /// `None` by internal callers (CLI bootstrap, consolidator from hooks,
+ /// tests) — when the chain is configured, `None` is treated as a
+ /// default [`AdmissionContext`] with `actor = unknown`.
+ pub admission_ctx: Option<AdmissionContext>,
}
fn ai_memory_wiki_error(msg: &str) -> crate::WikiError {
@@ -440,6 +527,7 @@ mod tests {
tier: Tier::Semantic,
pinned: false,
title: None,
+ admission_ctx: None,
}
}
@@ -619,6 +707,7 @@ mod tests {
tier: Tier::Semantic,
pinned: false,
title: None,
+ admission_ctx: None,
})
.collect();
let ids = wiki.apply_batch(batch).await.unwrap();
@@ -667,6 +756,7 @@ mod tests {
tier: Tier::Semantic,
pinned: false,
title: None,
+ admission_ctx: None,
})
.await
.unwrap();
@@ -680,6 +770,7 @@ mod tests {
tier: Tier::Semantic,
pinned: false,
title: None,
+ admission_ctx: None,
})
.await
.unwrap();
@@ -722,4 +813,97 @@ mod tests {
let c = wiki.write_page(r("body two")).await.unwrap();
assert_ne!(b, c);
}
+
+ /// End-to-end gate for the workspace/project name resolution:
+ /// when a wiki is built with both a store reader and an admission
+ /// chain, `write_page` populates `AdmissionContext.workspace` and
+ /// `AdmissionContext.project` from the resolved store rows before
+ /// invoking the chain. Without [`Wiki::with_store_reader`] the
+ /// fields stay empty (backward compat with external test setups).
+ #[tokio::test]
+ async fn write_page_resolves_workspace_and_project_names_for_chain() {
+ use crate::admission::{
+ AdmissionChain, AdmissionContext, AdmissionOp, FailurePolicy, WebhookConfig,
+ };
+ use axum::http::StatusCode;
+ use axum::response::IntoResponse;
+ use axum::routing::post;
+ use axum::{Json, Router};
+ use std::sync::Mutex;
+ use tokio::net::TcpListener;
+
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("staging")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "ai-memory-ops", None)
+ .await
+ .unwrap();
+
+ // Throwaway HTTP server that records the payload it receives.
+ let recorder: Arc<Mutex<Option<serde_json::Value>>> = Arc::new(Mutex::new(None));
+ let recorder_clone = recorder.clone();
+ let app = Router::new().route(
+ "/sync",
+ post(move |Json(payload): Json<serde_json::Value>| {
+ let recorder = recorder_clone.clone();
+ async move {
+ *recorder.lock().unwrap() = Some(payload);
+ StatusCode::NO_CONTENT.into_response()
+ }
+ }),
+ );
+ 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 chain = AdmissionChain::new(vec![WebhookConfig {
+ name: "recorder".into(),
+ url: format!("http://{addr}/sync"),
+ timeout_ms: 1_000,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::WritePage],
+ }])
+ .unwrap();
+
+ let wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_admission_chain(chain)
+ .with_store_reader(store.reader.clone());
+
+ wiki.write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new("notes/x.md").unwrap(),
+ frontmatter: serde_json::json!({"title": "X"}),
+ body: "hi".into(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: None,
+ admission_ctx: Some(AdmissionContext {
+ op: AdmissionOp::WritePage,
+ ..AdmissionContext::default()
+ }),
+ })
+ .await
+ .unwrap();
+
+ let payload = recorder
+ .lock()
+ .unwrap()
+ .clone()
+ .expect("webhook should have recorded the payload");
+ assert_eq!(payload["ctx"]["workspace"], serde_json::json!("staging"));
+ assert_eq!(
+ payload["ctx"]["project"],
+ serde_json::json!("ai-memory-ops")
+ );
+ }
}
diff --git a/crates/ai-memory-wiki/tests/admission.rs b/crates/ai-memory-wiki/tests/admission.rs
new file mode 100644
index 00000000..102e4d5c
--- /dev/null
+++ b/crates/ai-memory-wiki/tests/admission.rs
@@ -0,0 +1,511 @@
+//! Integration tests for the admission webhook chain.
+//!
+//! Each test spins up a real `axum` server bound to a random loopback
+//! port, points an [`AdmissionChain`] at it, and exercises the chain end
+//! to end. We deliberately do NOT build a full `Wiki` here — those are
+//! covered by the engine-level test suite. These tests pin down the
+//! HTTP contract: payload shape, mutation semantics, failure policy,
+//! and the loop-prevention skip list.
+
+use std::sync::Arc;
+use std::sync::Mutex;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::time::Duration;
+
+use ai_memory_core::PagePath;
+use ai_memory_wiki::{
+ ActorContext, AdmissionChain, AdmissionContext, AdmissionOp, FailurePolicy, Markdown,
+ WebhookConfig,
+};
+use axum::http::{HeaderMap, StatusCode};
+use axum::response::IntoResponse;
+use axum::routing::post;
+use axum::{Json, Router};
+use serde_json::{Value, json};
+
+/// Spawn an axum app on a random loopback port. Returns the base URL.
+async fn spawn_server(app: Router) -> String {
+ 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();
+ });
+ // Give the runtime a tick to start accepting.
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ format!("http://{addr}")
+}
+
+fn page() -> (PagePath, Markdown) {
+ (
+ PagePath::new("gotchas/example.md").unwrap(),
+ Markdown {
+ frontmatter: json!({"title": "Example", "tags": ["t1"]}),
+ body: "body content\n".to_string(),
+ },
+ )
+}
+
+#[tokio::test]
+async fn webhook_mutating_frontmatter_is_applied() {
+ let app = Router::new().route(
+ "/enrich",
+ post(|Json(payload): Json<Value>| async move {
+ // Echo back a mutation: add `contributors: ["claude-code"]`.
+ let mut fm = payload["page"]["frontmatter"].clone();
+ let arr = fm
+ .as_object_mut()
+ .unwrap()
+ .entry("contributors")
+ .or_insert_with(|| json!([]));
+ arr.as_array_mut().unwrap().push(json!("claude-code"));
+ (
+ StatusCode::OK,
+ Json(json!({ "page": { "frontmatter": fm } })),
+ )
+ }),
+ );
+ let base = spawn_server(app).await;
+
+ let chain = AdmissionChain::new(vec![WebhookConfig {
+ name: "contributors".into(),
+ url: format!("{base}/enrich"),
+ timeout_ms: 2_000,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::WritePage],
+ }])
+ .unwrap();
+
+ let (path, mut md) = page();
+ chain
+ .run(&path, &mut md, &AdmissionContext::default())
+ .await
+ .unwrap();
+
+ let contribs = md.frontmatter.get("contributors").expect("set by webhook");
+ assert_eq!(contribs[0], json!("claude-code"));
+ // Body untouched (webhook only returned frontmatter).
+ assert_eq!(md.body, "body content\n");
+}
+
+#[tokio::test]
+async fn webhook_204_is_noop() {
+ let app = Router::new().route("/enrich", post(|| async { StatusCode::NO_CONTENT }));
+ let base = spawn_server(app).await;
+ let chain = AdmissionChain::new(vec![WebhookConfig {
+ name: "noop".into(),
+ url: format!("{base}/enrich"),
+ timeout_ms: 1_000,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::WritePage],
+ }])
+ .unwrap();
+
+ let (path, mut md) = page();
+ let before_fm = md.frontmatter.clone();
+ let before_body = md.body.clone();
+ chain
+ .run(&path, &mut md, &AdmissionContext::default())
+ .await
+ .unwrap();
+ assert_eq!(md.frontmatter, before_fm);
+ assert_eq!(md.body, before_body);
+}
+
+#[tokio::test]
+async fn failure_policy_ignore_swallows_error() {
+ let app = Router::new().route(
+ "/enrich",
+ post(|| async { (StatusCode::INTERNAL_SERVER_ERROR, "boom") }),
+ );
+ let base = spawn_server(app).await;
+ let chain = AdmissionChain::new(vec![WebhookConfig {
+ name: "flaky".into(),
+ url: format!("{base}/enrich"),
+ timeout_ms: 1_000,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::WritePage],
+ }])
+ .unwrap();
+
+ let (path, mut md) = page();
+ // Should NOT return Err — Ignore policy swallows the 500.
+ let res = chain
+ .run(&path, &mut md, &AdmissionContext::default())
+ .await;
+ assert!(
+ res.is_ok(),
+ "ignore policy should not propagate error; got {res:?}"
+ );
+}
+
+#[tokio::test]
+async fn failure_policy_reject_aborts_write() {
+ let app = Router::new().route(
+ "/enrich",
+ post(|| async { (StatusCode::FORBIDDEN, "no secrets") }),
+ );
+ let base = spawn_server(app).await;
+ let chain = AdmissionChain::new(vec![WebhookConfig {
+ name: "validate-no-secrets".into(),
+ url: format!("{base}/enrich"),
+ timeout_ms: 1_000,
+ failure_policy: FailurePolicy::Reject,
+ events: vec![AdmissionOp::WritePage],
+ }])
+ .unwrap();
+
+ let (path, mut md) = page();
+ let res = chain
+ .run(&path, &mut md, &AdmissionContext::default())
+ .await;
+ assert!(res.is_err(), "reject policy should propagate the error");
+}
+
+#[tokio::test]
+async fn skip_webhooks_short_circuits_named_hook() {
+ // Track whether the webhook was invoked. Asserted false at end —
+ // proves the chain never POSTed (rather than panicking inside the
+ // handler, which axum would convert into a 500 the chain might swallow).
+ let fired = Arc::new(AtomicBool::new(false));
+ let fired_in_handler = fired.clone();
+ let app = Router::new().route(
+ "/enrich",
+ post(move || {
+ let fired = fired_in_handler.clone();
+ async move {
+ fired.store(true, Ordering::SeqCst);
+ StatusCode::NO_CONTENT
+ }
+ }),
+ );
+ let base = spawn_server(app).await;
+ let chain = AdmissionChain::new(vec![WebhookConfig {
+ name: "contributors".into(),
+ url: format!("{base}/enrich"),
+ timeout_ms: 1_000,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::WritePage],
+ }])
+ .unwrap();
+
+ let (path, mut md) = page();
+ let ctx = AdmissionContext {
+ skip_webhooks: vec!["contributors".to_string()],
+ ..AdmissionContext::default()
+ };
+ chain.run(&path, &mut md, &ctx).await.unwrap();
+ assert!(
+ !fired.load(Ordering::SeqCst),
+ "webhook must not have been called"
+ );
+}
+
+#[tokio::test]
+async fn op_filter_skips_webhook_not_subscribed_to_event() {
+ // Webhook subscribes only to Consolidate; we call with WritePage.
+ let fired = Arc::new(AtomicBool::new(false));
+ let fired_in_handler = fired.clone();
+ let app = Router::new().route(
+ "/enrich",
+ post(move || {
+ let fired = fired_in_handler.clone();
+ async move {
+ fired.store(true, Ordering::SeqCst);
+ StatusCode::NO_CONTENT
+ }
+ }),
+ );
+ let base = spawn_server(app).await;
+ let chain = AdmissionChain::new(vec![WebhookConfig {
+ name: "only-consolidate".into(),
+ url: format!("{base}/enrich"),
+ timeout_ms: 1_000,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::Consolidate],
+ }])
+ .unwrap();
+
+ let (path, mut md) = page();
+ let ctx = AdmissionContext {
+ op: AdmissionOp::WritePage,
+ ..AdmissionContext::default()
+ };
+ chain.run(&path, &mut md, &ctx).await.unwrap();
+ assert!(
+ !fired.load(Ordering::SeqCst),
+ "webhook must not have been called"
+ );
+}
+
+#[tokio::test]
+async fn chain_runs_in_order_each_sees_previous_mutation() {
+ // Two webhooks. First adds `step: 1` to frontmatter. Second adds
+ // `step_after: <whatever step is>`. Order must be preserved.
+ let recorder: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
+ let app = Router::new()
+ .route(
+ "/first",
+ post(|Json(payload): Json<Value>| async move {
+ let mut fm = payload["page"]["frontmatter"].clone();
+ fm["step"] = json!(1);
+ Json(json!({ "page": { "frontmatter": fm } }))
+ }),
+ )
+ .route(
+ "/second",
+ post({
+ let recorder = recorder.clone();
+ move |Json(payload): Json<Value>| {
+ let recorder = recorder.clone();
+ async move {
+ let step = payload["page"]["frontmatter"]["step"].clone();
+ recorder.lock().unwrap().push(format!("step_seen={step}"));
+ let mut fm = payload["page"]["frontmatter"].clone();
+ fm["step_after"] = step;
+ Json(json!({ "page": { "frontmatter": fm } }))
+ }
+ }
+ }),
+ );
+ let base = spawn_server(app).await;
+ let chain = AdmissionChain::new(vec![
+ WebhookConfig {
+ name: "first".into(),
+ url: format!("{base}/first"),
+ timeout_ms: 1_000,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::WritePage],
+ },
+ WebhookConfig {
+ name: "second".into(),
+ url: format!("{base}/second"),
+ timeout_ms: 1_000,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::WritePage],
+ },
+ ])
+ .unwrap();
+
+ let (path, mut md) = page();
+ chain
+ .run(&path, &mut md, &AdmissionContext::default())
+ .await
+ .unwrap();
+
+ assert_eq!(md.frontmatter["step"], json!(1));
+ assert_eq!(md.frontmatter["step_after"], json!(1));
+ let log = recorder.lock().unwrap();
+ assert_eq!(log.len(), 1);
+ assert_eq!(log[0], "step_seen=1");
+}
+
+#[tokio::test]
+async fn x_memory_op_header_is_sent() {
+ // Track received header so we can assert on it.
+ let recorder: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
+ let recorder_clone = recorder.clone();
+ let app = Router::new().route(
+ "/enrich",
+ post(move |headers: HeaderMap| {
+ let recorder = recorder_clone.clone();
+ async move {
+ let v = headers
+ .get("X-Memory-Op")
+ .and_then(|v| v.to_str().ok())
+ .map(str::to_string);
+ *recorder.lock().unwrap() = v;
+ StatusCode::NO_CONTENT.into_response()
+ }
+ }),
+ );
+ let base = spawn_server(app).await;
+ let chain = AdmissionChain::new(vec![WebhookConfig {
+ name: "any".into(),
+ url: format!("{base}/enrich"),
+ timeout_ms: 1_000,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::Consolidate],
+ }])
+ .unwrap();
+
+ let (path, mut md) = page();
+ let ctx = AdmissionContext {
+ op: AdmissionOp::Consolidate,
+ ..AdmissionContext::default()
+ };
+ chain.run(&path, &mut md, &ctx).await.unwrap();
+
+ assert_eq!(recorder.lock().unwrap().as_deref(), Some("consolidate"));
+}
+
+#[tokio::test]
+async fn actor_context_is_propagated_in_payload() {
+ let recorder: Arc<Mutex<Option<Value>>> = Arc::new(Mutex::new(None));
+ let recorder_clone = recorder.clone();
+ let app = Router::new().route(
+ "/enrich",
+ post(move |Json(payload): Json<Value>| {
+ let recorder = recorder_clone.clone();
+ async move {
+ *recorder.lock().unwrap() = Some(payload);
+ StatusCode::NO_CONTENT.into_response()
+ }
+ }),
+ );
+ let base = spawn_server(app).await;
+ let chain = AdmissionChain::new(vec![WebhookConfig {
+ name: "echo".into(),
+ url: format!("{base}/enrich"),
+ timeout_ms: 1_000,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::WritePage],
+ }])
+ .unwrap();
+
+ let (path, mut md) = page();
+ let ctx = AdmissionContext {
+ actor: ActorContext {
+ agent: Some("claude-code".into()),
+ user: Some("djalmajr".into()),
+ sub: Some("8f3a-uuid".into()),
+ client: Some("72836f52-uuid".into()),
+ session_id: Some("019e6d-session".into()),
+ },
+ ..AdmissionContext::default()
+ };
+ chain.run(&path, &mut md, &ctx).await.unwrap();
+
+ let payload = recorder.lock().unwrap().clone().expect("recorded");
+ let actor = &payload["ctx"]["actor"];
+ assert_eq!(actor["agent"], json!("claude-code"));
+ assert_eq!(actor["user"], json!("djalmajr"));
+ assert_eq!(actor["client"], json!("72836f52-uuid"));
+ assert_eq!(payload["page"]["path"], json!("gotchas/example.md"));
+}
+
+#[tokio::test]
+async fn webhook_can_mutate_body_too() {
+ let app = Router::new().route(
+ "/enrich",
+ post(|Json(_payload): Json<Value>| async move {
+ (
+ StatusCode::OK,
+ Json(json!({ "page": { "body": "REWRITTEN" } })),
+ )
+ }),
+ );
+ let base = spawn_server(app).await;
+ let chain = AdmissionChain::new(vec![WebhookConfig {
+ name: "body-mutator".into(),
+ url: format!("{base}/enrich"),
+ timeout_ms: 1_000,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::WritePage],
+ }])
+ .unwrap();
+
+ let (path, mut md) = page();
+ let before_fm = md.frontmatter.clone();
+ chain
+ .run(&path, &mut md, &AdmissionContext::default())
+ .await
+ .unwrap();
+ assert_eq!(md.body, "REWRITTEN");
+ assert_eq!(md.frontmatter, before_fm, "frontmatter untouched");
+}
+
+#[tokio::test]
+async fn chain_rejects_more_than_max_admission_webhooks() {
+ // Mis-templated configs (helm loops etc.) shouldn't be able to
+ // serialise a 1000-webhook chain — sequential latency would
+ // dominate the write_page critical path.
+ let too_many: Vec<WebhookConfig> = (0..=ai_memory_wiki::MAX_ADMISSION_WEBHOOKS)
+ .map(|i| WebhookConfig {
+ name: format!("w{i}"),
+ url: format!("http://127.0.0.1:1/{i}"),
+ timeout_ms: 100,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::WritePage],
+ })
+ .collect();
+ let err = AdmissionChain::new(too_many).expect_err("should refuse");
+ assert!(
+ err.to_string().contains("admission chain capped"),
+ "unexpected error message: {err}"
+ );
+}
+
+#[tokio::test]
+async fn oversized_response_is_treated_as_noop() {
+ // A webhook returning > MAX_RESPONSE_BYTES gets dropped — never
+ // forces the engine to buffer the payload or attempt to apply it.
+ let big_body = "x".repeat(ai_memory_wiki::MAX_RESPONSE_BYTES + 1);
+ let body_arc = Arc::new(big_body);
+ let body_clone = body_arc.clone();
+ let app = Router::new().route(
+ "/enrich",
+ post(move || {
+ let body = body_clone.clone();
+ async move { (StatusCode::OK, Json(json!({ "page": { "body": &*body } }))) }
+ }),
+ );
+ let base = spawn_server(app).await;
+ let chain = AdmissionChain::new(vec![WebhookConfig {
+ name: "huge".into(),
+ url: format!("{base}/enrich"),
+ timeout_ms: 5_000,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::WritePage],
+ }])
+ .unwrap();
+
+ let (path, mut md) = page();
+ let before_body = md.body.clone();
+ chain
+ .run(&path, &mut md, &AdmissionContext::default())
+ .await
+ .unwrap();
+ assert_eq!(md.body, before_body, "oversized response must not mutate");
+}
+
+#[tokio::test]
+async fn workspace_and_project_names_propagate_in_payload() {
+ // Webhooks need human-readable workspace/project to address pages by
+ // the same names the engine and UI use — otherwise external mirrors
+ // (git-mirror, etc.) have to fall back to header introspection or
+ // `_unscoped` placeholders. The chain serialises both fields directly
+ // from the AdmissionContext.
+ let recorder: Arc<Mutex<Option<Value>>> = Arc::new(Mutex::new(None));
+ let recorder_clone = recorder.clone();
+ let app = Router::new().route(
+ "/sync",
+ post(move |Json(payload): Json<Value>| {
+ let recorder = recorder_clone.clone();
+ async move {
+ *recorder.lock().unwrap() = Some(payload);
+ StatusCode::NO_CONTENT.into_response()
+ }
+ }),
+ );
+ let base = spawn_server(app).await;
+ let chain = AdmissionChain::new(vec![WebhookConfig {
+ name: "git-mirror".into(),
+ url: format!("{base}/sync"),
+ timeout_ms: 1_000,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::WritePage],
+ }])
+ .unwrap();
+
+ let (path, mut md) = page();
+ let ctx = AdmissionContext {
+ workspace: "default".into(),
+ project: "ai-memory-ops".into(),
+ ..AdmissionContext::default()
+ };
+ chain.run(&path, &mut md, &ctx).await.unwrap();
+
+ let payload = recorder.lock().unwrap().clone().expect("recorded");
+ assert_eq!(payload["ctx"]["workspace"], json!("default"));
+ assert_eq!(payload["ctx"]["project"], json!("ai-memory-ops"));
+}