Skip to content

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

Rust

fix(consolidate): resolve target from observations + preflight admission before the LLM

Djalma Júnior95ca148d104b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7b585473..fff7af79 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
migration, reports the highest schema version this build ships, and tells the
operator to run a build at least as new as the one that wrote the data. Every
other migration failure is unchanged.
+- `memory_consolidate` now resolves its target `(workspace, project)` from
+ where the session's observations actually landed, rather than trusting the
+ `sessions` row. A session that adopts its scope marker mid-run keeps a
+ session row frozen on the pre-marker scope (`begin_session` uses
+ `ON CONFLICT DO NOTHING`), while each observation carries the correct
+ per-cwd scope — so a "hybrid" session used to consolidate into the wrong
+ project. Resolution now prefers the majority observation scope, then the
+ session row, then the server's startup IDs ([#186]).
+
+### Changed
+- `memory_consolidate` runs the blocking admission chain up front, before the
+ LLM, so a rejected scope/actor fails fast and identically in every mode
+ instead of only surfacing at write time — previously a single-page write
+ spent the LLM before the 403, and a multi-page / dry-run request ran the
+ full completion only for the client to time out before seeing the
+ rejection. Consequently `dry_run=true` is now a cheap plan: it runs the
+ admission preflight and reports the resolved page path without calling the
+ LLM (it no longer returns an LLM-generated body preview); a real
+ (non-dry) run still produces the page bodies ([#186]).
## [1.13.0] - 2026-07-14
diff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rs
index 1eff77b1..72a92e5b 100644
--- a/crates/ai-memory-consolidate/src/consolidator.rs
+++ b/crates/ai-memory-consolidate/src/consolidator.rs
@@ -111,18 +111,33 @@ impl Consolidator {
return Err(ConsolidatorError::EmptySession(session_id));
}
- // Look up the session's actual (workspace, project) IDs — the
- // hook router stamped them per-cwd at session start, so this
- // is the correct target for the resulting wiki page. The
- // server's startup IDs (self.workspace_id / self.project_id)
- // are the fallback for sessions that pre-date per-cwd routing.
- let (ws, proj) = self
- .reader
- .session_project_ids(session_id)
- .await?
- .unwrap_or((self.workspace_id, self.project_id));
-
+ let (ws, proj) = self.resolve_target(session_id).await?;
let path = PagePath::new(format!("sessions/{session_id}.md"))?;
+
+ // Run the blocking admission chain BEFORE the LLM so a rejected
+ // scope/actor fails fast without spending a completion. This makes
+ // both dry runs and real writes reject identically and cheaply
+ // (previously the reject only surfaced at write time, after the LLM).
+ self.wiki
+ .preflight_admission(ws, proj, &path, AdmissionOp::Consolidate, actor.clone())
+ .await?;
+
+ // A dry run is a cheap plan: the preflight above already confirmed
+ // admission (a rejected scope errored out), and reporting where the
+ // page would land does not need the LLM. Skip the completion and
+ // return the resolved plan. Callers wanting the actual rewritten body
+ // run a real (non-dry) consolidation.
+ if dry_run {
+ return Ok(ConsolidationOutcome {
+ path,
+ dry_run: true,
+ new_title: String::new(),
+ new_body_markdown: String::new(),
+ page_id: None,
+ tags: Vec::new(),
+ });
+ }
+
let current_body = self
.wiki
.read_page(ws, proj, &path)
@@ -137,17 +152,6 @@ impl Consolidator {
);
let page: ConsolidatedPage = complete_structured(&*self.llm, request).await?;
- if dry_run {
- return Ok(ConsolidationOutcome {
- path,
- dry_run: true,
- new_title: page.title,
- new_body_markdown: page.body_markdown,
- page_id: None,
- tags: page.tags,
- });
- }
-
let frontmatter = build_frontmatter(&page);
let id = self
.wiki
@@ -212,6 +216,32 @@ impl Consolidator {
self.llm.clone()
}
+ /// Resolve the `(workspace, project)` the session should consolidate into.
+ ///
+ /// Prefer where the session's observations actually landed: the hook router
+ /// stamps each observation with its per-cwd scope, so this is correct even
+ /// for a "hybrid" session whose `sessions` row froze on a pre-marker scope
+ /// (`begin_session` uses `ON CONFLICT DO NOTHING`, so the row never
+ /// re-anchors). Fall back to the session row, then to the server's startup
+ /// IDs for sessions that pre-date per-cwd routing.
+ async fn resolve_target(
+ &self,
+ session_id: SessionId,
+ ) -> ConsolidatorResult<(WorkspaceId, ProjectId)> {
+ if let Some(scope) = self
+ .reader
+ .session_scope_from_observations(session_id)
+ .await?
+ {
+ return Ok(scope);
+ }
+ Ok(self
+ .reader
+ .session_project_ids(session_id)
+ .await?
+ .unwrap_or((self.workspace_id, self.project_id)))
+ }
+
fn should_skip_high_resistance_slot_update(
&self,
workspace_id: WorkspaceId,
@@ -278,13 +308,34 @@ impl Consolidator {
if observations.is_empty() {
return Err(ConsolidatorError::EmptySession(session_id));
}
- // Resolve the session's actual (workspace, project) IDs from
- // its row — see `consolidate_session` for the rationale.
- let (ws, proj) = self
- .reader
- .session_project_ids(session_id)
- .await?
- .unwrap_or((self.workspace_id, self.project_id));
+ // Resolve the target from where the observations landed — see
+ // `resolve_target` / `consolidate_session` for the rationale.
+ let (ws, proj) = self.resolve_target(session_id).await?;
+
+ // Preflight admission BEFORE the LLM (see `consolidate_session`). The
+ // session page is the canonical episodic anchor, so it stands in for
+ // the batch's scope/actor check; the scope-guard decision is on
+ // op/actor/workspace/project, not the specific path.
+ let anchor = PagePath::new(format!("sessions/{session_id}.md"))?;
+ self.wiki
+ .preflight_admission(ws, proj, &anchor, AdmissionOp::Consolidate, actor.clone())
+ .await?;
+
+ // A dry run is a cheap plan (see `consolidate_session`): admission is
+ // already confirmed and the concrete page set is only knowable after a
+ // real LLM run, so report the resolved scope via the session anchor and
+ // skip the completion. A real (non-dry) run enumerates every page.
+ if dry_run {
+ return Ok(vec![ConsolidationOutcome {
+ path: anchor,
+ dry_run: true,
+ new_title: String::new(),
+ new_body_markdown: String::new(),
+ page_id: None,
+ tags: Vec::new(),
+ }]);
+ }
+
let slots = self.slot_snapshots(ws, proj).await?;
let request = build_batch_request_with_slots(session_id, &observations, &slots);
debug!(
@@ -295,10 +346,12 @@ impl Consolidator {
let batch: ConsolidatedBatch =
ai_memory_llm::complete_structured(&*self.llm, request).await?;
+ // `dry_run` is always false past the early return above, so every
+ // update here is a real write.
let mut requests = Vec::with_capacity(batch.updates.len());
let mut outcomes_preview = Vec::with_capacity(batch.updates.len());
for upd in &batch.updates {
- let (req, outcome) = build_update(ws, proj, upd, dry_run, &actor, author_id)?;
+ let (req, outcome) = build_update(ws, proj, upd, false, &actor, author_id)?;
if self.should_skip_high_resistance_slot_update(ws, proj, &req)? {
debug!(
path = %req.path.as_str(),
@@ -310,10 +363,6 @@ impl Consolidator {
outcomes_preview.push(outcome);
}
- if dry_run {
- return Ok(outcomes_preview);
- }
-
let ids = self.wiki.apply_batch(requests).await?;
let rationale_short = batch.rationale.chars().take(60).collect::<String>();
let _ = self.wiki.commit_all(&format!(
@@ -1030,6 +1079,154 @@ mod tests {
assert!(prompt.contains("This is stable unless"));
}
+ /// An LLM provider that panics if any completion is attempted — proves a
+ /// code path never reaches the model.
+ struct PanicLlm;
+
+ #[async_trait::async_trait]
+ impl LlmProvider for PanicLlm {
+ fn name(&self) -> &'static str {
+ "panic"
+ }
+ fn model(&self) -> &str {
+ "panic"
+ }
+ async fn complete(
+ &self,
+ _request: ChatRequest,
+ ) -> ai_memory_llm::LlmResult<ai_memory_llm::ChatResponse> {
+ panic!("dry_run must not call the LLM");
+ }
+ async fn complete_structured_raw(
+ &self,
+ _request: ChatRequest,
+ _schema: serde_json::Value,
+ ) -> ai_memory_llm::LlmResult<serde_json::Value> {
+ panic!("dry_run must not call the LLM");
+ }
+ }
+
+ /// Seed a session plus one observation under `(ws, proj)` via raw SQL so the
+ /// consolidator can resolve a target and (in a real run) read observations.
+ fn seed_session(
+ db_path: &std::path::Path,
+ session: SessionId,
+ ws: WorkspaceId,
+ proj: ProjectId,
+ ) {
+ let conn = rusqlite::Connection::open(db_path).unwrap();
+ let now = 1_700_000_000_000_i64;
+ conn.execute(
+ "INSERT INTO sessions (id, workspace_id, project_id, agent_kind, cwd, started_at) \
+ VALUES (?1, ?2, ?3, 'claude-code', ?4, ?5)",
+ rusqlite::params![
+ session.as_bytes(),
+ ws.as_bytes(),
+ proj.as_bytes(),
+ "/w",
+ now
+ ],
+ )
+ .unwrap();
+ let mut obs = [0u8; 16];
+ obs[15] = 1;
+ conn.execute(
+ "INSERT INTO observations \
+ (id, session_id, workspace_id, project_id, kind, title, body, created_at) \
+ VALUES (?1, ?2, ?3, ?4, 'other', 't', 'x', ?5)",
+ rusqlite::params![
+ &obs[..],
+ session.as_bytes(),
+ ws.as_bytes(),
+ proj.as_bytes(),
+ now
+ ],
+ )
+ .unwrap();
+ }
+
+ async fn consolidator_with_panic_llm(
+ tmp: &std::path::Path,
+ ) -> (
+ ai_memory_store::Store,
+ Consolidator,
+ SessionId,
+ WorkspaceId,
+ ProjectId,
+ ) {
+ let store = ai_memory_store::Store::open(tmp).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 session = SessionId::new();
+ seed_session(store.db_path(), session, ws, proj);
+ let wiki = Wiki::new(tmp, store.writer.clone()).unwrap();
+ let consolidator = Consolidator::new(
+ store.reader.clone(),
+ store.writer.clone(),
+ wiki,
+ Arc::new(PanicLlm),
+ ws,
+ proj,
+ );
+ (store, consolidator, session, ws, proj)
+ }
+
+ /// A single-page dry run returns the resolved plan (path + dry_run flag)
+ /// without ever touching the LLM.
+ #[tokio::test]
+ async fn single_page_dry_run_returns_plan_without_calling_the_llm() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (_store, consolidator, session, _ws, _proj) =
+ consolidator_with_panic_llm(tmp.path()).await;
+
+ let outcome = consolidator
+ .consolidate_session(
+ session,
+ true,
+ ai_memory_core::ActorContext::anonymous(),
+ None,
+ )
+ .await
+ .expect("dry_run plan should succeed without the LLM");
+
+ assert!(outcome.dry_run);
+ assert_eq!(outcome.path.as_str(), format!("sessions/{session}.md"));
+ assert!(outcome.new_body_markdown.is_empty());
+ assert!(outcome.new_title.is_empty());
+ assert!(outcome.page_id.is_none());
+ }
+
+ /// A multi-page dry run reports the resolved scope via the session anchor
+ /// (the page set needs a real run) and also never calls the LLM.
+ #[tokio::test]
+ async fn multi_page_dry_run_returns_anchor_plan_without_calling_the_llm() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (_store, consolidator, session, _ws, _proj) =
+ consolidator_with_panic_llm(tmp.path()).await;
+
+ let outcomes = consolidator
+ .consolidate_session_multi(
+ session,
+ true,
+ ai_memory_core::ActorContext::anonymous(),
+ None,
+ )
+ .await
+ .expect("multi-page dry_run plan should succeed without the LLM");
+
+ assert_eq!(outcomes.len(), 1);
+ assert!(outcomes[0].dry_run);
+ assert_eq!(outcomes[0].path.as_str(), format!("sessions/{session}.md"));
+ }
+
#[test]
fn page_update_deserialisation_defaults_slot_kind_to_state() {
let update: crate::types::ConsolidatedPageUpdate =
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 87cf8fc3..ce6ad144 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -1448,7 +1448,14 @@ impl AiMemoryServer {
gotcha pages plus the session page, all written in one atomic \
SQL transaction. Off by default; requires \
AI_MEMORY_LLM_PROVIDER + AI_MEMORY_LLM_MODEL set on the server. \
- Pass dry_run=true to preview without writing.")]
+ The consolidation target is resolved from where the session's \
+ observations actually landed, so a session that adopted its scope \
+ marker mid-run still consolidates into the right project. Admission \
+ is checked up front, before the LLM, so a rejected scope fails fast \
+ without spending a completion. Pass dry_run=true for a cheap plan: \
+ it runs that admission preflight and reports the resolved page path \
+ WITHOUT calling the LLM (no body preview); run without dry_run to \
+ produce the actual page(s).")]
async fn memory_consolidate(
&self,
Parameters(args): Parameters<ConsolidateArgs>,
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index bd895db7..0d0e4f8f 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1360,6 +1360,47 @@ impl ReaderPool {
.await
}
+ /// Resolve the `(workspace, project)` where a session's observations
+ /// actually landed, independent of the (possibly stale) `sessions` row.
+ ///
+ /// The `sessions` row is frozen at the first session-start (`begin_session`
+ /// uses `ON CONFLICT(id) DO NOTHING`), so a "hybrid" session that installed
+ /// its scope marker mid-flight stays anchored to the pre-marker scope. The
+ /// observation log, in contrast, carries the correct per-cwd scope for each
+ /// captured event. Returns the scope holding the most observations for the
+ /// session (ties broken by the most recent observation), or `None` when the
+ /// session has no observations.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn session_scope_from_observations(
+ &self,
+ session_id: SessionId,
+ ) -> StoreResult<Option<(WorkspaceId, ProjectId)>> {
+ self.with_conn(move |conn| {
+ let mut stmt = conn.prepare_cached(
+ "SELECT workspace_id, project_id \
+ FROM observations \
+ WHERE session_id = ?1 \
+ GROUP BY workspace_id, project_id \
+ ORDER BY COUNT(*) DESC, MAX(created_at) DESC \
+ LIMIT 1",
+ )?;
+ let mut rows = stmt.query(params![session_id.as_bytes()])?;
+ let Some(row) = rows.next()? else {
+ return Ok(None);
+ };
+ let ws_bytes: Vec<u8> = row.get(0)?;
+ let proj_bytes: Vec<u8> = row.get(1)?;
+ let ws = WorkspaceId::from_slice(&ws_bytes)
+ .map_err(|_| rusqlite::Error::IntegralValueOutOfRange(0, 0))?;
+ let proj = ProjectId::from_slice(&proj_bytes)
+ .map_err(|_| rusqlite::Error::IntegralValueOutOfRange(1, 0))?;
+ Ok(Some((ws, proj)))
+ })
+ .await
+ }
+
/// Load every `is_latest=1` page's embedding for the project, but
/// only when the stored `(provider, model, dim)` matches the
/// caller's expectation. Mismatched rows are skipped (the
diff --git a/crates/ai-memory-store/tests/session_scope_from_observations.rs b/crates/ai-memory-store/tests/session_scope_from_observations.rs
new file mode 100644
index 00000000..513addb2
--- /dev/null
+++ b/crates/ai-memory-store/tests/session_scope_from_observations.rs
@@ -0,0 +1,106 @@
+//! Integration tests for `session_scope_from_observations`.
+//!
+//! A "hybrid" session — one that installed its scope marker mid-flight — keeps
+//! a `sessions` row frozen on the pre-marker scope (`begin_session` uses
+//! `ON CONFLICT DO NOTHING`). Its observations, however, carry the correct
+//! per-cwd scope. These tests prove the reader resolves the scope from where
+//! the observations actually landed, independent of the stale session row.
+
+use ai_memory_core::{ProjectId, SessionId, WorkspaceId};
+use ai_memory_store::Store;
+use rusqlite::{Connection, params};
+
+fn id(n: u8) -> [u8; 16] {
+ let mut b = [0u8; 16];
+ b[15] = n;
+ b
+}
+
+/// Seed a workspace with two projects and a session anchored to `proj-b`
+/// (the stale pre-marker scope) whose observations mostly landed in `proj-a`.
+fn seed(db_path: &std::path::Path) {
+ let conn = Connection::open(db_path).unwrap();
+ let now = 1_700_000_000_000_i64;
+ let (ws, a, b) = (id(1), id(2), id(3));
+ let session = id(10);
+
+ conn.execute(
+ "INSERT INTO workspaces (id, name, created_at) VALUES (?1, 'w', ?2)",
+ params![&ws[..], now],
+ )
+ .unwrap();
+ for (pid, name, rp) in [(&a, "proj-a", "/w/a"), (&b, "proj-b", "/w/b")] {
+ conn.execute(
+ "INSERT INTO projects (id, workspace_id, name, repo_path, created_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5)",
+ params![&pid[..], &ws[..], name, rp, now],
+ )
+ .unwrap();
+ }
+ // The session row froze on proj-b at session start (pre-marker scope).
+ conn.execute(
+ "INSERT INTO sessions (id, workspace_id, project_id, agent_kind, cwd, started_at) \
+ VALUES (?1, ?2, ?3, 'claude-code', ?4, ?5)",
+ params![&session[..], &ws[..], &b[..], "/w/b", now],
+ )
+ .unwrap();
+ // But the durable work happened under proj-a: 3 observations there vs 1 in
+ // proj-b, so the majority scope is proj-a.
+ for (n, proj, ts) in [
+ (20u8, &a, now + 1),
+ (21, &a, now + 2),
+ (22, &a, now + 3),
+ (23, &b, now + 4),
+ ] {
+ conn.execute(
+ "INSERT INTO observations \
+ (id, session_id, workspace_id, project_id, kind, title, body, created_at) \
+ VALUES (?1, ?2, ?3, ?4, 'note', 't', 'x', ?5)",
+ params![&id(n)[..], &session[..], &ws[..], &proj[..], ts],
+ )
+ .unwrap();
+ }
+}
+
+#[tokio::test]
+async fn resolves_majority_observation_scope_over_stale_session_row() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ seed(store.db_path());
+
+ let session = SessionId::from_slice(&id(10)).unwrap();
+ let ws = WorkspaceId::from_slice(&id(1)).unwrap();
+ let proj_a = ProjectId::from_slice(&id(2)).unwrap();
+ let proj_b = ProjectId::from_slice(&id(3)).unwrap();
+
+ // The session ROW is anchored to proj-b (the stale pre-marker scope)...
+ assert_eq!(
+ store.reader.session_project_ids(session).await.unwrap(),
+ Some((ws, proj_b)),
+ );
+ // ...but the observations resolve to proj-a, where the work actually landed.
+ assert_eq!(
+ store
+ .reader
+ .session_scope_from_observations(session)
+ .await
+ .unwrap(),
+ Some((ws, proj_a)),
+ );
+}
+
+#[tokio::test]
+async fn returns_none_when_session_has_no_observations() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ // No seed: an unknown session has no observations to resolve from.
+ let session = SessionId::from_slice(&id(99)).unwrap();
+ assert_eq!(
+ store
+ .reader
+ .session_scope_from_observations(session)
+ .await
+ .unwrap(),
+ None,
+ );
+}
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index 1a819f14..951ee1ce 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -578,6 +578,39 @@ impl Wiki {
}
}
+ /// Run just the blocking admission chain for a would-be write, without
+ /// touching the store, disk, or any upstream cost (e.g. an LLM call). A
+ /// `failure_policy = reject` webhook can still abort here, so callers use
+ /// this to fail fast on a scope/actor that admission would refuse anyway.
+ ///
+ /// The webhook receives an empty placeholder body: the blocking chain
+ /// decides on `ctx` (op / actor / workspace / project + path), not on
+ /// content, so no real body is needed and any mutation it returns is
+ /// discarded. Returns `Ok(())` when no chain is attached (nothing to gate).
+ ///
+ /// # Errors
+ /// Returns [`WikiError`] when a reject-policy webhook refuses the write.
+ pub async fn preflight_admission(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ path: &PagePath,
+ op: AdmissionOp,
+ actor: ActorContext,
+ ) -> WikiResult<()> {
+ if let Some(chain) = &self.admission_chain {
+ let mut ctx = AdmissionContext {
+ op,
+ actor,
+ ..Default::default()
+ };
+ self.resolve_admission_names(workspace_id, project_id, &mut ctx)
+ .await;
+ chain.notify(Some(path.as_str()), &ctx).await?;
+ }
+ Ok(())
+ }
+
/// Remove the project's on-disk directory without running admission.
///
/// # Errors
@@ -2724,6 +2757,103 @@ mod tests {
assert_eq!(hits.len(), 1);
}
+ /// The preflight runs the blocking chain with no body and rejects when a
+ /// `reject`-policy webhook refuses — so a caller can fail fast before
+ /// spending an LLM call — while writing nothing to disk.
+ #[tokio::test]
+ async fn preflight_admission_rejects_without_writing() {
+ use crate::admission::{AdmissionChain, AdmissionOp, FailurePolicy, WebhookConfig};
+ use axum::http::StatusCode;
+ use axum::routing::post;
+ use axum::{Json, Router};
+ use tokio::net::TcpListener;
+
+ // A scope-guard-style webhook that refuses the write outright.
+ let app = Router::new().route(
+ "/gate",
+ post(|Json(_payload): Json<serde_json::Value>| async move {
+ (StatusCode::FORBIDDEN, "denied for this scope")
+ }),
+ );
+ 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: "gate".into(),
+ url: format!("http://{addr}/gate"),
+ 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 path = PagePath::new("sessions/abc.md").unwrap();
+ let err = wiki
+ .preflight_admission(
+ ws,
+ proj,
+ &path,
+ AdmissionOp::Consolidate,
+ ai_memory_core::ActorContext::anonymous(),
+ )
+ .await
+ .expect_err("reject-policy webhook must fail the preflight");
+ assert!(
+ format!("{err}").contains("denied for this scope"),
+ "the webhook rejection reason should surface: {err}",
+ );
+ // The preflight never persists anything.
+ assert!(!wiki.abs_path(ws, proj, &path).exists());
+ }
+
+ /// With no admission chain attached there is nothing to gate, so the
+ /// preflight is a no-op that always succeeds.
+ #[tokio::test]
+ async fn preflight_admission_is_noop_without_chain() {
+ 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();
+ wiki.preflight_admission(
+ ws,
+ proj,
+ &PagePath::new("sessions/abc.md").unwrap(),
+ AdmissionOp::Consolidate,
+ ai_memory_core::ActorContext::anonymous(),
+ )
+ .await
+ .expect("no chain → preflight is a no-op");
+ }
+
/// Two projects writing the same relative path must produce two distinct
/// files under their respective UUID-namespaced directories.
#[tokio::test]