Skip to content

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

Rust

fix(consolidate): validate cross-scope wikilinks against the store before applying

AkitaOnRails200d56a83586
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 84390c7e..f9316e7e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Fixed
+- Fixed consolidation still writing invented `[[_global:…]]` / `[[project:…]]`
+ wikilinks when a model ignored the #1207 prompt wording. The single-page,
+ batch and bootstrap apply paths now resolve every cross-scope wikilink
+ target against the store with no-create lookups before the write and
+ rewrite an unresolvable one to its plain label text, so a missing target
+ can no longer mint the dangling cross-project edge that `ai-memory lint`
+ reports as `broken_link`. Resolved cross-scope links survive
+ byte-identical, and same-project pending links stay untouched by design.
+ (#1218)
- Fixed consolidation inventing `[[_global:…]]` and `[[project:…]]` wikilinks to
pages that never existed, which `ai-memory lint` then reported as
`broken_link`. The single, batch and bootstrap prompts told the model that a
diff --git a/crates/ai-memory-consolidate/src/bootstrap.rs b/crates/ai-memory-consolidate/src/bootstrap.rs
index ea012f18..826ae8de 100644
--- a/crates/ai-memory-consolidate/src/bootstrap.rs
+++ b/crates/ai-memory-consolidate/src/bootstrap.rs
@@ -91,6 +91,10 @@ pub enum BootstrapError {
/// Store read failed (used by the idempotency check).
#[error(transparent)]
Store(#[from] ai_memory_store::StoreError),
+ /// Cross-scope link validation could not resolve a named scope (a real
+ /// store failure — a merely absent scope is de-linked, not an error).
+ #[error(transparent)]
+ Scope(#[from] ai_memory_store::ScopeResolutionError),
/// IO error (reading docs, walking the repo, …).
#[error(transparent)]
Io(#[from] std::io::Error),
@@ -640,6 +644,25 @@ impl Bootstrap {
evidence: Vec::new(),
});
+ // #1218: de-link any cross-scope wikilink the model invented before
+ // the write — same guard the consolidation apply paths run, so a
+ // bootstrap page cannot mint a dangling cross-project edge either.
+ // In-memory rewrite only; `apply_batch` stays the single atomic write.
+ let unresolved = {
+ let bodies: Vec<(&PagePath, &str)> = requests
+ .iter()
+ .map(|req| (&req.path, req.body.as_str()))
+ .collect();
+ crate::link_guard::unresolved_cross_scope_links(&self.reader, cfg.workspace_id, &bodies)
+ .await?
+ };
+ if !unresolved.is_empty() {
+ for req in &mut requests {
+ req.body =
+ crate::link_guard::delink_body(&req.body, &req.path, &unresolved).into_owned();
+ }
+ }
+
let _ids = self.wiki.apply_batch(requests).await?;
let _ = self.wiki.commit_all(&format!(
"bootstrap: {llm_chunks} LLM chunk(s), ingested {collected} sources, wrote {} pages",
@@ -2650,4 +2673,86 @@ mod tests {
path.ensure_portable()
.expect("the sanitized path must pass the portability guard");
}
+
+ /// #1218 on the bootstrap apply path: model output that invents a
+ /// cross-scope wikilink (`[[_global:nope]]` here — the reserved project
+ /// does not even exist in this fixture) must be de-linked to plain text
+ /// before the write, while a cross-scope link to a real page and a
+ /// same-project pending link survive byte-identical.
+ #[tokio::test]
+ async fn bootstrap_delinks_invented_cross_scope_wikilinks() {
+ let tmp = TempDir::new().unwrap();
+ let sources = vec![BootstrapSource {
+ kind: SourceKind::Readme,
+ label: "readme".into(),
+ text: "hello".into(),
+ }];
+ let response = serde_json::json!({
+ "pages": [{
+ "path": "concepts/links.md",
+ "title": "Links",
+ "body_markdown": "Invented: [[_global:nope]] and [[otherproj:notes/missing.md]]. \
+ Controls: [[otherproj:notes/exists.md]] and [[notes/pending.md]].",
+ "tags": [],
+ }],
+ "rationale": "r",
+ });
+ let llm = Arc::new(SequencedLlm {
+ calls: AtomicUsize::new(0),
+ responses: vec![response],
+ fail_at: None,
+ });
+ let (store, bootstrap, ws, proj) = bootstrap_fixture(tmp.path(), llm).await;
+
+ // The legitimate control target: an existing page in another project
+ // of the same workspace.
+ let other = store
+ .writer
+ .get_or_create_project(ws, "otherproj".to_string(), None)
+ .await
+ .unwrap();
+ bootstrap
+ .wiki
+ .write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: other,
+ path: PagePath::new("notes/exists.md").unwrap(),
+ frontmatter: serde_json::json!({}),
+ body: "Existing target page.".into(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: None,
+ admission_ctx: None,
+ author_id: None,
+ actor: ai_memory_core::ActorContext::anonymous(),
+ evidence: Vec::new(),
+ })
+ .await
+ .unwrap();
+
+ let cfg = resume_test_config(ws, proj, false);
+ bootstrap
+ .process_sources(&cfg, sources)
+ .await
+ .expect("bootstrap completes");
+
+ let stored = bootstrap
+ .wiki
+ .read_page(ws, proj, &PagePath::new("concepts/links.md").unwrap())
+ .unwrap();
+ assert!(!stored.body.contains("[[_global:nope]]"));
+ assert!(!stored.body.contains("[[otherproj:notes/missing.md]]"));
+ assert!(stored.body.contains("_global:nope"));
+ assert!(stored.body.contains("otherproj:notes/missing.md"));
+ assert!(
+ stored.body.contains("[[otherproj:notes/exists.md]]"),
+ "a cross-scope link to an existing page survives: {}",
+ stored.body
+ );
+ assert!(
+ stored.body.contains("[[notes/pending.md]]"),
+ "a same-project pending link is by design untouched: {}",
+ stored.body
+ );
+ }
}
diff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rs
index c76089ea..efb6429d 100644
--- a/crates/ai-memory-consolidate/src/consolidator.rs
+++ b/crates/ai-memory-consolidate/src/consolidator.rs
@@ -38,6 +38,11 @@ pub enum ConsolidatorError {
#[error(transparent)]
Store(#[from] ai_memory_store::StoreError),
+ /// Cross-scope link validation could not resolve a named scope (a real
+ /// store failure — a merely absent scope is de-linked, not an error).
+ #[error(transparent)]
+ Scope(#[from] ai_memory_store::ScopeResolutionError),
+
/// Underlying wiki error.
#[error(transparent)]
Wiki(#[from] ai_memory_wiki::WikiError),
@@ -81,6 +86,7 @@ pub fn redacted_error_summary(error: &ConsolidatorError) -> String {
let (class, status) = match error {
ConsolidatorError::Memory(_) => ("memory", None),
ConsolidatorError::Store(_) => ("store", None),
+ ConsolidatorError::Scope(_) => ("scope", None),
ConsolidatorError::Wiki(_) => ("wiki", None),
ConsolidatorError::Llm(llm) => (llm.class(), llm.http_status()),
ConsolidatorError::Serde(_) => ("serde", None),
@@ -319,6 +325,19 @@ impl Consolidator {
page.title = new_title;
}
+ // #1218: a cross-scope wikilink the model invented must not be
+ // written — resolve each against the store and de-link the ones that
+ // do not land on an existing page, so the write cannot mint a
+ // dangling cross-project edge the lint pass would flag.
+ let unresolved = crate::link_guard::unresolved_cross_scope_links(
+ &self.reader,
+ ws,
+ &[(&path, page.body_markdown.as_str())],
+ )
+ .await?;
+ page.body_markdown =
+ crate::link_guard::delink_body(&page.body_markdown, &path, &unresolved).into_owned();
+
let frontmatter = build_frontmatter(&page, session_id, agent_kind);
let id = self
.wiki
@@ -807,6 +826,26 @@ impl Consolidator {
outcomes_preview.push(outcome);
}
+ // #1218: same cross-scope link guard as the single-page path, run
+ // once over every proposed body so the store checks batch too.
+ // De-linking rewrites in memory only; `apply_batch` below stays the
+ // single atomic write.
+ let unresolved = {
+ let bodies: Vec<(&PagePath, &str)> = requests
+ .iter()
+ .map(|req| (&req.path, req.body.as_str()))
+ .collect();
+ crate::link_guard::unresolved_cross_scope_links(&self.reader, ws, &bodies).await?
+ };
+ if !unresolved.is_empty() {
+ for (req, outcome) in requests.iter_mut().zip(outcomes_preview.iter_mut()) {
+ let rewritten =
+ crate::link_guard::delink_body(&req.body, &req.path, &unresolved).into_owned();
+ req.body = rewritten.clone();
+ outcome.new_body_markdown = rewritten;
+ }
+ }
+
let ids = self.wiki.apply_batch(requests).await?;
let rationale_short = batch.rationale.chars().take(60).collect::<String>();
let _ = self
@@ -5563,4 +5602,178 @@ mod tests {
"state slots still refresh"
);
}
+
+ /// Write one page into a second project of the fixture's workspace, so a
+ /// cross-scope wikilink has something real to resolve to.
+ async fn seed_other_project_page(
+ store: &ai_memory_store::Store,
+ wiki: &Wiki,
+ ws: WorkspaceId,
+ project: &str,
+ path: &str,
+ ) {
+ let other = store
+ .writer
+ .get_or_create_project(ws, project.to_string(), None)
+ .await
+ .unwrap();
+ wiki.write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: other,
+ path: PagePath::new(path).unwrap(),
+ frontmatter: serde_json::json!({}),
+ body: "Existing target page.".into(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: None,
+ admission_ctx: None,
+ author_id: None,
+ actor: ai_memory_core::ActorContext::anonymous(),
+ evidence: Vec::new(),
+ })
+ .await
+ .unwrap();
+ }
+
+ /// Same, for the reserved `_global` preferences project, which lives in
+ /// the default workspace and goes through its own scope helper.
+ async fn seed_global_page(store: &ai_memory_store::Store, wiki: &Wiki, path: &str) {
+ let global = ai_memory_store::create_global_scope(&store.writer)
+ .await
+ .unwrap();
+ wiki.write_page(WritePageRequest {
+ workspace_id: global.workspace_id,
+ project_id: global.project_id,
+ path: PagePath::new(path).unwrap(),
+ frontmatter: serde_json::json!({}),
+ body: "A standing preference.".into(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: None,
+ admission_ctx: None,
+ author_id: None,
+ actor: ai_memory_core::ActorContext::anonymous(),
+ evidence: Vec::new(),
+ })
+ .await
+ .unwrap();
+ }
+
+ /// #1218: a batch whose model output invents cross-scope wikilinks must
+ /// not write them as links. `[[_global:nope]]` (missing page in the
+ /// reserved project), `[[otherproj:notes/missing.md]]` (missing page in
+ /// a real project) and `[[ghostproj:x.md]]` (a project that does not
+ /// exist at all) are all de-linked to plain text before the write.
+ /// Controls in the same body: a cross-scope link to an existing page
+ /// survives byte-identical, and a same-project pending link stays
+ /// untouched — pending links are by design (#1218 scope).
+ #[tokio::test]
+ async fn batch_delinks_invented_cross_scope_wikilinks() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (store, wiki, session, ws, proj) = batch_fixture(tmp.path()).await;
+ seed_other_project_page(&store, &wiki, ws, "otherproj", "notes/exists.md").await;
+ seed_global_page(&store, &wiki, "prefs.md").await;
+
+ let path = PagePath::new("notes/with-links.md").unwrap();
+ let body = "Invented: [[_global:nope]], [[otherproj:notes/missing.md]], \
+ [[ghostproj:x.md]]. \
+ Controls: [[otherproj:notes/exists.md]], [[_global:prefs.md|the prefs]], \
+ [[notes/pending.md]].";
+ let outcomes = Consolidator::new(
+ store.reader.clone(),
+ store.writer.clone(),
+ wiki.clone(),
+ Arc::new(ScriptedLlm(batch_targeting(path.as_str(), body))),
+ ws,
+ proj,
+ )
+ .consolidate_session_multi(
+ session,
+ false,
+ ai_memory_core::ActorContext::anonymous(),
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+
+ let stored = wiki.read_page(ws, proj, &path).unwrap();
+ // Invented links are plain text now: brackets dropped, label kept.
+ assert!(!stored.body.contains("[[_global:nope]]"));
+ assert!(!stored.body.contains("[[otherproj:notes/missing.md]]"));
+ assert!(!stored.body.contains("[[ghostproj:x.md]]"));
+ assert!(stored.body.contains("_global:nope"));
+ assert!(stored.body.contains("otherproj:notes/missing.md"));
+ assert!(stored.body.contains("ghostproj:x.md"));
+ assert!(
+ stored.body.contains("[[otherproj:notes/exists.md]]"),
+ "a cross-scope link to an existing page survives byte-identical: {}",
+ stored.body
+ );
+ assert!(
+ stored.body.contains("[[_global:prefs.md|the prefs]]"),
+ "a resolved _global link keeps its label form: {}",
+ stored.body
+ );
+ assert!(
+ stored.body.contains("[[notes/pending.md]]"),
+ "a same-project pending link is by design untouched: {}",
+ stored.body
+ );
+ // The outcome reports the body as actually written.
+ assert_eq!(outcomes.len(), 1);
+ assert_eq!(outcomes[0].new_body_markdown, stored.body);
+
+ // And the lint pass has nothing left to flag: no dangling
+ // cross-project edge was minted.
+ let dangling = store
+ .reader
+ .dangling_cross_project_links(ws, proj)
+ .await
+ .unwrap();
+ assert!(
+ dangling.is_empty(),
+ "de-linking must leave no dangling cross-project edges: {dangling:?}"
+ );
+ }
+
+ /// #1218 on the single-page path: the session page gets the same guard
+ /// before `Wiki::write_page`.
+ #[tokio::test]
+ async fn single_page_delinks_invented_cross_scope_wikilinks() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (store, wiki, session, ws, proj) = batch_fixture(tmp.path()).await;
+ seed_other_project_page(&store, &wiki, ws, "otherproj", "notes/exists.md").await;
+
+ let response = serde_json::json!({
+ "title": "Link cleanup",
+ "body_markdown": "Saw [[otherproj:notes/missing.md]] and \
+ [[otherproj:notes/exists.md]] and [[notes/pending.md]].",
+ "tags": [],
+ });
+ Consolidator::new(
+ store.reader.clone(),
+ store.writer.clone(),
+ wiki.clone(),
+ Arc::new(ScriptedLlm(response)),
+ ws,
+ proj,
+ )
+ .consolidate_session(
+ session,
+ false,
+ ai_memory_core::ActorContext::anonymous(),
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+
+ let path = PagePath::new(format!("sessions/{session}.md")).unwrap();
+ let stored = wiki.read_page(ws, proj, &path).unwrap();
+ assert!(!stored.body.contains("[[otherproj:notes/missing.md]]"));
+ assert!(stored.body.contains("otherproj:notes/missing.md"));
+ assert!(stored.body.contains("[[otherproj:notes/exists.md]]"));
+ assert!(stored.body.contains("[[notes/pending.md]]"));
+ }
}
diff --git a/crates/ai-memory-consolidate/src/lib.rs b/crates/ai-memory-consolidate/src/lib.rs
index 2320af04..62755157 100644
--- a/crates/ai-memory-consolidate/src/lib.rs
+++ b/crates/ai-memory-consolidate/src/lib.rs
@@ -21,6 +21,7 @@ pub mod embed;
pub mod entropy_filter;
pub mod experience;
pub mod keep_tokens;
+mod link_guard;
pub mod lint;
mod path_sanitize;
pub mod profile;
diff --git a/crates/ai-memory-consolidate/src/link_guard.rs b/crates/ai-memory-consolidate/src/link_guard.rs
new file mode 100644
index 00000000..41102f86
--- /dev/null
+++ b/crates/ai-memory-consolidate/src/link_guard.rs
@@ -0,0 +1,127 @@
+//! Cross-scope wikilink validation for LLM-produced page bodies (#1218).
+//!
+//! The consolidation prompts tell the model not to invent
+//! `[[project:path]]` / `[[_global:path]]` links, but a prompt cannot
+//! guarantee it (#1207 shipped the wording; this is the code backstop).
+//! Whatever the lint pass would later flag as a dangling cross-project
+//! dependency is instead caught here, before the write: every cross-scope
+//! wikilink in a proposed body is resolved against the store with no-create
+//! lookups, and an unresolved one is rewritten to its plain label text
+//! (brackets dropped, label kept) so the prose still reads. Resolved links
+//! survive byte-identical; same-project `[[target]]` links are by design
+//! allowed to dangle (the target may be written later) and are never
+//! touched.
+
+use std::borrow::Cow;
+use std::collections::{BTreeMap, BTreeSet};
+
+use ai_memory_core::{PagePath, WorkspaceId};
+use ai_memory_store::{ReaderPool, ScopeResolutionError, lookup_existing_scope};
+use tracing::warn;
+
+/// A normalised link key as `ai_memory_wiki::extract_links` yields it:
+/// `(workspace, project, path)`, with `workspace`/`project` `None` for a
+/// same-project link. Only project-qualified keys ever enter the sets this
+/// module handles.
+pub(crate) type LinkKey = (Option<String>, Option<String>, String);
+
+/// Collect the cross-scope wikilink targets across `bodies` that do NOT
+/// resolve to an existing latest page in the store.
+///
+/// Lookups are no-create and batched: each named scope is resolved once via
+/// [`lookup_existing_scope`], then every path under it is checked in a
+/// single query. A missing workspace, a missing project, or an ambiguous
+/// project name all count as unresolved — the link can never resolve
+/// deterministically, so keeping it would only mint a lint finding. A
+/// genuine store failure propagates rather than stripping links that may be
+/// fine.
+///
+/// `source_workspace_id` supplies the workspace name for project-only
+/// `[[project:path]]` links, exactly as the write-path link resolver treats
+/// a missing workspace qualifier as "the source page's workspace".
+pub(crate) async fn unresolved_cross_scope_links(
+ reader: &ReaderPool,
+ source_workspace_id: WorkspaceId,
+ bodies: &[(&PagePath, &str)],
+) -> Result<BTreeSet<LinkKey>, ScopeResolutionError> {
+ let mut targets: BTreeSet<LinkKey> = BTreeSet::new();
+ for (page_path, body) in bodies {
+ for link in ai_memory_wiki::extract_links(body, page_path) {
+ if link.project.is_some() {
+ targets.insert((link.workspace, link.project, link.path.as_str().to_string()));
+ }
+ }
+ }
+ if targets.is_empty() {
+ return Ok(BTreeSet::new());
+ }
+
+ // The source workspace exists by construction — the session's
+ // observations landed in it — so a miss here is a genuine store
+ // inconsistency worth failing on rather than silently de-linking.
+ let source_workspace = reader
+ .workspace_name_by_id(source_workspace_id)
+ .await?
+ .ok_or_else(|| ScopeResolutionError::WorkspaceNotFound {
+ workspace: source_workspace_id.to_string(),
+ })?;
+
+ let mut by_scope: BTreeMap<(String, String), Vec<LinkKey>> = BTreeMap::new();
+ for key in targets {
+ let workspace = key.0.clone().unwrap_or_else(|| source_workspace.clone());
+ let project = key.1.clone().unwrap_or_default();
+ by_scope.entry((workspace, project)).or_default().push(key);
+ }
+
+ let mut unresolved = BTreeSet::new();
+ for ((workspace, project), keys) in by_scope {
+ let scope = match lookup_existing_scope(reader, &workspace, &project).await {
+ Ok(scope) => scope,
+ Err(
+ error @ (ScopeResolutionError::WorkspaceNotFound { .. }
+ | ScopeResolutionError::ProjectNotFoundInWorkspace { .. }
+ | ScopeResolutionError::ProjectNameAmbiguous { .. }),
+ ) => {
+ warn!(
+ target_scope = %format!("{workspace}/{project}"),
+ error = %error,
+ "de-linking cross-scope wikilinks: the named scope does not resolve",
+ );
+ unresolved.extend(keys);
+ continue;
+ }
+ Err(error) => return Err(error),
+ };
+ let paths: Vec<String> = keys.iter().map(|key| key.2.clone()).collect();
+ let existing: std::collections::HashSet<String> = reader
+ .existing_latest_paths(scope.workspace_id, scope.project_id, paths)
+ .await?
+ .into_iter()
+ .collect();
+ for key in keys {
+ if !existing.contains(&key.2) {
+ warn!(
+ target = %format!("{}:{}", key.1.as_deref().unwrap_or_default(), key.2),
+ "de-linking cross-scope wikilink: no such page in the target project",
+ );
+ unresolved.insert(key);
+ }
+ }
+ }
+ Ok(unresolved)
+}
+
+/// Rewrite `body`, replacing every wikilink whose key is in `unresolved`
+/// with its plain label text. A borrowed no-op when the set is empty.
+pub(crate) fn delink_body<'a>(
+ body: &'a str,
+ page_path: &PagePath,
+ unresolved: &BTreeSet<LinkKey>,
+) -> Cow<'a, str> {
+ if unresolved.is_empty() {
+ return Cow::Borrowed(body);
+ }
+ Cow::Owned(ai_memory_wiki::delink_wikilinks(
+ body, page_path, unresolved,
+ ))
+}
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 750a5681..34568794 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -8545,6 +8545,53 @@ impl ReaderPool {
.await
}
+ /// Return the subset of `paths` that name a latest page in this scope, in
+ /// a single query. The batched counterpart of [`Self::latest_page_id_by_ids`]
+ /// for callers that need to know *which* paths resolve — the consolidation
+ /// link guard validates proposed cross-scope wikilinks against it (#1218).
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn existing_latest_paths(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ paths: Vec<String>,
+ ) -> StoreResult<Vec<String>> {
+ if paths.is_empty() {
+ return Ok(Vec::new());
+ }
+ self.with_conn(move |conn| {
+ let mut distinct: Vec<String> = paths;
+ distinct.sort();
+ distinct.dedup();
+ let placeholders = std::iter::repeat_n("?", distinct.len())
+ .collect::<Vec<_>>()
+ .join(", ");
+ let sql = format!(
+ "SELECT path FROM pages \
+ WHERE workspace_id = ?1 AND project_id = ?2 AND is_latest = 1 \
+ AND path IN ({placeholders})"
+ );
+ let mut stmt = conn.prepare(&sql)?;
+ let ws_bytes = workspace_id.as_bytes();
+ let proj_bytes = project_id.as_bytes();
+ let mut binds: Vec<&dyn rusqlite::ToSql> = Vec::with_capacity(distinct.len() + 2);
+ binds.push(ws_bytes as &dyn rusqlite::ToSql);
+ binds.push(proj_bytes as &dyn rusqlite::ToSql);
+ for p in &distinct {
+ binds.push(p as &dyn rusqlite::ToSql);
+ }
+ let rows = stmt.query_map(binds.as_slice(), |row| row.get::<_, String>(0))?;
+ let mut found = Vec::new();
+ for r in rows {
+ found.push(r?);
+ }
+ Ok(found)
+ })
+ .await
+ }
+
/// Return whether the latest version of one fully scoped page is expired.
/// Returns `None` when the path has no latest indexed row.
///
diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rs
index 2c23bd31..ee84fbdb 100644
--- a/crates/ai-memory-store/tests/suite/multi_session.rs
+++ b/crates/ai-memory-store/tests/suite/multi_session.rs
@@ -477,6 +477,80 @@ async fn concurrent_writes_to_one_path_supersede_rather_than_destroy() {
);
}
+/// The batched path-existence probe the consolidation link guard validates
+/// proposed cross-scope wikilinks against (#1218): it reports exactly the
+/// paths with a latest row, in any input order, and never invents one.
+#[tokio::test]
+async fn existing_latest_paths_reports_exactly_the_live_paths() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+
+ store
+ .writer
+ .upsert_page(page(ws, proj, "notes/real.md", "Real", "a real page"))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(page(ws, proj, "decisions/adr.md", "ADR", "a decision"))
+ .await
+ .unwrap();
+
+ let mut found = store
+ .reader
+ .existing_latest_paths(
+ ws,
+ proj,
+ vec![
+ "notes/missing.md".to_string(),
+ "decisions/adr.md".to_string(),
+ "notes/real.md".to_string(),
+ // A duplicate must not double-report.
+ "notes/real.md".to_string(),
+ ],
+ )
+ .await
+ .unwrap();
+ found.sort();
+ assert_eq!(found, vec!["decisions/adr.md", "notes/real.md"]);
+
+ // A superseded path still counts: the latest version is the one a link
+ // resolves to.
+ store
+ .writer
+ .upsert_page(page(ws, proj, "notes/real.md", "Real", "rewritten"))
+ .await
+ .unwrap();
+ let found = store
+ .reader
+ .existing_latest_paths(ws, proj, vec!["notes/real.md".to_string()])
+ .await
+ .unwrap();
+ assert_eq!(found, vec!["notes/real.md"]);
+
+ // A foreign scope never sees this project's pages.
+ let other_proj = store
+ .writer
+ .get_or_create_project(ws, "other-app".to_string(), None)
+ .await
+ .unwrap();
+ let found = store
+ .reader
+ .existing_latest_paths(ws, other_proj, vec!["notes/real.md".to_string()])
+ .await
+ .unwrap();
+ assert!(found.is_empty());
+
+ // Empty input is a no-op, not an error.
+ let found = store
+ .reader
+ .existing_latest_paths(ws, proj, Vec::new())
+ .await
+ .unwrap();
+ assert!(found.is_empty());
+}
+
/// Re-writing identical content must not churn a new version.
///
/// Two harnesses syncing the same file would otherwise manufacture a version
diff --git a/crates/ai-memory-wiki/src/lib.rs b/crates/ai-memory-wiki/src/lib.rs
index da4daa14..bd0ef325 100644
--- a/crates/ai-memory-wiki/src/lib.rs
+++ b/crates/ai-memory-wiki/src/lib.rs
@@ -26,7 +26,9 @@ pub use confinement::validate_wiki_tree;
pub use error::{WikiError, WikiResult};
pub use git::{COMMIT_AUTHOR_EMAIL, COMMIT_AUTHOR_NAME, GitAdapter};
pub use ledger::is_rotated_event_ledger;
-pub use markdown::{Markdown, derive_title, emit, parse, rewrite_local_wikilinks};
+pub use markdown::{
+ Markdown, delink_wikilinks, derive_title, emit, extract_links, parse, rewrite_local_wikilinks,
+};
pub use migrations::run_pending as run_wiki_migrations;
pub use watcher::{DEBOUNCE_WINDOW, RECONCILE_INTERVAL, WatcherHandle};
pub use wiki::{MoveSessionOutcome, PurgeSessionOutcome, SessionPageFile, Wiki, WritePageRequest};
diff --git a/crates/ai-memory-wiki/src/markdown.rs b/crates/ai-memory-wiki/src/markdown.rs
index 1b74102f..a7d5fa87 100644
--- a/crates/ai-memory-wiki/src/markdown.rs
+++ b/crates/ai-memory-wiki/src/markdown.rs
@@ -520,6 +520,95 @@ fn rewrite_wikilinks_in_segment(
}
}
+/// Rewrite `body`, replacing each wikilink whose normalised
+/// `(workspace, project, path)` key appears in `delink` with its plain label
+/// text: the `|label` when one is present, otherwise the raw target text.
+/// Every other wikilink — resolved cross-scope links and all same-project
+/// links included — is copied byte-identically, and fenced code blocks /
+/// inline code spans are skipped exactly as [`extract_links`] skips them, so
+/// an example `[[project:path]]` shown as code is never rewritten.
+///
+/// The consolidation apply path uses this to strip cross-scope links the
+/// store cannot resolve (#1218): the `delink` set is built from
+/// [`extract_links`] keys, so a key computed here matches byte-for-byte.
+/// Wikilink targets are project-root-relative, so `page_path` only matters
+/// for the (never-delinked) same-project form.
+#[must_use]
+pub fn delink_wikilinks(
+ body: &str,
+ page_path: &PagePath,
+ delink: &BTreeSet<(Option<String>, Option<String>, String)>,
+) -> String {
+ if delink.is_empty() {
+ return body.to_string();
+ }
+ let mut out = String::with_capacity(body.len());
+ let mut fence: Option<CodeFence> = None;
+ for raw_line in body.split_inclusive('\n') {
+ let (line, terminator) = split_line_terminator(raw_line);
+ let (next_fence, is_fence_or_code) = CodeFence::step(fence, line);
+ fence = next_fence;
+ if is_fence_or_code {
+ out.push_str(line);
+ out.push_str(terminator);
+ continue;
+ }
+ let code_spans = inline_code_spans(line);
+ let mut pos = 0;
+ for span in &code_spans {
+ delink_wikilinks_in_segment(&line[pos..span.start], page_path, delink, &mut out);
+ out.push_str(&line[span.clone()]);
+ pos = span.end;
+ }
+ delink_wikilinks_in_segment(&line[pos..], page_path, delink, &mut out);
+ out.push_str(terminator);
+ }
+ out
+}
+
+fn delink_wikilinks_in_segment(
+ seg: &str,
+ page_path: &PagePath,
+ delink: &BTreeSet<(Option<String>, Option<String>, String)>,
+ out: &mut String,
+) {
+ let mut rest = seg;
+ loop {
+ let Some(start) = rest.find("[[") else {
+ out.push_str(rest);
+ return;
+ };
+ out.push_str(&rest[..start]);
+ let after_start = &rest[start + 2..];
+ let Some(end) = after_start.find("]]") else {
+ out.push_str(&rest[start..]);
+ return;
+ };
+ let raw = &after_start[..end];
+ // Parse exactly as `extract_wikilinks` does so a key in `delink`
+ // (built from `extract_links` output) hits the same occurrence.
+ let (target_part, label) = raw
+ .split_once('|')
+ .map_or((raw, None), |(t, l)| (t, Some(l)));
+ let unlabelled = target_part.trim();
+ let (workspace, project, path_part) = split_scope(unlabelled);
+ let delinked = normalize_link_target(&path_part, page_path, true)
+ .is_some_and(|path| delink.contains(&(workspace, project, path)));
+ if delinked {
+ let text = label
+ .map(str::trim)
+ .filter(|l| !l.is_empty())
+ .unwrap_or(unlabelled);
+ out.push_str(text);
+ } else {
+ out.push_str("[[");
+ out.push_str(raw);
+ out.push_str("]]");
+ }
+ rest = &after_start[end + 2..];
+ }
+}
+
/// Resolve a local `[[...]]` wikilink target into `(bundle-relative href,
/// display label)`. Returns `None` when the target is cross-project,
/// cross-workspace, empty, or otherwise not a page — the caller then keeps
@@ -1253,6 +1342,63 @@ mod tests {
assert_eq!(paths, vec!["notes/kept.md"]);
}
+ /// Build a `delink` key exactly as the consolidation guard does: from
+ /// `extract_links` output for the cross-project targets named in
+ /// `targets`.
+ fn delink_set(body: &str, page: &PagePath, targets: &[&str]) -> BTreeSet<LinkKey> {
+ extract_links(body, page)
+ .into_iter()
+ .filter(|l| l.project.is_some() && targets.contains(&l.path.as_str()))
+ .map(|l| (l.workspace, l.project, l.path.as_str().to_string()))
+ .collect()
+ }
+
+ #[test]
+ fn delink_wikilinks_strips_only_listed_cross_scope_links() {
+ let page = PagePath::new("notes/a.md").unwrap();
+ let body = "See [[infra:runbooks/02.md]] and [[infra:runbooks/missing.md|the gap]], \
+ plus [[notes/pending.md]] and [[infra:runbooks/02.md|again]].\n";
+ let delink = delink_set(body, &page, &["runbooks/missing.md"]);
+ let out = delink_wikilinks(body, &page, &delink);
+ assert_eq!(
+ out,
+ "See [[infra:runbooks/02.md]] and the gap, \
+ plus [[notes/pending.md]] and [[infra:runbooks/02.md|again]].\n",
+ "only the unresolved link is de-linked; the resolved one and the \
+ same-project pending link stay byte-identical"
+ );
+ }
+
+ #[test]
+ fn delink_wikilinks_without_label_keeps_the_target_text() {
+ let page = PagePath::new("notes/a.md").unwrap();
+ let body = "Depends on [[_global:nope]].\n";
+ let delink = delink_set(body, &page, &["nope.md"]);
+ assert_eq!(delink.len(), 1, "_global target is extracted");
+ assert_eq!(
+ delink_wikilinks(body, &page, &delink),
+ "Depends on _global:nope.\n"
+ );
+ }
+
+ #[test]
+ fn delink_wikilinks_skips_code_and_leaves_empty_set_untouched() {
+ let page = PagePath::new("notes/a.md").unwrap();
+ let body = "```\n[[infra:runbooks/missing.md]]\n```\n\
+ Inline `[[infra:runbooks/missing.md]]` stays code, \
+ but [[infra:runbooks/missing.md]] is prose.\n";
+ let delink = delink_set(body, &page, &["runbooks/missing.md"]);
+ let out = delink_wikilinks(body, &page, &delink);
+ assert_eq!(
+ out,
+ "```\n[[infra:runbooks/missing.md]]\n```\n\
+ Inline `[[infra:runbooks/missing.md]]` stays code, \
+ but infra:runbooks/missing.md is prose.\n"
+ );
+ // An empty set must be a byte-identical no-op.
+ assert_eq!(delink_wikilinks(body, &page, &BTreeSet::new()), body);
+ }
+
#[test]
fn extract_links_ignores_inline_code_spans() {
// The web page renders all of these code spans as code, so a link
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 07aea70c..5ff0a124 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -90,6 +90,7 @@ means the boundary is not built yet.
| 14c | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) |
| 14d | `include_related` shows and walks only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` applies, so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed; `ai-memory-mcp` `server.rs` `bob_does_not_see_restricted_pages_through_the_related_walk` (an ungranted user's `memory_read_page{include_related}` omits the restricted page; control: no viewer still reaches it) — fails with `memory_read_page` passing `None` instead of `viewer_from_parts` | STRONG |
| 14e | `memory_write_page` session evidence cites only a session of the target project (#708) | `ai-memory-mcp/src/server.rs` `memory_write_page` — a `session_id` is accepted only when `require_session_in_scope` resolves the session (where its observations landed, else its session row, as `Consolidator::session_target` does) to the same `(workspace_id, project_id)` the write grant was checked against; unknown and foreign ids get one refusal, so the error is no existence oracle; `scope: "global"` with a `session_id` is refused; `refuse_pinned_page_overwrite` keeps a write that cites a session off a pinned page; only a write to `sessions/<id>.md` reconciles the session's queued SessionEnd job | `server.rs` `write_page_refuses_a_session_from_another_project` (a foreign and an unknown session refused, no evidence row written, the foreign job still queued; control: the project's own session accepted), `session_evidence_write_leaves_a_pinned_page_alone` (control: the same write without `session_id` edits the page), `session_evidence_on_another_path_leaves_the_job_queued`, `write_page_rejects_a_malformed_or_global_session_id` — each of the scope check, the pinned check and the session-page-only reconcile proven to fail its test when removed | STRONG |
+| 14f | Consolidation apply path validates cross-scope wikilinks against the store (#1218) | `ai-memory-consolidate/src/link_guard.rs` `unresolved_cross_scope_links` — every `[[project:path]]` / `[[workspace/project:path]]` / `[[_global:path]]` target in a proposed body is resolved with the no-create `lookup_existing_scope` (never creates a scope) and batch-checked via `reader.rs` `existing_latest_paths`; a missing workspace/project, an ambiguous project name, or a missing target page de-links the wikilink, while a genuine store failure aborts the consolidation before any write. `delink_body` → `ai-memory-wiki/src/markdown.rs` `delink_wikilinks` drops the brackets and keeps the label, skipping code fences and inline code exactly as `extract_links` does. Wired into all three apply paths (`consolidator.rs` single-page and batch, `bootstrap.rs`) after the pinned/foreign-slot/portable guards and before the atomic `Wiki::apply_batch` / `write_page`, so an invented cross-project dependency can no longer be written and flagged by the lint pass later. Same-project `[[target]]` links stay untouched by design (the target may be written later) | `consolidator.rs` `batch_delinks_invented_cross_scope_wikilinks` (invented `[[_global:nope]]`, `[[otherproj:notes/missing.md]]`, `[[ghostproj:x.md]]` de-linked to plain text; controls: a cross-scope link to an existing page and a same-project pending link survive byte-identical; `dangling_cross_project_links` left empty), `single_page_delinks_invented_cross_scope_wikilinks`, `bootstrap.rs` `bootstrap_delinks_invented_cross_scope_wikilinks` — each proven to fail with the guard neutralized; `markdown.rs` `delink_wikilinks_strips_only_listed_cross_scope_links`, `delink_wikilinks_without_label_keeps_the_target_text`, `delink_wikilinks_skips_code_and_leaves_empty_set_untouched`; store `multi_session.rs` `existing_latest_paths_reports_exactly_the_live_paths` (exact live-path set, superseded path still resolves, foreign scope sees nothing) | STRONG |
| 15 | Agent-archive restore path confinement, resource bounds, and consistency | `ai-memory-cli/src/commands/restore_agents.rs` stages only bounded regular UTF-8 entries; requires a one-to-one manifest/body/checksum/target mapping; allowlists destinations by scope; rejects symlinked descendants; writes each file atomically and rolls back earlier writes after a later failure. `backup_agents.rs` skips direct and directory-root source symlinks, bounds individual assets, and atomically replaces a private archive only after gzip completion | `backup_agents.rs` `restore_agents_rejects_path_traversal`, `restore_agents_rejects_unauthorized_destination_path`, `restore_agents_verifies_sha256_integrity`, `restore_agents_requires_a_complete_one_to_one_manifest`, `restore_agents_rejects_oversized_entries_from_the_header`, `restore_agents_rejects_a_symlinked_destination_parent`, `backup_agents_does_not_follow_config_or_asset_root_symlinks`, and `failed_backup_leaves_the_previous_archive_intact`; `backup_and_restore_agents_round_trip` is the valid-path control; `restore_agents::tests::rollback_removes_new_files_and_restores_overwrites` covers recovery | STRONG |
| 16 | Relay queue identity, migration, and private filesystem state | `companions/ai-memory-relay/src/queue.rs` `Queue::open_inner` performs read-only identity preflight, rechecks under `IMMEDIATE`, commits schema and metadata together; `configure` checks the presence of user objects and rechecks `identity`/`schema_version` metadata on the same connection before every bounded BUSY/LOCKED retry; `fsguard.rs` checks existing paths and creates owner-only files before SQLite opens them | `tests/relay.rs` `a_foreign_database_is_refused_byte_for_byte`, `unknown_schemas_refuse_without_mutation`, `a_foreign_database_with_a_writer_is_refused_before_write_coordination`, `a_foreign_identity_after_preflight_is_refused_without_mutation`, `a_foreign_identity_during_journal_retry_is_refused_without_mutation`, `journal_retry_refuses_a_changed_version_or_empty_database_without_mutation`; controls: `journal_transition_retries_sqlite_lock_without_losing_v1_values`, `fresh_queue_init_and_v1_reopens_work_across_processes`; recovery: `interrupted_and_failed_migrations_roll_back_and_recover`, `journal_reclassification_busy_preserves_committed_migration_and_retries_same_queue`; diagnostics: `classification_read_failures_display_the_sqlite_cause_once_and_preserve_foreign_bytes`; Unix privacy: `the_queue_database_and_its_sidecars_are_owner_only` and the contended migration control | Guard-removal proof covers preflight, locked recheck, and journal retry identity/version checks; full table structure is outside this classification. Windows path rejection is preserved; Windows ACL hardening remains operator-owned |